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 12830cd0c..a75bfa444 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 @@ -291,11 +291,11 @@ public class AccountNumberPreferencesTest { this.groupAccountNo = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "accountNo"); if (isAccountPreferenceSetUp) { - String groupsPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference( + String groupsPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference( this.groupsAccountNumberPreferenceId, "prefixType.value"); - + if (groupsPrefixName.equals(this.officeName)) { - + final String groupOfficeName = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "officeName"); this.validateAccountNumberLengthAndStartsWithPrefix(this.groupAccountNo, groupOfficeName); @@ -316,15 +316,15 @@ public class AccountNumberPreferencesTest { Assert.assertTrue(center.getName().equals(name)); if (isAccountPreferenceSetUp) { - String centerPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference( + 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)) { final String centerOfficeName = Utils.performServerGet(requestSpec, responseSpec, CENTER_URL, "officeName"); this.validateAccountNumberLengthAndStartsWithPrefix(center.getAccountNo(), centerOfficeName); } - } else { + } else { validateAccountNumberLengthAndStartsWithPrefix(center.getAccountNo(), null); } } @@ -375,7 +375,7 @@ public class AccountNumberPreferencesTest { private void validateAccountNumberLengthAndStartsWithPrefix(final String accountNumber, String prefix) { if (prefix != null) { - prefix = prefix.substring(0, Math.min(prefix.length(), 10)); + prefix = prefix.substring(0, Math.min(prefix.length(), 10)); Assert.assertEquals(accountNumber.length(), prefix.length() + 9); Assert.assertTrue(accountNumber.startsWith(prefix)); } else { 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 index 172304578..3bb0f4aae 100755 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientSavingsIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientSavingsIntegrationTest.java @@ -786,435 +786,435 @@ public class ClientSavingsIntegrationTest { savingsAccountErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); } - @SuppressWarnings("unchecked") - @Test - public void testSavingsAccountPostInterestOnLastDayWithOverdraft() { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, - this.responseSpec); + @SuppressWarnings("unchecked") + @Test + public void testSavingsAccountPostInterestOnLastDayWithOverdraft() { + 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); - Assert.assertNotNull(clientID); - final String minBalanceForInterestCalculation = null; + /*** + * Create a client to apply for savings account (overdraft account). + */ + final Integer clientID = ClientHelper.createClient(this.requestSpec, + this.responseSpec); + Assert.assertNotNull(clientID); + final String minBalanceForInterestCalculation = null; - /*** - * Create savings product with zero opening balance and overdraft - * enabled - */ - final String zeroOpeningBalance = "0.0"; - 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); - Assert.assertNotNull(savingsProductID); + /*** + * Create savings product with zero opening balance and overdraft + * enabled + */ + final String zeroOpeningBalance = "0.0"; + 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); + Assert.assertNotNull(savingsProductID); - /*** - * Apply for Savings account - */ - final Integer savingsId = this.savingsAccountHelper - .applyForSavingsApplication(clientID, savingsProductID, - ACCOUNT_TYPE_INDIVIDUAL); - Assert.assertNotNull(savingsProductID); + /*** + * Apply for Savings account + */ + final Integer savingsId = this.savingsAccountHelper + .applyForSavingsApplication(clientID, savingsProductID, + ACCOUNT_TYPE_INDIVIDUAL); + Assert.assertNotNull(savingsProductID); - HashMap modifications = this.savingsAccountHelper.updateSavingsAccount( - clientID, savingsProductID, savingsId, ACCOUNT_TYPE_INDIVIDUAL); - Assert.assertTrue(modifications.containsKey("submittedOnDate")); + HashMap modifications = this.savingsAccountHelper.updateSavingsAccount( + clientID, savingsProductID, savingsId, ACCOUNT_TYPE_INDIVIDUAL); + Assert.assertTrue(modifications.containsKey("submittedOnDate")); - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings( - this.requestSpec, this.responseSpec, savingsId); - SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings( + this.requestSpec, this.responseSpec, savingsId); + SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); - /*** - * Approve the savings account - */ - savingsStatusHashMap = this.savingsAccountHelper - .approveSavings(savingsId); - SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); + /*** + * Approve the savings account + */ + savingsStatusHashMap = this.savingsAccountHelper + .approveSavings(savingsId); + SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - Calendar todaysDate = Calendar.getInstance(); - todaysDate.add(Calendar.MONTH, -1); + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + Calendar todaysDate = Calendar.getInstance(); + todaysDate.add(Calendar.MONTH, -1); - final String ACTIVATION_DATE = dateFormat.format(todaysDate.getTime()); + final String ACTIVATION_DATE = dateFormat.format(todaysDate.getTime()); - /*** - * Activate the application and verify account status - * - * @param activationDate - * this value is every time first day of previous month - */ - savingsStatusHashMap = activateSavingsAccount(savingsId, - ACTIVATION_DATE); - SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); - /*** - * Verify the account summary - */ - final HashMap summaryBefore = this.savingsAccountHelper - .getSavingsSummary(savingsId); - this.savingsAccountHelper.calculateInterestForSavings(savingsId); - HashMap summary = this.savingsAccountHelper - .getSavingsSummary(savingsId); - assertEquals(summaryBefore, summary); + /*** + * Activate the application and verify account status + * + * @param activationDate + * this value is every time first day of previous month + */ + savingsStatusHashMap = activateSavingsAccount(savingsId, + ACTIVATION_DATE); + SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); + /*** + * Verify the account summary + */ + final HashMap summaryBefore = this.savingsAccountHelper + .getSavingsSummary(savingsId); + this.savingsAccountHelper.calculateInterestForSavings(savingsId); + HashMap summary = this.savingsAccountHelper + .getSavingsSummary(savingsId); + assertEquals(summaryBefore, summary); - 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); + 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); - Calendar transactionDate = Calendar.getInstance(); - transactionDate.set(Calendar.DAY_OF_MONTH, 2); - String TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); + //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 Deposit transaction on last day of month and verify account - * balance. - * - * @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); - balance += new Float(DEPOSIT_AMOUNT); - assertEquals("Verifying Deposit Amount", new Float(DEPOSIT_AMOUNT), - depositTransaction.get("amount")); - assertEquals("Verifying Balance after Deposit", balance, - depositTransaction.get("runningBalance")); + /*** + * Perform Deposit transaction on last day of month and verify account + * balance. + * + * @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); + balance += new Float(DEPOSIT_AMOUNT); + assertEquals("Verifying Deposit Amount", new Float(DEPOSIT_AMOUNT), + depositTransaction.get("amount")); + assertEquals("Verifying Balance after Deposit", balance, + depositTransaction.get("runningBalance")); - /*** - * Calculate expected interest to be posted, interest should be posted - * for one day only because deposit transaction happened on last day of - * month before this account balance is negative. - */ - this.savingsAccountHelper.postInterestForSavings(savingsId); - HashMap accountDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); - summary = (HashMap) accountDetails.get("summary"); - Float accountDetailsPostInterestPosted = 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 + * month before this account balance is negative. + */ + this.savingsAccountHelper.postInterestForSavings(savingsId); + HashMap accountDetails = this.savingsAccountHelper + .getSavingsDetails(savingsId); + summary = (HashMap) accountDetails.get("summary"); + 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()); - double interestRateInFraction = (nominalAnnualInterest / 100); - double perDay = (double) 1 / (daysInYear); - double interestPerDay = interestRateInFraction * perDay; - Float interestPosted = (float) (interestPerDay * balance * 1); + 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; + Float interestPosted = (float) (interestPerDay * balance * 1); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - DecimalFormat decimalFormat = new DecimalFormat("", - new DecimalFormatSymbols(Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + DecimalFormat decimalFormat = new DecimalFormat("", + new DecimalFormatSymbols(Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); - 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()); + 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()); - 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; - interestPosted = (float) (interestPerDay * balance * 1); + 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; + interestPosted = (float) (interestPerDay * balance * 1); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked----------"); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----Post Interest As on Successfully Worked----------"); - transactionDate.set(Calendar.DAY_OF_MONTH, 3); - TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); + transactionDate.set(Calendar.DAY_OF_MONTH, 3); + TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); - summary = (HashMap) accountDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, + TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper + .getSavingsDetails(savingsId); + summary = (HashMap) accountDetails.get("summary"); + 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()); - interestRateInFraction = (nominalAnnualInterest / 100); - perDay = (double) 1 / (daysInYear); - interestPerDay = interestRateInFraction * perDay; - interestPosted = (float) (interestPerDay * balance * 1); + 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; + interestPosted = (float) (interestPerDay * balance * 1); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked-------"); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----Post Interest As on Successfully Worked-------"); - //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); - summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + //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); + summary = (HashMap) accountTransactionDetails.get("summary"); + 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()); - interestRateInFraction = (nominalAnnualInterest / 100); - perDay = (double) 1 / (daysInYear); - interestPerDay = interestRateInFraction * perDay; - interestPosted = (float) (interestPerDay * balance * 19); + 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; + interestPosted = (float) (interestPerDay * balance * 19); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked----------"); - } - 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()); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----Post Interest As on Successfully Worked----------"); + } + 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()); - if (Calendar.DAY_OF_MONTH == numberOfDateOfMonth) { + if (Calendar.DAY_OF_MONTH == numberOfDateOfMonth) { - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); - summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, + TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper + .getSavingsDetails(savingsId); + summary = (HashMap) accountTransactionDetails.get("summary"); + 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()); - interestRateInFraction = (nominalAnnualInterest / 100); - perDay = (double) 1 / (daysInYear); - interestPerDay = interestRateInFraction * perDay; - interestPosted = (float) (interestPerDay * balance * 8); + 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; + interestPosted = (float) (interestPerDay * balance * 8); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked----------"); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----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); - summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + } + transactionDate.set(Calendar.DAY_OF_MONTH, 1); + TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, + TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper + .getSavingsDetails(savingsId); + summary = (HashMap) accountTransactionDetails.get("summary"); + 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()); - interestRateInFraction = (nominalAnnualInterest / 100); - perDay = (double) 1 / (daysInYear); - interestPerDay = interestRateInFraction * perDay; - interestPosted = (float) (interestPerDay * balance * 1); + 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; + interestPosted = (float) (interestPerDay * balance * 1); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked----------"); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----Post Interest As on Successfully Worked----------"); - } - - @SuppressWarnings("unchecked") - @Test - public void testSavingsAccountPostInterestOnLastDayWithdrawalWithOverdraft() { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, - this.responseSpec); + } + + @SuppressWarnings("unchecked") + @Test + public void testSavingsAccountPostInterestOnLastDayWithdrawalWithOverdraft() { + 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); - Assert.assertNotNull(clientID); - final String minBalanceForInterestCalculation = null; + /*** + * Create a client to apply for savings account (overdraft account). + */ + final Integer clientID = ClientHelper.createClient(this.requestSpec, + this.responseSpec); + Assert.assertNotNull(clientID); + final String minBalanceForInterestCalculation = null; - /*** - * Create savings product with zero opening balance and overdraft - * enabled - */ - final String zeroOpeningBalance = "0.0"; - 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); - Assert.assertNotNull(savingsProductID); + /*** + * Create savings product with zero opening balance and overdraft + * enabled + */ + final String zeroOpeningBalance = "0.0"; + 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); + Assert.assertNotNull(savingsProductID); - /*** - * Apply for Savings account - */ - final Integer savingsId = this.savingsAccountHelper - .applyForSavingsApplication(clientID, savingsProductID, - ACCOUNT_TYPE_INDIVIDUAL); - Assert.assertNotNull(savingsProductID); + /*** + * Apply for Savings account + */ + final Integer savingsId = this.savingsAccountHelper + .applyForSavingsApplication(clientID, savingsProductID, + ACCOUNT_TYPE_INDIVIDUAL); + Assert.assertNotNull(savingsProductID); - HashMap modifications = this.savingsAccountHelper.updateSavingsAccount( - clientID, savingsProductID, savingsId, ACCOUNT_TYPE_INDIVIDUAL); - Assert.assertTrue(modifications.containsKey("submittedOnDate")); + HashMap modifications = this.savingsAccountHelper.updateSavingsAccount( + clientID, savingsProductID, savingsId, ACCOUNT_TYPE_INDIVIDUAL); + Assert.assertTrue(modifications.containsKey("submittedOnDate")); - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings( - this.requestSpec, this.responseSpec, savingsId); - SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings( + this.requestSpec, this.responseSpec, savingsId); + SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); - /*** - * Approve the savings account - */ - savingsStatusHashMap = this.savingsAccountHelper - .approveSavings(savingsId); - SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); + /*** + * Approve the savings account + */ + savingsStatusHashMap = this.savingsAccountHelper + .approveSavings(savingsId); + SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - Calendar todaysDate = Calendar.getInstance(); - todaysDate.add(Calendar.MONTH, -1); + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + Calendar todaysDate = Calendar.getInstance(); + todaysDate.add(Calendar.MONTH, -1); - final String ACTIVATION_DATE = dateFormat.format(todaysDate.getTime()); + final String ACTIVATION_DATE = dateFormat.format(todaysDate.getTime()); - /*** - * Activate the application and verify account status - * - * @param activationDate - * this value is every time first day of previous month - */ - savingsStatusHashMap = activateSavingsAccount(savingsId, - ACTIVATION_DATE); - SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); - /*** - * Verify the account summary - */ - final HashMap summaryBefore = this.savingsAccountHelper - .getSavingsSummary(savingsId); - this.savingsAccountHelper.calculateInterestForSavings(savingsId); - HashMap summary = this.savingsAccountHelper - .getSavingsSummary(savingsId); - assertEquals(summaryBefore, summary); + /*** + * Activate the application and verify account status + * + * @param activationDate + * this value is every time first day of previous month + */ + savingsStatusHashMap = activateSavingsAccount(savingsId, + ACTIVATION_DATE); + SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); + /*** + * Verify the account summary + */ + final HashMap summaryBefore = this.savingsAccountHelper + .getSavingsSummary(savingsId); + this.savingsAccountHelper.calculateInterestForSavings(savingsId); + HashMap summary = this.savingsAccountHelper + .getSavingsSummary(savingsId); + assertEquals(summaryBefore, summary); - 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); + 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); - Calendar transactionDate = Calendar.getInstance(); - transactionDate.set(Calendar.DAY_OF_MONTH, 2); - String TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); + //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) */ Integer withdrawTransactionId = (Integer) this.savingsAccountHelper.withdrawalFromSavingsAccount(savingsId, WITHDRAW_AMOUNT, - ACTIVATION_DATE, CommonConstants.RESPONSE_RESOURCE_ID); + ACTIVATION_DATE, CommonConstants.RESPONSE_RESOURCE_ID); HashMap withdrawTransaction = this.savingsAccountHelper.getSavingsTransaction(savingsId, withdrawTransactionId); balance -= new Float(WITHDRAW_AMOUNT); assertEquals("Verifying Withdrawal Amount", new Float(WITHDRAW_AMOUNT), withdrawTransaction.get("amount")); @@ -1228,240 +1228,240 @@ public class ClientSavingsIntegrationTest { * 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); + WITHDRAWAL_DATE, CommonConstants.RESPONSE_RESOURCE_ID); HashMap depositTransaction = this.savingsAccountHelper.getSavingsTransaction(savingsId, depositTransactionId); balance += new Float(DEPOSIT_AMOUNT); assertEquals("Verifying Deposit Amount", new Float(DEPOSIT_AMOUNT), depositTransaction.get("amount")); assertEquals("Verifying Balance after Deposit", balance, depositTransaction.get("runningBalance")); - /*** - * Calculate expected interest to be posted, interest should be posted - * for one day only because deposit transaction happened on last day of - * month before this account balance is negative. - */ - this.savingsAccountHelper.postInterestForSavings(savingsId); - HashMap accountDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); - summary = (HashMap) accountDetails.get("summary"); - Float accountDetailsPostInterestPosted = 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 + * month before this account balance is negative. + */ + this.savingsAccountHelper.postInterestForSavings(savingsId); + HashMap accountDetails = this.savingsAccountHelper + .getSavingsDetails(savingsId); + summary = (HashMap) accountDetails.get("summary"); + 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()); - double interestRateInFraction = (nominalAnnualInterest / 100); - double perDay = (double) 1 / (daysInYear); - double interestPerDay = interestRateInFraction * perDay; - Float interestPosted = (float) (interestPerDay * balance * 1); + 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; + Float interestPosted = (float) (interestPerDay * balance * 1); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - DecimalFormat decimalFormat = new DecimalFormat("", - new DecimalFormatSymbols(Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + DecimalFormat decimalFormat = new DecimalFormat("", + new DecimalFormatSymbols(Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); - 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()); + 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()); - 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; - interestPosted = (float) (interestPerDay * balance * 1); + 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; + interestPosted = (float) (interestPerDay * balance * 1); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked----------"); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----Post Interest As on Successfully Worked----------"); - transactionDate.set(Calendar.DAY_OF_MONTH, 3); - TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); + transactionDate.set(Calendar.DAY_OF_MONTH, 3); + TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); - summary = (HashMap) accountDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, + TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper + .getSavingsDetails(savingsId); + summary = (HashMap) accountDetails.get("summary"); + 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()); - interestRateInFraction = (nominalAnnualInterest / 100); - perDay = (double) 1 / (daysInYear); - interestPerDay = interestRateInFraction * perDay; - interestPosted = (float) (interestPerDay * balance * 1); + 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; + interestPosted = (float) (interestPerDay * balance * 1); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked-------"); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----Post Interest As on Successfully Worked-------"); - //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); - summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + //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); + summary = (HashMap) accountTransactionDetails.get("summary"); + 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()); - interestRateInFraction = (nominalAnnualInterest / 100); - perDay = (double) 1 / (daysInYear); - interestPerDay = interestRateInFraction * perDay; - interestPosted = (float) (interestPerDay * balance * 19); + 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; + interestPosted = (float) (interestPerDay * balance * 19); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked----------"); - } - 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()); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----Post Interest As on Successfully Worked----------"); + } + 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()); - if (Calendar.DAY_OF_MONTH == numberOfDateOfMonth) { + if (Calendar.DAY_OF_MONTH == numberOfDateOfMonth) { - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); - summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, + TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper + .getSavingsDetails(savingsId); + summary = (HashMap) accountTransactionDetails.get("summary"); + 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()); - interestRateInFraction = (nominalAnnualInterest / 100); - perDay = (double) 1 / (daysInYear); - interestPerDay = interestRateInFraction * perDay; - interestPosted = (float) (interestPerDay * balance * 8); + 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; + interestPosted = (float) (interestPerDay * balance * 8); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked----------"); + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----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); - summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + } + transactionDate.set(Calendar.DAY_OF_MONTH, 1); + TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, + TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper + .getSavingsDetails(savingsId); + summary = (HashMap) accountTransactionDetails.get("summary"); + 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()); - interestRateInFraction = (nominalAnnualInterest / 100); - perDay = (double) 1 / (daysInYear); - interestPerDay = interestRateInFraction * perDay; - interestPosted = (float) (interestPerDay * balance * 1); + 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; + interestPosted = (float) (interestPerDay * balance * 1); - /*** - * Apply rounding on interestPosted, actualInterestPosted and verify - * both are same - */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); - decimalFormat.applyPattern("#.###"); - interestPosted = new Float(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = new Float( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals("Verifying interest posted", interestPosted, - accountDetailsPostInterestPosted); - System.out - .println("-----Post Interest As on Successfully Worked----------"); - } + /*** + * Apply rounding on interestPosted, actualInterestPosted and verify + * both are same + */ + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( + Locale.US)); + decimalFormat.applyPattern("#.###"); + interestPosted = new Float(decimalFormat.format(interestPosted)); + accountDetailsPostInterestPosted = new Float( + decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals("Verifying interest posted", interestPosted, + accountDetailsPostInterestPosted); + System.out + .println("-----Post Interest As on Successfully Worked----------"); + } @SuppressWarnings("unchecked") @Test @@ -1956,18 +1956,18 @@ public class ClientSavingsIntegrationTest { final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd MMMM yyyy"); LocalDate transactionDate = new LocalDate(); for(int i=0; i< 4; i++){ - String TRANSACTION_DATE = formatter.print(transactionDate); + String TRANSACTION_DATE = formatter.print(transactionDate); Integer depositTransactionId = (Integer) this.savingsAccountHelper.depositToSavingsAccount(savingsList.get(i), DEPOSIT_AMOUNT, TRANSACTION_DATE, CommonConstants.RESPONSE_RESOURCE_ID); - transactionDate = transactionDate.minusDays(30); + transactionDate = transactionDate.minusDays(30); } SchedulerJobHelper jobHelper = new SchedulerJobHelper(this.requestSpec, this.responseSpec); try { - jobHelper.executeJob("Update Savings Dormant Accounts"); - } catch (InterruptedException e) { - e.printStackTrace(); - } + jobHelper.executeJob("Update Savings Dormant Accounts"); + } catch (InterruptedException e) { + e.printStackTrace(); + } //VERIFY WITHIN PROVIDED RANGE DOESN'T INACTIVATE savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(0)); @@ -1992,7 +1992,7 @@ public class ClientSavingsIntegrationTest { balance -= chargeAmt; assertEquals("Verifying account Balance", balance, summary.get("accountBalance")); - String TRANSACTION_DATE = formatter.print(new LocalDate()); + String TRANSACTION_DATE = formatter.print(new LocalDate()); Integer depositTransactionId = (Integer) this.savingsAccountHelper.depositToSavingsAccount(savingsList.get(1), DEPOSIT_AMOUNT, TRANSACTION_DATE, CommonConstants.RESPONSE_RESOURCE_ID); savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(1)); @@ -2068,7 +2068,7 @@ public class ClientSavingsIntegrationTest { savingsProductHelper = savingsProductHelper.withOverDraft(overDraftLimit); } if(withDormancy){ - savingsProductHelper = savingsProductHelper.withDormancy(); + savingsProductHelper = savingsProductHelper.withDormancy(); } final String savingsProductJSON = savingsProductHelper diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientTest.java index 0d1b86e6d..7e6664d93 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientTest.java @@ -81,8 +81,8 @@ public class ClientTest { @Test public void testClientAsPersonStatus() { - - this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); + + this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); final Integer clientId = ClientHelper.createClientAsPerson(this.requestSpec, this.responseSpec); Assert.assertNotNull(clientId); @@ -114,8 +114,8 @@ public class ClientTest { @Test public void testClientAsEntityStatus() { - - this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); + + this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); final Integer clientId = ClientHelper.createClientAsEntity(this.requestSpec, this.responseSpec); Assert.assertNotNull(clientId); 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 c7558e852..45540e522 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 @@ -42,301 +42,301 @@ import static org.junit.Assert.assertEquals; @SuppressWarnings({ "unused" }) public class ClientUndoRejectAndWithdrawalIntegrationTest { - private static final String CREATE_CLIENT_URL = "/fineract-provider/api/v1/clients?" + Utils.TENANT_IDENTIFIER; - public static final String DATE_FORMAT = "dd MMMM yyyy"; - private final String submittedOnDate = "submittedOnDate"; - private final String officeId = "officeId"; - private ResponseSpecification responseSpec; - private RequestSpecification requestSpec; - private ClientHelper clientHelper; - - @Before - 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(); + private static final String CREATE_CLIENT_URL = "/fineract-provider/api/v1/clients?" + Utils.TENANT_IDENTIFIER; + public static final String DATE_FORMAT = "dd MMMM yyyy"; + private final String submittedOnDate = "submittedOnDate"; + private final String officeId = "officeId"; + private ResponseSpecification responseSpec; + private RequestSpecification requestSpec; + private ClientHelper clientHelper; + + @Before + 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.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); - } + this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); + } - @Test - public void clientUndoRejectIntegrationTest() { - - // CREATE CLIENT - this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); - final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); - Assert.assertNotNull(clientId); - - // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); - - ClientStatusChecker.verifyClientPending(status); - - status = this.clientHelper.rejectClient(clientId); - ClientStatusChecker.verifyClientRejected(status); - - status = this.clientHelper.undoReject(clientId); - ClientStatusChecker.verifyClientPending(status); - - } - - @Test - public void testClientUndoRejectWithDateBeforeRejectDate() { - final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build(); - final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse); + @Test + public void clientUndoRejectIntegrationTest() { + + // CREATE CLIENT + this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); + final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); + Assert.assertNotNull(clientId); + + // GET CLIENT STATUS + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, + String.valueOf(clientId)); + + ClientStatusChecker.verifyClientPending(status); + + status = this.clientHelper.rejectClient(clientId); + ClientStatusChecker.verifyClientRejected(status); + + status = this.clientHelper.undoReject(clientId); + ClientStatusChecker.verifyClientPending(status); + + } + + @Test + public void testClientUndoRejectWithDateBeforeRejectDate() { + final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build(); + 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); - Assert.assertNotNull(clientId); + // CREATE CLIENT + this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); + final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); + Assert.assertNotNull(clientId); - // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + // GET CLIENT STATUS + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, + String.valueOf(clientId)); - ClientStatusChecker.verifyClientPending(status); + ClientStatusChecker.verifyClientPending(status); - status = this.clientHelper.rejectClient(clientId); - ClientStatusChecker.verifyClientRejected(status); + status = this.clientHelper.rejectClient(clientId); + ClientStatusChecker.verifyClientRejected(status); - ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoRejectedclient(clientId, - CommonConstants.RESPONSE_ERROR, ClientHelper.CREATED_DATE); - assertEquals("error.msg.client.reopened.date.cannot.before.client.rejected.date", - ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoRejectedclient(clientId, + CommonConstants.RESPONSE_ERROR, ClientHelper.CREATED_DATE); + assertEquals("error.msg.client.reopened.date.cannot.before.client.rejected.date", + ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - status = this.clientHelper.undoReject(clientId); - ClientStatusChecker.verifyClientPending(status); - } + status = this.clientHelper.undoReject(clientId); + ClientStatusChecker.verifyClientPending(status); + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testClientUndoRejectWithoutReject() { - final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build(); - final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse); + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testClientUndoRejectWithoutReject() { + final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build(); + 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); - Assert.assertNotNull(clientId); + // CREATE CLIENT + this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); + final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); + Assert.assertNotNull(clientId); - // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); - ClientStatusChecker.verifyClientPending(status); + // GET CLIENT STATUS + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, + String.valueOf(clientId)); + ClientStatusChecker.verifyClientPending(status); - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - Calendar todaysDate = Calendar.getInstance(); - final String undoRejectDate = dateFormat.format(todaysDate.getTime()); + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + Calendar todaysDate = Calendar.getInstance(); + final String undoRejectDate = dateFormat.format(todaysDate.getTime()); - ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoRejectedclient(clientId, - CommonConstants.RESPONSE_ERROR, undoRejectDate); - assertEquals("error.msg.client.undorejection.on.nonrejected.account", - ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoRejectedclient(clientId, + CommonConstants.RESPONSE_ERROR, undoRejectDate); + assertEquals("error.msg.client.undorejection.on.nonrejected.account", + ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - status = this.clientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); - ClientStatusChecker.verifyClientPending(status); + status = this.clientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); + ClientStatusChecker.verifyClientPending(status); - } + } - @Test - public void testClientUndoRejectWithFutureDate() { + @Test + public void testClientUndoRejectWithFutureDate() { - final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); - final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse); + final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); + 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); - Assert.assertNotNull(clientId); + // CREATE CLIENT + this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); + final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); + Assert.assertNotNull(clientId); - // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + // GET CLIENT STATUS + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, + String.valueOf(clientId)); - ClientStatusChecker.verifyClientPending(status); + ClientStatusChecker.verifyClientPending(status); - status = this.clientHelper.rejectClient(clientId); - ClientStatusChecker.verifyClientRejected(status); - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - Calendar todaysDate = Calendar.getInstance(); - todaysDate.add(Calendar.DATE, 1); - final String undoRejectDate = dateFormat.format(todaysDate.getTime()); - ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoWithdrawclient(clientId, - CommonConstants.RESPONSE_ERROR, undoRejectDate); - assertEquals("validation.msg.client.reopenedDate.is.greater.than.date", - ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + status = this.clientHelper.rejectClient(clientId); + ClientStatusChecker.verifyClientRejected(status); + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + Calendar todaysDate = Calendar.getInstance(); + todaysDate.add(Calendar.DATE, 1); + final String undoRejectDate = dateFormat.format(todaysDate.getTime()); + ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoWithdrawclient(clientId, + CommonConstants.RESPONSE_ERROR, undoRejectDate); + assertEquals("validation.msg.client.reopenedDate.is.greater.than.date", + ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - status = this.clientHelper.undoReject(clientId); - ClientStatusChecker.verifyClientPending(status); + status = this.clientHelper.undoReject(clientId); + ClientStatusChecker.verifyClientPending(status); - } + } - @Test - public void clientUndoWithDrawnIntegrationTest() { + @Test + public void clientUndoWithDrawnIntegrationTest() { - // CREATE CLIENT - this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); - final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); - Assert.assertNotNull(clientId); + // CREATE CLIENT + this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); + final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); + Assert.assertNotNull(clientId); - // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + // GET CLIENT STATUS + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, + String.valueOf(clientId)); - ClientStatusChecker.verifyClientPending(status); + ClientStatusChecker.verifyClientPending(status); - status = this.clientHelper.withdrawClient(clientId); - ClientStatusChecker.verifyClientWithdrawn(status); + status = this.clientHelper.withdrawClient(clientId); + ClientStatusChecker.verifyClientWithdrawn(status); - status = this.clientHelper.undoWithdrawn(clientId); - ClientStatusChecker.verifyClientPending(status); + status = this.clientHelper.undoWithdrawn(clientId); + ClientStatusChecker.verifyClientPending(status); - } + } - @Test - public void testClientUndoWithDrawnWithDateBeforeWithdrawal() { + @Test + public void testClientUndoWithDrawnWithDateBeforeWithdrawal() { - final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build(); - final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse); + final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build(); + 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); - Assert.assertNotNull(clientId); - - // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); - - ClientStatusChecker.verifyClientPending(status); - - status = this.clientHelper.withdrawClient(clientId); - ClientStatusChecker.verifyClientWithdrawn(status); - - ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoWithdrawclient(clientId, - CommonConstants.RESPONSE_ERROR, ClientHelper.CREATED_DATE); - assertEquals("error.msg.client.reopened.date.cannot.before.client.withdrawal.date", - ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - - status = this.clientHelper.undoWithdrawn(clientId); - ClientStatusChecker.verifyClientPending(status); - - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testClientUndoWithDrawnWithoutWithdrawal() { - final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build(); - 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); - Assert.assertNotNull(clientId); - - // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); - - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - Calendar todaysDate = Calendar.getInstance(); - final String undoWithdrawDate = dateFormat.format(todaysDate.getTime()); - - ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoWithdrawclient(clientId, - CommonConstants.RESPONSE_ERROR, undoWithdrawDate); - assertEquals("error.msg.client.undoWithdrawal.on.nonwithdrawal.account", - ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - - status = this.clientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); - ClientStatusChecker.verifyClientPending(status); - - } - - @Test - public void testClientUndoWithDrawnWithFutureDate() { - - final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); - 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); - Assert.assertNotNull(clientId); - - // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); - - ClientStatusChecker.verifyClientPending(status); - - status = this.clientHelper.withdrawClient(clientId); - ClientStatusChecker.verifyClientWithdrawn(status); - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - Calendar todaysDate = Calendar.getInstance(); - todaysDate.add(Calendar.DATE, 1); - final String undoWithdrawDate = dateFormat.format(todaysDate.getTime()); - ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoWithdrawclient(clientId, - CommonConstants.RESPONSE_ERROR, undoWithdrawDate); - assertEquals("validation.msg.client.reopenedDate.is.greater.than.date", - ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - - status = this.clientHelper.undoWithdrawn(clientId); - ClientStatusChecker.verifyClientPending(status); - - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testValidateReopenedDate() { - final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); - 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); - Assert.assertNotNull(clientId); - // GET CLIENT STATUS - 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 = (ArrayList) validationErrorHelper.activateClient(clientId, - CommonConstants.RESPONSE_ERROR); - assertEquals("error.msg.clients.submittedOnDate.after.reopened.date", - ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - - } - - @Test - public void testReopenedDate() { - final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); - //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); - Assert.assertNotNull(clientId); - // GET CLIENT STATUS - 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); - status = this.clientHelper.activateClientWithDiffDateOption(clientId, ClientHelper.CREATED_DATE_PLUS_TWO); - - } - - private static String randomIDGenerator(final String prefix, final int lenOfRandomSuffix) { - return Utils.randomStringGenerator(prefix, lenOfRandomSuffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - } + // CREATE CLIENT + this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); + final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); + Assert.assertNotNull(clientId); + + // GET CLIENT STATUS + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, + String.valueOf(clientId)); + + ClientStatusChecker.verifyClientPending(status); + + status = this.clientHelper.withdrawClient(clientId); + ClientStatusChecker.verifyClientWithdrawn(status); + + ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoWithdrawclient(clientId, + CommonConstants.RESPONSE_ERROR, ClientHelper.CREATED_DATE); + assertEquals("error.msg.client.reopened.date.cannot.before.client.withdrawal.date", + ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + + status = this.clientHelper.undoWithdrawn(clientId); + ClientStatusChecker.verifyClientPending(status); + + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testClientUndoWithDrawnWithoutWithdrawal() { + final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build(); + 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); + Assert.assertNotNull(clientId); + + // GET CLIENT STATUS + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, + String.valueOf(clientId)); + + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + Calendar todaysDate = Calendar.getInstance(); + final String undoWithdrawDate = dateFormat.format(todaysDate.getTime()); + + ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoWithdrawclient(clientId, + CommonConstants.RESPONSE_ERROR, undoWithdrawDate); + assertEquals("error.msg.client.undoWithdrawal.on.nonwithdrawal.account", + ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + + status = this.clientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); + ClientStatusChecker.verifyClientPending(status); + + } + + @Test + public void testClientUndoWithDrawnWithFutureDate() { + + final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); + 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); + Assert.assertNotNull(clientId); + + // GET CLIENT STATUS + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, + String.valueOf(clientId)); + + ClientStatusChecker.verifyClientPending(status); + + status = this.clientHelper.withdrawClient(clientId); + ClientStatusChecker.verifyClientWithdrawn(status); + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + Calendar todaysDate = Calendar.getInstance(); + todaysDate.add(Calendar.DATE, 1); + final String undoWithdrawDate = dateFormat.format(todaysDate.getTime()); + ArrayList clientErrorData = (ArrayList) validationErrorHelper.undoWithdrawclient(clientId, + CommonConstants.RESPONSE_ERROR, undoWithdrawDate); + assertEquals("validation.msg.client.reopenedDate.is.greater.than.date", + ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + + status = this.clientHelper.undoWithdrawn(clientId); + ClientStatusChecker.verifyClientPending(status); + + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testValidateReopenedDate() { + final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); + 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); + Assert.assertNotNull(clientId); + // GET CLIENT STATUS + 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 = (ArrayList) validationErrorHelper.activateClient(clientId, + CommonConstants.RESPONSE_ERROR); + assertEquals("error.msg.clients.submittedOnDate.after.reopened.date", + ((HashMap) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + + } + + @Test + public void testReopenedDate() { + final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); + //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); + Assert.assertNotNull(clientId); + // GET CLIENT STATUS + 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); + status = this.clientHelper.activateClientWithDiffDateOption(clientId, ClientHelper.CREATED_DATE_PLUS_TWO); + + } + + private static String randomIDGenerator(final String prefix, final int lenOfRandomSuffix) { + return Utils.randomStringGenerator(prefix, lenOfRandomSuffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + } } 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 87f94a67f..c81b90846 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 @@ -146,83 +146,83 @@ public class GlobalConfigurationTest { } @Test - public void testGlobalConfigForcePasswordResetDays() { + public void testGlobalConfigForcePasswordResetDays() { - // Retrieving All Global Configuration details - final ArrayList globalConfig = this.globalConfigurationHelper - .getAllGlobalConfigurations(this.requestSpec, this.responseSpec); - Assert.assertNotNull(globalConfig); + // Retrieving All Global Configuration details + final ArrayList globalConfig = this.globalConfigurationHelper + .getAllGlobalConfigurations(this.requestSpec, this.responseSpec); + Assert.assertNotNull(globalConfig); - String configName = "force-password-reset-days"; - String newValue = "0"; - String newBooleanValue = "true"; + String configName = "force-password-reset-days"; + String newValue = "0"; + String newBooleanValue = "true"; - 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"); - Assert.assertNotNull(configId); + 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"); + Assert.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); - HashMap hash = (HashMap) error.get(0); + /* + * 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); + HashMap hash = (HashMap) error.get(0); - Assert.assertEquals( - "Force Password Reset days value must be greater than zero.", - "error.msg.password.reset.days.value.must.be.greater.than.zero", - hash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + Assert.assertEquals( + "Force Password Reset days value must be greater than zero.", + "error.msg.password.reset.days.value.must.be.greater.than.zero", + hash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - /* - * 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"); - Assert.assertNotNull(updateSuccess); + /* + * 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"); + Assert.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"); - Assert.assertNotNull(updateSuccess1); + /* 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"); + Assert.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); - HashMap failureHash = (HashMap) failure.get(0); - Assert.assertEquals( - "Force Password Reset days value must be greater than zero.", - "error.msg.password.reset.days.value.must.be.greater.than.zero", - failureHash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + /* 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); + Assert.assertEquals( + "Force Password Reset days value must be greater than zero.", + "error.msg.password.reset.days.value.must.be.greater.than.zero", + failureHash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - break; - } - } - /* 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); - Assert.assertNotNull(updateConfigId); - break; - } - } - } + break; + } + } + /* 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); + Assert.assertNotNull(updateConfigId); + break; + } + } + } } \ No newline at end of file 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 ae3c68bc6..3203f4efc 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 @@ -99,19 +99,19 @@ public class HookIntegrationTest { @Test public void createUpdateAndDeleteHook(){ - final String payloadURL = "http://echo-webhook.herokuapp.com:80/Z7RXoCBdLSFMDrpn?"; - final String updateURL = "http://localhost"; + final String payloadURL = "http://echo-webhook.herokuapp.com:80/Z7RXoCBdLSFMDrpn?"; + final String updateURL = "http://localhost"; Long hookId = this.hookHelper.createHook(payloadURL).longValue(); Assert.assertNotNull(hookId); this.hookHelper.verifyHookCreatedOnServer(hookId); - System.out.println("---------------------SUCCESSFULLY CREATED AND VERIFIED HOOK-------------------------"+hookId); - this.hookHelper.updateHook(updateURL, hookId); - this.hookHelper.verifyUpdateHook(updateURL, hookId); - System.out.println("---------------------SUCCESSFULLY UPDATED AND VERIFIED HOOK-------------------------"+hookId); - this.hookHelper.deleteHook(hookId); - this.hookHelper.verifyDeleteHook(hookId); - System.out.println("---------------------SUCCESSFULLY DELETED AND VERIFIED HOOK-------------------------"+hookId); + System.out.println("---------------------SUCCESSFULLY CREATED AND VERIFIED HOOK-------------------------"+hookId); + this.hookHelper.updateHook(updateURL, hookId); + this.hookHelper.verifyUpdateHook(updateURL, hookId); + System.out.println("---------------------SUCCESSFULLY UPDATED AND VERIFIED HOOK-------------------------"+hookId); + this.hookHelper.deleteHook(hookId); + this.hookHelper.verifyDeleteHook(hookId); + System.out.println("---------------------SUCCESSFULLY DELETED AND VERIFIED HOOK-------------------------"+hookId); } } 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 c7235dab4..6b9ed26d0 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 @@ -95,13 +95,13 @@ public class LoanDisbursalDateValidationTest { List disbursalError = (List) this.loanTransactionHelper.disburseLoan(disbursalDate, loanID, this.responseForbiddenError); Assert.assertEquals("error.msg.actual.disbursement.date.does.not.match.with.expected.disbursal.date", - disbursalError.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + disbursalError.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); } private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID, final String proposedAmount) { final String loanApplication = new LoanApplicationTestBuilder() - .withPrincipal(proposedAmount).withLoanTermFrequency("5") + .withPrincipal(proposedAmount).withLoanTermFrequency("5") .withLoanTermFrequencyAsMonths().withNumberOfRepayments("5") .withRepaymentEveryAfter("1") .withRepaymentFrequencyTypeAsMonths() 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 b56f25dd2..f4275da90 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 @@ -46,7 +46,7 @@ import com.jayway.restassured.specification.ResponseSpecification; @SuppressWarnings("rawtypes") public class LoanRepaymentRescheduleAtDisbursementTest { - private ResponseSpecification responseSpec; + private ResponseSpecification responseSpec; private RequestSpecification requestSpec; private LoanTransactionHelper loanTransactionHelper; private LoanApplicationApprovalTest loanApplicationApprovalTest; @@ -63,10 +63,10 @@ public class LoanRepaymentRescheduleAtDisbursementTest { this.generalResponseSpec = new ResponseSpecBuilder().build(); } - @SuppressWarnings("unchecked") - @Test + @SuppressWarnings("unchecked") + @Test public void testLoanRepaymentRescheduleAtDisbursement(){ - + final String approvalAmount = "10000"; final String approveDate = "01 March 2015"; final String expectedDisbursementDate = "01 March 2015"; @@ -74,7 +74,7 @@ public class LoanRepaymentRescheduleAtDisbursementTest { final String adjustRepaymentDate = "16 March 2015"; // CREATE CLIENT - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014"); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014"); System.out.println("---------------------------------CLIENT CREATED WITH ID---------------------------------------------------" + clientID); @@ -89,7 +89,7 @@ public class LoanRepaymentRescheduleAtDisbursementTest { List createTranches = new ArrayList<>(); createTranches.add(this.loanApplicationApprovalTest.createTrancheDetail("01 March 2015", "5000")); createTranches.add(this.loanApplicationApprovalTest.createTrancheDetail("01 May 2015", "5000")); - + // APPROVE TRANCHES List approveTranches = new ArrayList<>(); approveTranches.add(this.loanApplicationApprovalTest.createTrancheDetail("01 March 2015", "5000")); @@ -132,15 +132,15 @@ public class LoanRepaymentRescheduleAtDisbursementTest { verifyLoanRepaymentSchedule(firstInstallement, expectedvalues); } - - private void verifyLoanRepaymentSchedule(final HashMap firstInstallement, final Map expectedvalues) { + + private void verifyLoanRepaymentSchedule(final HashMap firstInstallement, final Map expectedvalues) { - assertEquals(expectedvalues.get("dueDate"), firstInstallement.get("dueDate")); - assertEquals(String.valueOf(expectedvalues.get("principalDue")), String.valueOf(firstInstallement.get("principalDue"))); - assertEquals(String.valueOf(expectedvalues.get("interestDue")), String.valueOf(firstInstallement.get("interestDue"))); - assertEquals(String.valueOf(expectedvalues.get("feeChargesDue")), String.valueOf(firstInstallement.get("feeChargesDue"))); - assertEquals(String.valueOf(expectedvalues.get("penaltyChargesDue")), String.valueOf(firstInstallement.get("penaltyChargesDue"))); - assertEquals(String.valueOf(expectedvalues.get("totalDueForPeriod")), String.valueOf(firstInstallement.get("totalDueForPeriod"))); + assertEquals(expectedvalues.get("dueDate"), firstInstallement.get("dueDate")); + assertEquals(String.valueOf(expectedvalues.get("principalDue")), String.valueOf(firstInstallement.get("principalDue"))); + assertEquals(String.valueOf(expectedvalues.get("interestDue")), String.valueOf(firstInstallement.get("interestDue"))); + assertEquals(String.valueOf(expectedvalues.get("feeChargesDue")), String.valueOf(firstInstallement.get("feeChargesDue"))); + assertEquals(String.valueOf(expectedvalues.get("penaltyChargesDue")), String.valueOf(firstInstallement.get("penaltyChargesDue"))); + assertEquals(String.valueOf(expectedvalues.get("totalDueForPeriod")), String.valueOf(firstInstallement.get("totalDueForPeriod"))); } @@ -237,8 +237,8 @@ public class LoanRepaymentRescheduleAtDisbursementTest { } private List getDateAsArray(Calendar date, int addvalue, int type) { - date.add(type, addvalue); + date.add(type, addvalue); return new ArrayList<>(Arrays.asList(date.get(Calendar.YEAR), date.get(Calendar.MONTH) + 1, - date.get(Calendar.DAY_OF_MONTH))); + 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 ae3943365..bfa89ddd7 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,8 +44,8 @@ import com.jayway.restassured.specification.ResponseSpecification; **/ @SuppressWarnings({ "rawtypes" }) public class LoanRescheduleRequestTest { - private ResponseSpecification responseSpec; - private ResponseSpecification generalResponseSpec; + private ResponseSpecification responseSpec; + private ResponseSpecification generalResponseSpec; private RequestSpecification requestSpec; private LoanTransactionHelper loanTransactionHelper; private LoanRescheduleRequestHelper loanRescheduleRequestHelper; @@ -60,7 +60,7 @@ public class LoanRescheduleRequestTest { @Before public void initialize() { - Utils.initializeRESTAssured(); + Utils.initializeRESTAssured(); this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); @@ -77,17 +77,17 @@ public class LoanRescheduleRequestTest { * Creates the client, loan product, and loan entities **/ private void createRequiredEntities() { - this.createClientEntity(); - this.createLoanProductEntity(); - this.createLoanEntity(); + this.createClientEntity(); + this.createLoanProductEntity(); + this.createLoanEntity(); } /** * create a new client **/ private void createClientEntity() { - this.clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); - + this.clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); + ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, this.clientId); } @@ -95,28 +95,28 @@ public class LoanRescheduleRequestTest { * create a new loan product **/ private void createLoanProductEntity() { - System.out.println("---------------------------------CREATING LOAN PRODUCT------------------------------------------"); - - final String loanProductJSON = new LoanProductTestBuilder() - .withPrincipal(loanPrincipalAmount) - .withNumberOfRepayments(numberOfRepayments) - .withinterestRatePerPeriod(interestRatePerPeriod) - .withInterestRateFrequencyTypeAsYear() - .build(null); - - this.loanProductId = this.loanTransactionHelper.getLoanProductId(loanProductJSON); - System.out.println("Successfully created loan product (ID: " + this.loanProductId + ")"); + System.out.println("---------------------------------CREATING LOAN PRODUCT------------------------------------------"); + + final String loanProductJSON = new LoanProductTestBuilder() + .withPrincipal(loanPrincipalAmount) + .withNumberOfRepayments(numberOfRepayments) + .withinterestRatePerPeriod(interestRatePerPeriod) + .withInterestRateFrequencyTypeAsYear() + .build(null); + + this.loanProductId = this.loanTransactionHelper.getLoanProductId(loanProductJSON); + System.out.println("Successfully created loan product (ID: " + this.loanProductId + ")"); } /** * submit a new loan application, approve and disburse the loan **/ private void createLoanEntity() { - System.out.println("---------------------------------NEW LOAN APPLICATION------------------------------------------"); - - final String loanApplicationJSON = new LoanApplicationTestBuilder() - .withPrincipal(loanPrincipalAmount) - .withLoanTermFrequency(numberOfRepayments) + System.out.println("---------------------------------NEW LOAN APPLICATION------------------------------------------"); + + final String loanApplicationJSON = new LoanApplicationTestBuilder() + .withPrincipal(loanPrincipalAmount) + .withLoanTermFrequency(numberOfRepayments) .withLoanTermFrequencyAsMonths() .withNumberOfRepayments(numberOfRepayments) .withRepaymentEveryAfter("1") @@ -129,91 +129,91 @@ public class LoanRescheduleRequestTest { .withExpectedDisbursementDate(dateString) .withPrincipalGrace("2") .withInterestGrace("2") - .build(this.clientId.toString(), this.loanProductId.toString(), null); - - this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON); - - System.out.println("Sucessfully created loan (ID: " + this.loanId + ")"); - - this.approveLoanApplication(); - this.disburseLoan(); + .build(this.clientId.toString(), this.loanProductId.toString(), null); + + this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON); + + System.out.println("Sucessfully created loan (ID: " + this.loanId + ")"); + + this.approveLoanApplication(); + this.disburseLoan(); } /** * approve the loan application **/ private void approveLoanApplication() { - - if(this.loanId != null) { - this.loanTransactionHelper.approveLoan(this.dateString, this.loanId); - System.out.println("Successfully approved loan (ID: " + this.loanId + ")"); - } + + if(this.loanId != null) { + this.loanTransactionHelper.approveLoan(this.dateString, this.loanId); + System.out.println("Successfully approved loan (ID: " + this.loanId + ")"); + } } /** * disburse the newly created loan **/ private void disburseLoan() { - - if(this.loanId != null) { - this.loanTransactionHelper.disburseLoan(this.dateString, this.loanId); - System.out.println("Successfully disbursed loan (ID: " + this.loanId + ")"); - } + + if(this.loanId != null) { + this.loanTransactionHelper.disburseLoan(this.dateString, this.loanId); + System.out.println("Successfully disbursed loan (ID: " + this.loanId + ")"); + } } /** * create new loan reschedule request **/ private void createLoanRescheduleRequest() { - System.out.println("---------------------------------CREATING LOAN RESCHEDULE REQUEST------------------------------------------"); - - final String requestJSON = new LoanRescheduleRequestTestBuilder().build(this.loanId.toString()); - - this.loanRescheduleRequestId = this.loanRescheduleRequestHelper.createLoanRescheduleRequest(requestJSON); - this.loanRescheduleRequestHelper.verifyCreationOfLoanRescheduleRequest(this.loanRescheduleRequestId); - - System.out.println("Successfully created loan reschedule request (ID: " + this.loanRescheduleRequestId + ")"); + System.out.println("---------------------------------CREATING LOAN RESCHEDULE REQUEST------------------------------------------"); + + final String requestJSON = new LoanRescheduleRequestTestBuilder().build(this.loanId.toString()); + + this.loanRescheduleRequestId = this.loanRescheduleRequestHelper.createLoanRescheduleRequest(requestJSON); + this.loanRescheduleRequestHelper.verifyCreationOfLoanRescheduleRequest(this.loanRescheduleRequestId); + + System.out.println("Successfully created loan reschedule request (ID: " + this.loanRescheduleRequestId + ")"); } @Test public void testCreateLoanRescheduleRequest() { - this.createLoanRescheduleRequest(); + this.createLoanRescheduleRequest(); } @Test public void testRejectLoanRescheduleRequest() { - this.createLoanRescheduleRequest(); - - System.out.println("-----------------------------REJECTING LOAN RESCHEDULE REQUEST--------------------------"); - - final String requestJSON = new LoanRescheduleRequestTestBuilder().getRejectLoanRescheduleRequestJSON(); - this.loanRescheduleRequestHelper.rejectLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON); - - final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum"); - assertTrue((Boolean)response.get("rejected")); - - System.out.println("Successfully rejected loan reschedule request (ID: " + this.loanRescheduleRequestId + ")"); + this.createLoanRescheduleRequest(); + + System.out.println("-----------------------------REJECTING LOAN RESCHEDULE REQUEST--------------------------"); + + final String requestJSON = new LoanRescheduleRequestTestBuilder().getRejectLoanRescheduleRequestJSON(); + this.loanRescheduleRequestHelper.rejectLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON); + + final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum"); + assertTrue((Boolean)response.get("rejected")); + + System.out.println("Successfully rejected loan reschedule request (ID: " + this.loanRescheduleRequestId + ")"); } @Test public void testApproveLoanRescheduleRequest() { - this.createLoanRescheduleRequest(); - - System.out.println("-----------------------------APPROVING LOAN RESCHEDULE REQUEST--------------------------"); - - final String requestJSON = new LoanRescheduleRequestTestBuilder().getApproveLoanRescheduleRequestJSON(); - this.loanRescheduleRequestHelper.approveLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON); - - final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum"); - assertTrue((Boolean)response.get("approved")); - - 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("NUMBER OF REPAYMENTS SHOULD BE 16, NOT 12", "12", numberOfRepayments.toString()); - assertEquals("TOTAL EXPECTED REPAYMENT MUST BE EQUAL TO 118000.0", "118000.0", totalExpectedRepayment.toString()); - - System.out.println("Successfully approved loan reschedule request (ID: " + this.loanRescheduleRequestId + ")"); + this.createLoanRescheduleRequest(); + + System.out.println("-----------------------------APPROVING LOAN RESCHEDULE REQUEST--------------------------"); + + final String requestJSON = new LoanRescheduleRequestTestBuilder().getApproveLoanRescheduleRequestJSON(); + this.loanRescheduleRequestHelper.approveLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON); + + final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum"); + assertTrue((Boolean)response.get("approved")); + + 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("NUMBER OF REPAYMENTS SHOULD BE 16, NOT 12", "12", numberOfRepayments.toString()); + assertEquals("TOTAL EXPECTED REPAYMENT MUST BE EQUAL TO 118000.0", "118000.0", totalExpectedRepayment.toString()); + + System.out.println("Successfully approved loan reschedule request (ID: " + this.loanRescheduleRequestId + ")"); } } 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 574ba6ccd..35029f247 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 @@ -33,34 +33,34 @@ import com.jayway.restassured.specification.ResponseSpecification; public class OfficeIntegrationTest { - private ResponseSpecification responseSpec; - private RequestSpecification requestSpec; + private ResponseSpecification responseSpec; + private RequestSpecification requestSpec; - @Before - 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(); - } + @Before + 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 testOfficeModification() { - OfficeHelper oh = new OfficeHelper(requestSpec, responseSpec); - int officeId = oh.createOffice("01 July 2007"); - String name = Utils.randomNameGenerator("New_Office_", 4); - String date = "02 July 2007"; - String[] dateArr = { "2007", "7", "2" }; + @Test + public void testOfficeModification() { + OfficeHelper oh = new OfficeHelper(requestSpec, responseSpec); + int officeId = oh.createOffice("01 July 2007"); + String name = Utils.randomNameGenerator("New_Office_", 4); + String date = "02 July 2007"; + String[] dateArr = { "2007", "7", "2" }; - oh.updateOffice(officeId, name, date); - OfficeDomain newOffice = oh.retrieveOfficeByID(officeId); + oh.updateOffice(officeId, name, date); + OfficeDomain newOffice = oh.retrieveOfficeByID(officeId); - Assert.assertTrue(name.equals(newOffice.getName())); - Assert.assertArrayEquals(dateArr, newOffice.getOpeningDate()); - } + Assert.assertTrue(name.equals(newOffice.getName())); + Assert.assertArrayEquals(dateArr, newOffice.getOpeningDate()); + } } 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 5178856fc..90fa5020d 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 @@ -142,14 +142,14 @@ public class SchedulerJobsTestResults { 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")); + 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")); - Assert.assertTrue("Verifying that all due Annual Fees have been paid ", - nextDueDateForAnnualFee.isAfter(todaysDate)); + Assert.assertTrue("Verifying that all due Annual Fees have been paid ", + nextDueDateForAnnualFee.isAfter(todaysDate)); } 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 a34913991..a0c4907ce 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 @@ -47,130 +47,130 @@ import junit.framework.Assert; @SuppressWarnings({ "static-access", "rawtypes", "unchecked", "deprecation" }) public class SkipRepaymentOnMonthFirstTest { - private ResponseSpecification responseSpec; - private RequestSpecification requestSpec; - private GlobalConfigurationHelper globalConfigurationHelper; - private LoanTransactionHelper loanTransactionHelper; - private CalendarHelper calendarHelper; + private ResponseSpecification responseSpec; + private RequestSpecification requestSpec; + private GlobalConfigurationHelper globalConfigurationHelper; + private LoanTransactionHelper loanTransactionHelper; + private CalendarHelper calendarHelper; - @Before - 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(); - } + @Before + 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(); + } - @After - public void tearDown() { - GlobalConfigurationHelper.resetAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec); - GlobalConfigurationHelper.verifyAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec); - } + @After + public void tearDown() { + GlobalConfigurationHelper.resetAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec); + GlobalConfigurationHelper.verifyAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec); + } - @Test - public void testSkippingRepaymentOnFirstDayOfMonth() { - this.globalConfigurationHelper = new GlobalConfigurationHelper(this.requestSpec, this.responseSpec); + @Test + public void testSkippingRepaymentOnFirstDayOfMonth() { + this.globalConfigurationHelper = new GlobalConfigurationHelper(this.requestSpec, this.responseSpec); - // Retrieving All Global Configuration details - final ArrayList globalConfig = this.globalConfigurationHelper - .getAllGlobalConfigurations(this.requestSpec, this.responseSpec); - Assert.assertNotNull(globalConfig); + // Retrieving All Global Configuration details + final ArrayList globalConfig = this.globalConfigurationHelper + .getAllGlobalConfigurations(this.requestSpec, this.responseSpec); + Assert.assertNotNull(globalConfig); - String configName = "skip-repayment-on-first-day-of-month"; - boolean newBooleanValue = true; + String configName = "skip-repayment-on-first-day-of-month"; + 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); - Assert.assertNotNull(updateConfigId); - break; - } - } + 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); + Assert.assertNotNull(updateConfigId); + break; + } + } - } + } - @Test - public void checkRepaymentSkipOnFirstDayOfMonth() { - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + @Test + public void checkRepaymentSkipOnFirstDayOfMonth() { + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - 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()); - 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); - System.out.println("caladerId --------------------" + calendarID); - final Integer loanProductID = createLoanProduct(); - final Integer loanID = applyForLoanApplication(groupID, loanProductID, calendarID, clientID); - System.out.println("loanID----" + loanID); - final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); - verifyLoanRepaymentSchedule(loanSchedule); + 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()); + 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); + System.out.println("caladerId --------------------" + calendarID); + final Integer loanProductID = createLoanProduct(); + final Integer loanID = applyForLoanApplication(groupID, loanProductID, calendarID, clientID); + System.out.println("loanID----" + loanID); + final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, + this.responseSpec, loanID); + verifyLoanRepaymentSchedule(loanSchedule); - } + } - private Integer createLoanProduct() { - System.out.println( - "------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); - final String loanProductJSON = new LoanProductTestBuilder() // - .withPrincipal("12,000.00") // - .withNumberOfRepayments("4") // - .withRepaymentAfterEvery("1") // - .withRepaymentTypeAsMonth() // - .withinterestRatePerPeriod("1") // - .withInterestRateFrequencyTypeAsMonths() // - .withAmortizationTypeAsEqualInstallments() // - .withInterestTypeAsDecliningBalance() // - .build(null); - return this.loanTransactionHelper.getLoanProductId(loanProductJSON); - } + private Integer createLoanProduct() { + System.out.println( + "------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); + final String loanProductJSON = new LoanProductTestBuilder() // + .withPrincipal("12,000.00") // + .withNumberOfRepayments("4") // + .withRepaymentAfterEvery("1") // + .withRepaymentTypeAsMonth() // + .withinterestRatePerPeriod("1") // + .withInterestRateFrequencyTypeAsMonths() // + .withAmortizationTypeAsEqualInstallments() // + .withInterestTypeAsDecliningBalance() // + .build(null); + return this.loanTransactionHelper.getLoanProductId(loanProductJSON); + } - private Integer applyForLoanApplication(final Integer groupID, final Integer loanProductID, Integer calendarID, - Integer clientID) { - System.out.println( - "--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); - final String loanApplicationJSON = new LoanApplicationTestBuilder() // - .withPrincipal("12,000.00") // - .withLoanTermFrequency("4") // - .withLoanTermFrequencyAsMonths() // - .withNumberOfRepayments("4") // - .withRepaymentEveryAfter("1") // - .withRepaymentFrequencyTypeAsMonths() // - .withInterestRatePerPeriod("2") // - .withAmortizationTypeAsEqualInstallments() // - .withInterestTypeAsDecliningBalance() // - .withInterestCalculationPeriodTypeSameAsRepaymentPeriod() // - .withExpectedDisbursementDate("01 October 2011") // - .withCalendarID(calendarID.toString()) // - .withSubmittedOnDate("01 October 2011") // - .withLoanType("jlg").build(clientID.toString(), groupID.toString(), loanProductID.toString(), null); - System.out.println(loanApplicationJSON); - return this.loanTransactionHelper.getLoanId(loanApplicationJSON); - } + private Integer applyForLoanApplication(final Integer groupID, final Integer loanProductID, Integer calendarID, + Integer clientID) { + System.out.println( + "--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); + final String loanApplicationJSON = new LoanApplicationTestBuilder() // + .withPrincipal("12,000.00") // + .withLoanTermFrequency("4") // + .withLoanTermFrequencyAsMonths() // + .withNumberOfRepayments("4") // + .withRepaymentEveryAfter("1") // + .withRepaymentFrequencyTypeAsMonths() // + .withInterestRatePerPeriod("2") // + .withAmortizationTypeAsEqualInstallments() // + .withInterestTypeAsDecliningBalance() // + .withInterestCalculationPeriodTypeSameAsRepaymentPeriod() // + .withExpectedDisbursementDate("01 October 2011") // + .withCalendarID(calendarID.toString()) // + .withSubmittedOnDate("01 October 2011") // + .withLoanType("jlg").build(clientID.toString(), groupID.toString(), loanProductID.toString(), null); + System.out.println(loanApplicationJSON); + return this.loanTransactionHelper.getLoanId(loanApplicationJSON); + } - private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule) { - System.out.println("--------------------VERIFYING THE REPAYMENT DATE--------------------------"); - assertEquals("Checking for Repayment Date for 1st Month", new ArrayList<>(Arrays.asList(2011, 10, 15)), - loanSchedule.get(1).get("dueDate")); - System.out.println("Repayment Date for 1st Month--" + loanSchedule.get(1).get("dueDate")); - - assertEquals("Checking for Repayment Date for 2nd Month", new ArrayList<>(Arrays.asList(2011, 11, 15)), - loanSchedule.get(2).get("dueDate")); - System.out.println("Repayment Date for 2nd Month--" + loanSchedule.get(2).get("dueDate")); - - assertEquals("Checking for Repayment Date for 3rd Month", new ArrayList<>(Arrays.asList(2011, 12, 15)), - loanSchedule.get(3).get("dueDate")); - System.out.println("Repayment Date for 3rd Month--" + loanSchedule.get(3).get("dueDate")); - - assertEquals("Checking for Repayment Date for 4th Month", new ArrayList<>(Arrays.asList(2012, 1, 15)), - loanSchedule.get(4).get("dueDate")); - System.out.println("Repayment Date for 4th Month--" + loanSchedule.get(4).get("dueDate")); - } + private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule) { + System.out.println("--------------------VERIFYING THE REPAYMENT DATE--------------------------"); + assertEquals("Checking for Repayment Date for 1st Month", new ArrayList<>(Arrays.asList(2011, 10, 15)), + loanSchedule.get(1).get("dueDate")); + System.out.println("Repayment Date for 1st Month--" + loanSchedule.get(1).get("dueDate")); + + assertEquals("Checking for Repayment Date for 2nd Month", new ArrayList<>(Arrays.asList(2011, 11, 15)), + loanSchedule.get(2).get("dueDate")); + System.out.println("Repayment Date for 2nd Month--" + loanSchedule.get(2).get("dueDate")); + + assertEquals("Checking for Repayment Date for 3rd Month", new ArrayList<>(Arrays.asList(2011, 12, 15)), + loanSchedule.get(3).get("dueDate")); + System.out.println("Repayment Date for 3rd Month--" + loanSchedule.get(3).get("dueDate")); + + assertEquals("Checking for Repayment Date for 4th Month", new ArrayList<>(Arrays.asList(2012, 1, 15)), + loanSchedule.get(4).get("dueDate")); + System.out.println("Repayment Date for 4th Month--" + loanSchedule.get(4).get("dueDate")); + } } 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 e4bac9361..1f0e54731 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 @@ -92,14 +92,14 @@ public class CalendarHelper { 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) { - System.out.println("---------------------------------CREATING A MEETING CALENDAR FOR THE GROUP------------------------------"); + System.out.println("---------------------------------CREATING A MEETING CALENDAR FOR THE GROUP------------------------------"); - final String CALENDAR_RESOURCE_URL = BASE_URL + Center_Entity + groupId + ENITY_NAME + "?" + Utils.TENANT_IDENTIFIER; + final String CALENDAR_RESOURCE_URL = BASE_URL + Center_Entity + groupId + ENITY_NAME + "?" + Utils.TENANT_IDENTIFIER; - System.out.println(CALENDAR_RESOURCE_URL); + System.out.println(CALENDAR_RESOURCE_URL); - return Utils.performServerPost(requestSpec, responseSpec, CALENDAR_RESOURCE_URL, - getTestCalendarAsJSON(frequency, interval, repeatsOnDay, startDate), "resourceId"); + return Utils.performServerPost(requestSpec, responseSpec, CALENDAR_RESOURCE_URL, + getTestCalendarAsJSON(frequency, interval, repeatsOnDay, startDate), "resourceId"); } public static Integer updateMeetingCalendarForCenter(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, 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 1e4c5e251..ae8386980 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 @@ -197,7 +197,7 @@ public class CenterDomain implements Comparable { } public String getAccountNo(){ - return this.accountNo; + return this.accountNo; } public int[] getGroupMembers() { 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 425064466..f22970cbd 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 @@ -43,7 +43,7 @@ public class CenterHelper { final String GET_CENTER_BY_ID_URL = CENTERS_URL + "/" + id + "?associations=groupMembers&" + Utils.TENANT_IDENTIFIER; System.out.println("------------------------ RETRIEVING CENTER AT " + id + "-------------------------"); Object get = Utils.performServerGet(requestSpec, responseSpec, GET_CENTER_BY_ID_URL, ""); - final String jsonData = new Gson().toJson(get); + final String jsonData = new Gson().toJson(get); return new Gson().fromJson(jsonData, new TypeToken() {}.getType()); } 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 index 1fb2b4d28..762211e93 100755 --- 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 @@ -128,7 +128,7 @@ public class ClientHelper { public static Integer createClientAsPerson(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String activationDate, final String officeId) { - + System.out.println("---------------------------------CREATING A CLIENT NON PERSON(ORGANISATION)---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, getTestPersonClientAsJSON(activationDate, officeId), "clientId"); @@ -145,10 +145,10 @@ public class ClientHelper { public static Integer createClientAsEntity(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String activationDate, final String officeId) { - - Integer constitutionCodeId = (Integer) CodeHelper.getCodeByName(requestSpec, responseSpec, "Constitution").get("id"); - Integer soleProprietorCodeValueId = (Integer) CodeHelper.retrieveOrCreateCodeValue(constitutionCodeId, requestSpec, responseSpec).get("id"); - + + Integer constitutionCodeId = (Integer) CodeHelper.getCodeByName(requestSpec, responseSpec, "Constitution").get("id"); + Integer soleProprietorCodeValueId = (Integer) CodeHelper.retrieveOrCreateCodeValue(constitutionCodeId, requestSpec, responseSpec).get("id"); + System.out.println("---------------------------------CREATING A CLIENT NON PERSON(ORGANISATION)---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, getTestEntityClientAsJSON(activationDate, officeId, soleProprietorCodeValueId), "clientId"); @@ -185,11 +185,11 @@ public class ClientHelper { map.put("lastname", Utils.randomNameGenerator("Client_LastName_", 4)); map.put("externalId", randomIDGenerator("ID_", 7)); map.put("dateFormat", DATE_FORMAT); - map.put("locale", "en"); - map.put("active", "true"); - map.put("activationDate", dateOfJoining); - System.out.println("map : " + map); - return new Gson().toJson(map); + map.put("locale", "en"); + map.put("active", "true"); + map.put("activationDate", dateOfJoining); + System.out.println("map : " + map); + return new Gson().toJson(map); } public static String getTestClientAsJSONPending(final String submittedOnDate, final String officeId) { @@ -199,11 +199,11 @@ public class ClientHelper { map.put("lastname", Utils.randomNameGenerator("Client_LastName_", 4)); map.put("externalId", randomIDGenerator("ID_", 7)); map.put("dateFormat", DATE_FORMAT); - map.put("locale", "en"); - map.put("active", "false"); - map.put("submittedOnDate", submittedOnDate); - System.out.println("map : " + map); - return new Gson().toJson(map); + map.put("locale", "en"); + map.put("active", "false"); + map.put("submittedOnDate", submittedOnDate); + System.out.println("map : " + map); + return new Gson().toJson(map); } public static String getTestPendingClientWithDatatableAsJson(final String registeredTableName) { @@ -344,60 +344,60 @@ public class ClientHelper { } - private String getReactivateClientAsJSON() { - final HashMap map = new HashMap<>(); - map.put("locale", CommonConstants.locale); - map.put("dateFormat", CommonConstants.dateFormat); - map.put("reactivationDate", CREATED_DATE_PLUS_ONE); - String clientJson = new Gson().toJson(map); - System.out.println(clientJson); - return clientJson; + private String getReactivateClientAsJSON() { + final HashMap map = new HashMap<>(); + map.put("locale", CommonConstants.locale); + map.put("dateFormat", CommonConstants.dateFormat); + map.put("reactivationDate", CREATED_DATE_PLUS_ONE); + String clientJson = new Gson().toJson(map); + System.out.println(clientJson); + return clientJson; - } + } - private String getUndoRejectClientAsJSON(final String date) { - final HashMap map = new HashMap<>(); - map.put("locale", CommonConstants.locale); - map.put("dateFormat", CommonConstants.dateFormat); - map.put("reopenedDate", date); - String clientJson = new Gson().toJson(map); - System.out.println(clientJson); - return clientJson; + private String getUndoRejectClientAsJSON(final String date) { + final HashMap map = new HashMap<>(); + map.put("locale", CommonConstants.locale); + map.put("dateFormat", CommonConstants.dateFormat); + map.put("reopenedDate", date); + String clientJson = new Gson().toJson(map); + System.out.println(clientJson); + return clientJson; - } + } - private String getUndoWithdrawnClientAsJSON(final String date) { - final HashMap map = new HashMap<>(); - map.put("locale", CommonConstants.locale); - map.put("dateFormat", CommonConstants.dateFormat); - map.put("reopenedDate", date); - String clientJson = new Gson().toJson(map); - System.out.println(clientJson); - return clientJson; + private String getUndoWithdrawnClientAsJSON(final String date) { + final HashMap map = new HashMap<>(); + map.put("locale", CommonConstants.locale); + map.put("dateFormat", CommonConstants.dateFormat); + map.put("reopenedDate", date); + String clientJson = new Gson().toJson(map); + System.out.println(clientJson); + return clientJson; - } + } - private String getRejectClientAsJSON() { - final HashMap map = new HashMap<>(); - /* Retrieve Code id for the Code "ClientRejectReason" */ - String codeName = "ClientRejectReason"; - HashMap code = CodeHelper.getCodeByName(this.requestSpec, this.responseSpec, codeName); - Integer clientRejectionReasonCodeId = (Integer) code.get("id"); + private String getRejectClientAsJSON() { + final HashMap map = new HashMap<>(); + /* Retrieve Code id for the Code "ClientRejectReason" */ + String codeName = "ClientRejectReason"; + HashMap code = CodeHelper.getCodeByName(this.requestSpec, this.responseSpec, codeName); + Integer clientRejectionReasonCodeId = (Integer) code.get("id"); - /* Retrieve/Create Code Values for the Code "ClientRejectReason" */ - HashMap codeValue = CodeHelper.retrieveOrCreateCodeValue(clientRejectionReasonCodeId, - this.requestSpec, this.responseSpec); - Integer rejectionReasonId = (Integer) codeValue.get("id"); + /* Retrieve/Create Code Values for the Code "ClientRejectReason" */ + HashMap codeValue = CodeHelper.retrieveOrCreateCodeValue(clientRejectionReasonCodeId, + this.requestSpec, this.responseSpec); + Integer rejectionReasonId = (Integer) codeValue.get("id"); - map.put("locale", CommonConstants.locale); - map.put("dateFormat", CommonConstants.dateFormat); - map.put("rejectionDate", CREATED_DATE_PLUS_ONE); - map.put("rejectionReasonId", rejectionReasonId.toString()); - String clientJson = new Gson().toJson(map); - System.out.println(clientJson); - return clientJson; + map.put("locale", CommonConstants.locale); + map.put("dateFormat", CommonConstants.dateFormat); + map.put("rejectionDate", CREATED_DATE_PLUS_ONE); + map.put("rejectionReasonId", rejectionReasonId.toString()); + String clientJson = new Gson().toJson(map); + System.out.println(clientJson); + return clientJson; - } + } private String getActivateClientAsJSON(String date) { final HashMap map = new HashMap<>(); @@ -490,55 +490,55 @@ public class ClientHelper { return performClientActions(createClientOperationURL(WITHDRAW_CLIENT_COMMAND, clientId), getWithdrawClientAsJSON(), clientId); } - private String createClientOperationURL(final String command, final Integer clientId) { - return CLIENT_URL + "/" + clientId + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; - } + private String createClientOperationURL(final String command, final Integer clientId) { + return CLIENT_URL + "/" + clientId + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; + } - public HashMap undoReject(final Integer clientId) { - System.out.println("--------------------------------- UNDO REJECT CLIENT -------------------------------"); - return performClientActions(createClientOperationURL(UNDOREJECT_CLIENT_COMMAND, clientId), - getUndoRejectClientAsJSON(CREATED_DATE_PLUS_TWO), clientId); - } + public HashMap undoReject(final Integer clientId) { + System.out.println("--------------------------------- UNDO REJECT CLIENT -------------------------------"); + return performClientActions(createClientOperationURL(UNDOREJECT_CLIENT_COMMAND, clientId), + getUndoRejectClientAsJSON(CREATED_DATE_PLUS_TWO), clientId); + } - public HashMap undoWithdrawn(final Integer clientId) { - System.out.println("--------------------------------- UNDO WITHDRAWN CLIENT -------------------------------"); - return performClientActions(createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId), - getUndoWithdrawnClientAsJSON(CREATED_DATE_PLUS_TWO), clientId); - } + public HashMap undoWithdrawn(final Integer clientId) { + System.out.println("--------------------------------- UNDO WITHDRAWN CLIENT -------------------------------"); + return performClientActions(createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId), + getUndoWithdrawnClientAsJSON(CREATED_DATE_PLUS_TWO), clientId); + } - public Object undoRejectedclient(final Integer clientId, final String jsonAttributeToGetBack, - final String rejectedDate) { - System.out.println("----------------------------------UNDO REJECT CLIENT ----------------------------------"); - return performClientActionsWithValidationErrors(createClientOperationURL(UNDOREJECT_CLIENT_COMMAND, clientId), - getUndoRejectClientAsJSON(rejectedDate), jsonAttributeToGetBack); - } + public Object undoRejectedclient(final Integer clientId, final String jsonAttributeToGetBack, + final String rejectedDate) { + System.out.println("----------------------------------UNDO REJECT CLIENT ----------------------------------"); + return performClientActionsWithValidationErrors(createClientOperationURL(UNDOREJECT_CLIENT_COMMAND, clientId), + getUndoRejectClientAsJSON(rejectedDate), jsonAttributeToGetBack); + } - public Object undoWithdrawclient(final Integer clientId, final String jsonAttributeToGetBack, - final String rejectedDate) { - System.out.println("----------------------------------UNDO WITHDRAW CLIENT ----------------------------------"); - return performClientActionsWithValidationErrors( - createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId), - getUndoWithdrawnClientAsJSON(rejectedDate), jsonAttributeToGetBack); - } + public Object undoWithdrawclient(final Integer clientId, final String jsonAttributeToGetBack, + final String rejectedDate) { + System.out.println("----------------------------------UNDO WITHDRAW CLIENT ----------------------------------"); + return performClientActionsWithValidationErrors( + createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId), + getUndoWithdrawnClientAsJSON(rejectedDate), jsonAttributeToGetBack); + } - public Object activateClient(final Integer clientId, final String jsonAttributeToGetBack) { - System.out.println("--------------------------------- ACTIVATE CLIENT -------------------------------"); - return performClientActionsWithValidationErrors(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId), - getActivateClientAsJSON(CREATED_DATE_PLUS_ONE), jsonAttributeToGetBack); - } + public Object activateClient(final Integer clientId, final String jsonAttributeToGetBack) { + System.out.println("--------------------------------- ACTIVATE CLIENT -------------------------------"); + return performClientActionsWithValidationErrors(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId), + getActivateClientAsJSON(CREATED_DATE_PLUS_ONE), jsonAttributeToGetBack); + } - public HashMap activateClientWithDiffDateOption(final Integer clientId, - final String activationDate) { - System.out.println("--------------------------------- ACTIVATE CLIENT -------------------------------"); - return performClientActions(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId), - getActivateClientAsJSON(activationDate), clientId); - } + public HashMap activateClientWithDiffDateOption(final Integer clientId, + final String activationDate) { + System.out.println("--------------------------------- ACTIVATE CLIENT -------------------------------"); + 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); - } + private ArrayList performClientActionsWithValidationErrors(final String postURLForClient, + final String jsonToBeSent, final String 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); 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 c2ca23fcb..2b4f73631 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 @@ -29,8 +29,8 @@ import com.jayway.restassured.specification.RequestSpecification; import com.jayway.restassured.specification.ResponseSpecification; public class HookHelper { - - private final RequestSpecification requestSpec; + + private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; private static final String CREATE_HOOK_URL = "/fineract-provider/api/v1/hooks?" + Utils.TENANT_IDENTIFIER; @@ -47,9 +47,9 @@ public class HookHelper { } public String getTestHookAsJson(final String payloadURL) { - final HashMap map = new HashMap<>(); - map.put("name", "Web"); - map.put("displayName", Utils.randomNameGenerator("Hook_DisplayName_", 5)); + final HashMap map = new HashMap<>(); + map.put("name", "Web"); + map.put("displayName", Utils.randomNameGenerator("Hook_DisplayName_", 5)); map.put("isActive", "true"); final HashMap config = new HashMap<>(); config.put("Content Type", "json"); @@ -97,7 +97,7 @@ public class HookHelper { 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"); - HashMap map = (HashMap)array.get(0); + HashMap map = (HashMap)array.get(0); assertEquals("error.msg.hook.identifier.not.found",map.get("userMessageGlobalisationCode")); } } 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 7e10e9d41..badcaa492 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,7 +24,7 @@ import com.jayway.restassured.specification.RequestSpecification; import com.jayway.restassured.specification.ResponseSpecification; public class LoanRescheduleRequestHelper { - private final RequestSpecification requestSpec; + private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; private static final String LOAN_RESCHEDULE_REQUEST_URL = "/fineract-provider/api/v1/rescheduleloans"; @@ -35,32 +35,32 @@ public class LoanRescheduleRequestHelper { } public Integer createLoanRescheduleRequest(final String requestJSON) { - final String URL = LOAN_RESCHEDULE_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER; - return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId"); + final String URL = LOAN_RESCHEDULE_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER; + return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId"); } public Integer rejectLoanRescheduleRequest(final Integer requestId, final String requestJSON) { - final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER + "&command=reject"; - - return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId"); + final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER + "&command=reject"; + + return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId"); } public Integer approveLoanRescheduleRequest(final Integer requestId, final String requestJSON) { - final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER + "&command=approve"; - - return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId"); + final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER + "&command=approve"; + + return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId"); } public Object getLoanRescheduleRequest(final Integer requestId, final String param) { - final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER; - - return Utils.performServerGet(requestSpec, responseSpec, URL, param); + final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER; + + return Utils.performServerGet(requestSpec, responseSpec, URL, param); } public void verifyCreationOfLoanRescheduleRequest(final Integer requestId) { - final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER; - - final Integer id = Utils.performServerGet(requestSpec, responseSpec, URL, "id"); - assertEquals("ERROR IN CREATING LOAN RESCHEDULE REQUEST", requestId, id); + final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER; + + final Integer id = Utils.performServerGet(requestSpec, responseSpec, URL, "id"); + assertEquals("ERROR IN CREATING LOAN RESCHEDULE REQUEST", requestId, id); } } 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 1032b24f8..b08be13d3 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 @@ -22,132 +22,132 @@ import com.google.gson.Gson; public class OfficeDomain { - public static class Builder { + public static class Builder { - private int id; - private String name; - private String nameDecorated; - private String externalId; - private String[] openingDate; - private String hierarchy; + private int id; + private String name; + private String nameDecorated; + private String externalId; + 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) { - this.id = id; - this.name = name; - this.nameDecorated = nameDecorated; - this.externalId = externalId; - this.openingDate = openingDate; - this.hierarchy = 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; + this.externalId = externalId; + this.openingDate = openingDate; + this.hierarchy = hierarchy; + } - public OfficeDomain build() { - return new OfficeDomain(this.id, this.name, this.nameDecorated, - this.externalId, this.openingDate, this.hierarchy); - } - } + public OfficeDomain build() { + return new OfficeDomain(this.id, this.name, this.nameDecorated, + this.externalId, this.openingDate, this.hierarchy); + } + } - private int id; - private String name; - private String nameDecorated; - private String externalId; - private String[] openingDate; - private String hierarchy; + private int id; + private String name; + private String nameDecorated; + private String externalId; + private String[] openingDate; + private String hierarchy; - OfficeDomain() { - super(); - } + OfficeDomain() { + super(); + } - 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; - this.nameDecorated = nameDecorated; - this.externalId = externalId; - this.openingDate = openingDate; - this.hierarchy = 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; + this.nameDecorated = nameDecorated; + this.externalId = externalId; + this.openingDate = openingDate; + this.hierarchy = hierarchy; + } - public String toJSON() { - return new Gson().toJson(this); - } + public String toJSON() { + return new Gson().toJson(this); + } - public static OfficeDomain fromJSON(final String jsonData) { - return new Gson().fromJson(jsonData, OfficeDomain.class); - } + public static OfficeDomain fromJSON(final String jsonData) { + return new Gson().fromJson(jsonData, OfficeDomain.class); + } - 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); - } + 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); + } - public int getId() { - return this.id; - } + public int getId() { + return this.id; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public String getNameDecorated() { - return this.nameDecorated; - } + public String getNameDecorated() { + return this.nameDecorated; + } - public String getExternalId() { - return this.externalId; - } + public String getExternalId() { + return this.externalId; + } - public String[] getOpeningDate() { - return this.openingDate; - } + public String[] getOpeningDate() { + return this.openingDate; + } - public String getHierarchy() { - return this.hierarchy; - } + public String getHierarchy() { + return this.hierarchy; + } - @Override - public int hashCode() { - int hash = 1; + @Override + public int hashCode() { + int hash = 1; - if (this.id > 0) - hash += this.id; - if (this.name != null) - hash += this.name.hashCode(); - if (this.nameDecorated != null) - hash += this.nameDecorated.hashCode(); - if (this.externalId != null) - hash += this.externalId.hashCode(); - if (this.openingDate != null) - hash += this.openingDate.hashCode(); - if (this.hierarchy != null) - hash += this.hierarchy.hashCode(); + if (this.id > 0) + hash += this.id; + if (this.name != null) + hash += this.name.hashCode(); + if (this.nameDecorated != null) + hash += this.nameDecorated.hashCode(); + if (this.externalId != null) + hash += this.externalId.hashCode(); + if (this.openingDate != null) + hash += this.openingDate.hashCode(); + if (this.hierarchy != null) + hash += this.hierarchy.hashCode(); - return hash; - } + return hash; + } - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } - if (!(obj instanceof OfficeDomain)) - return false; + if (!(obj instanceof OfficeDomain)) + return false; - OfficeDomain od = (OfficeDomain) obj; + OfficeDomain od = (OfficeDomain) obj; - if (this.id == od.getId() && this.name.equals(od.getName()) - && this.nameDecorated.equals(od.getName()) - && this.externalId.equals(od.getExternalId()) - && this.openingDate.equals(od.getOpeningDate()) - && this.hierarchy.equals(od.getHierarchy())) - return true; + if (this.id == od.getId() && this.name.equals(od.getName()) + && this.nameDecorated.equals(od.getName()) + && this.externalId.equals(od.getExternalId()) + && this.openingDate.equals(od.getOpeningDate()) + && this.hierarchy.equals(od.getHierarchy())) + return true; - return false; - } + return false; + } } \ No newline at end of file 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 index 2940576f3..cd72f2b37 100755 --- 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 @@ -37,77 +37,77 @@ import javax.ws.rs.core.MediaType; public class OfficeHelper { - private static final String OFFICE_URL = "/fineract-provider/api/v1/offices"; - private final RequestSpecification requestSpec; - private final ResponseSpecification responseSpec; + 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) { - this.requestSpec = requestSpec; - this.responseSpec = 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, ""); - final String json = new Gson().toJson(get); - return new Gson().fromJson(json, new TypeToken() { - }.getType()); - } + public OfficeDomain retrieveOfficeByID(int id) { + 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()); + } - public Integer createOffice(final String openingDate) { - String json = getAsJSON(openingDate); - return Utils.performServerPost(this.requestSpec, this.responseSpec, - OFFICE_URL + "?" + Utils.TENANT_IDENTIFIER, json, - CommonConstants.RESPONSE_RESOURCE_ID); - } + public Integer createOffice(final String openingDate) { + String json = getAsJSON(openingDate); + return Utils.performServerPost(this.requestSpec, this.responseSpec, + OFFICE_URL + "?" + Utils.TENANT_IDENTIFIER, json, + CommonConstants.RESPONSE_RESOURCE_ID); + } - public Integer updateOffice(int id, String name, String openingDate) { - final HashMap map = new HashMap<>(); - map.put("name", name); - map.put("dateFormat", "dd MMMM yyyy"); - map.put("locale", "en"); - map.put("openingDate", openingDate); + public Integer updateOffice(int id, String name, String openingDate) { + final HashMap map = new HashMap<>(); + map.put("name", name); + map.put("dateFormat", "dd MMMM yyyy"); + map.put("locale", "en"); + map.put("openingDate", openingDate); - System.out.println("map : " + map); + System.out.println("map : " + map); - return Utils.performServerPut(requestSpec, responseSpec, OFFICE_URL - + "/" + id + "?" + Utils.TENANT_IDENTIFIER, - new Gson().toJson(map), "resourceId"); - } + return Utils.performServerPut(requestSpec, responseSpec, OFFICE_URL + + "/" + id + "?" + Utils.TENANT_IDENTIFIER, + new Gson().toJson(map), "resourceId"); + } - public static String getAsJSON(final String openingDate) { - final HashMap map = new HashMap<>(); - map.put("parentId", "1"); - map.put("name", Utils.randomNameGenerator("Office_", 4)); - map.put("dateFormat", "dd MMMM yyyy"); - map.put("locale", "en"); - map.put("openingDate", openingDate); - System.out.println("map : " + map); - return new Gson().toJson(map); - } + public static String getAsJSON(final String openingDate) { + final HashMap map = new HashMap<>(); + map.put("parentId", "1"); + map.put("name", Utils.randomNameGenerator("Office_", 4)); + map.put("dateFormat", "dd MMMM yyyy"); + map.put("locale", "en"); + map.put("openingDate", openingDate); + System.out.println("map : " + map); + return new Gson().toJson(map); + } - 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); + 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); - } + } - 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); - return workbook; - } + 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); + return workbook; + } } 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 f07fdeea1..b03ce5ec0 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 @@ -158,10 +158,10 @@ public class ProvisioningIntegrationTest { Object requestedCategoryId = requestedMap.get("categoryId") ; boolean found = false ; for(int j = 0 ; j < newdefintions.size(); j++) { - Map newMap = (Map)newdefintions.get(j) ; + Map newMap = (Map)newdefintions.get(j) ; Object newCategoryId = newMap.get("categoryId") ; if(requestedCategoryId.equals(newCategoryId)) { - found = true ; + found = true ; checkProperty("categoryId", requestedMap, newMap) ; checkProperty("categoryName", requestedMap, newMap) ; checkProperty("minAge", requestedMap, newMap) ; 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 339f28757..4ba7c068c 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 @@ -23,86 +23,86 @@ import static org.junit.Assert.assertEquals; import java.util.HashMap; public class LoanDisbursementTestBuilder { - - String dueDate = null; - Float totalOriginalDueForPeriod = null; - Float totalOutstandingForPeriod = null; - Float interestOutstanding = null; - Float principalOutstanding = null; - Float principalLoanBalanceOutstanding = null; - Float principalDue = null; - Float principalOriginalDue = null; - String fromDate = null; - - public LoanDisbursementTestBuilder(String dueDate,Float totalOriginalDueForPeriod,Float totalOutstandingForPeriod, - Float interestOutstanding, Float principalOutstanding, Float principalLoanBalanceOutstanding, Float principalDue, - Float principalOriginalDue, String fromDate) { - this.dueDate = dueDate; - this.totalOriginalDueForPeriod = totalOriginalDueForPeriod; - this.totalOutstandingForPeriod = totalOutstandingForPeriod; - this.interestOutstanding = interestOutstanding; - this.principalOutstanding = principalOutstanding; - this.principalLoanBalanceOutstanding = principalLoanBalanceOutstanding; - this.principalDue = principalDue; - this.principalOriginalDue = principalOriginalDue; - this.fromDate = fromDate; - } + + String dueDate = null; + Float totalOriginalDueForPeriod = null; + Float totalOutstandingForPeriod = null; + Float interestOutstanding = null; + Float principalOutstanding = null; + Float principalLoanBalanceOutstanding = null; + Float principalDue = null; + Float principalOriginalDue = null; + String fromDate = null; + + public LoanDisbursementTestBuilder(String dueDate,Float totalOriginalDueForPeriod,Float totalOutstandingForPeriod, + Float interestOutstanding, Float principalOutstanding, Float principalLoanBalanceOutstanding, Float principalDue, + Float principalOriginalDue, String fromDate) { + this.dueDate = dueDate; + this.totalOriginalDueForPeriod = totalOriginalDueForPeriod; + this.totalOutstandingForPeriod = totalOutstandingForPeriod; + this.interestOutstanding = interestOutstanding; + this.principalOutstanding = principalOutstanding; + this.principalLoanBalanceOutstanding = principalLoanBalanceOutstanding; + this.principalDue = principalDue; + this.principalOriginalDue = principalOriginalDue; + this.fromDate = fromDate; + } - public String getDueDate() { - return this.dueDate; - } + public String getDueDate() { + return this.dueDate; + } - public Float getTotalOriginalDueForPeriod() { - return this.totalOriginalDueForPeriod; - } + public Float getTotalOriginalDueForPeriod() { + return this.totalOriginalDueForPeriod; + } - public Float getTotalOutstandingForPeriod() { - return this.totalOutstandingForPeriod; - } + public Float getTotalOutstandingForPeriod() { + return this.totalOutstandingForPeriod; + } - public Float getInterestOutstanding() { - return this.interestOutstanding; - } + public Float getInterestOutstanding() { + return this.interestOutstanding; + } - public Float getPrincipalOutstanding() { - return this.principalOutstanding; - } + public Float getPrincipalOutstanding() { + return this.principalOutstanding; + } - public Float getPrincipalLoanBalanceOutstanding() { - return this.principalLoanBalanceOutstanding; - } + public Float getPrincipalLoanBalanceOutstanding() { + return this.principalLoanBalanceOutstanding; + } - public Float getPrincipalDue() { - return this.principalDue; - } + public Float getPrincipalDue() { + return this.principalDue; + } - public Float getPrincipalOriginalDue() { - return this.principalOriginalDue; - } + public Float getPrincipalOriginalDue() { + return this.principalOriginalDue; + } - public String getFromDate() { - 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 String getFromDate() { + 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; + }*/ } 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 45dae9f0c..63e8075c8 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 @@ -213,7 +213,7 @@ public class LoanProductTestBuilder { map.put("maximumGap", maximumGap) ; } map.put("syncExpectedWithDisbursementDate", - this.syncExpectedWithDisbursementDate); + this.syncExpectedWithDisbursementDate); return new Gson().toJson(map); } @@ -504,7 +504,7 @@ public class LoanProductTestBuilder { public LoanProductTestBuilder withSyncExpectedWithDisbursementDate(Boolean syncExpectedWithDisbursementDate) { this.syncExpectedWithDisbursementDate = - 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 index 1e4196dd9..8ef9b4635 100755 --- 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 @@ -193,7 +193,7 @@ public class LoanTransactionHelper { public HashMap disburseLoanWithRepaymentReschedule(final String date, final Integer loanID, String adjustRepaymentDate) { return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), getDisburseLoanWithRepaymentRescheduleAsJSON(date, - null, adjustRepaymentDate)); + null, adjustRepaymentDate)); } public HashMap disburseLoan(final String date, final Integer loanID, final String disburseAmt) { @@ -522,8 +522,8 @@ public class LoanTransactionHelper { } 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, @@ -648,17 +648,17 @@ public class LoanTransactionHelper { } 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), jsonAttributeToGetBack); + final String updatedExpectedDisbursementDate, final String updatedPrincipal, final String jsonAttributeToGetBack) { + + 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) { - - return Utils.performServerPut(this.requestSpec, this.responseSpec, createAddAndDeleteDisbursementURL(loanID), - getAddAndDeleteDisbursementsAsJSON(approvalAmount, expectedDisbursementDate, disbursementData), jsonAttributeToGetBack); + , List disbursementData, final String jsonAttributeToGetBack) { + + return Utils.performServerPut(this.requestSpec, this.responseSpec, createAddAndDeleteDisbursementURL(loanID), + getAddAndDeleteDisbursementsAsJSON(approvalAmount, expectedDisbursementDate, disbursementData), jsonAttributeToGetBack); } private String createEditDisbursementURL(Integer loanID, Integer disbursementId) { @@ -670,7 +670,7 @@ public class LoanTransactionHelper { } public static String getEditDisbursementsAsJSON(final String approvalAmount, final String expectedDisbursementDate, - final String updatedExpectedDisbursementDate, final String updatedPrincipal) { + final String updatedExpectedDisbursementDate, final String updatedPrincipal) { final HashMap map = new HashMap<>(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); @@ -684,7 +684,7 @@ public class LoanTransactionHelper { } public static String getAddAndDeleteDisbursementsAsJSON(final String approvalAmount, final String expectedDisbursementDate, - final List disbursementData) { + final List disbursementData) { final HashMap map = new HashMap<>(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); 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 89a695d67..8af62fe8e 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 @@ -136,10 +136,10 @@ public class SavingsProductHelper { map.putAll(getAccountMappingForCashBased()); } if(this.isDormancyTrackingActive){ - map.put("isDormancyTrackingActive", Boolean.toString(this.isDormancyTrackingActive)); - map.put("daysToInactive", this.daysToInactive); - map.put("daysToDormancy", this.daysToDormancy); - map.put("daysToEscheat", this.daysToEscheat); + map.put("isDormancyTrackingActive", Boolean.toString(this.isDormancyTrackingActive)); + map.put("daysToInactive", this.daysToInactive); + map.put("daysToDormancy", this.daysToDormancy); + map.put("daysToEscheat", this.daysToEscheat); } String savingsProductCreateJson = new Gson().toJson(map); @@ -285,13 +285,13 @@ public class SavingsProductHelper { assertEquals("ERROR IN CREATING THE Savings Product", generatedProductID, responseSavingsProductID); } - public SavingsProductHelper withDormancy() { - this.isDormancyTrackingActive = true; - this.daysToInactive = "30"; - this.daysToDormancy = "60"; - this.daysToEscheat = "90"; + public SavingsProductHelper withDormancy() { + this.isDormancyTrackingActive = true; + this.daysToInactive = "30"; + this.daysToDormancy = "60"; + this.daysToEscheat = "90"; - return this; - } + return this; + } } \ No newline at end of file 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 index 4a7f6368b..afbee0eb5 100755 --- 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 @@ -90,38 +90,38 @@ public class SavingsStatusChecker { return (Boolean) savingsStatusMap.get(nameOfSavingsStatusString); } - public static void verifySavingsSubStatusInactive(HashMap savingsStatusHashMap) { + public static void verifySavingsSubStatusInactive(HashMap savingsStatusHashMap) { System.out.println("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); assertTrue("UNEXPECTED SAVINGS ACCOUNT SUB STATUS", getStatus(savingsStatusHashMap, "inactive")); System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n"); - } - - public static void verifySavingsSubStatusDormant(HashMap savingsStatusHashMap) { + } + + public static void verifySavingsSubStatusDormant(HashMap savingsStatusHashMap) { System.out.println("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); assertTrue("UNEXPECTED SAVINGS ACCOUNT SUB STATUS", getStatus(savingsStatusHashMap, "dormant")); System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n"); - } - - public static void verifySavingsSubStatusEscheat(HashMap savingsStatusHashMap) { + } + + public static void verifySavingsSubStatusEscheat(HashMap savingsStatusHashMap) { System.out.println("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); assertTrue("UNEXPECTED SAVINGS ACCOUNT SUB STATUS", getStatus(savingsStatusHashMap, "escheat")); System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n"); - } + } - public static void verifySavingsSubStatusNone(HashMap savingsStatusHashMap) { + public static void verifySavingsSubStatusNone(HashMap savingsStatusHashMap) { System.out.println("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); assertTrue("UNEXPECTED SAVINGS ACCOUNT SUB STATUS", getStatus(savingsStatusHashMap, "none")); System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n"); - } - - public static void verifySavingsSubStatusblock(HashMap savingsStatusHashMap) { + } + + public static void verifySavingsSubStatusblock(HashMap savingsStatusHashMap) { System.out.println( "\n-------------------------------------- VERIFYING SAVINGS ACCOUNT IS BLOCKED ------------------------------------"); assertTrue("block", getStatus(savingsStatusHashMap, "block")); System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n"); } - public static void verifySavingsSubStatusIsNone(HashMap savingsStatusHashMap) { + public static void verifySavingsSubStatusIsNone(HashMap savingsStatusHashMap) { System.out.println("\n------------------------- VERIFYING SAVINGS ACCOUNT IS NOT BLOCKED FOR ANY TYPE OF TRANSACTIONS ---------------------------"); assertTrue("none", getStatus(savingsStatusHashMap, "none")); System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n"); 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 abdedf329..0a950237a 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 @@ -28,199 +28,199 @@ import com.jayway.restassured.specification.ResponseSpecification; public class AccountNumberPreferencesHelper { - private final RequestSpecification requestSpec; + private final RequestSpecification requestSpec; - private final ResponseSpecification responseSpec; + private final ResponseSpecification responseSpec; - private static final String ACCOUNT_NUMBER_FORMATS_REQUEST_URL = "/fineract-provider/api/v1/accountnumberformats"; + private static final String ACCOUNT_NUMBER_FORMATS_REQUEST_URL = "/fineract-provider/api/v1/accountnumberformats"; - public AccountNumberPreferencesHelper( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - this.requestSpec = requestSpec; - this.responseSpec = responseSpec; - } + public AccountNumberPreferencesHelper( + final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { + this.requestSpec = requestSpec; + this.responseSpec = responseSpec; + } - public Object createClientAccountNumberPreference( - ResponseSpecification responseSpec, String jsonAttributeToGetBack) { - System.out - .println("---------------------------------CREATING CLIENT ACCOUNT NUMBER PREFERENCE------------------------------------------"); + public Object createClientAccountNumberPreference( + ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + System.out + .println("---------------------------------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) { - System.out - .println("---------------------------------CREATING LOAN ACCOUNT NUMBER PREFERENCE------------------------------------------"); + public Object createLoanAccountNumberPreference( + ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + System.out + .println("---------------------------------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) { - System.out - .println("---------------------------------CREATING SAVINGS ACCOUNT NUMBER PREFERENCE------------------------------------------"); + public Object createSavingsAccountNumberPreference( + ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + System.out + .println("---------------------------------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) { - System.out - .println("---------------------------------CREATING GROUPS ACCOUNT NUMBER PREFERENCE------------------------------------------"); + } + + public Object createGroupsAccountNumberPreference( + ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + System.out + .println("---------------------------------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) { - System.out - .println("---------------------------------CREATING CENTER ACCOUNT NUMBER PREFERENCE------------------------------------------"); + } + + public Object createCenterAccountNumberPreference( + ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + System.out + .println("---------------------------------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, - String prefixType, String jsonAttributeToGetBack) { + 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, - ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + 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) { - System.out - .println("---------------------------------DELETING ACCOUNT NUMBER PREFERENCE------------------------------------------"); + System.out + .println("---------------------------------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, ""); - return response; - } + public ArrayList> getAllAccountNumberPreferences() { + 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, - ResponseSpecification responseSpec, RequestSpecification requestSpec) { + 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"); + 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"); + Utils.performServerGet(requestSpec, responseSpec, loanURL, "id"); - final String savingsURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + savingsAccountNumberPreferenceId + "?" - + Utils.TENANT_IDENTIFIER; + 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; + Utils.performServerGet(requestSpec, responseSpec, savingsURL, "id"); + + 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; + Utils.performServerGet(requestSpec, responseSpec, groupsURL, "id"); + + final String centerURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + + centerAccountNumberPreferenceId + "?" + + Utils.TENANT_IDENTIFIER; - Utils.performServerGet(requestSpec, responseSpec, centerURL, "id"); - } + 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; - Utils.performServerGet(requestSpec, responseSpec, URL, "id"); + 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 6c6e897e4..d10deddef 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 @@ -23,69 +23,69 @@ import java.util.HashMap; import com.google.gson.Gson; public class AccountNumberPreferencesTestBuilder { - private String clientAccountType = "1"; - private String clientPrefixType = "101"; - private String loanAccountType = "2"; - private String loanPrefixType = "1"; - private String savingsAccountType = "3"; - private String savingsPrefixType = "1"; - private String centerAccountType = "4"; - private String centerPrefixType = "1"; - private String groupsAccountType = "5"; - private String groupsPrefixType = "1"; + private String clientAccountType = "1"; + private String clientPrefixType = "101"; + private String loanAccountType = "2"; + private String loanPrefixType = "1"; + private String savingsAccountType = "3"; + private String savingsPrefixType = "1"; + private String centerAccountType = "4"; + private String centerPrefixType = "1"; + private String groupsAccountType = "5"; + private String groupsPrefixType = "1"; - public String clientBuild() { - final HashMap map = new HashMap<>(); - map.put("accountType", clientAccountType); - map.put("prefixType", clientPrefixType); + public String clientBuild() { + final HashMap map = new HashMap<>(); + map.put("accountType", clientAccountType); + map.put("prefixType", clientPrefixType); - return new Gson().toJson(map); - } + return new Gson().toJson(map); + } - public String loanBuild() { - final HashMap map = new HashMap<>(); - map.put("accountType", loanAccountType); - map.put("prefixType", loanPrefixType); + public String loanBuild() { + final HashMap map = new HashMap<>(); + map.put("accountType", loanAccountType); + map.put("prefixType", loanPrefixType); - return new Gson().toJson(map); - } + return new Gson().toJson(map); + } - public String savingsBuild() { - final HashMap map = new HashMap<>(); - map.put("accountType", savingsAccountType); - map.put("prefixType", savingsPrefixType); + public String savingsBuild() { + final HashMap map = new HashMap<>(); + map.put("accountType", savingsAccountType); + map.put("prefixType", savingsPrefixType); - return new Gson().toJson(map); - } - - public String groupsBuild() { - final HashMap map = new HashMap<>(); - map.put("accountType", groupsAccountType); - map.put("prefixType", groupsPrefixType); + return new Gson().toJson(map); + } + + public String groupsBuild() { + final HashMap map = new HashMap<>(); + map.put("accountType", groupsAccountType); + map.put("prefixType", groupsPrefixType); - return new Gson().toJson(map); - } + return new Gson().toJson(map); + } - public String centerBuild() { - final HashMap map = new HashMap<>(); - map.put("accountType", centerAccountType); - map.put("prefixType", centerPrefixType); + public String centerBuild() { + final HashMap map = new HashMap<>(); + map.put("accountType", centerAccountType); + map.put("prefixType", centerPrefixType); - return new Gson().toJson(map); - } - - public String invalidDataBuild(String accountType, String prefixType) { - final HashMap map = new HashMap<>(); - map.put("accountType", accountType); - map.put("prefixType", prefixType); + return new Gson().toJson(map); + } + + public String invalidDataBuild(String accountType, String prefixType) { + final HashMap map = new HashMap<>(); + map.put("accountType", accountType); + map.put("prefixType", prefixType); - return new Gson().toJson(map); - } + return new Gson().toJson(map); + } - public String updatePrefixType(final String prefixType) { + public String updatePrefixType(final String prefixType) { - final HashMap map = new HashMap<>(); - map.put("prefixType", prefixType); - return new Gson().toJson(map); - } + final HashMap map = new HashMap<>(); + map.put("prefixType", prefixType); + return new Gson().toJson(map); + } } 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 f85d7b555..f6319a4f4 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 @@ -33,221 +33,221 @@ import com.jayway.restassured.specification.ResponseSpecification; public class CodeHelper { - public static final String CODE_ID_ATTRIBUTE_NAME = "id"; - public static final String RESPONSE_ID_ATTRIBUTE_NAME = "resourceId"; - public static final String SUBRESPONSE_ID_ATTRIBUTE_NAME = "subResourceId"; - public static final String CODE_NAME_ATTRIBUTE_NAME = "name"; - public static final String CODE_SYSTEM_DEFINED_ATTRIBUTE_NAME = "systemDefined"; - public static final String CODE_URL = "/fineract-provider/api/v1/codes"; + public static final String CODE_ID_ATTRIBUTE_NAME = "id"; + public static final String RESPONSE_ID_ATTRIBUTE_NAME = "resourceId"; + public static final String SUBRESPONSE_ID_ATTRIBUTE_NAME = "subResourceId"; + public static final String CODE_NAME_ATTRIBUTE_NAME = "name"; + public static final String CODE_SYSTEM_DEFINED_ATTRIBUTE_NAME = "systemDefined"; + public static final String CODE_URL = "/fineract-provider/api/v1/codes"; - public static final String CODE_VALUE_ID_ATTRIBUTE_NAME = "id"; - public static final String CODE_VALUE_NAME_ATTRIBUTE_NAME = "name"; - public static final String CODE_VALUE_DESCRIPTION_ATTRIBUTE_NAME = "description"; - 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 final String CODE_VALUE_ID_ATTRIBUTE_NAME = "id"; + public static final String CODE_VALUE_NAME_ATTRIBUTE_NAME = "name"; + public static final String CODE_VALUE_DESCRIPTION_ATTRIBUTE_NAME = "description"; + 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, - final String jsonAttributeToGetback) { + 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), - jsonAttributeToGetback); - } + 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, - final String codeName, final String jsonAttributeToGetback) { + 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, - getTestCodeAsJSON(codeName), jsonAttributeToGetback); - } + 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, - final String jsonAttributeToGetback) { + 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, - jsonAttributeToGetback); + 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<>(); + final HashMap code = new HashMap<>(); - ArrayList> getAllCodes = CodeHelper - .getAllCodes(requestSpec, responseSpec); - for (HashMap map : getAllCodes) { - String name = (String) map.get("name"); - if (name.equals(codeName)) { - code.put("id", map.get("id")); - code.put("name", map.get("name")); - code.put("systemDefined", map.get("systemDefined")); - break; - } - } - return code; - } + ArrayList> getAllCodes = CodeHelper + .getAllCodes(requestSpec, responseSpec); + for (HashMap map : getAllCodes) { + String name = (String) map.get("name"); + if (name.equals(codeName)) { + code.put("id", map.get("id")); + code.put("name", map.get("name")); + code.put("systemDefined", map.get("systemDefined")); + break; + } + } + return code; + } - public static HashMap retrieveOrCreateCodeValue( - Integer codeId, final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - Integer codeValueId = null; - 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, - "subResourceId"); - - } else { - return codeValuesList.get(0); - } - return Utils.performServerGet(requestSpec, responseSpec, - CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" - + codeValueId.toString() + "?" - + Utils.TENANT_IDENTIFIER, ""); - - } + public static HashMap retrieveOrCreateCodeValue( + Integer codeId, final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { + Integer codeValueId = null; + 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, + "subResourceId"); + + } else { + return codeValuesList.get(0); + } + return Utils.performServerGet(requestSpec, responseSpec, + CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" + + codeValueId.toString() + "?" + + Utils.TENANT_IDENTIFIER, ""); + + } - public static ArrayList> getAllCodes( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + 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); + final JsonPath getResponseJsonPath = new JsonPath(getResponse); - // get any systemDefined code - return getResponseJsonPath.get("find { e -> e.systemDefined == true }"); + // get any systemDefined code + return getResponseJsonPath.get("find { e -> e.systemDefined == true }"); - } + } - public static String getTestCodeAsJSON(final String codeName) { - final HashMap map = new HashMap<>(); - map.put(CODE_NAME_ATTRIBUTE_NAME, codeName); - return new Gson().toJson(map); - } + public static String getTestCodeAsJSON(final String codeName) { + final HashMap map = new HashMap<>(); + map.put(CODE_NAME_ATTRIBUTE_NAME, codeName); + return new Gson().toJson(map); + } - 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) { - map.put(CODE_VALUE_DESCRIPTION_ATTRIBUTE_NAME, description); - } - map.put(CODE_VALUE_POSITION_ATTRIBUTE_NAME, position); - return new Gson().toJson(map); - } + 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) { + map.put(CODE_VALUE_DESCRIPTION_ATTRIBUTE_NAME, description); + } + map.put(CODE_VALUE_POSITION_ATTRIBUTE_NAME, position); + 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, - jsonAttributeToGetback); + 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) { - String description = null; - 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 Integer position, + final String jsonAttributeToGetback) { + String description = null; + 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), - jsonAttributeToGetback); - } + return Utils.performServerPost(requestSpec, responseSpec, + 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) { + 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); - - } + 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) { + 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); - } + 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); - } + return Utils.performServerDelete(requestSpec, responseSpec, + 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) { - String description = null; - 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 Integer position, final String jsonAttributeToGetback) { + String description = null; + 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, - final String 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, + final String jsonAttributeToGetback) { - return Utils.performServerPut(requestSpec, responseSpec, - CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" - + codeValueId + "?" + Utils.TENANT_IDENTIFIER, - getTestCodeValueAsJSON(codeValueName, description, position), - jsonAttributeToGetback); - } + return Utils.performServerPut(requestSpec, responseSpec, + 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/main/java/org/apache/fineract/ServerApplication.java b/fineract-provider/src/main/java/org/apache/fineract/ServerApplication.java index 9f8666624..d9fa2c866 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/ServerApplication.java +++ b/fineract-provider/src/main/java/org/apache/fineract/ServerApplication.java @@ -45,12 +45,12 @@ import org.springframework.context.annotation.Import; */ public class ServerApplication { - @Import({ DataSourceConfiguration.class, EmbeddedTomcatWithSSLConfiguration.class }) - private static class Configuration extends AbstractApplicationConfiguration { } + @Import({ DataSourceConfiguration.class, EmbeddedTomcatWithSSLConfiguration.class }) + private static class Configuration extends AbstractApplicationConfiguration { } - public static void main(String[] args) throws Exception { - ConfigurableApplicationContext ctx = SpringApplication.run(Configuration.class, args); - ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx); - } + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext ctx = SpringApplication.run(Configuration.class, args); + ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/ServerWithMariaDB4jApplication.java b/fineract-provider/src/main/java/org/apache/fineract/ServerWithMariaDB4jApplication.java index 0ed31fd26..aa844cf77 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/ServerWithMariaDB4jApplication.java +++ b/fineract-provider/src/main/java/org/apache/fineract/ServerWithMariaDB4jApplication.java @@ -49,57 +49,57 @@ import org.springframework.core.io.Resource; public class ServerWithMariaDB4jApplication { private final static Logger logger = LoggerFactory.getLogger(ServerWithMariaDB4jApplication.class); - @Import({ MariaDB4jDataSourceConfiguration.class, EmbeddedTomcatWithSSLConfiguration.class }) - public static class Configuration extends AbstractApplicationConfiguration { } + @Import({ MariaDB4jDataSourceConfiguration.class, EmbeddedTomcatWithSSLConfiguration.class }) + public static class Configuration extends AbstractApplicationConfiguration { } - public static void main(String[] args) throws Exception { - ConfigurableApplicationContext ctx = SpringApplication.run(Configuration.class, args); - if (!Desktop.isDesktopSupported()) { - logger.info("Not going to open UI homepage in local web browser, because !Desktop.isDesktopSupported()"); + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext ctx = SpringApplication.run(Configuration.class, args); + if (!Desktop.isDesktopSupported()) { + logger.info("Not going to open UI homepage in local web browser, because !Desktop.isDesktopSupported()"); - } else { - // apps/community-app/dist/community-app/index.html - Resource distResource = ctx.getResource("file:" + System.getProperty("user.dir") + - System.getProperty("file.separator") + "apps" + - System.getProperty("file.separator") + "community-app" + - System.getProperty("file.separator") + "dist" + - System.getProperty("file.separator") + "community-app" + - System.getProperty("file.separator") + "index.html"); - URI distURI = URI.create("https://localhost:8443/fineract-provider" + - "/apps/community-app/index.html?baseApiUrl=https://localhost:8443" + - "&tenantIdentifier=default#/"); + } else { + // apps/community-app/dist/community-app/index.html + Resource distResource = ctx.getResource("file:" + System.getProperty("user.dir") + + System.getProperty("file.separator") + "apps" + + System.getProperty("file.separator") + "community-app" + + System.getProperty("file.separator") + "dist" + + System.getProperty("file.separator") + "community-app" + + System.getProperty("file.separator") + "index.html"); + URI distURI = URI.create("https://localhost:8443/fineract-provider" + + "/apps/community-app/index.html?baseApiUrl=https://localhost:8443" + + "&tenantIdentifier=default#/"); - // apps/community-app/app/index.html - Resource devResource = ctx.getResource("file:" + System.getProperty("user.dir") + - System.getProperty("file.separator") + "apps" + - System.getProperty("file.separator") + "community-app" + - System.getProperty("file.separator") + "app" + - System.getProperty("file.separator") + "index.html"); - URI devURI = URI.create("https://localhost:8443/fineract-provider" + - "/apps/community-app/app/index.html?baseApiUrl=https://localhost:8443" + - "&tenantIdentifier=default#/"); + // apps/community-app/app/index.html + Resource devResource = ctx.getResource("file:" + System.getProperty("user.dir") + + System.getProperty("file.separator") + "apps" + + System.getProperty("file.separator") + "community-app" + + System.getProperty("file.separator") + "app" + + System.getProperty("file.separator") + "index.html"); + URI devURI = URI.create("https://localhost:8443/fineract-provider" + + "/apps/community-app/app/index.html?baseApiUrl=https://localhost:8443" + + "&tenantIdentifier=default#/"); - if (distResource.exists()) { - openWebBrowser(distURI); - } else if (devResource.exists()) { - openWebBrowser(devURI); - } else { - logger.error("Cannot open Fineract UI in browser; not found: " + distResource.toString()); - } - } - - // TODO Tray Icon stuff; dig out my very own old @see https://github.com/mifos/head/tree/hudsonBuild-MIFOS-5157_Launch4j-EXE_NewDist-squash1/server-jetty/src/main/java/org/mifos/server/tray - - ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx); - } + if (distResource.exists()) { + openWebBrowser(distURI); + } else if (devResource.exists()) { + openWebBrowser(devURI); + } else { + logger.error("Cannot open Fineract UI in browser; not found: " + distResource.toString()); + } + } + + // TODO Tray Icon stuff; dig out my very own old @see https://github.com/mifos/head/tree/hudsonBuild-MIFOS-5157_Launch4j-EXE_NewDist-squash1/server-jetty/src/main/java/org/mifos/server/tray + + ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx); + } - private static void openWebBrowser(URI uri) { - try { - logger.info("Opening Fineract UI in browser: " + uri.toString()); - Desktop.getDesktop().browse(uri); - } catch (IOException e) { - logger.error("IOException when opening Fineract UI in browser: " + uri.toString(), e); - } - } + private static void openWebBrowser(URI uri) { + try { + logger.info("Opening Fineract UI in browser: " + uri.toString()); + Desktop.getDesktop().browse(uri); + } catch (IOException e) { + logger.error("IOException when opening Fineract UI in browser: " + uri.toString(), e); + } + } } 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 index f024c1cad..6524b2c42 100755 --- 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 @@ -54,9 +54,9 @@ import com.google.gson.reflect.TypeToken; 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)); + private static final Set LOAN_PERIODIC_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(accrueTillParamName, AccrualAccountingConstants.localeParamName, + AccrualAccountingConstants.dateFormatParamName)); @Autowired public AccrualAccountingDataValidator(final FromJsonHelper fromApiJsonfromApiJsonHelper) { 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 index 26cc1adb9..b34aeb2eb 100755 --- 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 @@ -246,7 +246,7 @@ public class AccountingConstants { private static List financialActivities; static { - financialActivities = new ArrayList<>(); + financialActivities = new ArrayList<>(); for (final FINANCIAL_ACTIVITY type : FINANCIAL_ACTIVITY.values()) { FinancialActivityData financialActivityData = convertToFinancialActivityData(type); financialActivities.add(financialActivityData); 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 418d0d400..040b17b7a 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"; + 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/service/FinancialActivityAccountWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountWritePlatformServiceImpl.java index c5e2e222c..5d4aa2ae6 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 @@ -82,8 +82,8 @@ public class FinancialActivityAccountWritePlatformServiceImpl implements Financi handleFinancialActivityAccountDataIntegrityIssues(command, dataIntegrityViolationException.getMostSpecificCause(), dataIntegrityViolationException); return CommandProcessingResult.empty(); }catch(final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; - handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee); + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee); return CommandProcessingResult.empty(); } } @@ -132,9 +132,9 @@ public class FinancialActivityAccountWritePlatformServiceImpl implements Financi handleFinancialActivityAccountDataIntegrityIssues(command, dataIntegrityViolationException.getMostSpecificCause(), dataIntegrityViolationException); return CommandProcessingResult.empty(); }catch(final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; - handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee); + return CommandProcessingResult.empty(); } } 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 54ec15145..173a488a5 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 @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - + package org.apache.fineract.accounting.glaccount.domain; 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 5ad06588b..fbae542b4 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 @@ -26,10 +26,10 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR * disable the gl account */ public class GLAccountDisableException extends - AbstractPlatformDomainRuleException { + AbstractPlatformDomainRuleException { - public GLAccountDisableException() { - super("error.msg.glaccount.attached.to.product", - "General Ledger Account is already attached to product."); - } + public GLAccountDisableException() { + 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/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java index e5ec48d73..3a7088af1 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 @@ -121,13 +121,13 @@ 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())) { - validateForAttachedProduct(glAccountId); - } + if (command.hasParameter(GLAccountJsonInputParams.DISABLED + .getValue()) + && command + .booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.DISABLED + .getValue())) { + validateForAttachedProduct(glAccountId); + } final Long parentId = command.longValueOfParameterNamed(GLAccountJsonInputParams.PARENT_ID.getValue()); if (glAccountId.equals(parentId)) { throw new InvalidParentGLAccountHeadException(glAccountId, parentId); } // is the glAccount valid @@ -178,17 +178,17 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount } private void validateForAttachedProduct(Long glAccountId) { - 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(); - } - } catch (EmptyResultDataAccessException e) { - } - } + 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(); + } + } catch (EmptyResultDataAccessException e) { + } + } - @Transactional + @Transactional @Override public CommandProcessingResult deleteGLAccount(final Long glAccountId) { final GLAccount glAccount = this.glAccountRepository.findById(glAccountId) 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 index 95f595717..e0774444d 100755 --- 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 @@ -145,7 +145,7 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess else if (savingsTransactionDTO.getTransactionType().isEscheat()) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, - CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL.getValue(), CASH_ACCOUNTS_FOR_SAVINGS.ESCHEAT_LIABILITY.getValue(), + CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL.getValue(), CASH_ACCOUNTS_FOR_SAVINGS.ESCHEAT_LIABILITY.getValue(), savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } /** 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 3de44d158..cef515e66 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 @@ -125,7 +125,7 @@ public class CashBasedAccountingProcessorForShares implements AccountingProcesso transactionId, transactionDate, amount); }else{ - this.helper.createJournalEntriesForShares(office, currencyCode, CASH_ACCOUNTS_FOR_SHARES.SHARES_SUSPENSE.getValue(), + this.helper.createJournalEntriesForShares(office, currencyCode, CASH_ACCOUNTS_FOR_SHARES.SHARES_SUSPENSE.getValue(), CASH_ACCOUNTS_FOR_SHARES.SHARES_REFERENCE.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount); } 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 index 3a539b628..dccd7cb40 100755 --- 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 @@ -138,7 +138,7 @@ 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")); } @@ -168,7 +168,7 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry ArrayList updateSql = new ArrayList<>(); int batchIndex = 0; for (int index = 0 ; index < entryDatas.size() ; index++) { - JournalEntryData entryData = entryDatas.get(index) ; + JournalEntryData entryData = entryDatas.get(index) ; Map officeRunningBalanceMap = null; if (officesRunningBalance.containsKey(entryData.getOfficeId())) { officeRunningBalanceMap = officesRunningBalance.get(entryData.getOfficeId()); @@ -184,8 +184,8 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry 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; 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 index 7b301e181..8fc62d975 100755 --- 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 @@ -249,9 +249,9 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa } } } - if (credits.length != validCredits.length) { - throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.credits", "Invalid Credits."); - } + if (credits.length != validCredits.length) { + throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.credits", "Invalid Credits."); + } } if (debits != null && debits.length > 0) { @@ -264,11 +264,11 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa validDebits[i] = debit; } } - } - if (debits.length != validDebits.length) { - throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.debits","Invalid Debits"); - } - } + } + if (debits.length != validDebits.length) { + throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.debits","Invalid Debits"); + } + } } private void checkDebitAndCreditAmounts(final SingleDebitOrCreditEntryCommand[] credits, final SingleDebitOrCreditEntryCommand[] debits) { 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 e5bd31168..4fb845921 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 @@ -68,8 +68,8 @@ 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 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 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 042a1876c..21ba3bc64 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 @@ -95,50 +95,50 @@ public class LoanProductProvisioningEntry extends AbstractPersistableCustom, 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); 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 43067fb8a..74492432b 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 @@ -46,8 +46,8 @@ import com.google.gson.reflect.TypeToken; public class ProvisioningEntriesDefinitionJsonDeserializer implements ProvisioningEntriesApiConstants { private final FromJsonHelper fromApiJsonHelper; - private static final Set supportedParameters = new HashSet<>( - Arrays.asList(JSON_DATE_PARAM, JSON_DATEFORMAT_PARAM, JSON_LOCALE_PARAM, JSON_CREATEJOURNALENTRIES_PARAM)); + private static final Set supportedParameters = new HashSet<>( + Arrays.asList(JSON_DATE_PARAM, JSON_DATEFORMAT_PARAM, JSON_LOCALE_PARAM, JSON_CREATEJOURNALENTRIES_PARAM)); @Autowired 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 09e018740..2fbc7ccf4 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 @@ -87,7 +87,7 @@ public class AdHocApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAll(@Context final UriInfo uriInfo) { - + this.context.authenticatedUser(); final Collection adhocs = this.adHocReadPlatformService.retrieveAllAdHocQuery(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); 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 81cfc9199..f0b217469 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 @@ -34,31 +34,31 @@ public class AdHocData { - @SuppressWarnings("unused") + @SuppressWarnings("unused") private final Long id; @SuppressWarnings("unused") private final String name; - @SuppressWarnings("unused") + @SuppressWarnings("unused") private final String query; - @SuppressWarnings("unused") + @SuppressWarnings("unused") private final String tableName; - @SuppressWarnings("unused") + @SuppressWarnings("unused") private final String tableFields; - @SuppressWarnings("unused") - private final String email; - @SuppressWarnings("unused") + @SuppressWarnings("unused") + private final String email; + @SuppressWarnings("unused") private final boolean isActive; - @SuppressWarnings("unused") + @SuppressWarnings("unused") private final DateTime createdOn; - @SuppressWarnings("unused") - private final Long createdById; - @SuppressWarnings("unused") + @SuppressWarnings("unused") + private final Long createdById; + @SuppressWarnings("unused") private final Long updatedById; - @SuppressWarnings("unused") + @SuppressWarnings("unused") private final DateTime updatedOn; - @SuppressWarnings("unused") - private final String createdBy; - + @SuppressWarnings("unused") + private final String createdBy; + private final List reportRunFrequencies; private final Long reportRunFrequency; @@ -84,65 +84,65 @@ public class AdHocData { this.updatedOn=updatedOn; this.createdBy=createdBy; this.email=email; - this.reportRunFrequencies = reportRunFrequencies; - this.reportRunFrequency = reportRunFrequency; - this.reportRunEvery = reportRunEvery; - this.lastRun = lastRun; + 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( - (long) rrf.getValue(), rrf.getCode(), rrf.getCode() - )).collect(Collectors.toList()); + List reportRunFrequencies = Arrays.stream(ReportRunFrequency.values()).map(rrf -> new EnumOptionData( + (long) 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; + 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; - } + 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; + } } \ No newline at end of file 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 54f98f37d..fab80d313 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 @@ -38,19 +38,19 @@ import org.apache.fineract.useradministration.domain.AppUser; @Table(name = "m_adhoc") public class AdHoc extends AbstractAuditableCustom { - @Column(name = "name", length = 100) + @Column(name = "name", length = 100) private String name; @Column(name = "query", length = 2000) private String query; - + @Column(name = "table_name", length = 100) private String tableName; @Column(name = "table_fields", length = 2000) private String tableFields; - + @Column(name = "email", length = 500) private String email; @@ -60,9 +60,9 @@ public class AdHoc extends AbstractAuditableCustom { @Column(name = "report_run_every") private Long reportRunEvery; - @Column(name = "IsActive", nullable = false) + @Column(name = "IsActive", nullable = false) private boolean isActive = false; - + 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); @@ -139,7 +139,7 @@ public class AdHoc extends AbstractAuditableCustom { } final String paramisActive = "isActive"; if (command.isChangeInBooleanParameterNamed(paramisActive, this.isActive)) { - final Boolean newValue = command.booleanObjectValueOfParameterNamed(paramisActive); + final Boolean newValue = command.booleanObjectValueOfParameterNamed(paramisActive); actualChanges.put(paramisActive, newValue); this.isActive = newValue; } @@ -147,28 +147,28 @@ 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; - } + 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 String getEmail() { + return email; + } public void disableActive() { this.isActive = true; } public void enableActive() { - this.isActive = false; + this.isActive = false; } public Long getReportRunFrequency() { return this.reportRunFrequency; 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 c5c7a0af6..996554dba 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 @@ -98,16 +98,16 @@ public class AdHocReadPlatformServiceImpl implements AdHocReadPlatformService { public String schema() { return " r.id as id, r.name as name, r.query as query, r.table_name as tableName,r.table_fields as tableField ,r.IsActive as isActive ,r.email as email ," + " r.report_run_frequency_code, r.report_run_every, r.last_run, " - + " r.created_date as createdDate, r.createdby_id as createdById,cb.username as createdBy,r.lastmodifiedby_id as updatedById ,r.lastmodified_date as updatedOn " + + " r.created_date as createdDate, r.createdby_id as createdById,cb.username as createdBy,r.lastmodifiedby_id as updatedById ,r.lastmodified_date as updatedOn " + " from m_adhoc r left join m_appuser cb on cb.id=r.createdby_id left join m_appuser mb on mb.id=r.lastmodifiedby_id"; - + } } - @Override - public AdHocData retrieveNewAdHocDetails() { - return AdHocData.template(); - } + @Override + public AdHocData retrieveNewAdHocDetails() { + return AdHocData.template(); + } } \ No newline at end of file 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 c92121c98..728c33d45 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 @@ -48,9 +48,9 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn @Autowired public AdHocScheduledJobRunnerServiceImpl(final RoutingDataSource dataSource, - final AdHocReadPlatformService adHocReadPlatformService + final AdHocReadPlatformService adHocReadPlatformService ) { - this.jdbcTemplate = new JdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.adHocReadPlatformService = adHocReadPlatformService; } @@ -59,12 +59,12 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn @Override @CronTarget(jobName = JobName.GENERATE_ADHOCCLIENT_SCEHDULE) public void generateClientSchedule() { - final Collection adhocs = this.adHocReadPlatformService.retrieveAllActiveAdHocQuery(); + final Collection adhocs = this.adHocReadPlatformService.retrieveAllActiveAdHocQuery(); if(adhocs.size()>0){ - adhocs.forEach(adhoc->{ - boolean run = true; + adhocs.forEach(adhoc->{ + boolean run = true; LocalDate next = null; - if (adhoc.getReportRunFrequency() != null) { + if (adhoc.getReportRunFrequency() != null) { if (adhoc.getLastRun() != null) { LocalDate start = adhoc.getLastRun().toLocalDate(); LocalDate end = new DateTime().toLocalDate(); @@ -113,9 +113,9 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn } else { logger.info(ThreadLocalContextUtil.getTenant().getName() + ": Skipping execution of " + adhoc.getName() + ", scheduled for execution on " + next); } - }); + }); }else{ - logger.info(ThreadLocalContextUtil.getTenant().getName() + "Nothing to update "); + logger.info(ThreadLocalContextUtil.getTenant().getName() + "Nothing to update "); } 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 9d13c163f..f1e52fe21 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 @@ -22,8 +22,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class ClientDetailsNotFoundException extends AbstractPlatformDomainRuleException{ - public ClientDetailsNotFoundException() { - super("validation.msg.batch.jlg.no.clients.defined", "No Client details found", ""); - } + 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 f88d955f0..0730d84d1 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 @@ -70,12 +70,12 @@ public class ErrorHandler extends RuntimeException { */ public static ErrorInfo handler(final RuntimeException exception) { - if(exception instanceof AbstractPlatformDomainRuleException) { - PlatformDomainRuleExceptionMapper mapper = new PlatformDomainRuleExceptionMapper() ; - final String errorBody = jsonHelper + 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) { + return new ErrorInfo(500, 9999, errorBody); + }else if (exception instanceof AbstractPlatformResourceNotFoundException) { final PlatformResourceNotFoundExceptionMapper mapper = new PlatformResourceNotFoundExceptionMapper(); final String errorBody = jsonHelper @@ -128,7 +128,7 @@ public class ErrorHandler extends RuntimeException { return new ErrorInfo(500, 5001, errorBody); }else if(exception instanceof NonTransientDataAccessException) { - return new ErrorInfo(400, 4001, "{\"Exception\": " + exception.getMessage()+"}"); + 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/service/BatchApiServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/batch/service/BatchApiServiceImpl.java index 2ca9950c5..a5be4d12c 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 @@ -95,8 +95,8 @@ public class BatchApiServiceImpl implements BatchApiService { final List batchRequestNodes = this.resolutionHelper.getDependingRequests(requestList); if(batchRequestNodes.isEmpty()) { - final BatchResponse response = new BatchResponse(); - ErrorInfo ex = ErrorHandler.handler(new ClientDetailsNotFoundException()); + final BatchResponse response = new BatchResponse(); + ErrorInfo ex = ErrorHandler.handler(new ClientDetailsNotFoundException()); response.setStatusCode(500); response.setBody(ex.getMessage()); responseList.add(response) ; @@ -222,7 +222,7 @@ public class BatchApiServiceImpl implements BatchApiService { return errResponseList; }catch (final NonTransientDataAccessException ex) { - ErrorInfo e = ErrorHandler.handler(ex); + ErrorInfo e = ErrorHandler.handler(ex); BatchResponse errResponse = new BatchResponse(); errResponse.setStatusCode(e.getStatusCode()); 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 index 447fbb565..c30899801 100755 --- 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 @@ -274,7 +274,7 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { } sql += extraCriteria; if(isExtraCritereaIncluded){ - this.columnValidator.validateSqlInjection(sql, extraCriteria); + this.columnValidator.validateSqlInjection(sql, extraCriteria); } logger.info("sql: " + sql); 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 index eb3fe6dce..daee0818e 100755 --- 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 @@ -2836,31 +2836,31 @@ public class CommandWrapperBuilder { return this; } - public CommandWrapperBuilder addSelfServiceBeneficiaryTPT() { + public CommandWrapperBuilder addSelfServiceBeneficiaryTPT() { this.actionName = "CREATE"; this.entityName = "SSBENEFICIARYTPT"; this.entityId = null; this.href = "/self/beneficiaries/tpt"; return this; - } + } - public CommandWrapperBuilder updateSelfServiceBeneficiaryTPT(final Long beneficiaryId) { + public CommandWrapperBuilder updateSelfServiceBeneficiaryTPT(final Long beneficiaryId) { this.actionName = "UPDATE"; this.entityName = "SSBENEFICIARYTPT"; this.entityId = beneficiaryId; this.href = "/self/beneficiaries/tpt/"+beneficiaryId; return this; - } + } - public CommandWrapperBuilder deleteSelfServiceBeneficiaryTPT(final Long beneficiaryId) { + public CommandWrapperBuilder deleteSelfServiceBeneficiaryTPT(final Long beneficiaryId) { this.actionName = "DELETE"; this.entityName = "SSBENEFICIARYTPT"; this.entityId = beneficiaryId; this.href = "/self/beneficiaries/tpt/"+beneficiaryId; return this; - } + } - public CommandWrapperBuilder createReportMailingJob(final String entityName) { + public CommandWrapperBuilder createReportMailingJob(final String entityName) { this.actionName = "CREATE"; this.entityName = entityName; this.entityId = null; @@ -3003,7 +3003,7 @@ public class CommandWrapperBuilder { this.href = "/savingsaccounts/" + accountId + "?command=unblock"; return this; } - public CommandWrapperBuilder disableAdHoc(Long adHocId) { + public CommandWrapperBuilder disableAdHoc(Long adHocId) { this.actionName = "DISABLE"; this.entityName = "ADHOC"; this.entityId = adHocId; 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 c7294af8e..1227e377c 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 @@ -66,10 +66,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, @@ -98,8 +98,8 @@ 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 @@ -115,8 +115,8 @@ 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 @@ -139,8 +139,8 @@ public class AccountNumberFormatsApiResource { 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 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 a9b90f750..da719a244 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 @@ -49,8 +49,8 @@ public class AccountNumberFormatDataValidator { 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)); + private static final Set ACCOUNT_NUMBER_FORMAT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(AccountNumberFormatConstants.prefixTypeParamName)); @Autowired public AccountNumberFormatDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -61,8 +61,8 @@ 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<>(); @@ -105,31 +105,31 @@ public class AccountNumberFormatDataValidator { } - public Set determineValidAccountNumberPrefixes( - EntityAccountType entityAccountType) { - Set validAccountNumberPrefixes = new HashSet<>(); + public Set determineValidAccountNumberPrefixes( + EntityAccountType entityAccountType) { + Set validAccountNumberPrefixes = new HashSet<>(); - switch (entityAccountType) { - case CLIENT: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForClientAccounts; - break; + switch (entityAccountType) { + case CLIENT: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForClientAccounts; + break; - case LOAN: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForLoanAccounts; - break; + case LOAN: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForLoanAccounts; + break; - case SAVINGS: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForSavingsAccounts; - break; + case SAVINGS: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForSavingsAccounts; + break; - case CENTER: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForCenters; - break; - - case GROUP: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForGroups; - break; - } + case CENTER: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForCenters; + break; + + case GROUP: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForGroups; + break; + } Set validAccountNumberPrefixValues = new HashSet<>(); for (AccountNumberPrefixType validAccountNumberPrefix : validAccountNumberPrefixes) { @@ -143,8 +143,8 @@ 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<>(); 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 2ba4784e5..47835f3d3 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 @@ -92,11 +92,11 @@ public enum EntityAccountType { } public Boolean isCenterAccount(){ - return this.value.equals(EntityAccountType.CENTER.getValue()); + return this.value.equals(EntityAccountType.CENTER.getValue()); } public Boolean isGroupAccount(){ - return this.value.equals(EntityAccountType.GROUP.getValue()); + return this.value.equals(EntityAccountType.GROUP.getValue()); } } 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 31fe1b2c0..98e39d317 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 @@ -80,9 +80,9 @@ public class AccountNumberFormatWritePlatformServiceJpaRepositoryImpl implements handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; - handleDataIntegrityIssues(command, throwable, ee); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + handleDataIntegrityIssues(command, throwable, ee); + return CommandProcessingResult.empty(); } } @@ -120,9 +120,9 @@ public class AccountNumberFormatWritePlatformServiceJpaRepositoryImpl implements handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); } catch (final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; - handleDataIntegrityIssues(command, throwable, ee); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + handleDataIntegrityIssues(command, throwable, ee); + return CommandProcessingResult.empty(); } } 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 1e794ed34..a451f5cce 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 @@ -126,7 +126,7 @@ public class ImportHandlerUtils { public static String trimEmptyDecimalPortion(String result) { if(result != null && result.endsWith(".0")) - return result.split("\\.")[0]; + return result.split("\\.")[0]; else return result; } 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 28ab011df..c02608312 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 @@ -177,9 +177,9 @@ public class ClientEntityImportHandler implements ImportHandler { 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); - } + 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); 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 1e828c102..c2f7ec485 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 @@ -163,10 +163,10 @@ public class ClientPersonImportHandler implements ImportHandler { 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, clientClassicationId, isStaff, - addressList, locale, dateFormat); + officeId, staffId, mobileNo, dob, clientTypeId, genderId, clientClassicationId, isStaff, + addressList, locale, dateFormat); - } + } public Count importEntity(String dateFormat) { Sheet clientSheet=workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME); 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 731390bbc..7d9d9e062 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 @@ -88,8 +88,8 @@ public abstract class AbstractWorkbookPopulator implements WorkbookPopulator { } protected void writeBigDecimal(int colIndex, Row row, BigDecimal value) { - row.createCell(colIndex).setCellValue(((value != null) ? value.doubleValue() : 0)); - } + row.createCell(colIndex).setCellValue(((value != null) ? value.doubleValue() : 0)); + } protected void setOfficeDateLookupTable(Sheet sheet, List offices, int officeNameCol, int activationDateCol,String dateFormat) { @@ -142,23 +142,23 @@ public abstract class AbstractWorkbookPopulator implements WorkbookPopulator { } } - if (groups != null) { - for (GroupGeneralData group : groups) { - Row row = sheet.getRow(++rowIndex); - if (row == null) - row = sheet.createRow(rowIndex); - writeString(nameCol, row, group.getName().replaceAll("[ )(] ", "_")); + if (groups != null) { + for (GroupGeneralData group : groups) { + Row row = sheet.getRow(++rowIndex); + if (row == null) + row = sheet.createRow(rowIndex); + writeString(nameCol, row, group.getName().replaceAll("[ )(] ", "_")); - if (group.getActivationDate() != null) { - date = inputFormat.parse(group.getActivationDate().toString()); - writeDate(activationDateCol, row, outputFormat.format(date), dateCellStyle, dateFormat); - } + if (group.getActivationDate() != null) { + date = inputFormat.parse(group.getActivationDate().toString()); + writeDate(activationDateCol, row, outputFormat.format(date), dateCellStyle, dateFormat); + } - } - } + } + } } catch (ParseException e) { e.printStackTrace(); } - } + } } \ No newline at end of file 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 bf828b403..4c86da1ef 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 @@ -31,93 +31,93 @@ import java.util.List; import java.util.Map; public class CenterSheetPopulator extends AbstractWorkbookPopulator { - private List allCenters; - private List offices; + private List allCenters; + private List offices; - private Map> officeToCenters; - private Map officeNameToBeginEndIndexesOfCenters; - private Map centerNameToCenterId; + private Map> officeToCenters; + private Map officeNameToBeginEndIndexesOfCenters; + private Map centerNameToCenterId; - private static final int OFFICE_NAME_COL = 0; - private static final int CENTER_NAME_COL = 1; - private static final int CENTER_ID_COL = 2; + private static final int OFFICE_NAME_COL = 0; + private static final int CENTER_NAME_COL = 1; + private static final int CENTER_ID_COL = 2; - public CenterSheetPopulator(List centers, List offices) { - this.allCenters = centers; - this.offices = offices; - } + public CenterSheetPopulator(List centers, List offices) { + this.allCenters = centers; + this.offices = offices; + } - @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet centerSheet = workbook.createSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME); - setLayout(centerSheet); - setOfficeToCentersMap(); - centerNameToCenterIdMap(); - populateCentersByOfficeName(centerSheet); - centerSheet.protectSheet(""); - } + @Override + public void populate(Workbook workbook,String dateFormat) { + Sheet centerSheet = workbook.createSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME); + setLayout(centerSheet); + setOfficeToCentersMap(); + centerNameToCenterIdMap(); + populateCentersByOfficeName(centerSheet); + centerSheet.protectSheet(""); + } - private void centerNameToCenterIdMap() { - centerNameToCenterId = new HashMap(); - for (CenterData centerData : allCenters) { - centerNameToCenterId.put(centerData.getName(), centerData.getId()); - } - } + private void centerNameToCenterIdMap() { + centerNameToCenterId = new HashMap(); + for (CenterData centerData : allCenters) { + centerNameToCenterId.put(centerData.getName(), centerData.getId()); + } + } - private void populateCentersByOfficeName(Sheet centerSheet) { - int rowIndex = 1, officeIndex = 0, startIndex = 1; - officeNameToBeginEndIndexesOfCenters = new HashMap(); - Row row = centerSheet.createRow(rowIndex); - for (OfficeData office : offices) { - startIndex = rowIndex + 1; - writeString(OFFICE_NAME_COL, row, office.name()); - ArrayList centersList = new ArrayList(); + private void populateCentersByOfficeName(Sheet centerSheet) { + int rowIndex = 1, officeIndex = 0, startIndex = 1; + officeNameToBeginEndIndexesOfCenters = new HashMap(); + Row row = centerSheet.createRow(rowIndex); + for (OfficeData office : offices) { + startIndex = rowIndex + 1; + writeString(OFFICE_NAME_COL, row, office.name()); + ArrayList centersList = new ArrayList(); - 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); - } - officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex }); - } else { - officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex + 1 }); - } - } - } - } + 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); + } + officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex }); + } else { + officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex + 1 }); + } + } + } + } - private void setLayout(Sheet worksheet) { - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - for (int colIndex = 0; colIndex <= 10; colIndex++) - worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - writeString(OFFICE_NAME_COL, rowHeader, "Office Names"); - writeString(CENTER_NAME_COL, rowHeader, "Center Names"); - writeString(CENTER_ID_COL, rowHeader, "Center ID"); - } + private void setLayout(Sheet worksheet) { + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + for (int colIndex = 0; colIndex <= 10; colIndex++) + worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + writeString(OFFICE_NAME_COL, rowHeader, "Office Names"); + writeString(CENTER_NAME_COL, rowHeader, "Center Names"); + writeString(CENTER_ID_COL, rowHeader, "Center ID"); + } - private void setOfficeToCentersMap() { - officeToCenters = new HashMap<>(); - for (CenterData center : allCenters) { - add(center.getOfficeName().trim().replaceAll("[ )(]", "_"), center.getName().trim()); - } - } + private void setOfficeToCentersMap() { + officeToCenters = new HashMap<>(); + for (CenterData center : allCenters) { + add(center.getOfficeName().trim().replaceAll("[ )(]", "_"), center.getName().trim()); + } + } - // Guava Multi-map can reduce this. - private void add(String key, String value) { - ArrayList values = officeToCenters.get(key); - if (values == null) { - values = new ArrayList<>(); - } - values.add(value); - officeToCenters.put(key, values); - } + // Guava Multi-map can reduce this. + private void add(String key, String value) { + ArrayList values = officeToCenters.get(key); + if (values == null) { + values = new ArrayList<>(); + } + values.add(value); + officeToCenters.put(key, values); + } - public Map getOfficeNameToBeginEndIndexesOfCenters() { - return officeNameToBeginEndIndexesOfCenters; - } + public Map getOfficeNameToBeginEndIndexesOfCenters() { + return officeNameToBeginEndIndexesOfCenters; + } } \ No newline at end of file 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 69c4ba4d8..18d1567b7 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 @@ -31,114 +31,114 @@ import java.util.List; import java.util.Map; public class ClientSheetPopulator extends AbstractWorkbookPopulator { - private List allClients; - private List officesDataList; + private List allClients; + private List officesDataList; - private Map> officeToClients; - private Map officeNameToBeginEndIndexesOfClients; - private Map clientNameToClientId; - private Map clientNameToSavingsAccountIds; + private Map> officeToClients; + private Map officeNameToBeginEndIndexesOfClients; + private Map clientNameToClientId; + private Map clientNameToSavingsAccountIds; - private static final int OFFICE_NAME_COL = 0; - private static final int CLIENT_NAME_COL = 1; - private static final int CLIENT_ID_COL = 2; + private static final int OFFICE_NAME_COL = 0; + private static final int CLIENT_NAME_COL = 1; + private static final int CLIENT_ID_COL = 2; - public ClientSheetPopulator(final List clients, final List Offices) { - this.allClients = clients; - this.officesDataList = Offices; - } + public ClientSheetPopulator(final List clients, final List Offices) { + this.allClients = clients; + this.officesDataList = Offices; + } - @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet clientSheet = workbook.createSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME); - setLayout(clientSheet); - setOfficeToClientsMap(); - setClientNameToClientIdMap(); - populateClientsByOfficeName(clientSheet); - clientSheet.protectSheet(""); - setClientNameToSavingsAccountsIdsMap(); - } + @Override + public void populate(Workbook workbook,String dateFormat) { + Sheet clientSheet = workbook.createSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME); + setLayout(clientSheet); + setOfficeToClientsMap(); + setClientNameToClientIdMap(); + populateClientsByOfficeName(clientSheet); + clientSheet.protectSheet(""); + setClientNameToSavingsAccountsIdsMap(); + } - private void setClientNameToClientIdMap() { - clientNameToClientId = new HashMap<>(); - for (ClientData clientData : allClients) { - clientNameToClientId.put(clientData.displayName().trim() + "(" + clientData.id() + ")", - clientData.id()); - } - } + private void setClientNameToClientIdMap() { + clientNameToClientId = new HashMap<>(); + for (ClientData clientData : allClients) { + clientNameToClientId.put(clientData.displayName().trim() + "(" + clientData.id() + ")", + clientData.id()); + } + } - private void setLayout(Sheet worksheet) { - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - worksheet.setColumnWidth(OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - for (int colIndex = 1; colIndex <= 10; colIndex++) - worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - writeString(OFFICE_NAME_COL, rowHeader, "Office Names"); - writeString(CLIENT_NAME_COL, rowHeader, "Client Names"); - writeString(CLIENT_ID_COL, rowHeader, "Client ID"); - } + private void setLayout(Sheet worksheet) { + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + worksheet.setColumnWidth(OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + for (int colIndex = 1; colIndex <= 10; colIndex++) + worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + writeString(OFFICE_NAME_COL, rowHeader, "Office Names"); + writeString(CLIENT_NAME_COL, rowHeader, "Client Names"); + writeString(CLIENT_ID_COL, rowHeader, "Client ID"); + } - private void setOfficeToClientsMap() { - officeToClients = new HashMap<>(); - for (ClientData person : allClients) { - addToOfficeClientMap(person.getOfficeName().trim().replaceAll("[ )(]", "_"), - person.displayName().trim() + "(" + person.id() + ")"); - } - } + private void setOfficeToClientsMap() { + officeToClients = new HashMap<>(); + for (ClientData person : allClients) { + addToOfficeClientMap(person.getOfficeName().trim().replaceAll("[ )(]", "_"), + person.displayName().trim() + "(" + person.id() + ")"); + } + } - 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()); + } - } + } - // Guava Multi-map can reduce this. - private void addToOfficeClientMap(String key, String value) { - ArrayList values = officeToClients.get(key); - if (values == null) { - values = new ArrayList(); - } - values.add(value); - officeToClients.put(key, values); - } + // Guava Multi-map can reduce this. + private void addToOfficeClientMap(String key, String value) { + ArrayList values = officeToClients.get(key); + if (values == null) { + values = new ArrayList(); + } + values.add(value); + officeToClients.put(key, values); + } - private void populateClientsByOfficeName(Sheet clientSheet) { - int rowIndex = 1, startIndex = 1, officeIndex = 0; - officeNameToBeginEndIndexesOfClients = new HashMap<>(); - Row row = clientSheet.createRow(rowIndex); - for (OfficeData office : officesDataList) { - startIndex = rowIndex + 1; - writeString(OFFICE_NAME_COL, row, office.name()); - ArrayList clientList = new ArrayList(); - if (officeToClients.containsKey(office.name().trim().replaceAll("[ )(]", "_"))) - clientList = officeToClients.get(office.name().trim().replaceAll("[ )(]", "_")); - if (!clientList.isEmpty()) { - for (String clientName : clientList) { - writeString(CLIENT_NAME_COL, row, clientName); - writeLong(CLIENT_ID_COL, row, clientNameToClientId.get(clientName)); - row = clientSheet.createRow(++rowIndex); - } - officeNameToBeginEndIndexesOfClients.put(officeIndex++, new Integer[] { startIndex, rowIndex }); - } else - officeIndex++; - } - } + private void populateClientsByOfficeName(Sheet clientSheet) { + int rowIndex = 1, startIndex = 1, officeIndex = 0; + officeNameToBeginEndIndexesOfClients = new HashMap<>(); + Row row = clientSheet.createRow(rowIndex); + for (OfficeData office : officesDataList) { + startIndex = rowIndex + 1; + writeString(OFFICE_NAME_COL, row, office.name()); + ArrayList clientList = new ArrayList(); + if (officeToClients.containsKey(office.name().trim().replaceAll("[ )(]", "_"))) + clientList = officeToClients.get(office.name().trim().replaceAll("[ )(]", "_")); + if (!clientList.isEmpty()) { + for (String clientName : clientList) { + writeString(CLIENT_NAME_COL, row, clientName); + writeLong(CLIENT_ID_COL, row, clientNameToClientId.get(clientName)); + row = clientSheet.createRow(++rowIndex); + } + officeNameToBeginEndIndexesOfClients.put(officeIndex++, new Integer[] { startIndex, rowIndex }); + } else + officeIndex++; + } + } - public List getClients() { - return allClients; - } + public List getClients() { + return allClients; + } - public Integer getClientsSize() { - return allClients.size(); - } + public Integer getClientsSize() { + return allClients.size(); + } - public Map getOfficeNameToBeginEndIndexesOfClients() { - return officeNameToBeginEndIndexesOfClients; - } + public Map getOfficeNameToBeginEndIndexesOfClients() { + return officeNameToBeginEndIndexesOfClients; + } - public Map getClientNameToSavingsAccountIds() { - return clientNameToSavingsAccountIds; - } + public Map getClientNameToSavingsAccountIds() { + return clientNameToSavingsAccountIds; + } } \ No newline at end of file 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 e97eb7aeb..2da7881da 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 @@ -30,87 +30,87 @@ import java.util.List; public class ExtrasSheetPopulator extends AbstractWorkbookPopulator { - private List funds; - private List paymentTypes; - private List currencies; + private List funds; + private List paymentTypes; + private List currencies; - private static final int FUND_ID_COL = 0; - private static final int FUND_NAME_COL = 1; - private static final int PAYMENT_TYPE_ID_COL = 2; - private static final int PAYMENT_TYPE_NAME_COL = 3; - private static final int CURRENCY_CODE_COL = 4; - private static final int CURRENCY_NAME_COL = 5; + private static final int FUND_ID_COL = 0; + private static final int FUND_NAME_COL = 1; + private static final int PAYMENT_TYPE_ID_COL = 2; + private static final int PAYMENT_TYPE_NAME_COL = 3; + private static final int CURRENCY_CODE_COL = 4; + private static final int CURRENCY_NAME_COL = 5; - - public ExtrasSheetPopulator(List funds, List paymentTypes, - List currencies) { - this.funds = funds; - this.paymentTypes = paymentTypes; - this.currencies = 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) { - int fundRowIndex = 1; - Sheet extrasSheet = workbook.createSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME); - setLayout(extrasSheet); - for (FundData fund : funds) { - Row row = extrasSheet.createRow(fundRowIndex++); - writeLong(FUND_ID_COL, row, fund.getId()); - writeString(FUND_NAME_COL, row, fund.getName()); - } - int paymentTypeRowIndex = 1; - for (PaymentTypeData paymentType : paymentTypes) { - Row row; - if (paymentTypeRowIndex < fundRowIndex) - row = extrasSheet.getRow(paymentTypeRowIndex++); - else - row = extrasSheet.createRow(paymentTypeRowIndex++); - writeLong(PAYMENT_TYPE_ID_COL, row, paymentType.getId()); - writeString(PAYMENT_TYPE_NAME_COL, row, paymentType.getName().trim().replaceAll("[ )(]", "_")); - } - int currencyCodeRowIndex = 1; - for (CurrencyData currencies : currencies) { - Row row; - if (currencyCodeRowIndex < paymentTypeRowIndex) - row = extrasSheet.getRow(currencyCodeRowIndex++); - else - row = extrasSheet.createRow(currencyCodeRowIndex++); + @Override + public void populate(Workbook workbook,String dateFormat) { + int fundRowIndex = 1; + Sheet extrasSheet = workbook.createSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME); + setLayout(extrasSheet); + for (FundData fund : funds) { + Row row = extrasSheet.createRow(fundRowIndex++); + writeLong(FUND_ID_COL, row, fund.getId()); + writeString(FUND_NAME_COL, row, fund.getName()); + } + int paymentTypeRowIndex = 1; + for (PaymentTypeData paymentType : paymentTypes) { + Row row; + if (paymentTypeRowIndex < fundRowIndex) + row = extrasSheet.getRow(paymentTypeRowIndex++); + else + row = extrasSheet.createRow(paymentTypeRowIndex++); + writeLong(PAYMENT_TYPE_ID_COL, row, paymentType.getId()); + writeString(PAYMENT_TYPE_NAME_COL, row, paymentType.getName().trim().replaceAll("[ )(]", "_")); + } + int currencyCodeRowIndex = 1; + for (CurrencyData currencies : currencies) { + Row row; + if (currencyCodeRowIndex < paymentTypeRowIndex) + row = extrasSheet.getRow(currencyCodeRowIndex++); + else + row = extrasSheet.createRow(currencyCodeRowIndex++); - writeString(CURRENCY_NAME_COL, row, currencies.getName().trim().replaceAll("[ )(]", "_")); - writeString(CURRENCY_CODE_COL, row, currencies.code()); - } - extrasSheet.protectSheet(""); + writeString(CURRENCY_NAME_COL, row, currencies.getName().trim().replaceAll("[ )(]", "_")); + writeString(CURRENCY_CODE_COL, row, currencies.code()); + } + extrasSheet.protectSheet(""); - } + } - private void setLayout(Sheet worksheet) { - worksheet.setColumnWidth(FUND_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(FUND_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(PAYMENT_TYPE_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(PAYMENT_TYPE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(CURRENCY_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(CURRENCY_CODE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - writeString(FUND_ID_COL, rowHeader, "Fund ID"); - writeString(FUND_NAME_COL, rowHeader, "Name"); - writeString(PAYMENT_TYPE_ID_COL, rowHeader, "Payment Type ID"); - writeString(PAYMENT_TYPE_NAME_COL, rowHeader, "Payment Type Name"); - 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(); - } + private void setLayout(Sheet worksheet) { + worksheet.setColumnWidth(FUND_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(FUND_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(PAYMENT_TYPE_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(PAYMENT_TYPE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(CURRENCY_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(CURRENCY_CODE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + writeString(FUND_ID_COL, rowHeader, "Fund ID"); + writeString(FUND_NAME_COL, rowHeader, "Name"); + writeString(PAYMENT_TYPE_ID_COL, rowHeader, "Payment Type ID"); + writeString(PAYMENT_TYPE_NAME_COL, rowHeader, "Payment Type Name"); + 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(); + } - public Integer getCurrenciesSize() { - return currencies.size(); - } + public Integer getCurrenciesSize() { + return currencies.size(); + } - - + + } \ No newline at end of file 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 04390c1af..3479703b9 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 @@ -27,45 +27,45 @@ import org.apache.poi.ss.usermodel.Workbook; import java.util.List; public class GlAccountSheetPopulator extends AbstractWorkbookPopulator { - private List allGlAccounts; + private List allGlAccounts; - private static final int ID_COL = 0; - private static final int ACCOUNT_NAME_COL = 1; + private static final int ID_COL = 0; + private static final int ACCOUNT_NAME_COL = 1; - public GlAccountSheetPopulator(List glAccounts) { - this.allGlAccounts = glAccounts; - } + public GlAccountSheetPopulator(List glAccounts) { + this.allGlAccounts = glAccounts; + } - @Override - public void populate(Workbook workbook,String dateFormat) { - int rowIndex = 1; - Sheet glAccountSheet = workbook.createSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME); - setLayout(glAccountSheet); - populateglAccounts(glAccountSheet, rowIndex); - glAccountSheet.protectSheet(""); + @Override + public void populate(Workbook workbook,String dateFormat) { + int rowIndex = 1; + Sheet glAccountSheet = workbook.createSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME); + setLayout(glAccountSheet); + populateglAccounts(glAccountSheet, rowIndex); + glAccountSheet.protectSheet(""); - } + } - private void setLayout(Sheet worksheet) { - worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ACCOUNT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - writeString(ID_COL, rowHeader, "Gl Account ID"); - writeString(ACCOUNT_NAME_COL, rowHeader, "Gl Account Name"); - } + private void setLayout(Sheet worksheet) { + worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ACCOUNT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + writeString(ID_COL, rowHeader, "Gl Account ID"); + writeString(ACCOUNT_NAME_COL, rowHeader, "Gl Account Name"); + } - private void populateglAccounts(Sheet GlAccountSheet, int rowIndex) { - for (GLAccountData glAccount : allGlAccounts) { - Row row = GlAccountSheet.createRow(rowIndex); - writeLong(ID_COL, row, glAccount.getId()); - writeString(ACCOUNT_NAME_COL, row, glAccount.getName().trim().replaceAll("[ )(]", "_")); - rowIndex++; - } - } + private void populateglAccounts(Sheet GlAccountSheet, int rowIndex) { + for (GLAccountData glAccount : allGlAccounts) { + Row row = GlAccountSheet.createRow(rowIndex); + writeLong(ID_COL, row, glAccount.getId()); + writeString(ACCOUNT_NAME_COL, row, glAccount.getName().trim().replaceAll("[ )(]", "_")); + rowIndex++; + } + } - public Integer getGlAccountNamesSize() { - return allGlAccounts.size(); - } + public Integer getGlAccountNamesSize() { + 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 4d6e1b38d..d5c601d08 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 @@ -32,49 +32,49 @@ import java.util.Map; public class GroupSheetPopulator extends AbstractWorkbookPopulator { - private List groups; - private List offices; - - private Map> officeToGroups; - private Map officeNameToBeginEndIndexesOfGroups; - private Map groupNameToGroupId; + private List groups; + private List offices; + + private Map> officeToGroups; + private Map officeNameToBeginEndIndexesOfGroups; + private Map groupNameToGroupId; - private static final int OFFICE_NAME_COL = 0; - private static final int GROUP_NAME_COL = 1; - private static final int GROUP_ID_COL = 2; + private static final int OFFICE_NAME_COL = 0; + private static final int GROUP_NAME_COL = 1; + private static final int GROUP_ID_COL = 2; - public GroupSheetPopulator(final List groups, final List offices) { - this.groups = groups; - this.offices = offices; - } + public GroupSheetPopulator(final List groups, final List offices) { + this.groups = groups; + this.offices = offices; + } - @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet groupSheet = workbook.createSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME); - setLayout(groupSheet); - setGroupNameToGroupIdMap(); - setOfficeToGroupsMap(); - populateGroupsByOfficeName(groupSheet); - groupSheet.protectSheet(""); - } + @Override + public void populate(Workbook workbook,String dateFormat) { + Sheet groupSheet = workbook.createSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME); + setLayout(groupSheet); + setGroupNameToGroupIdMap(); + setOfficeToGroupsMap(); + populateGroupsByOfficeName(groupSheet); + groupSheet.protectSheet(""); + } - private void setLayout(Sheet worksheet) { - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - for (int colIndex = 0; colIndex <= 10; colIndex++) - worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - writeString(OFFICE_NAME_COL, rowHeader, "Office Names"); - writeString(GROUP_NAME_COL, rowHeader, "Group Names"); - writeString(GROUP_ID_COL, rowHeader, "Group ID"); - } + private void setLayout(Sheet worksheet) { + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + for (int colIndex = 0; colIndex <= 10; colIndex++) + worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + writeString(OFFICE_NAME_COL, rowHeader, "Office Names"); + writeString(GROUP_NAME_COL, rowHeader, "Group Names"); + writeString(GROUP_ID_COL, rowHeader, "Group ID"); + } - private void setOfficeToGroupsMap() { - officeToGroups = new HashMap<>(); - for (GroupGeneralData group : groups) { - add(group.getOfficeName().trim().replaceAll("[ )(]", "_"), group.getName().trim()); - } - } - //Guava Multi-map can reduce this. + private void setOfficeToGroupsMap() { + officeToGroups = new HashMap<>(); + for (GroupGeneralData group : groups) { + add(group.getOfficeName().trim().replaceAll("[ )(]", "_"), group.getName().trim()); + } + } + //Guava Multi-map can reduce this. private void add(String key, String value) { ArrayList values = officeToGroups.get(key); if (values == null) { @@ -84,43 +84,43 @@ public class GroupSheetPopulator extends AbstractWorkbookPopulator { officeToGroups.put(key, values); } private void populateGroupsByOfficeName(Sheet groupSheet) { - int rowIndex = 1, officeIndex = 0, 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<>(); - - if(officeToGroups.containsKey(office.name().trim().replaceAll("[ )(]", "_"))) - groupsList = officeToGroups.get(office.name().trim().replaceAll("[ )(]", "_")); - - 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}); - } - } + int rowIndex = 1, officeIndex = 0, 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<>(); + + if(officeToGroups.containsKey(office.name().trim().replaceAll("[ )(]", "_"))) + groupsList = officeToGroups.get(office.name().trim().replaceAll("[ )(]", "_")); + + 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}); + } + } } public List getGroups() { - return groups; + return groups; } public Integer getGroupsSize() { - return groups.size(); + return groups.size(); } public Map getOfficeNameToBeginEndIndexesOfGroups() { - return officeNameToBeginEndIndexesOfGroups; + return officeNameToBeginEndIndexesOfGroups; } private void setGroupNameToGroupIdMap(){ - groupNameToGroupId=new HashMap(); - for (GroupGeneralData group : groups) { - groupNameToGroupId.put(group.getName().trim(), group.getId()); - } + groupNameToGroupId=new HashMap(); + for (GroupGeneralData group : groups) { + groupNameToGroupId.put(group.getName().trim(), group.getId()); + } } } \ No newline at end of file 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 93de8841d..bca076dd3 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 @@ -30,170 +30,170 @@ import java.util.List; public class LoanProductSheetPopulator extends AbstractWorkbookPopulator { - private List products; - - private static final int ID_COL = 0; - private static final int NAME_COL = 1; - private static final int FUND_NAME_COL = 2; - private static final int PRINCIPAL_COL = 3; - private static final int MIN_PRINCIPAL_COL = 4; - private static final int MAX_PRINCIPAL_COL = 5; - private static final int NO_OF_REPAYMENTS_COL = 6; - private static final int MIN_REPAYMENTS_COL = 7; - private static final int MAX_REPAYMENTS_COL = 8; - private static final int REPAYMENT_EVERY_COL = 9; - private static final int REPAYMENT_FREQUENCY_COL = 10; - private static final int INTEREST_RATE_COL = 11; - private static final int MIN_INTEREST_RATE_COL = 12; - private static final int MAX_INTEREST_RATE_COL = 13; - private static final int INTEREST_RATE_FREQUENCY_COL = 14; - private static final int AMORTIZATION_TYPE_COL = 15; - private static final int INTEREST_TYPE_COL = 16; - private static final int INTEREST_CALCULATION_PERIOD_TYPE_COL = 17; - private static final int IN_ARREARS_TOLERANCE_COL = 18; - private static final int TRANSACTION_PROCESSING_STRATEGY_NAME_COL = 19; - private static final int GRACE_ON_PRINCIPAL_PAYMENT_COL = 20; - private static final int GRACE_ON_INTEREST_PAYMENT_COL = 21; - private static final int GRACE_ON_INTEREST_CHARGED_COL = 22; - private static final int START_DATE_COL = 23; - private static final int CLOSE_DATE_COL = 24; + private List products; + + private static final int ID_COL = 0; + private static final int NAME_COL = 1; + private static final int FUND_NAME_COL = 2; + private static final int PRINCIPAL_COL = 3; + private static final int MIN_PRINCIPAL_COL = 4; + private static final int MAX_PRINCIPAL_COL = 5; + private static final int NO_OF_REPAYMENTS_COL = 6; + private static final int MIN_REPAYMENTS_COL = 7; + private static final int MAX_REPAYMENTS_COL = 8; + private static final int REPAYMENT_EVERY_COL = 9; + private static final int REPAYMENT_FREQUENCY_COL = 10; + private static final int INTEREST_RATE_COL = 11; + private static final int MIN_INTEREST_RATE_COL = 12; + private static final int MAX_INTEREST_RATE_COL = 13; + private static final int INTEREST_RATE_FREQUENCY_COL = 14; + private static final int AMORTIZATION_TYPE_COL = 15; + private static final int INTEREST_TYPE_COL = 16; + private static final int INTEREST_CALCULATION_PERIOD_TYPE_COL = 17; + private static final int IN_ARREARS_TOLERANCE_COL = 18; + private static final int TRANSACTION_PROCESSING_STRATEGY_NAME_COL = 19; + private static final int GRACE_ON_PRINCIPAL_PAYMENT_COL = 20; + private static final int GRACE_ON_INTEREST_PAYMENT_COL = 21; + private static final int GRACE_ON_INTEREST_CHARGED_COL = 22; + private static final int START_DATE_COL = 23; + private static final int CLOSE_DATE_COL = 24; - - - public LoanProductSheetPopulator(List products) { - this.products = products; - } + + + public LoanProductSheetPopulator(List products) { + this.products = products; + } - @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 (LoanProductData product : products) { - Row row = productSheet.createRow(rowIndex++); - writeLong(ID_COL, row, product.getId()); - writeString(NAME_COL, row, product.getName().trim().replaceAll("[ )(]", "_")); - if (product.getFundName() != null) - writeString(FUND_NAME_COL, row, product.getFundName()); - writeBigDecimal(PRINCIPAL_COL, row, product.getPrincipal()); - if (product.getMinPrincipal() != null) - writeBigDecimal(MIN_PRINCIPAL_COL, row, product.getMinPrincipal()); - else - writeInt(MIN_PRINCIPAL_COL, row, 1); - if (product.getMaxPrincipal() != null) - writeBigDecimal(MAX_PRINCIPAL_COL, row, product.getMaxPrincipal()); - else - writeInt(MAX_PRINCIPAL_COL, row, 999999999); - writeInt(NO_OF_REPAYMENTS_COL, row, product.getNumberOfRepayments()); - if (product.getMinNumberOfRepayments() != null) - writeInt(MIN_REPAYMENTS_COL, row, product.getMinNumberOfRepayments()); - else - writeInt(MIN_REPAYMENTS_COL, row, 1); - if (product.getMaxNumberOfRepayments() != null) - writeInt(MAX_REPAYMENTS_COL, row, product.getMaxNumberOfRepayments()); - else - writeInt(MAX_REPAYMENTS_COL, row, 999999999); - writeInt(REPAYMENT_EVERY_COL, row, product.getRepaymentEvery()); - writeString(REPAYMENT_FREQUENCY_COL, row, product.getRepaymentFrequencyType().getValue()); - writeBigDecimal(INTEREST_RATE_COL, row, product.getInterestRatePerPeriod()); - if (product.getMinInterestRatePerPeriod() != null) - writeBigDecimal(MIN_INTEREST_RATE_COL, row, product.getMinInterestRatePerPeriod()); - else - writeInt(MIN_INTEREST_RATE_COL, row, 1); - if (product.getMaxInterestRatePerPeriod() != null) - writeBigDecimal(MAX_INTEREST_RATE_COL, row, product.getMaxInterestRatePerPeriod()); - else - writeInt(MAX_INTEREST_RATE_COL, row, 999999999); - 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()); - if (product.getInArrearsTolerance() != null) - writeBigDecimal(IN_ARREARS_TOLERANCE_COL, row, product.getInArrearsTolerance()); - writeString(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, row, product.getTransactionProcessingStrategyName()); - if (product.getGraceOnPrincipalPayment() != null) - writeInt(GRACE_ON_PRINCIPAL_PAYMENT_COL, row, product.getGraceOnPrincipalPayment()); - if (product.getGraceOnInterestPayment() != null) - writeInt(GRACE_ON_INTEREST_PAYMENT_COL, row, product.getGraceOnInterestPayment()); - if (product.getGraceOnInterestCharged() != null) - writeInt(GRACE_ON_INTEREST_CHARGED_COL, row, product.getGraceOnInterestCharged()); - if (product.getStartDate() != null) - writeDate(START_DATE_COL, row, product.getStartDate().toString(), dateCellStyle,dateFormat); - else - writeDate(START_DATE_COL, row, "1/1/1970", dateCellStyle,dateFormat); - if (product.getCloseDate() != null) - writeDate(CLOSE_DATE_COL, row, product.getCloseDate().toString(), dateCellStyle,dateFormat); - else - writeDate(CLOSE_DATE_COL, row, "1/1/2040", dateCellStyle,dateFormat); - productSheet.protectSheet(""); - } + @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 (LoanProductData product : products) { + Row row = productSheet.createRow(rowIndex++); + writeLong(ID_COL, row, product.getId()); + writeString(NAME_COL, row, product.getName().trim().replaceAll("[ )(]", "_")); + if (product.getFundName() != null) + writeString(FUND_NAME_COL, row, product.getFundName()); + writeBigDecimal(PRINCIPAL_COL, row, product.getPrincipal()); + if (product.getMinPrincipal() != null) + writeBigDecimal(MIN_PRINCIPAL_COL, row, product.getMinPrincipal()); + else + writeInt(MIN_PRINCIPAL_COL, row, 1); + if (product.getMaxPrincipal() != null) + writeBigDecimal(MAX_PRINCIPAL_COL, row, product.getMaxPrincipal()); + else + writeInt(MAX_PRINCIPAL_COL, row, 999999999); + writeInt(NO_OF_REPAYMENTS_COL, row, product.getNumberOfRepayments()); + if (product.getMinNumberOfRepayments() != null) + writeInt(MIN_REPAYMENTS_COL, row, product.getMinNumberOfRepayments()); + else + writeInt(MIN_REPAYMENTS_COL, row, 1); + if (product.getMaxNumberOfRepayments() != null) + writeInt(MAX_REPAYMENTS_COL, row, product.getMaxNumberOfRepayments()); + else + writeInt(MAX_REPAYMENTS_COL, row, 999999999); + writeInt(REPAYMENT_EVERY_COL, row, product.getRepaymentEvery()); + writeString(REPAYMENT_FREQUENCY_COL, row, product.getRepaymentFrequencyType().getValue()); + writeBigDecimal(INTEREST_RATE_COL, row, product.getInterestRatePerPeriod()); + if (product.getMinInterestRatePerPeriod() != null) + writeBigDecimal(MIN_INTEREST_RATE_COL, row, product.getMinInterestRatePerPeriod()); + else + writeInt(MIN_INTEREST_RATE_COL, row, 1); + if (product.getMaxInterestRatePerPeriod() != null) + writeBigDecimal(MAX_INTEREST_RATE_COL, row, product.getMaxInterestRatePerPeriod()); + else + writeInt(MAX_INTEREST_RATE_COL, row, 999999999); + 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()); + if (product.getInArrearsTolerance() != null) + writeBigDecimal(IN_ARREARS_TOLERANCE_COL, row, product.getInArrearsTolerance()); + writeString(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, row, product.getTransactionProcessingStrategyName()); + if (product.getGraceOnPrincipalPayment() != null) + writeInt(GRACE_ON_PRINCIPAL_PAYMENT_COL, row, product.getGraceOnPrincipalPayment()); + if (product.getGraceOnInterestPayment() != null) + writeInt(GRACE_ON_INTEREST_PAYMENT_COL, row, product.getGraceOnInterestPayment()); + if (product.getGraceOnInterestCharged() != null) + writeInt(GRACE_ON_INTEREST_CHARGED_COL, row, product.getGraceOnInterestCharged()); + if (product.getStartDate() != null) + writeDate(START_DATE_COL, row, product.getStartDate().toString(), dateCellStyle,dateFormat); + else + writeDate(START_DATE_COL, row, "1/1/1970", dateCellStyle,dateFormat); + if (product.getCloseDate() != null) + writeDate(CLOSE_DATE_COL, row, product.getCloseDate().toString(), dateCellStyle,dateFormat); + else + writeDate(CLOSE_DATE_COL, row, "1/1/2040", dateCellStyle,dateFormat); + productSheet.protectSheet(""); + } - } + } - private void setLayout(Sheet worksheet) { - worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(FUND_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(MIN_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(MAX_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(NO_OF_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(MIN_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(MAX_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(REPAYMENT_EVERY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(REPAYMENT_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(MIN_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(MAX_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(INTEREST_RATE_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(AMORTIZATION_TYPE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(INTEREST_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(INTEREST_CALCULATION_PERIOD_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - 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(START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(CLOSE_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + private void setLayout(Sheet worksheet) { + worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(FUND_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(MIN_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(MAX_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(NO_OF_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(MIN_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(MAX_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(REPAYMENT_EVERY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(REPAYMENT_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(MIN_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(MAX_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(INTEREST_RATE_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(AMORTIZATION_TYPE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(INTEREST_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(INTEREST_CALCULATION_PERIOD_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + 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(START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(CLOSE_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - writeString(ID_COL, rowHeader, "ID"); - writeString(NAME_COL, rowHeader, "Name"); - writeString(FUND_NAME_COL, rowHeader, "Fund"); - writeString(PRINCIPAL_COL, rowHeader, "Principal"); - writeString(MIN_PRINCIPAL_COL, rowHeader, "Min Principal"); - writeString(MAX_PRINCIPAL_COL, rowHeader, "Max Principal"); - writeString(NO_OF_REPAYMENTS_COL, rowHeader, "# of Repayments"); - writeString(MIN_REPAYMENTS_COL, rowHeader, "Min Repayments"); - writeString(MAX_REPAYMENTS_COL, rowHeader, "Max Repayments"); - writeString(REPAYMENT_EVERY_COL, rowHeader, "Repayment Every"); - writeString(REPAYMENT_FREQUENCY_COL, rowHeader, "Frequency"); - writeString(INTEREST_RATE_COL, rowHeader, "Interest"); - writeString(MIN_INTEREST_RATE_COL, rowHeader, "Min Interest"); - writeString(MAX_INTEREST_RATE_COL, rowHeader, "Max Interest"); - writeString(INTEREST_RATE_FREQUENCY_COL, rowHeader, "Frequency"); - writeString(AMORTIZATION_TYPE_COL, rowHeader, "Amortization Type"); - writeString(INTEREST_TYPE_COL, rowHeader, "Interest Type"); - writeString(INTEREST_CALCULATION_PERIOD_TYPE_COL, rowHeader, "Interest Calculation Period"); - writeString(IN_ARREARS_TOLERANCE_COL, rowHeader, "In Arrears Tolerance"); - writeString(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, rowHeader, "Transaction Processing Strategy"); - writeString(GRACE_ON_PRINCIPAL_PAYMENT_COL, rowHeader, "Grace On Principal Payment"); - writeString(GRACE_ON_INTEREST_PAYMENT_COL, rowHeader, "Grace on Interest Payment"); - writeString(GRACE_ON_INTEREST_CHARGED_COL, rowHeader, "Grace on Interest Charged"); - writeString(START_DATE_COL, rowHeader, "Start Date"); - writeString(CLOSE_DATE_COL, rowHeader, "End Date"); - } - public List getProducts(){ - return products; - - } - public Integer getProductsSize() { - return products.size(); - } + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + writeString(ID_COL, rowHeader, "ID"); + writeString(NAME_COL, rowHeader, "Name"); + writeString(FUND_NAME_COL, rowHeader, "Fund"); + writeString(PRINCIPAL_COL, rowHeader, "Principal"); + writeString(MIN_PRINCIPAL_COL, rowHeader, "Min Principal"); + writeString(MAX_PRINCIPAL_COL, rowHeader, "Max Principal"); + writeString(NO_OF_REPAYMENTS_COL, rowHeader, "# of Repayments"); + writeString(MIN_REPAYMENTS_COL, rowHeader, "Min Repayments"); + writeString(MAX_REPAYMENTS_COL, rowHeader, "Max Repayments"); + writeString(REPAYMENT_EVERY_COL, rowHeader, "Repayment Every"); + writeString(REPAYMENT_FREQUENCY_COL, rowHeader, "Frequency"); + writeString(INTEREST_RATE_COL, rowHeader, "Interest"); + writeString(MIN_INTEREST_RATE_COL, rowHeader, "Min Interest"); + writeString(MAX_INTEREST_RATE_COL, rowHeader, "Max Interest"); + writeString(INTEREST_RATE_FREQUENCY_COL, rowHeader, "Frequency"); + writeString(AMORTIZATION_TYPE_COL, rowHeader, "Amortization Type"); + writeString(INTEREST_TYPE_COL, rowHeader, "Interest Type"); + writeString(INTEREST_CALCULATION_PERIOD_TYPE_COL, rowHeader, "Interest Calculation Period"); + writeString(IN_ARREARS_TOLERANCE_COL, rowHeader, "In Arrears Tolerance"); + writeString(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, rowHeader, "Transaction Processing Strategy"); + writeString(GRACE_ON_PRINCIPAL_PAYMENT_COL, rowHeader, "Grace On Principal Payment"); + writeString(GRACE_ON_INTEREST_PAYMENT_COL, rowHeader, "Grace on Interest Payment"); + writeString(GRACE_ON_INTEREST_CHARGED_COL, rowHeader, "Grace on Interest Charged"); + writeString(START_DATE_COL, rowHeader, "Start Date"); + writeString(CLOSE_DATE_COL, rowHeader, "End Date"); + } + 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 a2ff62070..9d689dc9a 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 @@ -72,11 +72,11 @@ public class OfficeSheetPopulator extends AbstractWorkbookPopulator { } public List getOfficeNames() { - List officeNames=new ArrayList<>(); - for (OfficeData office : offices) { - officeNames.add(office.name()); - } - return officeNames; + List officeNames=new ArrayList<>(); + for (OfficeData office : offices) { + officeNames.add(office.name()); + } + return officeNames; } } \ 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 27248c620..3382f3683 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 @@ -37,152 +37,152 @@ import java.util.List; public class CentersWorkbookPopulator extends AbstractWorkbookPopulator { - private OfficeSheetPopulator officeSheetPopulator; - private PersonnelSheetPopulator personnelSheetPopulator; - private GroupSheetPopulator groupSheetPopulator; + private OfficeSheetPopulator officeSheetPopulator; + private PersonnelSheetPopulator personnelSheetPopulator; + private GroupSheetPopulator groupSheetPopulator; - public CentersWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - PersonnelSheetPopulator personnelSheetPopulator,GroupSheetPopulator groupSheetPopulator) { - this.officeSheetPopulator = officeSheetPopulator; - this.personnelSheetPopulator = personnelSheetPopulator; - this.groupSheetPopulator=groupSheetPopulator; - } + public CentersWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, + PersonnelSheetPopulator personnelSheetPopulator,GroupSheetPopulator groupSheetPopulator) { + this.officeSheetPopulator = officeSheetPopulator; + this.personnelSheetPopulator = personnelSheetPopulator; + this.groupSheetPopulator=groupSheetPopulator; + } - @Override - 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); - setLayout(centerSheet); - setLookupTable(centerSheet,dateFormat); - setRules(centerSheet,dateFormat); - } - + @Override + 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); + setLayout(centerSheet); + setLookupTable(centerSheet,dateFormat); + setRules(centerSheet,dateFormat); + } + - private void setLayout(Sheet worksheet) { - Row rowHeader = worksheet.createRow(0); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - worksheet.setColumnWidth(CenterConstants.CENTER_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(CenterConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(CenterConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - 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.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); - worksheet.setColumnWidth(CenterConstants.INTERVAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(CenterConstants.REPEATS_ON_DAY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - 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.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); - worksheet.setColumnWidth(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + private void setLayout(Sheet worksheet) { + Row rowHeader = worksheet.createRow(0); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + worksheet.setColumnWidth(CenterConstants.CENTER_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(CenterConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(CenterConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + 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.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); + worksheet.setColumnWidth(CenterConstants.INTERVAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(CenterConstants.REPEATS_ON_DAY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + 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.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); + worksheet.setColumnWidth(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CenterConstants.CENTER_NAME_COL, rowHeader, "Center Name*"); - writeString(CenterConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); - writeString(CenterConstants.STAFF_NAME_COL, rowHeader, "Staff Name*"); - 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.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.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); - int rowIndex; - for(rowIndex = 1; rowIndex <= 11; rowIndex++) { - Row row = centerSheet.getRow(rowIndex); - if(row == null) - row = centerSheet.createRow(rowIndex); - writeInt(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, row, rowIndex); - } - for(rowIndex = 1; rowIndex <= 3; rowIndex++) - writeInt(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, centerSheet.getRow(rowIndex), rowIndex); + writeString(CenterConstants.CENTER_NAME_COL, rowHeader, "Center Name*"); + writeString(CenterConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); + writeString(CenterConstants.STAFF_NAME_COL, rowHeader, "Staff Name*"); + 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.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.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); + int rowIndex; + for(rowIndex = 1; rowIndex <= 11; rowIndex++) { + Row row = centerSheet.getRow(rowIndex); + if(row == null) + row = centerSheet.createRow(rowIndex); + writeInt(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, row, 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++) - 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); - - - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet); - List offices = officeSheetPopulator.getOffices(); - setNames(worksheet, offices); - + 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); + + + 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 repeatsEveryConstraint = validationHelper.createFormulaListConstraint("INDIRECT($J1)"); - DataValidationConstraint repeatsOnConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE($J1,\"_DAYS\"))"); + 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 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 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); - + 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 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(activeValidation); worksheet.addValidationData(officeValidation); worksheet.addValidationData(staffValidation); worksheet.addValidationData(activationDateValidation); @@ -192,44 +192,44 @@ public class CentersWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.addValidationData(repeatsValidation); worksheet.addValidationData(repeatsEveryValidation); worksheet.addValidationData(repeatsOnValidation); - } - - private void setNames(Sheet worksheet, List offices) { - Workbook centerWorkbook = worksheet.getWorkbook(); - Name officeCenter = centerWorkbook.createName(); - officeCenter.setNameName("Office"); - officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME +"!$B$2:$B$" + (offices.size() + 1)); - - - //Repeat constraint names - Name repeatsDaily = centerWorkbook.createName(); - repeatsDaily.setNameName("Daily"); - 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"); - Name repeatYearly = centerWorkbook.createName(); - repeatYearly.setNameName("Yearly"); - 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"); - Name repeatsOnWeekly = centerWorkbook.createName(); - repeatsOnWeekly.setNameName("Weekly_Days"); - repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IV$2:$IV$8"); - - - //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) { - loanOfficerName.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_")); - loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); - } - } - - } - - + } + + private void setNames(Sheet worksheet, List offices) { + Workbook centerWorkbook = worksheet.getWorkbook(); + Name officeCenter = centerWorkbook.createName(); + officeCenter.setNameName("Office"); + officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME +"!$B$2:$B$" + (offices.size() + 1)); + + + //Repeat constraint names + Name repeatsDaily = centerWorkbook.createName(); + repeatsDaily.setNameName("Daily"); + 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"); + Name repeatYearly = centerWorkbook.createName(); + repeatYearly.setNameName("Yearly"); + 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"); + Name repeatsOnWeekly = centerWorkbook.createName(); + repeatsOnWeekly.setNameName("Weekly_Days"); + repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IV$2:$IV$8"); + + + //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) { + loanOfficerName.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_")); + 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/group/GroupsWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/group/GroupsWorkbookPopulator.java index 038e10872..cfb58aff8 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 @@ -32,167 +32,167 @@ import java.util.List; public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator { - private OfficeSheetPopulator officeSheetPopulator; - private PersonnelSheetPopulator personnelSheetPopulator; - private CenterSheetPopulator centerSheetPopulator; - private ClientSheetPopulator clientSheetPopulator; + private OfficeSheetPopulator officeSheetPopulator; + private PersonnelSheetPopulator personnelSheetPopulator; + private CenterSheetPopulator centerSheetPopulator; + private ClientSheetPopulator clientSheetPopulator; - public GroupsWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - PersonnelSheetPopulator personnelSheetPopulator, CenterSheetPopulator centerSheetPopulator, - ClientSheetPopulator clientSheetPopulator) { - this.officeSheetPopulator = officeSheetPopulator; - this.personnelSheetPopulator = personnelSheetPopulator; - this.centerSheetPopulator = centerSheetPopulator; - this.clientSheetPopulator = clientSheetPopulator; - } + public GroupsWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, + PersonnelSheetPopulator personnelSheetPopulator, CenterSheetPopulator centerSheetPopulator, + ClientSheetPopulator clientSheetPopulator) { + this.officeSheetPopulator = officeSheetPopulator; + this.personnelSheetPopulator = personnelSheetPopulator; + this.centerSheetPopulator = centerSheetPopulator; + this.clientSheetPopulator = clientSheetPopulator; + } - @Override - 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); - setLayout(groupSheet); - setLookupTable(groupSheet,dateFormat); - setRules(groupSheet,dateFormat); + @Override + 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); + setLayout(groupSheet); + setLookupTable(groupSheet,dateFormat); + setRules(groupSheet,dateFormat); - } + } - private void setLayout(Sheet worksheet) { - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - 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.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.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); - worksheet.setColumnWidth(GroupConstants.REPEATS_ON_DAY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GroupConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - 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_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); - worksheet.setColumnWidth(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + private void setLayout(Sheet worksheet) { + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + 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.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.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); + worksheet.setColumnWidth(GroupConstants.REPEATS_ON_DAY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GroupConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + 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_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); + worksheet.setColumnWidth(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(GroupConstants.NAME_COL, rowHeader, "Group Name*"); - writeString(GroupConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); - writeString(GroupConstants.STAFF_NAME_COL, rowHeader, "Staff Name*"); - writeString(GroupConstants.CENTER_NAME_COL, rowHeader, "Center Name"); - 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.MEETING_START_DATE_COL, rowHeader, "Meeting Start Date* (On or After)"); - writeString(GroupConstants.IS_REPEATING_COL, rowHeader, "Repeat*"); - writeString(GroupConstants.FREQUENCY_COL, rowHeader, "Frequency*"); - writeString(GroupConstants.INTERVAL_COL, rowHeader, "Interval*"); - writeString(GroupConstants.REPEATS_ON_DAY_COL, rowHeader, "Repeats On*"); - writeString(GroupConstants.CLIENT_NAMES_STARTING_COL, rowHeader, "Client Names* (Enter in consecutive cells horizontally)"); - writeString(GroupConstants.LOOKUP_OFFICE_NAME_COL, rowHeader, "Office Name"); - writeString(GroupConstants.LOOKUP_OFFICE_OPENING_DATE_COL, rowHeader, "Opening Date"); - writeString(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, rowHeader, "Repeat Normal Range"); - writeString(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, rowHeader, "Repeat Monthly Range"); - writeString(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, rowHeader, "If Repeat Weekly Range"); + writeString(GroupConstants.NAME_COL, rowHeader, "Group Name*"); + writeString(GroupConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); + writeString(GroupConstants.STAFF_NAME_COL, rowHeader, "Staff Name*"); + writeString(GroupConstants.CENTER_NAME_COL, rowHeader, "Center Name"); + 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.MEETING_START_DATE_COL, rowHeader, "Meeting Start Date* (On or After)"); + writeString(GroupConstants.IS_REPEATING_COL, rowHeader, "Repeat*"); + writeString(GroupConstants.FREQUENCY_COL, rowHeader, "Frequency*"); + writeString(GroupConstants.INTERVAL_COL, rowHeader, "Interval*"); + writeString(GroupConstants.REPEATS_ON_DAY_COL, rowHeader, "Repeats On*"); + writeString(GroupConstants.CLIENT_NAMES_STARTING_COL, rowHeader, "Client Names* (Enter in consecutive cells horizontally)"); + writeString(GroupConstants.LOOKUP_OFFICE_NAME_COL, rowHeader, "Office Name"); + writeString(GroupConstants.LOOKUP_OFFICE_OPENING_DATE_COL, rowHeader, "Opening Date"); + writeString(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, rowHeader, "Repeat Normal Range"); + writeString(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, rowHeader, "Repeat Monthly Range"); + 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); - int rowIndex; - for(rowIndex = 1; rowIndex <= 11; rowIndex++) { - Row row = groupSheet.getRow(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); - 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]); + setOfficeDateLookupTable(groupSheet, officeSheetPopulator.getOffices(),GroupConstants.LOOKUP_OFFICE_NAME_COL, + GroupConstants. LOOKUP_OFFICE_OPENING_DATE_COL,dateFormat); + int rowIndex; + for(rowIndex = 1; rowIndex <= 11; rowIndex++) { + Row row = groupSheet.getRow(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); + 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(), - GroupConstants.OFFICE_NAME_COL, GroupConstants.OFFICE_NAME_COL); - CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GroupConstants.STAFF_NAME_COL, GroupConstants.STAFF_NAME_COL); - CellRangeAddressList centerNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GroupConstants.CENTER_NAME_COL, GroupConstants.CENTER_NAME_COL); - 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 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); - CellRangeAddressList repeatsEveryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - 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); - List offices = officeSheetPopulator.getOffices(); - setNames(worksheet, offices); - - 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 repeatsEveryConstraint = validationHelper.createFormulaListConstraint("INDIRECT($K1)"); - DataValidationConstraint repeatsOnConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE($K1,\"_DAYS\"))"); - - 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 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(centerValidation); - worksheet.addValidationData(activeValidation); + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GroupConstants.OFFICE_NAME_COL, GroupConstants.OFFICE_NAME_COL); + CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GroupConstants.STAFF_NAME_COL, GroupConstants.STAFF_NAME_COL); + CellRangeAddressList centerNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GroupConstants.CENTER_NAME_COL, GroupConstants.CENTER_NAME_COL); + 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 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); + CellRangeAddressList repeatsEveryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + 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); + List offices = officeSheetPopulator.getOffices(); + setNames(worksheet, offices); + + 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 repeatsEveryConstraint = validationHelper.createFormulaListConstraint("INDIRECT($K1)"); + DataValidationConstraint repeatsOnConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE($K1,\"_DAYS\"))"); + + 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 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(centerValidation); + worksheet.addValidationData(activeValidation); worksheet.addValidationData(officeValidation); worksheet.addValidationData(staffValidation); worksheet.addValidationData(activationDateValidation); @@ -204,51 +204,51 @@ public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.addValidationData(repeatsOnValidation); } - private void setNames(Sheet worksheet, List offices) { - Workbook centerWorkbook = worksheet.getWorkbook(); - Name officeCenter = centerWorkbook.createName(); - officeCenter.setNameName("Office"); - officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (offices.size() + 1)); - - - //Repeat constraint names - Name repeatsDaily = centerWorkbook.createName(); - repeatsDaily.setNameName("Daily"); - 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"); - Name repeatYearly = centerWorkbook.createName(); - repeatYearly.setNameName("Yearly"); - 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"); - Name repeatsOnWeekly = centerWorkbook.createName(); - repeatsOnWeekly.setNameName("Weekly_Days"); - 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); - Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i); + private void setNames(Sheet worksheet, List offices) { + Workbook centerWorkbook = worksheet.getWorkbook(); + Name officeCenter = centerWorkbook.createName(); + officeCenter.setNameName("Office"); + officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (offices.size() + 1)); + + + //Repeat constraint names + Name repeatsDaily = centerWorkbook.createName(); + repeatsDaily.setNameName("Daily"); + 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"); + Name repeatYearly = centerWorkbook.createName(); + repeatYearly.setNameName("Yearly"); + 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"); + Name repeatsOnWeekly = centerWorkbook.createName(); + repeatsOnWeekly.setNameName("Weekly_Days"); + 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); + Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i); - Name loanOfficerName = centerWorkbook.createName(); - Name centerName=centerWorkbook.createName(); + Name loanOfficerName = centerWorkbook.createName(); + Name centerName=centerWorkbook.createName(); - 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]); - } - } - - } + 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]); + } + } + + } } \ 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 945526fca..ec02065dd 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 @@ -38,83 +38,83 @@ import java.util.HashMap; import java.util.List; public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator { - private OfficeSheetPopulator officeSheetPopulator; - private ClientSheetPopulator clientSheetPopulator; - private List loans; - private List savings; - private ListguarantorRelationshipTypes; + private OfficeSheetPopulator officeSheetPopulator; + private ClientSheetPopulator clientSheetPopulator; + private List loans; + private List savings; + private ListguarantorRelationshipTypes; - 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; + 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; - } + } - @Override - 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); - setRules(addGuarantorSheet); + @Override + 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); + 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"); - - } + 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"); + + } private void populateSavingsTable(Sheet addGuarantorSheet,String dateFormat) { Workbook workbook = addGuarantorSheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); @@ -154,68 +154,68 @@ public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator { 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(); - short df = workbook.createDataFormat().getFormat(dateFormat); - 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++); - } - writeString(GuarantorConstants.LOOKUP_GUARANTOR_RELATIONSHIPS,row,relationshipType.getName()+"-"+relationshipType.getId()); - } + private void populateGuarantorRelationshipTypes(Sheet addGuarantorSheet, String dateFormat) { + Workbook workbook = addGuarantorSheet.getWorkbook(); + CellStyle dateCellStyle = workbook.createCellStyle(); + short df = workbook.createDataFormat().getFormat(dateFormat); + 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++); + } + writeString(GuarantorConstants.LOOKUP_GUARANTOR_RELATIONSHIPS,row,relationshipType.getName()+"-"+relationshipType.getId()); + } - } - private void setRules(Sheet worksheet) { + } + 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(), - GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL); - - 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 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); - - - worksheet.addValidationData(officeValidation); + 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); + + 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))"); + + 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); @@ -223,92 +223,92 @@ public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator { 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 - Name officeGroup = addGurarantorWorkbook.createName(); - officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + + } + private void setNames(Sheet worksheet) { + Workbook addGurarantorWorkbook = worksheet.getWorkbook(); + ArrayList officeNames = new ArrayList(officeSheetPopulator.getOfficeNames()); + + //Office Names + Name officeGroup = addGurarantorWorkbook.createName(); + officeGroup.setNameName("Office"); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); - //GurantorRelationshipTypes Names - Name guarantorRelationshipsGroup = addGurarantorWorkbook.createName(); - guarantorRelationshipsGroup.setNameName("GuarantorRelationship"); - guarantorRelationshipsGroup.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CH$2:$CH$" + (guarantorRelationshipTypes.size() + 1)); - - //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]); - } - } - - //Counting clients with active loans and starting and end addresses of cells - HashMap clientNameToBeginEndIndexes = new HashMap(); - ArrayList clientsWithActiveLoans = new ArrayList(); - ArrayList clientIdsWithActiveLoans = new ArrayList(); - int startIndex = 1, endIndex = 1; - String clientName = ""; - String clientId = ""; - 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}); - 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) { - endIndex = i + 2; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); - } - } - - //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]); - } - ///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())) { - endIndex = i + 1; - 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) { - endIndex = i + 2; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); - } - } - //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]); - } - - } + //GurantorRelationshipTypes Names + Name guarantorRelationshipsGroup = addGurarantorWorkbook.createName(); + guarantorRelationshipsGroup.setNameName("GuarantorRelationship"); + guarantorRelationshipsGroup.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CH$2:$CH$" + (guarantorRelationshipTypes.size() + 1)); + + //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]); + } + } + + //Counting clients with active loans and starting and end addresses of cells + HashMap clientNameToBeginEndIndexes = new HashMap(); + ArrayList clientsWithActiveLoans = new ArrayList(); + ArrayList clientIdsWithActiveLoans = new ArrayList(); + int startIndex = 1, endIndex = 1; + String clientName = ""; + String clientId = ""; + 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}); + 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) { + endIndex = i + 2; + clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + } + } + + //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]); + } + ///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())) { + endIndex = i + 1; + 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) { + endIndex = i + 2; + clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + } + } + //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]); + } + + } } \ No newline at end of file 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 23ae4404e..64a63b415 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 @@ -34,158 +34,158 @@ import java.util.ArrayList; public class JournalEntriesWorkbookPopulator extends AbstractWorkbookPopulator { - - private OfficeSheetPopulator officeSheetPopulator; - private GlAccountSheetPopulator glAccountSheetPopulator; - private ExtrasSheetPopulator extrasSheetPopulator; + + private OfficeSheetPopulator officeSheetPopulator; + private GlAccountSheetPopulator glAccountSheetPopulator; + private ExtrasSheetPopulator extrasSheetPopulator; - public JournalEntriesWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - GlAccountSheetPopulator glAccountSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) { - this.officeSheetPopulator = officeSheetPopulator; - this.glAccountSheetPopulator = glAccountSheetPopulator; - this.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) { - Sheet addJournalEntriesSheet = workbook.createSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME); - officeSheetPopulator.populate(workbook,dateFormat); - glAccountSheetPopulator.populate(workbook,dateFormat); - extrasSheetPopulator.populate(workbook,dateFormat); - setRules(addJournalEntriesSheet); - setDefaults(addJournalEntriesSheet); - setLayout(addJournalEntriesSheet); - } - - private void setLayout(Sheet worksheet) { - 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); + @Override + 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); + setRules(addJournalEntriesSheet); + setDefaults(addJournalEntriesSheet); + setLayout(addJournalEntriesSheet); + } + + private void setLayout(Sheet worksheet) { + 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); - writeString(JournalEntryConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); - writeString(JournalEntryConstants.TRANSACION_ON_DATE_COL, rowHeader, "Transaction On *"); - writeString(JournalEntryConstants.CURRENCY_NAME_COL, rowHeader, "Currecy Type*"); - writeString(JournalEntryConstants.PAYMENT_TYPE_ID_COL, rowHeader, "Payment Type*"); - writeString(JournalEntryConstants.TRANSACTION_ID_COL, rowHeader, "Transaction Id*"); - writeString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, rowHeader, "Credit Account Type*"); - 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.OFFICE_NAME_COL, rowHeader, "Office Name*"); + writeString(JournalEntryConstants.TRANSACION_ON_DATE_COL, rowHeader, "Transaction On *"); + writeString(JournalEntryConstants.CURRENCY_NAME_COL, rowHeader, "Currecy Type*"); + writeString(JournalEntryConstants.PAYMENT_TYPE_ID_COL, rowHeader, "Payment Type*"); + writeString(JournalEntryConstants.TRANSACTION_ID_COL, rowHeader, "Transaction Id*"); + writeString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, rowHeader, "Credit Account Type*"); + 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"); - // TODO Auto-generated method stub + // TODO Auto-generated method stub - } - - private void setRules(Sheet worksheet) { - - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), - JournalEntryConstants.OFFICE_NAME_COL,JournalEntryConstants. OFFICE_NAME_COL); + } + + private void setRules(Sheet worksheet) { + + 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); - } - - private void setNames(Sheet worksheet) { - Workbook addJournalEntriesWorkbook = worksheet.getWorkbook(); - ArrayList officeNames = new ArrayList<>(officeSheetPopulator.getOfficeNames()); - // Office Names - Name officeGroup = addJournalEntriesWorkbook.createName(); - officeGroup.setNameName("Office"); - 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)); - // Currency Type Name - Name currencyGroup = addJournalEntriesWorkbook.createName(); - currencyGroup.setNameName("Currency"); - currencyGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$F$2:$F$" - + (extrasSheetPopulator.getCurrenciesSize() + 1)); + worksheet.addValidationData(glaccountCreditValidation); + worksheet.addValidationData(glaccountDebitValidation); + } + + private void setNames(Sheet worksheet) { + Workbook addJournalEntriesWorkbook = worksheet.getWorkbook(); + ArrayList officeNames = new ArrayList<>(officeSheetPopulator.getOfficeNames()); + // Office Names + Name officeGroup = addJournalEntriesWorkbook.createName(); + officeGroup.setNameName("Office"); + 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)); + // Currency Type Name + Name currencyGroup = addJournalEntriesWorkbook.createName(); + currencyGroup.setNameName("Currency"); + 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$" - + (glAccountSheetPopulator.getGlAccountNamesSize() + 1)); - } - - private void setDefaults(Sheet worksheet) { - for (Integer rowNo = 1; rowNo < 1000; rowNo++) { - Row row = worksheet.createRow(rowNo); - } + // Account Name + Name glaccountGroup = addJournalEntriesWorkbook.createName(); + glaccountGroup.setNameName("GlAccounts"); + glaccountGroup.setRefersToFormula(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME+"!$B$2:$B$" + + (glAccountSheetPopulator.getGlAccountNamesSize() + 1)); + } + + private void setDefaults(Sheet worksheet) { + for (Integer rowNo = 1; rowNo < 1000; rowNo++) { + Row row = worksheet.createRow(rowNo); + } - } + } - - + + } 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 2cbb18e59..fb8db58ae 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 @@ -33,533 +33,533 @@ import java.util.List; public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { - private OfficeSheetPopulator officeSheetPopulator; - private ClientSheetPopulator clientSheetPopulator; - private GroupSheetPopulator groupSheetPopulator; - private PersonnelSheetPopulator personnelSheetPopulator; - private LoanProductSheetPopulator productSheetPopulator; - private ExtrasSheetPopulator extrasSheetPopulator; + private OfficeSheetPopulator officeSheetPopulator; + private ClientSheetPopulator clientSheetPopulator; + private GroupSheetPopulator groupSheetPopulator; + private PersonnelSheetPopulator personnelSheetPopulator; + private LoanProductSheetPopulator productSheetPopulator; + private ExtrasSheetPopulator extrasSheetPopulator; - public LoanWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, - GroupSheetPopulator groupSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, - LoanProductSheetPopulator productSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) { - this.officeSheetPopulator = officeSheetPopulator; - this.clientSheetPopulator = clientSheetPopulator; - this.groupSheetPopulator = groupSheetPopulator; - this.personnelSheetPopulator = personnelSheetPopulator; - this.productSheetPopulator = productSheetPopulator; - this.extrasSheetPopulator = extrasSheetPopulator; - } + public LoanWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, + GroupSheetPopulator groupSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, + LoanProductSheetPopulator productSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) { + this.officeSheetPopulator = officeSheetPopulator; + this.clientSheetPopulator = clientSheetPopulator; + this.groupSheetPopulator = groupSheetPopulator; + this.personnelSheetPopulator = personnelSheetPopulator; + this.productSheetPopulator = productSheetPopulator; + this.extrasSheetPopulator = extrasSheetPopulator; + } - @Override - 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); - setLayout(loanSheet); - 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); - } + @Override + 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); + setLayout(loanSheet); + 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); + } - 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 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); - 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 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); - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); + 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 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); + 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 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); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); - setNames(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 clientNameConstraint = validationHelper.createFormulaListConstraint( - "IF($B1=\"Group\",INDIRECT(CONCATENATE(\"Group_\",$A1)),INDIRECT(CONCATENATE(\"Client_\",$A1)))"); - DataValidationConstraint productNameConstraint = validationHelper.createFormulaListConstraint("Products"); - DataValidationConstraint loanOfficerNameConstraint = validationHelper - .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$A1))"); - DataValidationConstraint submittedDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, - "=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))", - "=TODAY()", dateFormat); - DataValidationConstraint approvalDateConstraint = validationHelper - .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$G1", "=TODAY()", dateFormat); - DataValidationConstraint disbursedDateConstraint = validationHelper - .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$H1", "=TODAY()", dateFormat); - DataValidationConstraint paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes"); - DataValidationConstraint fundNameConstraint = validationHelper.createFormulaListConstraint("Funds"); - DataValidationConstraint principalConstraint = validationHelper.createDecimalConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=INDIRECT(CONCATENATE(\"MIN_PRINCIPAL_\",$E1))", - "=INDIRECT(CONCATENATE(\"MAX_PRINCIPAL_\",$E1))"); - DataValidationConstraint noOfRepaymentsConstraint = validationHelper.createIntegerConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=INDIRECT(CONCATENATE(\"MIN_REPAYMENT_\",$E1))", - "=INDIRECT(CONCATENATE(\"MAX_REPAYMENT_\",$E1))"); - DataValidationConstraint frequencyConstraint = validationHelper - .createExplicitListConstraint(new String[] { "Days", "Weeks", "Months" }); - DataValidationConstraint loanTermConstraint = validationHelper - .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "=$M1*$N1", null); - DataValidationConstraint interestFrequencyConstraint = validationHelper - .createFormulaListConstraint("INDIRECT(CONCATENATE(\"INTEREST_FREQUENCY_\",$E1))"); - DataValidationConstraint interestConstraint = validationHelper.createDecimalConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=INDIRECT(CONCATENATE(\"MIN_INTEREST_\",$E1))", - "=INDIRECT(CONCATENATE(\"MAX_INTEREST_\",$E1))"); - DataValidationConstraint amortizationConstraint = validationHelper - .createExplicitListConstraint(new String[] { "Equal principal payments", "Equal installments" }); - DataValidationConstraint interestMethodConstraint = validationHelper - .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 arrearsToleranceConstraint = validationHelper - .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0", null); - DataValidationConstraint graceOnPrincipalPaymentConstraint = validationHelper - .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0", null); - DataValidationConstraint graceOnInterestPaymentConstraint = validationHelper - .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0", null); - DataValidationConstraint graceOnInterestChargedConstraint = validationHelper - .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0", null); - DataValidationConstraint lastRepaymentDateConstraint = validationHelper - .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$I1", "=TODAY()", dateFormat); + DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); + 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"); + DataValidationConstraint loanOfficerNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$A1))"); + DataValidationConstraint submittedDateConstraint = validationHelper.createDateConstraint( + DataValidationConstraint.OperatorType.BETWEEN, + "=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))", + "=TODAY()", dateFormat); + DataValidationConstraint approvalDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$G1", "=TODAY()", dateFormat); + DataValidationConstraint disbursedDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$H1", "=TODAY()", dateFormat); + DataValidationConstraint paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes"); + DataValidationConstraint fundNameConstraint = validationHelper.createFormulaListConstraint("Funds"); + DataValidationConstraint principalConstraint = validationHelper.createDecimalConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=INDIRECT(CONCATENATE(\"MIN_PRINCIPAL_\",$E1))", + "=INDIRECT(CONCATENATE(\"MAX_PRINCIPAL_\",$E1))"); + DataValidationConstraint noOfRepaymentsConstraint = validationHelper.createIntegerConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=INDIRECT(CONCATENATE(\"MIN_REPAYMENT_\",$E1))", + "=INDIRECT(CONCATENATE(\"MAX_REPAYMENT_\",$E1))"); + DataValidationConstraint frequencyConstraint = validationHelper + .createExplicitListConstraint(new String[] { "Days", "Weeks", "Months" }); + DataValidationConstraint loanTermConstraint = validationHelper + .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "=$M1*$N1", null); + DataValidationConstraint interestFrequencyConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"INTEREST_FREQUENCY_\",$E1))"); + DataValidationConstraint interestConstraint = validationHelper.createDecimalConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=INDIRECT(CONCATENATE(\"MIN_INTEREST_\",$E1))", + "=INDIRECT(CONCATENATE(\"MAX_INTEREST_\",$E1))"); + DataValidationConstraint amortizationConstraint = validationHelper + .createExplicitListConstraint(new String[] { "Equal principal payments", "Equal installments" }); + DataValidationConstraint interestMethodConstraint = validationHelper + .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 arrearsToleranceConstraint = validationHelper + .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0", null); + DataValidationConstraint graceOnPrincipalPaymentConstraint = validationHelper + .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0", null); + DataValidationConstraint graceOnInterestPaymentConstraint = validationHelper + .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0", null); + DataValidationConstraint graceOnInterestChargedConstraint = validationHelper + .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0", null); + DataValidationConstraint lastRepaymentDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$I1", "=TODAY()", dateFormat); - 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 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 principalValidation = validationHelper.createValidation(principalConstraint, principalRange); - DataValidation loanTermValidation = validationHelper.createValidation(loanTermConstraint, loanTermRange); - 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 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 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 principalValidation = validationHelper.createValidation(principalConstraint, principalRange); + DataValidation loanTermValidation = validationHelper.createValidation(loanTermConstraint, loanTermRange); + 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); - interestFrequencyValidation.setSuppressDropDownArrow(true); + interestFrequencyValidation.setSuppressDropDownArrow(true); - worksheet.addValidationData(officeValidation); - worksheet.addValidationData(loanTypeValidation); - worksheet.addValidationData(clientValidation); - worksheet.addValidationData(productNameValidation); - worksheet.addValidationData(loanOfficerValidation); - worksheet.addValidationData(submittedDateValidation); - worksheet.addValidationData(approvalDateValidation); - worksheet.addValidationData(disbursedDateValidation); - worksheet.addValidationData(paymentTypeValidation); - worksheet.addValidationData(fundNameValidation); - worksheet.addValidationData(principalValidation); - worksheet.addValidationData(repaidFrequencyValidation); - worksheet.addValidationData(loanTermFrequencyValidation); - worksheet.addValidationData(noOfRepaymentsValidation); - worksheet.addValidationData(loanTermValidation); - worksheet.addValidationData(interestValidation); - worksheet.addValidationData(interestFrequencyValidation); - worksheet.addValidationData(amortizationValidation); - worksheet.addValidationData(interestMethodValidation); - worksheet.addValidationData(interestCalculationPeriodValidation); - worksheet.addValidationData(repaymentStrategyValidation); - worksheet.addValidationData(arrearsToleranceValidation); - worksheet.addValidationData(graceOnPrincipalPaymentValidation); - worksheet.addValidationData(graceOnInterestPaymentValidation); - worksheet.addValidationData(graceOnInterestChargedValidation); - worksheet.addValidationData(lastRepaymentDateValidation); - worksheet.addValidationData(repaymentTypeValidation); + worksheet.addValidationData(officeValidation); + worksheet.addValidationData(loanTypeValidation); + worksheet.addValidationData(clientValidation); + worksheet.addValidationData(productNameValidation); + worksheet.addValidationData(loanOfficerValidation); + worksheet.addValidationData(submittedDateValidation); + worksheet.addValidationData(approvalDateValidation); + worksheet.addValidationData(disbursedDateValidation); + worksheet.addValidationData(paymentTypeValidation); + worksheet.addValidationData(fundNameValidation); + worksheet.addValidationData(principalValidation); + worksheet.addValidationData(repaidFrequencyValidation); + worksheet.addValidationData(loanTermFrequencyValidation); + worksheet.addValidationData(noOfRepaymentsValidation); + worksheet.addValidationData(loanTermValidation); + worksheet.addValidationData(interestValidation); + worksheet.addValidationData(interestFrequencyValidation); + worksheet.addValidationData(amortizationValidation); + worksheet.addValidationData(interestMethodValidation); + worksheet.addValidationData(interestCalculationPeriodValidation); + worksheet.addValidationData(repaymentStrategyValidation); + worksheet.addValidationData(arrearsToleranceValidation); + worksheet.addValidationData(graceOnPrincipalPaymentValidation); + worksheet.addValidationData(graceOnInterestPaymentValidation); + worksheet.addValidationData(graceOnInterestChargedValidation); + worksheet.addValidationData(lastRepaymentDateValidation); + worksheet.addValidationData(repaymentTypeValidation); - } + } - private void setLayout(Sheet worksheet) { - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - 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.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); - worksheet.setColumnWidth(LoanConstants.APPROVED_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.DISBURSED_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.DISBURSED_PAYMENT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.FUND_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.LOAN_TERM_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.LOAN_TERM_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.NO_OF_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.REPAID_EVERY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.REPAID_EVERY_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.NOMINAL_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.NOMINAL_INTEREST_RATE_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.AMORTIZATION_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.INTEREST_METHOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.INTEREST_CALCULATION_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.ARREARS_TOLERANCE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.REPAYMENT_STRATEGY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.INTEREST_CHARGED_FROM_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.FIRST_REPAYMENT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - 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); + private void setLayout(Sheet worksheet) { + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + 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.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); + worksheet.setColumnWidth(LoanConstants.APPROVED_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.DISBURSED_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.DISBURSED_PAYMENT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.FUND_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.LOAN_TERM_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.LOAN_TERM_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.NO_OF_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.REPAID_EVERY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.REPAID_EVERY_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.NOMINAL_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.NOMINAL_INTEREST_RATE_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.AMORTIZATION_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.INTEREST_METHOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.INTEREST_CALCULATION_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.ARREARS_TOLERANCE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.REPAYMENT_STRATEGY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.INTEREST_CHARGED_FROM_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.FIRST_REPAYMENT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + 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); - 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.PRODUCT_COL, rowHeader, "Product*"); - writeString(LoanConstants.LOAN_OFFICER_NAME_COL, rowHeader, "Loan Officer*"); - writeString(LoanConstants.SUBMITTED_ON_DATE_COL, rowHeader, "Submitted On*"); - writeString(LoanConstants.APPROVED_DATE_COL, rowHeader, "Approved On"); - writeString(LoanConstants.DISBURSED_DATE_COL, rowHeader, "Disbursed Date"); - writeString(LoanConstants.DISBURSED_PAYMENT_TYPE_COL, rowHeader, "Payment Type*"); - writeString(LoanConstants.FUND_NAME_COL, rowHeader, "Fund Name"); - writeString(LoanConstants.PRINCIPAL_COL, rowHeader, "Principal*"); - writeString(LoanConstants.LOAN_TERM_COL, rowHeader, "Loan Term*"); - writeString(LoanConstants.NO_OF_REPAYMENTS_COL, rowHeader, "# of Repayments*"); - writeString(LoanConstants.REPAID_EVERY_COL, rowHeader, "Repaid Every*"); - writeString(LoanConstants.NOMINAL_INTEREST_RATE_COL, rowHeader, "Nominal Interest %*"); - writeString(LoanConstants.AMORTIZATION_COL, rowHeader, "Amortization*"); - writeString(LoanConstants.INTEREST_METHOD_COL, rowHeader, "Interest Method*"); - writeString(LoanConstants.INTEREST_CALCULATION_PERIOD_COL, rowHeader, "Interest Calculation Period*"); - writeString(LoanConstants.ARREARS_TOLERANCE_COL, rowHeader, "Arrears Tolerance"); - writeString(LoanConstants.REPAYMENT_STRATEGY_COL, rowHeader, "Repayment Strategy*"); - writeString(LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL, rowHeader, "Grace-Principal Payment"); - writeString(LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, rowHeader, "Grace-Interest Payment"); - writeString(LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, rowHeader, "Interest-Free Period(s)"); - writeString(LoanConstants.INTEREST_CHARGED_FROM_COL, rowHeader, "Interest Charged From"); - writeString(LoanConstants.FIRST_REPAYMENT_COL, rowHeader, "First Repayment On"); - writeString(LoanConstants.TOTAL_AMOUNT_REPAID_COL, rowHeader, "Amount Repaid"); - 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_ACTIVATION_DATE_COL, rowHeader, "Client Activation Date"); - writeString(LoanConstants.EXTERNAL_ID_COL, rowHeader, "External Id"); - writeString(LoanConstants.CHARGE_ID_1, rowHeader, "Charge Id"); - writeString(LoanConstants.CHARGE_AMOUNT_1, rowHeader, "Charged Amount"); - writeString(LoanConstants.CHARGE_DUE_DATE_1, rowHeader, "Charged On Date"); - writeString(LoanConstants.CHARGE_ID_2, rowHeader, "Charge Id"); - writeString(LoanConstants.CHARGE_AMOUNT_2, rowHeader, "Charged Amount"); - writeString(LoanConstants.CHARGE_DUE_DATE_2, rowHeader, "Charged On Date"); - writeString(LoanConstants.GROUP_ID, rowHeader, "GROUP ID"); - writeString(LoanConstants.LINK_ACCOUNT_ID, rowHeader, "Linked Account No."); + 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.PRODUCT_COL, rowHeader, "Product*"); + writeString(LoanConstants.LOAN_OFFICER_NAME_COL, rowHeader, "Loan Officer*"); + writeString(LoanConstants.SUBMITTED_ON_DATE_COL, rowHeader, "Submitted On*"); + writeString(LoanConstants.APPROVED_DATE_COL, rowHeader, "Approved On"); + writeString(LoanConstants.DISBURSED_DATE_COL, rowHeader, "Disbursed Date"); + writeString(LoanConstants.DISBURSED_PAYMENT_TYPE_COL, rowHeader, "Payment Type*"); + writeString(LoanConstants.FUND_NAME_COL, rowHeader, "Fund Name"); + writeString(LoanConstants.PRINCIPAL_COL, rowHeader, "Principal*"); + writeString(LoanConstants.LOAN_TERM_COL, rowHeader, "Loan Term*"); + writeString(LoanConstants.NO_OF_REPAYMENTS_COL, rowHeader, "# of Repayments*"); + writeString(LoanConstants.REPAID_EVERY_COL, rowHeader, "Repaid Every*"); + writeString(LoanConstants.NOMINAL_INTEREST_RATE_COL, rowHeader, "Nominal Interest %*"); + writeString(LoanConstants.AMORTIZATION_COL, rowHeader, "Amortization*"); + writeString(LoanConstants.INTEREST_METHOD_COL, rowHeader, "Interest Method*"); + writeString(LoanConstants.INTEREST_CALCULATION_PERIOD_COL, rowHeader, "Interest Calculation Period*"); + writeString(LoanConstants.ARREARS_TOLERANCE_COL, rowHeader, "Arrears Tolerance"); + writeString(LoanConstants.REPAYMENT_STRATEGY_COL, rowHeader, "Repayment Strategy*"); + writeString(LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL, rowHeader, "Grace-Principal Payment"); + writeString(LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, rowHeader, "Grace-Interest Payment"); + writeString(LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, rowHeader, "Interest-Free Period(s)"); + writeString(LoanConstants.INTEREST_CHARGED_FROM_COL, rowHeader, "Interest Charged From"); + writeString(LoanConstants.FIRST_REPAYMENT_COL, rowHeader, "First Repayment On"); + writeString(LoanConstants.TOTAL_AMOUNT_REPAID_COL, rowHeader, "Amount Repaid"); + 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_ACTIVATION_DATE_COL, rowHeader, "Client Activation Date"); + writeString(LoanConstants.EXTERNAL_ID_COL, rowHeader, "External Id"); + writeString(LoanConstants.CHARGE_ID_1, rowHeader, "Charge Id"); + writeString(LoanConstants.CHARGE_AMOUNT_1, rowHeader, "Charged Amount"); + writeString(LoanConstants.CHARGE_DUE_DATE_1, rowHeader, "Charged On Date"); + writeString(LoanConstants.CHARGE_ID_2, rowHeader, "Charge Id"); + writeString(LoanConstants.CHARGE_AMOUNT_2, rowHeader, "Charged Amount"); + writeString(LoanConstants.CHARGE_DUE_DATE_2, rowHeader, "Charged On Date"); + writeString(LoanConstants.GROUP_ID, rowHeader, "GROUP ID"); + writeString(LoanConstants.LINK_ACCOUNT_ID, rowHeader, "Linked Account No."); - CellStyle borderStyle = worksheet.getWorkbook().createCellStyle(); - CellStyle doubleBorderStyle = worksheet.getWorkbook().createCellStyle(); - borderStyle.setBorderBottom(CellStyle.BORDER_THIN); - doubleBorderStyle.setBorderBottom(CellStyle.BORDER_THIN); - doubleBorderStyle.setBorderRight(CellStyle.BORDER_THICK); - for (int colNo = 0; colNo < 35; colNo++) { - Cell cell = rowHeader.getCell(colNo); - if (cell == null) - rowHeader.createCell(colNo); - rowHeader.getCell(colNo).setCellStyle(borderStyle); - } - rowHeader.getCell(LoanConstants.FIRST_REPAYMENT_COL).setCellStyle(doubleBorderStyle); - rowHeader.getCell(LoanConstants.REPAYMENT_TYPE_COL).setCellStyle(doubleBorderStyle); - } + CellStyle borderStyle = worksheet.getWorkbook().createCellStyle(); + CellStyle doubleBorderStyle = worksheet.getWorkbook().createCellStyle(); + borderStyle.setBorderBottom(CellStyle.BORDER_THIN); + doubleBorderStyle.setBorderBottom(CellStyle.BORDER_THIN); + doubleBorderStyle.setBorderRight(CellStyle.BORDER_THICK); + for (int colNo = 0; colNo < 35; colNo++) { + Cell cell = rowHeader.getCell(colNo); + if (cell == null) + rowHeader.createCell(colNo); + rowHeader.getCell(colNo).setCellStyle(borderStyle); + } + rowHeader.getCell(LoanConstants.FIRST_REPAYMENT_COL).setCellStyle(doubleBorderStyle); + rowHeader.getCell(LoanConstants.REPAYMENT_TYPE_COL).setCellStyle(doubleBorderStyle); + } - private void setDefaults(Sheet worksheet) { + private void setDefaults(Sheet worksheet) { - 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)))"); - 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) - + "))),\"\",INDIRECT(CONCATENATE(\"PRINCIPAL_\",$E" + (rowNo + 1) + ")))"); - writeFormula(LoanConstants.REPAID_EVERY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"REPAYMENT_EVERY_\",$E" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"REPAYMENT_EVERY_\",$E" + (rowNo + 1) + ")))"); - writeFormula(LoanConstants.REPAID_EVERY_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"REPAYMENT_FREQUENCY_\",$E" - + (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_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.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.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) + ")))"); + 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)))"); + 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) + + "))),\"\",INDIRECT(CONCATENATE(\"PRINCIPAL_\",$E" + (rowNo + 1) + ")))"); + writeFormula(LoanConstants.REPAID_EVERY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"REPAYMENT_EVERY_\",$E" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"REPAYMENT_EVERY_\",$E" + (rowNo + 1) + ")))"); + writeFormula(LoanConstants.REPAID_EVERY_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"REPAYMENT_FREQUENCY_\",$E" + + (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_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.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.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) + ")))"); - } - } + } + } - private void setNames(Sheet worksheet) { - Workbook loanWorkbook = worksheet.getWorkbook(); - List officeNames = officeSheetPopulator.getOfficeNames(); - List products = productSheetPopulator.getProducts(); + private void setNames(Sheet worksheet) { + Workbook loanWorkbook = worksheet.getWorkbook(); + List officeNames = officeSheetPopulator.getOfficeNames(); + List products = productSheetPopulator.getProducts(); - // Office Names - Name officeGroup = loanWorkbook.createName(); - officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + // Office Names + Name officeGroup = loanWorkbook.createName(); + officeGroup.setNameName("Office"); + 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); - Name clientName = loanWorkbook.createName(); - Name loanOfficerName = loanWorkbook.createName(); - Name groupName = loanWorkbook.createName(); + // 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); + 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]); - } - if (officeNameToBeginEndIndexesOfClients != null) { - clientName.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - 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]); - } + if (officeNameToBeginEndIndexesOfStaff != null) { + loanOfficerName.setNameName("Staff_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); + 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]); + } + if (officeNameToBeginEndIndexesOfGroups != null) { + groupName.setNameName("Group_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); + groupName.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfGroups[0] + ":$B$" + + officeNameToBeginEndIndexesOfGroups[1]); + } - } + } - // Product Name - Name productGroup = loanWorkbook.createName(); - productGroup.setNameName("Products"); - productGroup.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$B$2:$B$" + (productSheetPopulator.getProductsSize() + 1)); + // Product Name + Name productGroup = loanWorkbook.createName(); + productGroup.setNameName("Products"); + 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)); + // Fund Name + Name fundGroup = loanWorkbook.createName(); + fundGroup.setNameName("Funds"); + 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)); + // Payment Type Name + Name paymentTypeGroup = loanWorkbook.createName(); + paymentTypeGroup.setNameName("PaymentTypes"); + 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 - // Every, - // Repayment Every Frequency, Interest Rate, Min Interest Rate, Max - // Interest Rate, Interest Frequency, Amortization, Interest Type, - // Interest Calculation Period, Transaction Processing Strategy, Arrears - // Tolerance, GraceOnPrincipalPayment, GraceOnInterestPayment, - // GraceOnInterestCharged, StartDate Names for each loan product - for (Integer i = 0; i < products.size(); i++) { - Name fundName = loanWorkbook.createName(); - Name principalName = loanWorkbook.createName(); - Name minPrincipalName = loanWorkbook.createName(); - Name maxPrincipalName = loanWorkbook.createName(); - Name noOfRepaymentName = loanWorkbook.createName(); - Name minNoOfRepayment = loanWorkbook.createName(); - Name maxNoOfRepaymentName = loanWorkbook.createName(); - Name repaymentEveryName = loanWorkbook.createName(); - Name repaymentFrequencyName = loanWorkbook.createName(); - Name interestName = loanWorkbook.createName(); - Name minInterestName = loanWorkbook.createName(); - Name maxInterestName = loanWorkbook.createName(); - Name interestFrequencyName = loanWorkbook.createName(); - Name amortizationName = loanWorkbook.createName(); - Name interestTypeName = loanWorkbook.createName(); - Name interestCalculationPeriodName = loanWorkbook.createName(); - Name transactionProcessingStrategyName = loanWorkbook.createName(); - Name arrearsToleranceName = loanWorkbook.createName(); - Name graceOnPrincipalPaymentName = loanWorkbook.createName(); - Name graceOnInterestPaymentName = loanWorkbook.createName(); - Name graceOnInterestChargedName = loanWorkbook.createName(); - Name startDateName = loanWorkbook.createName(); - String productName = products.get(i).getName().replaceAll("[ ]", "_"); - fundName.setNameName("FUND_" + productName); - principalName.setNameName("PRINCIPAL_" + productName); - minPrincipalName.setNameName("MIN_PRINCIPAL_" + productName); - maxPrincipalName.setNameName("MAX_PRINCIPAL_" + productName); - noOfRepaymentName.setNameName("NO_REPAYMENT_" + productName); - minNoOfRepayment.setNameName("MIN_REPAYMENT_" + productName); - maxNoOfRepaymentName.setNameName("MAX_REPAYMENT_" + productName); - repaymentEveryName.setNameName("REPAYMENT_EVERY_" + productName); - repaymentFrequencyName.setNameName("REPAYMENT_FREQUENCY_" + productName); - interestName.setNameName("INTEREST_" + productName); - minInterestName.setNameName("MIN_INTEREST_" + productName); - maxInterestName.setNameName("MAX_INTEREST_" + productName); - interestFrequencyName.setNameName("INTEREST_FREQUENCY_" + productName); - amortizationName.setNameName("AMORTIZATION_" + productName); - interestTypeName.setNameName("INTEREST_TYPE_" + productName); - interestCalculationPeriodName.setNameName("INTEREST_CALCULATION_" + productName); - transactionProcessingStrategyName.setNameName("STRATEGY_" + productName); - arrearsToleranceName.setNameName("ARREARS_TOLERANCE_" + productName); - graceOnPrincipalPaymentName.setNameName("GRACE_PRINCIPAL_" + productName); - graceOnInterestPaymentName.setNameName("GRACE_INTEREST_PAYMENT_" + productName); - 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)); - 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)); - } - } + // Default Fund, Default Principal, Min Principal, Max Principal, + // Default No. of Repayments, Min Repayments, Max Repayments, Repayment + // Every, + // Repayment Every Frequency, Interest Rate, Min Interest Rate, Max + // Interest Rate, Interest Frequency, Amortization, Interest Type, + // Interest Calculation Period, Transaction Processing Strategy, Arrears + // Tolerance, GraceOnPrincipalPayment, GraceOnInterestPayment, + // GraceOnInterestCharged, StartDate Names for each loan product + for (Integer i = 0; i < products.size(); i++) { + Name fundName = loanWorkbook.createName(); + Name principalName = loanWorkbook.createName(); + Name minPrincipalName = loanWorkbook.createName(); + Name maxPrincipalName = loanWorkbook.createName(); + Name noOfRepaymentName = loanWorkbook.createName(); + Name minNoOfRepayment = loanWorkbook.createName(); + Name maxNoOfRepaymentName = loanWorkbook.createName(); + Name repaymentEveryName = loanWorkbook.createName(); + Name repaymentFrequencyName = loanWorkbook.createName(); + Name interestName = loanWorkbook.createName(); + Name minInterestName = loanWorkbook.createName(); + Name maxInterestName = loanWorkbook.createName(); + Name interestFrequencyName = loanWorkbook.createName(); + Name amortizationName = loanWorkbook.createName(); + Name interestTypeName = loanWorkbook.createName(); + Name interestCalculationPeriodName = loanWorkbook.createName(); + Name transactionProcessingStrategyName = loanWorkbook.createName(); + Name arrearsToleranceName = loanWorkbook.createName(); + Name graceOnPrincipalPaymentName = loanWorkbook.createName(); + Name graceOnInterestPaymentName = loanWorkbook.createName(); + Name graceOnInterestChargedName = loanWorkbook.createName(); + Name startDateName = loanWorkbook.createName(); + String productName = products.get(i).getName().replaceAll("[ ]", "_"); + fundName.setNameName("FUND_" + productName); + principalName.setNameName("PRINCIPAL_" + productName); + minPrincipalName.setNameName("MIN_PRINCIPAL_" + productName); + maxPrincipalName.setNameName("MAX_PRINCIPAL_" + productName); + noOfRepaymentName.setNameName("NO_REPAYMENT_" + productName); + minNoOfRepayment.setNameName("MIN_REPAYMENT_" + productName); + maxNoOfRepaymentName.setNameName("MAX_REPAYMENT_" + productName); + repaymentEveryName.setNameName("REPAYMENT_EVERY_" + productName); + repaymentFrequencyName.setNameName("REPAYMENT_FREQUENCY_" + productName); + interestName.setNameName("INTEREST_" + productName); + minInterestName.setNameName("MIN_INTEREST_" + productName); + maxInterestName.setNameName("MAX_INTEREST_" + productName); + interestFrequencyName.setNameName("INTEREST_FREQUENCY_" + productName); + amortizationName.setNameName("AMORTIZATION_" + productName); + interestTypeName.setNameName("INTEREST_TYPE_" + productName); + interestCalculationPeriodName.setNameName("INTEREST_CALCULATION_" + productName); + transactionProcessingStrategyName.setNameName("STRATEGY_" + productName); + arrearsToleranceName.setNameName("ARREARS_TOLERANCE_" + productName); + graceOnPrincipalPaymentName.setNameName("GRACE_PRINCIPAL_" + productName); + graceOnInterestPaymentName.setNameName("GRACE_INTEREST_PAYMENT_" + productName); + 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)); + 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 cf17656d3..d705dc56c 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 @@ -38,262 +38,262 @@ import java.text.SimpleDateFormat; import java.util.*; public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { - private OfficeSheetPopulator officeSheetPopulator; - private ClientSheetPopulator clientSheetPopulator; - private ExtrasSheetPopulator extrasSheetPopulator; - private List allloans; - private Map clientIdToClientExternalId; + private OfficeSheetPopulator officeSheetPopulator; + private ClientSheetPopulator clientSheetPopulator; + private ExtrasSheetPopulator extrasSheetPopulator; + private List allloans; + private Map clientIdToClientExternalId; - public LoanRepaymentWorkbookPopulator(List loans, OfficeSheetPopulator officeSheetPopulator, - ClientSheetPopulator clientSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) { - this.allloans = loans; - this.officeSheetPopulator = officeSheetPopulator; - this.clientSheetPopulator = clientSheetPopulator; - this.extrasSheetPopulator = extrasSheetPopulator; - } + public LoanRepaymentWorkbookPopulator(List loans, OfficeSheetPopulator officeSheetPopulator, + ClientSheetPopulator clientSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) { + this.allloans = loans; + this.officeSheetPopulator = officeSheetPopulator; + this.clientSheetPopulator = clientSheetPopulator; + this.extrasSheetPopulator = extrasSheetPopulator; + } - @Override - 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); - setClientIdToClientExternalId(); - populateLoansTable(loanRepaymentSheet,dateFormat); - setRules(loanRepaymentSheet,dateFormat); - setDefaults(loanRepaymentSheet,dateFormat); - } + @Override + 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); + setClientIdToClientExternalId(); + 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.put(client.getId(),client.getExternalId()); - } - } + private void setClientIdToClientExternalId() { + clientIdToClientExternalId =new HashMap<>(); + Listallclients=clientSheetPopulator.getClients(); + for (ClientData client: allclients) { + if (client.getExternalId()!=null) + clientIdToClientExternalId.put(client.getId(),client.getExternalId()); + } + } - 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)))"); - 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))"); - 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))"); - 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))"); + 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)))"); + 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))"); + 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))"); + 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))"); - 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(); - CellStyle dateCellStyle = workbook.createCellStyle(); - short df = workbook.createDataFormat().getFormat(dateFormat); - dateCellStyle.setDataFormat(df); - row.getCell(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL).setCellStyle(dateCellStyle); - } - } + 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(); + CellStyle dateCellStyle = workbook.createCellStyle(); + short df = workbook.createDataFormat().getFormat(dateFormat); + dateCellStyle.setDataFormat(df); + row.getCell(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL).setCellStyle(dateCellStyle); + } + } - 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); + 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); - 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 paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes"); - DataValidationConstraint repaymentDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, - "=VLOOKUP($D1,$T$2:$X$" + (allloans.size() + 1) + ",4,FALSE)", "=TODAY()", dateFormat); + 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 paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes"); + DataValidationConstraint repaymentDateConstraint = validationHelper.createDateConstraint( + 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 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); - worksheet.addValidationData(officeValidation); - worksheet.addValidationData(clientValidation); - worksheet.addValidationData(accountNumberValidation); - worksheet.addValidationData(repaymentTypeValidation); - worksheet.addValidationData(repaymentDateValidation); + worksheet.addValidationData(officeValidation); + worksheet.addValidationData(clientValidation); + worksheet.addValidationData(accountNumberValidation); + worksheet.addValidationData(repaymentTypeValidation); + worksheet.addValidationData(repaymentDateValidation); - } + } - private void setNames(Sheet worksheet) { - ArrayList officeNames = new ArrayList<>(officeSheetPopulator.getOfficeNames()); - Workbook loanRepaymentWorkbook = worksheet.getWorkbook(); - // Office Names - Name officeGroup = loanRepaymentWorkbook.createName(); - officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + private void setNames(Sheet worksheet) { + ArrayList officeNames = new ArrayList<>(officeSheetPopulator.getOfficeNames()); + Workbook loanRepaymentWorkbook = worksheet.getWorkbook(); + // Office Names + Name officeGroup = loanRepaymentWorkbook.createName(); + officeGroup.setNameName("Office"); + 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); - 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]); - } - } + // Clients Named after Offices + for (Integer i = 0; i < officeNames.size(); 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]); + } + } - // Counting clients with active loans and starting and end addresses of - // cells - HashMap clientNameToBeginEndIndexes = new HashMap(); - ArrayList clientsWithActiveLoans = new ArrayList(); - ArrayList clientIdsWithActiveLoans = new ArrayList(); - int startIndex = 1, endIndex = 1; - String clientName = ""; - String clientId = ""; - for (int i = 0; i < allloans.size(); i++) { - if (!clientName.equals(allloans.get(i).getClientName())) { - endIndex = i + 1; - clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); - startIndex = i + 2; - clientName = allloans.get(i).getClientName(); - clientId = allloans.get(i).getClientId().toString(); - if (!clientsWithActiveLoans.contains(clientName)) { - clientsWithActiveLoans.add(clientName); - clientIdsWithActiveLoans.add(clientId); - } - } - if (i == allloans.size() - 1) { - endIndex = i + 2; - clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); - } - } + // Counting clients with active loans and starting and end addresses of + // cells + HashMap clientNameToBeginEndIndexes = new HashMap(); + ArrayList clientsWithActiveLoans = new ArrayList(); + ArrayList clientIdsWithActiveLoans = new ArrayList(); + int startIndex = 1, endIndex = 1; + String clientName = ""; + String clientId = ""; + for (int i = 0; i < allloans.size(); i++) { + if (!clientName.equals(allloans.get(i).getClientName())) { + endIndex = i + 1; + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); + startIndex = i + 2; + clientName = allloans.get(i).getClientName(); + clientId = allloans.get(i).getClientId().toString(); + if (!clientsWithActiveLoans.contains(clientName)) { + clientsWithActiveLoans.add(clientName); + clientIdsWithActiveLoans.add(clientId); + } + } + if (i == allloans.size() - 1) { + endIndex = i + 2; + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); + } + } - // 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]); - } + // 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]); + } - // Payment Type Name - Name paymentTypeGroup = loanRepaymentWorkbook.createName(); - paymentTypeGroup.setNameName("PaymentTypes"); - paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); - } + // Payment Type Name + Name paymentTypeGroup = loanRepaymentWorkbook.createName(); + paymentTypeGroup.setNameName("PaymentTypes"); + paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); + } - private void populateLoansTable(Sheet loanRepaymentSheet,String dateFormat) { - int rowIndex = 1; - Row row; - Workbook workbook = loanRepaymentSheet.getWorkbook(); - CellStyle dateCellStyle = workbook.createCellStyle(); - short df = workbook.createDataFormat().getFormat(dateFormat); - dateCellStyle.setDataFormat(df); - SimpleDateFormat outputFormat = new SimpleDateFormat(dateFormat); - SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date date = null; - 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_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()); - if (loan.getDisbursementDate() != null) { - try { - date = inputFormat.parse(loan.getDisbursementDate().toString()); - } catch (ParseException e) { - e.printStackTrace(); - } - writeDate(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, row, - outputFormat.format(date), dateCellStyle,dateFormat); - } - } - } + private void populateLoansTable(Sheet loanRepaymentSheet,String dateFormat) { + int rowIndex = 1; + Row row; + Workbook workbook = loanRepaymentSheet.getWorkbook(); + CellStyle dateCellStyle = workbook.createCellStyle(); + short df = workbook.createDataFormat().getFormat(dateFormat); + dateCellStyle.setDataFormat(df); + SimpleDateFormat outputFormat = new SimpleDateFormat(dateFormat); + SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + 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_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()); + if (loan.getDisbursementDate() != null) { + try { + date = inputFormat.parse(loan.getDisbursementDate().toString()); + } catch (ParseException e) { + e.printStackTrace(); + } + writeDate(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, row, + outputFormat.format(date), dateCellStyle,dateFormat); + } + } + } - private void setLayout(Sheet worksheet) { - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - 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.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.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); - worksheet.setColumnWidth(LoanRepaymentConstants.ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanRepaymentConstants.CHECK_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanRepaymentConstants.RECEIPT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - 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_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_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.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.AMOUNT_COL, rowHeader, "Amount Repaid*"); - writeString(LoanRepaymentConstants.REPAID_ON_DATE_COL, rowHeader, "Date*"); - writeString(LoanRepaymentConstants.REPAYMENT_TYPE_COL, rowHeader, "Type*"); - writeString(LoanRepaymentConstants.ACCOUNT_NO_COL, rowHeader, "Account No"); - writeString(LoanRepaymentConstants.CHECK_NO_COL, rowHeader, "Check No"); - writeString(LoanRepaymentConstants.RECEIPT_NO_COL, rowHeader, "Receipt No"); - 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_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_LOAN_DISBURSEMENT_DATE_COL, rowHeader, "Lookup Loan Disbursement Date"); + private void setLayout(Sheet worksheet) { + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + 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.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.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); + worksheet.setColumnWidth(LoanRepaymentConstants.ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanRepaymentConstants.CHECK_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanRepaymentConstants.RECEIPT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + 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_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_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.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.AMOUNT_COL, rowHeader, "Amount Repaid*"); + writeString(LoanRepaymentConstants.REPAID_ON_DATE_COL, rowHeader, "Date*"); + writeString(LoanRepaymentConstants.REPAYMENT_TYPE_COL, rowHeader, "Type*"); + writeString(LoanRepaymentConstants.ACCOUNT_NO_COL, rowHeader, "Account No"); + writeString(LoanRepaymentConstants.CHECK_NO_COL, rowHeader, "Check No"); + writeString(LoanRepaymentConstants.RECEIPT_NO_COL, rowHeader, "Receipt No"); + 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_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_LOAN_DISBURSEMENT_DATE_COL, rowHeader, "Lookup Loan Disbursement Date"); - } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookPopulatorServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookPopulatorServiceImpl.java index 14cf41046..a95e240f1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookPopulatorServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookPopulatorServiceImpl.java @@ -131,12 +131,12 @@ public class BulkImportWorkbookPopulatorServiceImpl implements BulkImportWorkboo final LoanReadPlatformService loanReadPlatformService, final GLAccountReadPlatformService glAccountReadPlatformService, final SavingsAccountReadPlatformService savingsAccountReadPlatformService, - final CodeValueReadPlatformService codeValueReadPlatformService, - final SavingsProductReadPlatformService savingsProductReadPlatformService, - final ProductReadPlatformService productReadPlatformService, - final ChargeReadPlatformService chargeReadPlatformService, - final DepositProductReadPlatformService depositProductReadPlatformService, - final RoleReadPlatformService roleReadPlatformService) { + final CodeValueReadPlatformService codeValueReadPlatformService, + final SavingsProductReadPlatformService savingsProductReadPlatformService, + final ProductReadPlatformService productReadPlatformService, + final ChargeReadPlatformService chargeReadPlatformService, + final DepositProductReadPlatformService depositProductReadPlatformService, + final RoleReadPlatformService roleReadPlatformService) { this.officeReadPlatformService = officeReadPlatformService; this.staffReadPlatformService = staffReadPlatformService; this.context = context; @@ -158,84 +158,84 @@ public class BulkImportWorkbookPopulatorServiceImpl implements BulkImportWorkboo this.roleReadPlatformService=roleReadPlatformService; } - @Override - public Response getTemplate(String entityType, Long officeId, Long staffId,final String dateFormat) { - WorkbookPopulator populator=null; - final Workbook workbook=new HSSFWorkbook(); - if(entityType!=null){ - if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_PERSON.toString())|| - entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())) { - populator = populateClientWorkbook(entityType,officeId, staffId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CENTERS.toString())) { - populator=populateCenterWorkbook(officeId,staffId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GROUPS.toString())) { - populator = populateGroupsWorkbook(officeId, staffId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.LOANS.toString())) { - populator = populateLoanWorkbook(officeId, staffId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.LOAN_TRANSACTIONS.toString())) { - populator = populateLoanRepaymentWorkbook(officeId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GL_JOURNAL_ENTRIES.toString())) { - populator = populateJournalEntriesWorkbook(officeId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GUARANTORS.toString())) { - populator = populateGuarantorWorkbook(officeId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.OFFICES.toString())) { - populator=populateOfficeWorkbook(); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CHART_OF_ACCOUNTS.toString())) { - populator=populateChartOfAccountsWorkbook(); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.STAFF.toString())) { - populator=populateStaffWorkbook(officeId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SHARE_ACCOUNTS.toString())) { - populator=populateSharedAcountsWorkbook(officeId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_ACCOUNT.toString())) { - populator=populateSavingsAccountWorkbook(officeId,staffId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_TRANSACTIONS.toString())) { - populator=populateSavingsTransactionWorkbook(officeId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS.toString())) { - populator=populateRecurringDepositWorkbook(officeId,staffId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString())) { - populator=populateRecurringDepositTransactionWorkbook(officeId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS.toString())) { - populator = populateFixedDepositWorkbook(officeId, staffId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS.toString())){ - populator=populateFixedDepositTransactionsWorkbook(officeId); - }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.USERS.toString())){ - populator=populateUserWorkbook(officeId,staffId); - }else { - throw new GeneralPlatformDomainRuleException("error.msg.unable.to.find.resource", - "Unable to find requested resource"); - } - populator.populate(workbook,dateFormat); - return buildResponse(workbook, entityType); - }else { - throw new GeneralPlatformDomainRuleException("error.msg.given.entity.type.null", - "Given Entity type is null"); - } - } + @Override + public Response getTemplate(String entityType, Long officeId, Long staffId,final String dateFormat) { + WorkbookPopulator populator=null; + final Workbook workbook=new HSSFWorkbook(); + if(entityType!=null){ + if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_PERSON.toString())|| + entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())) { + populator = populateClientWorkbook(entityType,officeId, staffId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CENTERS.toString())) { + populator=populateCenterWorkbook(officeId,staffId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GROUPS.toString())) { + populator = populateGroupsWorkbook(officeId, staffId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.LOANS.toString())) { + populator = populateLoanWorkbook(officeId, staffId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.LOAN_TRANSACTIONS.toString())) { + populator = populateLoanRepaymentWorkbook(officeId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GL_JOURNAL_ENTRIES.toString())) { + populator = populateJournalEntriesWorkbook(officeId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GUARANTORS.toString())) { + populator = populateGuarantorWorkbook(officeId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.OFFICES.toString())) { + populator=populateOfficeWorkbook(); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CHART_OF_ACCOUNTS.toString())) { + populator=populateChartOfAccountsWorkbook(); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.STAFF.toString())) { + populator=populateStaffWorkbook(officeId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SHARE_ACCOUNTS.toString())) { + populator=populateSharedAcountsWorkbook(officeId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_ACCOUNT.toString())) { + populator=populateSavingsAccountWorkbook(officeId,staffId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_TRANSACTIONS.toString())) { + populator=populateSavingsTransactionWorkbook(officeId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS.toString())) { + populator=populateRecurringDepositWorkbook(officeId,staffId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString())) { + populator=populateRecurringDepositTransactionWorkbook(officeId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS.toString())) { + populator = populateFixedDepositWorkbook(officeId, staffId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS.toString())){ + populator=populateFixedDepositTransactionsWorkbook(officeId); + }else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.USERS.toString())){ + populator=populateUserWorkbook(officeId,staffId); + }else { + throw new GeneralPlatformDomainRuleException("error.msg.unable.to.find.resource", + "Unable to find requested resource"); + } + populator.populate(workbook,dateFormat); + return buildResponse(workbook, entityType); + }else { + throw new GeneralPlatformDomainRuleException("error.msg.given.entity.type.null", + "Given Entity type is null"); + } + } - private WorkbookPopulator populateClientWorkbook(final String entityType ,final Long officeId, final Long staffId) { + 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; + 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) { @@ -279,395 +279,395 @@ public class BulkImportWorkbookPopulatorServiceImpl implements BulkImportWorkboo return staff; } private List fetchCodeValuesByCodeName(String codeName){ - List codeValues=null; - if (codeName!=null){ - codeValues=(List)codeValueReadPlatformService.retrieveCodeValuesByCode(codeName); - }else { - throw new NullPointerException(); - } - return codeValues; + 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; + 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)); + 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); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CENTER_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); - List offices = fetchOffices(officeId); - 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)); - } - private List fetchCenters(Long officeId) { - Listcenters=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); - } - - 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()) { - 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()) { - clients.add(client); - } - } - } - return clients; - } + private WorkbookPopulator populateGroupsWorkbook(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.CENTER_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); + List offices = fetchOffices(officeId); + 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)); + } + private List fetchCenters(Long officeId) { + Listcenters=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); + } + + 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()) { + 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()) { + clients.add(client); + } + } + } + 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); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.LOAN_PRODUCT_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List staff = fetchStaff(staffId); - List clients = fetchClients(officeId); - List groups = fetchGroups(officeId); - List loanproducts = fetchLoanProducts(); - List funds = fetchFunds(); - List paymentTypes = fetchPaymentTypes(); - List currencies = fetchCurrencies(); - return new LoanWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new GroupSheetPopulator(groups, offices), new PersonnelSheetPopulator(staff, offices), - new LoanProductSheetPopulator(loanproducts), new ExtrasSheetPopulator(funds, paymentTypes, currencies)); - } + private WorkbookPopulator populateLoanWorkbook(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); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.LOAN_PRODUCT_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List staff = fetchStaff(staffId); + List clients = fetchClients(officeId); + List groups = fetchGroups(officeId); + List loanproducts = fetchLoanProducts(); + List funds = fetchFunds(); + List paymentTypes = fetchPaymentTypes(); + List currencies = fetchCurrencies(); + return new LoanWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), + new GroupSheetPopulator(groups, offices), new PersonnelSheetPopulator(staff, offices), + new LoanProductSheetPopulator(loanproducts), new ExtrasSheetPopulator(funds, paymentTypes, currencies)); + } - private List fetchCurrencies() { - List currencies =(List) this.currencyReadPlatformService. - retrieveAllPlatformCurrencies(); - return currencies; - } + private List fetchCurrencies() { + List currencies =(List) this.currencyReadPlatformService. + retrieveAllPlatformCurrencies(); + return currencies; + } - private List fetchPaymentTypes() { - List paymentTypeData =(List) this.paymentTypeReadPlatformService - .retrieveAllPaymentTypes(); - return paymentTypeData; - } + private List fetchPaymentTypes() { + List paymentTypeData =(List) this.paymentTypeReadPlatformService + .retrieveAllPaymentTypes(); + return paymentTypeData; + } - private List fetchFunds() { - List funds =(List) this.fundReadPlatformService.retrieveAllFunds(); - return funds; - } + private List fetchFunds() { + List funds =(List) this.fundReadPlatformService.retrieveAllFunds(); + return funds; + } - private List fetchLoanProducts() { - Listloanproducts =(List) this.loanProductReadPlatformService - .retrieveAllLoanProducts(); - return loanproducts; - } + private List fetchLoanProducts() { + Listloanproducts =(List) this.loanProductReadPlatformService + .retrieveAllLoanProducts(); + return loanproducts; + } - private List fetchGroups(Long officeId) { - List groups = null; - if (officeId == null) { - groups = (List) this.groupReadPlatformService.retrieveAll(null, null); - } else { - SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null); - groups = (List)groupReadPlatformService.retrieveAll(searchParameters,null); - } + private List fetchGroups(Long officeId) { + List groups = null; + if (officeId == null) { + groups = (List) this.groupReadPlatformService.retrieveAll(null, null); + } else { + SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null); + groups = (List)groupReadPlatformService.retrieveAll(searchParameters,null); + } - return groups; - } + return groups; + } - private WorkbookPopulator populateLoanRepaymentWorkbook(Long officeId) { - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List clients = fetchClients(officeId); - List funds = fetchFunds(); - 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)); - } + private WorkbookPopulator populateLoanRepaymentWorkbook(Long officeId) { + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List clients = fetchClients(officeId); + List funds = fetchFunds(); + 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)); + } - private List fetchLoanAccounts(final Long officeId) { - List loanAccounts = null; - if(officeId==null){ - loanAccounts= loanReadPlatformService.retrieveAll(null).getPageItems(); - }else { - SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null); - loanAccounts = loanReadPlatformService.retrieveAll(searchParameters).getPageItems(); - } - return loanAccounts; - } + private List fetchLoanAccounts(final Long officeId) { + List loanAccounts = null; + if(officeId==null){ + loanAccounts= loanReadPlatformService.retrieveAll(null).getPageItems(); + }else { + SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null); + loanAccounts = loanReadPlatformService.retrieveAll(searchParameters).getPageItems(); + } + return loanAccounts; + } - private WorkbookPopulator populateJournalEntriesWorkbook(Long officeId) { - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GL_ACCOUNT_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List glAccounts = fetchGLAccounts(); - List funds = fetchFunds(); - List paymentTypes = fetchPaymentTypes(); - List currencies = fetchCurrencies(); - return new JournalEntriesWorkbookPopulator(new OfficeSheetPopulator(offices), - new GlAccountSheetPopulator(glAccounts), new ExtrasSheetPopulator(funds, paymentTypes, currencies)); - } + private WorkbookPopulator populateJournalEntriesWorkbook(Long officeId) { + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GL_ACCOUNT_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List glAccounts = fetchGLAccounts(); + List funds = fetchFunds(); + List paymentTypes = fetchPaymentTypes(); + List currencies = fetchCurrencies(); + return new JournalEntriesWorkbookPopulator(new OfficeSheetPopulator(offices), + new GlAccountSheetPopulator(glAccounts), new ExtrasSheetPopulator(funds, paymentTypes, currencies)); + } - private List fetchGLAccounts() { - List glaccounts = (List) this.glAccountReadPlatformService. - retrieveAllGLAccounts(null, null, null, - null, null, null); - return glaccounts; - } + private List fetchGLAccounts() { + List glaccounts = (List) this.glAccountReadPlatformService. + retrieveAllGLAccounts(null, null, null, + null, null, null); + return glaccounts; + } - private WorkbookPopulator populateGuarantorWorkbook(Long officeId) { - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); - List offices = fetchOffices(officeId); - Listclients=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); - } + private WorkbookPopulator populateGuarantorWorkbook(Long officeId) { + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); + List offices = fetchOffices(officeId); + Listclients=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); + } - private List fetchSavingsAccounts(Long officeId) { - 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(); - } - return savingsAccounts; - } + private List fetchSavingsAccounts(Long officeId) { + 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(); + } + return savingsAccounts; + } - private WorkbookPopulator populateOfficeWorkbook() { - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); - List offices = fetchOffices(null); - return new OfficeWorkbookPopulator(offices); - } + 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 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); - return new StaffWorkbookPopulator(new OfficeSheetPopulator(offices)); - } + private WorkbookPopulator populateStaffWorkbook(Long officeId) { + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); + 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 savingsAccounts = fetchSavingsAccounts(officeId); - return new SharedAccountWorkBookPopulator(new SharedProductsSheetPopulator(shareProductDataList,chargesForShares), - new ClientSheetPopulator(clientDataList,officeDataList),new SavingsAccountSheetPopulator(savingsAccounts)); - } + 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 savingsAccounts = fetchSavingsAccounts(officeId); + return new SharedAccountWorkBookPopulator(new SharedProductsSheetPopulator(shareProductDataList,chargesForShares), + new ClientSheetPopulator(clientDataList,officeDataList),new SavingsAccountSheetPopulator(savingsAccounts)); + } - private List fetchChargesForShares() { - ListchargesForShares=(List) chargeReadPlatformService.retrieveSharesApplicableCharges(); - return chargesForShares; - } + private List fetchChargesForShares() { + ListchargesForShares=(List) chargeReadPlatformService.retrieveSharesApplicableCharges(); + return chargesForShares; + } - private List fetchSharedProducts() { - 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); - } - } - return sharedProductDataList; - } + private List fetchSharedProducts() { + 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); + } + } + 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); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.SAVINGS_PRODUCT_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List staff = fetchStaff(staffId); - List clients = fetchClients(officeId); - List groups = fetchGroups(officeId); - 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 populateSavingsAccountWorkbook(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); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.SAVINGS_PRODUCT_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List staff = fetchStaff(staffId); + List clients = fetchClients(officeId); + List groups = fetchGroups(officeId); + 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); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List clients = fetchClients(officeId); - List funds = fetchFunds(); - List paymentTypes = fetchPaymentTypes(); - List currencies = fetchCurrencies(); - List savingsAccounts=fetchSavingsAccounts(officeId); - return new SavingsTransactionsWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts); - } + private WorkbookPopulator populateSavingsTransactionWorkbook(Long officeId) { + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List clients = fetchClients(officeId); + List funds = fetchFunds(); + List paymentTypes = fetchPaymentTypes(); + List currencies = fetchCurrencies(); + List savingsAccounts=fetchSavingsAccounts(officeId); + return new SavingsTransactionsWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), + new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts); + } - 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); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.RECURRING_DEPOSIT_PRODUCT_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List clients = fetchClients(officeId); - List staff = fetchStaff(staffId); - List recurringDepositProducts = fetchRecurringDepositProducts(); - return new RecurringDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new PersonnelSheetPopulator(staff,offices),new RecurringDepositProductSheetPopulator(recurringDepositProducts)); - } + 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); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.RECURRING_DEPOSIT_PRODUCT_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List clients = fetchClients(officeId); + List staff = fetchStaff(staffId); + List recurringDepositProducts = fetchRecurringDepositProducts(); + return new RecurringDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), + new PersonnelSheetPopulator(staff,offices),new RecurringDepositProductSheetPopulator(recurringDepositProducts)); + } - private List fetchRecurringDepositProducts() { - List depositProducts=(List)depositProductReadPlatformService - .retrieveAll(DepositAccountType.RECURRING_DEPOSIT); - List recurringDepositProducts=new ArrayList<>(); - for (DepositProductData depositproduct: depositProducts) { - RecurringDepositProductData recurringDepositProduct= (RecurringDepositProductData) depositproduct; - recurringDepositProducts.add(recurringDepositProduct); - } - return recurringDepositProducts; - } + private List fetchRecurringDepositProducts() { + List depositProducts=(List)depositProductReadPlatformService + .retrieveAll(DepositAccountType.RECURRING_DEPOSIT); + 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); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List clients = fetchClients(officeId); - 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); - } + private WorkbookPopulator populateRecurringDepositTransactionWorkbook(Long officeId) { + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List clients = fetchClients(officeId); + 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); + } - private WorkbookPopulator populateFixedDepositWorkbook(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); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FIXED_DEPOSIT_PRODUCT_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List clients = fetchClients(officeId); - List staff = fetchStaff(staffId); - List fixedDepositProducts = fetchFixedDepositProducts(); - return new FixedDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new PersonnelSheetPopulator(staff,offices),new FixedDepositProductSheetPopulator(fixedDepositProducts)); + private WorkbookPopulator populateFixedDepositWorkbook(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); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FIXED_DEPOSIT_PRODUCT_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List clients = fetchClients(officeId); + List staff = fetchStaff(staffId); + List fixedDepositProducts = fetchFixedDepositProducts(); + return new FixedDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), + new PersonnelSheetPopulator(staff,offices),new FixedDepositProductSheetPopulator(fixedDepositProducts)); - } + } - private List fetchFixedDepositProducts() { - List depositProducts=(List)depositProductReadPlatformService - .retrieveAll(DepositAccountType.FIXED_DEPOSIT); - List fixedDepositProducts=new ArrayList<>(); - for (DepositProductData depositproduct: depositProducts) { - FixedDepositProductData fixedDepositProduct= (FixedDepositProductData) depositproduct; - fixedDepositProducts.add(fixedDepositProduct); - } - return fixedDepositProducts; + private List fetchFixedDepositProducts() { + List depositProducts=(List)depositProductReadPlatformService + .retrieveAll(DepositAccountType.FIXED_DEPOSIT); + List fixedDepositProducts=new ArrayList<>(); + for (DepositProductData depositproduct: depositProducts) { + FixedDepositProductData fixedDepositProduct= (FixedDepositProductData) depositproduct; + fixedDepositProducts.add(fixedDepositProduct); + } + return fixedDepositProducts; - } + } - private WorkbookPopulator populateUserWorkbook(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), - new RoleSheetPopulator(roles)); - } + private WorkbookPopulator populateUserWorkbook(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), + new RoleSheetPopulator(roles)); + } - private List fetchRoles() { - List rolesList= (List) roleReadPlatformService.retrieveAllActiveRoles(); - return rolesList; - } + private List fetchRoles() { + List rolesList= (List) roleReadPlatformService.retrieveAllActiveRoles(); + return rolesList; + } - private WorkbookPopulator populateFixedDepositTransactionsWorkbook(Long officeId) { - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List clients = fetchClients(officeId); - List funds = fetchFunds(); - List paymentTypes = fetchPaymentTypes(); - List currencies = fetchCurrencies(); - List savingsAccounts=fetchSavingsAccounts(officeId); - return new FixedDepositTransactionWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts); - } + private WorkbookPopulator populateFixedDepositTransactionsWorkbook(Long officeId) { + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List clients = fetchClients(officeId); + List funds = fetchFunds(); + List paymentTypes = fetchPaymentTypes(); + List currencies = fetchCurrencies(); + List savingsAccounts=fetchSavingsAccounts(officeId); + return new FixedDepositTransactionWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), + new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts); + } } \ No newline at end of file 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 d85f38693..2d42cc1c7 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 @@ -115,9 +115,9 @@ public class EmailCampaignValidator { 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); + final String emailSubject = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.emailSubject, element); baseDataValidator.reset().parameter(EmailCampaignValidator.emailSubject).value(emailSubject).notBlank().notExceedingLengthOf(50); - + final String emailMessage = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.emailMessage, element); baseDataValidator.reset().parameter(EmailCampaignValidator.emailMessage).value(emailMessage).notBlank().notExceedingLengthOf(480); 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 6d005ea10..794669b7b 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,42 +22,42 @@ package org.apache.fineract.infrastructure.campaigns.email.data; * Immutable data object representing an Email configuration. */ public class EmailConfigurationData { - @SuppressWarnings("unused") - private final Long id; - - private final String name; - + @SuppressWarnings("unused") + private final Long id; + + private final String name; + private final String value; - - /** - * @return an instance of the EmailConfigurationData class - **/ - public static EmailConfigurationData instance(Long id, String name, String value) { - return new EmailConfigurationData(id, name, value); - } - - /** - * EmailConfigurationData constructor - **/ - private EmailConfigurationData(Long id, String name, String value) { - this.id = id; - this.name = name; - this.value = value; - } + + /** + * @return an instance of the EmailConfigurationData class + **/ + public static EmailConfigurationData instance(Long id, String name, String value) { + return new EmailConfigurationData(id, name, value); + } + + /** + * EmailConfigurationData constructor + **/ + private EmailConfigurationData(Long id, String name, String value) { + this.id = id; + this.name = name; + this.value = value; + } - /** - * @return the id - */ - public Long getId() { - return id; - } + /** + * @return the id + */ + public Long getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } } 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 280b4ea25..91a486b1b 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 @@ -35,126 +35,126 @@ public class EmailData { private final Long staffId; private final EnumOptionData status; private final String emailAddress; - private final String emailSubject; + private final String emailSubject; private final String emailMessage; - private final EnumOptionData emailAttachmentFileFormat; - private final ReportData stretchyReport; - private final String stretchyReportParamMap; - private final List emailAttachmentFileFormatOptions; - private final List stretchyReportParamDateOptions; + private final EnumOptionData emailAttachmentFileFormat; + private final ReportData stretchyReport; + private final String stretchyReportParamMap; + private final List emailAttachmentFileFormatOptions; + private final List stretchyReportParamDateOptions; private final String campaignName; - private final LocalDate sentDate; - private final String errorMessage; + 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) { + 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); + 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) { + 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; this.staffId = staffId; this.status = status; this.emailAddress = emailAddress; - this.emailSubject = emailSubject; + this.emailSubject = emailSubject; this.emailMessage = message; - this.emailAttachmentFileFormat = emailAttachmentFileFormat; - this.stretchyReport = stretchyReport; - this.stretchyReportParamMap = stretchyReportParamMap; - this.emailAttachmentFileFormatOptions = emailAttachmentFileFormatOptions; - this.stretchyReportParamDateOptions = stretchyReportParamDateOptions; + this.emailAttachmentFileFormat = emailAttachmentFileFormat; + this.stretchyReport = stretchyReport; + this.stretchyReportParamMap = stretchyReportParamMap; + this.emailAttachmentFileFormatOptions = emailAttachmentFileFormatOptions; + this.stretchyReportParamDateOptions = stretchyReportParamDateOptions; this.campaignName = campaignName; - this.sentDate = sentDate; - this.errorMessage = errorMessage; + this.sentDate = sentDate; + this.errorMessage = errorMessage; } - /** - * @return the id - */ - public Long getId() { - return id; - } + /** + * @return the id + */ + public Long getId() { + return id; + } - /** - * @return the groupId - */ - public Long getGroupId() { - return groupId; - } + /** + * @return the groupId + */ + public Long getGroupId() { + return groupId; + } - /** - * @return the clientId - */ - public Long getClientId() { - return clientId; - } + /** + * @return the clientId + */ + public Long getClientId() { + return clientId; + } - /** - * @return the staffId - */ - public Long getStaffId() { - return staffId; - } + /** + * @return the staffId + */ + public Long getStaffId() { + return staffId; + } - /** - * @return the status - */ - public EnumOptionData getStatus() { - return status; - } + /** + * @return the status + */ + public EnumOptionData getStatus() { + return status; + } - public String getErrorMessage() {return this.errorMessage;} + public String getErrorMessage() {return this.errorMessage;} - /** - * @return the emailAddress - */ - public String getEmailAddress() { - return emailAddress; - } + /** + * @return the emailAddress + */ + public String getEmailAddress() { + return emailAddress; + } - /** - * @return the message - */ - public String getMessage() { - return emailMessage; - } + /** + * @return the message + */ + public String getMessage() { + 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; - } + public String getEmailSubject() { + return emailSubject; + } - public EnumOptionData getEmailAttachmentFileFormat() { - return emailAttachmentFileFormat; - } + public EnumOptionData getEmailAttachmentFileFormat() { + return emailAttachmentFileFormat; + } - public ReportData getStretchyReport() { - return stretchyReport; - } + public ReportData getStretchyReport() { + return stretchyReport; + } - public String getStretchyReportParamMap() { - return stretchyReportParamMap; - } + public String getStretchyReportParamMap() { + return stretchyReportParamMap; + } - public List getEmailAttachmentFileFormatOptions() { - return emailAttachmentFileFormatOptions; - } + public List getEmailAttachmentFileFormatOptions() { + return emailAttachmentFileFormatOptions; + } - public List getStretchyReportParamDateOptions() { - return stretchyReportParamDateOptions; - } + 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/domain/EmailConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailConfiguration.java index ac451c7fa..2fb4a9826 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 @@ -27,34 +27,34 @@ import javax.persistence.Table; @Entity @Table(name = "scheduled_email_configuration") public class EmailConfiguration extends AbstractPersistableCustom { - @Column(name = "name", nullable = false) + @Column(name = "name", nullable = false) private String name; - - @Column(name = "value", nullable = false) + + @Column(name = "value", nullable = false) private String value; - - /** - * EmailConfiguration constructor - **/ - protected EmailConfiguration() {} - - /** - * EmailConfiguration constructor - **/ - public EmailConfiguration(String name, String value) { - this.name = name; - this.value = value; - } - - public void setValue(String value) { - this.value = value; - } + + /** + * EmailConfiguration constructor + **/ + protected EmailConfiguration() {} + + /** + * EmailConfiguration constructor + **/ + public EmailConfiguration(String name, String value) { + this.name = name; + this.value = value; + } + + public void setValue(String value) { + this.value = value; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public String getValue() { - return this.value; - } + public String getValue() { + return this.value; + } } 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 00ad729b2..a96c1cd80 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 @@ -22,5 +22,5 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface EmailConfigurationRepository extends JpaRepository, JpaSpecificationExecutor { - EmailConfiguration findByName(String name); + 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 6107e20b9..d514950c5 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 @@ -82,7 +82,7 @@ public class EmailMessage extends AbstractPersistableCustom { 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); + return new EmailMessage(group, client, staff,emailCampaign, statusType, emailSubject, message, emailAddress, campaignName); } protected EmailMessage() { @@ -91,7 +91,7 @@ public class EmailMessage extends AbstractPersistableCustom { 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.group = group; this.client = client; this.staff = staff; this.emailCampaign = emailCampaign; @@ -118,19 +118,19 @@ public class EmailMessage extends AbstractPersistableCustom { public Group getGroup() { - return group; + return group; } public Client getClient() { - return client; + return client; } public Staff getStaff() { - return staff; + return staff; } public Integer getStatusType() { - return statusType; + return statusType; } @@ -139,12 +139,12 @@ public class EmailMessage extends AbstractPersistableCustom { public String getEmailSubject() {return emailSubject; } public String getMessage() { - return message; + return message; } public void setStatusType(final Integer statusType) { - this.statusType = statusType; + this.statusType = statusType; } public String getCampaignName() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailConfigurationNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailConfigurationNotFoundException.java index 32aa906dd..2f8234b28 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailConfigurationNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailConfigurationNotFoundException.java @@ -25,7 +25,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc */ public class EmailConfigurationNotFoundException extends AbstractPlatformResourceNotFoundException { - public EmailConfigurationNotFoundException(final String name) { - super("error.msg.email.configuration.name.not.found", "Email configuration with name " + name + " does not exist", name); - } + public EmailConfigurationNotFoundException(final String name) { + super("error.msg.email.configuration.name.not.found", "Email configuration with name " + name + " does not exist", name); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationReadPlatformService.java index cc704e682..a8f3c4852 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationReadPlatformService.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.campaigns.email.data.EmailConfiguratio import java.util.Collection; public interface EmailConfigurationReadPlatformService { - - Collection retrieveAll(); + + Collection retrieveAll(); - EmailConfigurationData retrieveOne(String name); + EmailConfigurationData retrieveOne(String name); } 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 394e082c0..8efd5e7b6 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 @@ -34,66 +34,66 @@ import java.util.Collection; @Service public class EmailConfigurationReadPlatformServiceImpl implements EmailConfigurationReadPlatformService { - - private final JdbcTemplate jdbcTemplate; + + private final JdbcTemplate jdbcTemplate; private final EmailConfigurationRowMapper emailConfigurationRowMapper; @Autowired public EmailConfigurationReadPlatformServiceImpl(final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.emailConfigurationRowMapper = new EmailConfigurationRowMapper(); - + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.emailConfigurationRowMapper = new EmailConfigurationRowMapper(); + } - - private static final class EmailConfigurationRowMapper implements RowMapper { - - 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"); - - this.schema = sql.toString(); - } - - public String schema() { + + private static final class EmailConfigurationRowMapper implements RowMapper { + + 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"); + + this.schema = sql.toString(); + } + + public String schema() { return this.schema; } - @Override - public EmailConfigurationData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { - - final Long id = JdbcSupport.getLong(rs, "id"); - final String name = rs.getString("name"); - final String value = rs.getString("value"); - - return EmailConfigurationData.instance(id, name, value); - } - - } + @Override + public EmailConfigurationData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { + + final Long id = JdbcSupport.getLong(rs, "id"); + final String name = rs.getString("name"); + final String value = rs.getString("value"); + + return EmailConfigurationData.instance(id, name, value); + } + + } - @Override - public Collection retrieveAll() { - final String sql = "select " + this.emailConfigurationRowMapper.schema(); + @Override + public Collection retrieveAll() { + final String sql = "select " + this.emailConfigurationRowMapper.schema(); return this.jdbcTemplate.query(sql, this.emailConfigurationRowMapper, new Object[] {}); - } + } - @Override - public EmailConfigurationData retrieveOne(String name) { - try { - final String sql = "select " + this.emailConfigurationRowMapper.schema() + " where cnf.name = ?"; + @Override + public EmailConfigurationData retrieveOne(String name) { + try { + final String sql = "select " + this.emailConfigurationRowMapper.schema() + " where cnf.name = ?"; - return this.jdbcTemplate.queryForObject(sql, this.emailConfigurationRowMapper, name); - } - - catch(final EmptyResultDataAccessException e) { - - throw new EmailConfigurationNotFoundException(name); - } - } + return this.jdbcTemplate.queryForObject(sql, this.emailConfigurationRowMapper, name); + } + + catch(final EmptyResultDataAccessException e) { + + throw new EmailConfigurationNotFoundException(name); + } + } } 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 870251b7b..39b6a1065 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 @@ -83,7 +83,7 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService { } public String tableName() { - return "scheduled_email_messages_outbound"; + return "scheduled_email_messages_outbound"; } @Override @@ -130,31 +130,31 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService { } @Override - public Collection retrieveAllPending(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.PENDING.getValue() + sqlPlusLimit; + public Collection retrieveAllPending(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.PENDING.getValue() + sqlPlusLimit; return this.jdbcTemplate.query(sql, this.emailRowMapper, new Object[] {}); } - @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; + @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; return this.jdbcTemplate.query(sql, this.emailRowMapper, new Object[] {}); - } + } - @Override - public List retrieveExternalIdsOfAllSent(final Integer limit) { - final String sqlPlusLimit = (limit > 0) ? " limit 0, " + limit : ""; - final String sql = "select external_id from " + this.emailRowMapper.tableName() + " where status_enum = " - + EmailMessageStatusType.SENT.getValue() + sqlPlusLimit; - - return this.jdbcTemplate.queryForList(sql, Long.class); - } + @Override + public List retrieveExternalIdsOfAllSent(final Integer limit) { + final String sqlPlusLimit = (limit > 0) ? " limit 0, " + limit : ""; + final String sql = "select external_id from " + this.emailRowMapper.tableName() + " where status_enum = " + + EmailMessageStatusType.SENT.getValue() + sqlPlusLimit; + + return this.jdbcTemplate.queryForList(sql, Long.class); + } @Override public Collection retrieveAllDelivered(final Integer limit) { @@ -165,14 +165,14 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService { return this.jdbcTemplate.query(sql, this.emailRowMapper, new Object[] {}); } - @Override - public Collection retrieveAllFailed(final SearchParameters searchParameters) { - final String sqlPlusLimit = (searchParameters.getLimit() > 0) ? " limit 0, " + searchParameters.getLimit() : ""; + @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; 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) { 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 a7fc94264..8772e21aa 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 @@ -38,10 +38,10 @@ import org.springframework.stereotype.Component; @Component public class SmsConfigUtils { - @Autowired - private ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService; - - //This method will return uri and HttpEntry objects with keys as uri and entity + @Autowired + private ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService; + + //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(); @@ -72,5 +72,5 @@ public class SmsConfigUtils { return httpRequestdetails; } - + } 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 6e74932e9..bbe504e84 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 @@ -86,11 +86,11 @@ 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(), + if(!periodFrequencyType.getValue().equals(PeriodFrequencyType.INVALID.getValue())) { + final EnumOptionData optionData = new EnumOptionData(periodFrequencyType.getValue().longValue(), periodFrequencyType.getCode(), periodFrequencyType.toString()); - optionDatas.add(optionData); - } + optionDatas.add(optionData); + } } return optionDatas; } 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 cbd9bd550..b3bd3ec85 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 @@ -207,8 +207,8 @@ public class SmsCampaignData { return this.providerId; } - public boolean isNotification() { - return this.isNotification; - } + public boolean isNotification() { + return this.isNotification; + } } 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 1c023e441..91c8b7197 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 @@ -162,11 +162,11 @@ public class SmsCampaign extends AbstractPersistableCustom { final Long triggerType = command.longValueOfParameterNamed(SmsCampaignValidator.triggerType); boolean isNotification = false; if(command.parameterExists(SmsCampaignValidator.isNotificationParamName)){ - isNotification = command.booleanPrimitiveValueOfParameterNamed(SmsCampaignValidator.isNotificationParamName); + isNotification = command.booleanPrimitiveValueOfParameterNamed(SmsCampaignValidator.isNotificationParamName); } Long providerId = null; if(!isNotification){ - providerId = command.longValueOfParameterNamed(SmsCampaignValidator.providerId); + providerId = command.longValueOfParameterNamed(SmsCampaignValidator.providerId); } final String paramValue = command.jsonFragment(SmsCampaignValidator.paramValue); @@ -577,13 +577,13 @@ public class SmsCampaign extends AbstractPersistableCustom { return recurrenceBuilder.toString(); } - public boolean isNotification() { - return this.isNotification; - } + public boolean isNotification() { + return this.isNotification; + } - public void setNotification(boolean isNotification) { - this.isNotification = isNotification; - } + public void setNotification(boolean isNotification) { + this.isNotification = isNotification; + } } 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 d9eb56fd0..e48e96866 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 @@ -321,16 +321,16 @@ public class SmsCampaignValidator { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - public boolean isValidNotificationOrSms(Client client, SmsCampaign smsCampaign, Object mobileNo) { - if (smsCampaign.isNotification()) { - if (client != null) { - DeviceRegistration deviceRegistration = this.deviceRegistrationRepository - .findDeviceRegistrationByClientId(client.getId()); - return (deviceRegistration != null); - } - return false; - } - return (mobileNo != null); - } + public boolean isValidNotificationOrSms(Client client, SmsCampaign smsCampaign, Object mobileNo) { + if (smsCampaign.isNotification()) { + if (client != null) { + DeviceRegistration deviceRegistration = this.deviceRegistrationRepository + .findDeviceRegistrationByClientId(client.getId()); + return (deviceRegistration != null); + } + return false; + } + return (mobileNo != null); + } } 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 24968823e..a6644f55a 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,10 +66,10 @@ import org.springframework.stereotype.Service; @Service public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { - private static final Logger logger = LoggerFactory.getLogger(SmsCampaignDomainServiceImpl.class); - - //private final static int POOL_SIZE = 5 ; - + private static final Logger logger = LoggerFactory.getLogger(SmsCampaignDomainServiceImpl.class); + + //private final static int POOL_SIZE = 5 ; + private final SmsCampaignRepository smsCampaignRepository; private final SmsMessageRepository smsMessageRepository; private final OfficeRepository officeRepository; @@ -110,198 +110,198 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_WITHDRAWAL, new SavingsAccountTransactionListener(false)); } - private void notifyRejectedLoanOwner(Loan loan) { - List smsCampaigns = retrieveSmsCampaigns("Loan Rejected"); - if (smsCampaigns.size() > 0) { - for (SmsCampaign campaign : smsCampaigns) { - if (campaign.isActive()) { - SmsCampaignDomainServiceImpl.this.smsCampaignWritePlatformCommandHandler - .insertDirectCampaignIntoSmsOutboundTable(loan, campaign); - } - } - } - } + private void notifyRejectedLoanOwner(Loan loan) { + List smsCampaigns = retrieveSmsCampaigns("Loan Rejected"); + if (smsCampaigns.size() > 0) { + for (SmsCampaign campaign : smsCampaigns) { + if (campaign.isActive()) { + SmsCampaignDomainServiceImpl.this.smsCampaignWritePlatformCommandHandler + .insertDirectCampaignIntoSmsOutboundTable(loan, campaign); + } + } + } + } private void notifyAcceptedLoanOwner(Loan loan) { List smsCampaigns = retrieveSmsCampaigns("Loan Approved"); if(smsCampaigns.size()>0){ for (SmsCampaign campaign:smsCampaigns){ - this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(loan, campaign); + this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(loan, campaign); } } } private void notifyClientActivated(final Client client) { - List smsCampaigns = retrieveSmsCampaigns("Client Activated"); - if(smsCampaigns.size()>0){ + List smsCampaigns = retrieveSmsCampaigns("Client Activated"); + if(smsCampaigns.size()>0){ for (SmsCampaign campaign:smsCampaigns){ - this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign); + this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign); } } - + } private void notifyClientRejected(final Client client) { - List smsCampaigns = retrieveSmsCampaigns("Client Rejected"); - if(smsCampaigns.size()>0){ + List smsCampaigns = retrieveSmsCampaigns("Client Rejected"); + if(smsCampaigns.size()>0){ for (SmsCampaign campaign:smsCampaigns){ - this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign); + 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); - } - } + private void notifySavingsAccountActivated(final SavingsAccount savingsAccount) { + List smsCampaigns = retrieveSmsCampaigns("Savings Activated"); + if (smsCampaigns.size() > 0) { + for (SmsCampaign campaign : smsCampaigns) { + this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount, + campaign); + } + } - } + } - private void notifySavingsAccountRejected(final SavingsAccount savingsAccount) { - List smsCampaigns = retrieveSmsCampaigns("Savings Rejected"); - if (smsCampaigns.size() > 0) { - for (SmsCampaign campaign : smsCampaigns) { - this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount, - campaign); - } - } + private void notifySavingsAccountRejected(final SavingsAccount savingsAccount) { + List smsCampaigns = retrieveSmsCampaigns("Savings Rejected"); + if (smsCampaigns.size() > 0) { + for (SmsCampaign campaign : smsCampaigns) { + this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount, + campaign); + } + } - } - - private void sendSmsForLoanRepayment(LoanTransaction loanTransaction) { - List smsCampaigns = retrieveSmsCampaigns("Loan Repayment"); - if (smsCampaigns.size() > 0) { - for (SmsCampaign smsCampaign : smsCampaigns) { - try { - 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"); - } - if (loan.isGroupLoan()) { - Group group = this.groupRepository.findById(loan.getGroupId()).orElse(null); - groupClients.addAll(group.getClientMembers()); - } else { - groupClients.add(loan.client()); - } - HashMap campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(), - new TypeReference>() { - }); + } + + private void sendSmsForLoanRepayment(LoanTransaction loanTransaction) { + List smsCampaigns = retrieveSmsCampaigns("Loan Repayment"); + if (smsCampaigns.size() > 0) { + for (SmsCampaign smsCampaign : smsCampaigns) { + try { + 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"); + } + if (loan.isGroupLoan()) { + Group group = this.groupRepository.findById(loan.getGroupId()).orElse(null); + groupClients.addAll(group.getClientMembers()); + } else { + groupClients.add(loan.client()); + } + HashMap campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(), + new TypeReference>() { + }); - if (groupClients.size() > 0) { - for (Client client : groupClients) { - HashMap smsParams = processRepaymentDataForSms(loanTransaction, client); - for (String key : campaignParams.keySet()) { - String value = campaignParams.get(key); - String spvalue = null; - boolean spkeycheck = smsParams.containsKey(key); - if (spkeycheck) { - spvalue = smsParams.get(key).toString(); - } - 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"); - } - } else { - throw new SmsRuntimeException("error.msg.no.id.attribute", - "Office Id attribute is notfound"); - } - } - } - 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){ - mobileNumber = mobileNo.toString(); - } - SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message, - mobileNumber, smsCampaign, smsCampaign.isNotification()); - Collection messages = new ArrayList<>(); - messages.add(smsMessage); - Map> smsDataMap = new HashMap<>(); - smsDataMap.put(smsCampaign, messages); - this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap); - } - } - } - } catch (final IOException e) { - logger.error("smsParams does not contain the key: " + e.getMessage()); - } catch (final RuntimeException e) { - logger.debug("Client Office Id and SMS Campaign Office id doesn't match"); - } - } - } - } + if (groupClients.size() > 0) { + for (Client client : groupClients) { + HashMap smsParams = processRepaymentDataForSms(loanTransaction, client); + for (String key : campaignParams.keySet()) { + String value = campaignParams.get(key); + String spvalue = null; + boolean spkeycheck = smsParams.containsKey(key); + if (spkeycheck) { + spvalue = smsParams.get(key).toString(); + } + 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"); + } + } else { + throw new SmsRuntimeException("error.msg.no.id.attribute", + "Office Id attribute is notfound"); + } + } + } + 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){ + mobileNumber = mobileNo.toString(); + } + SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message, + mobileNumber, smsCampaign, smsCampaign.isNotification()); + Collection messages = new ArrayList<>(); + messages.add(smsMessage); + Map> smsDataMap = new HashMap<>(); + smsDataMap.put(smsCampaign, messages); + this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap); + } + } + } + } catch (final IOException e) { + logger.error("smsParams does not contain the key: " + e.getMessage()); + } catch (final RuntimeException e) { + logger.debug("Client Office Id and SMS Campaign Office id doesn't match"); + } + } + } + } - private void sendSmsForSavingsTransaction(final SavingsAccountTransaction savingsTransaction, boolean isDeposit) { - String campaignName = isDeposit ? "Savings Deposit" : "Savings Withdrawal"; - List smsCampaigns = retrieveSmsCampaigns(campaignName); - if (smsCampaigns.size() > 0) { - for (SmsCampaign smsCampaign : smsCampaigns) { - try { - final SavingsAccount savingsAccount = savingsTransaction.getSavingsAccount(); - final Client client = savingsAccount.getClient(); - HashMap campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(), - new TypeReference>() { - }); - HashMap smsParams = processSavingsTransactionDataForSms(savingsTransaction, client); - for (String key : campaignParams.keySet()) { - String value = campaignParams.get(key); - String spvalue = null; - boolean spkeycheck = smsParams.containsKey(key); - if (spkeycheck) { - spvalue = smsParams.get(key).toString(); - } - 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"); - } - } else { - throw new SmsRuntimeException("error.msg.no.id.attribute", - "Office Id attribute is notfound"); - } - } - } - 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){ - mobileNumber = mobileNo.toString(); - } - SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message, - mobileNumber, smsCampaign, smsCampaign.isNotification()); - this.smsMessageRepository.save(smsMessage); - Collection messages = new ArrayList<>(); - messages.add(smsMessage); - Map> smsDataMap = new HashMap<>(); - smsDataMap.put(smsCampaign, messages); - this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap); - } - } catch (final IOException e) { - logger.error("smsParams does not contain the key: " + e.getMessage()); - } catch (final RuntimeException e) { - logger.debug("Client Office Id and SMS Campaign Office id doesn't match"); - } - } - } - } + private void sendSmsForSavingsTransaction(final SavingsAccountTransaction savingsTransaction, boolean isDeposit) { + String campaignName = isDeposit ? "Savings Deposit" : "Savings Withdrawal"; + List smsCampaigns = retrieveSmsCampaigns(campaignName); + if (smsCampaigns.size() > 0) { + for (SmsCampaign smsCampaign : smsCampaigns) { + try { + final SavingsAccount savingsAccount = savingsTransaction.getSavingsAccount(); + final Client client = savingsAccount.getClient(); + HashMap campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(), + new TypeReference>() { + }); + HashMap smsParams = processSavingsTransactionDataForSms(savingsTransaction, client); + for (String key : campaignParams.keySet()) { + String value = campaignParams.get(key); + String spvalue = null; + boolean spkeycheck = smsParams.containsKey(key); + if (spkeycheck) { + spvalue = smsParams.get(key).toString(); + } + 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"); + } + } else { + throw new SmsRuntimeException("error.msg.no.id.attribute", + "Office Id attribute is notfound"); + } + } + } + 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){ + mobileNumber = mobileNo.toString(); + } + SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message, + mobileNumber, smsCampaign, smsCampaign.isNotification()); + this.smsMessageRepository.save(smsMessage); + Collection messages = new ArrayList<>(); + messages.add(smsMessage); + Map> smsDataMap = new HashMap<>(); + smsDataMap.put(smsCampaign, messages); + this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap); + } + } catch (final IOException e) { + logger.error("smsParams does not contain the key: " + e.getMessage()); + } catch (final RuntimeException e) { + logger.debug("Client Office Id and SMS Campaign Office id doesn't match"); + } + } + } + } private List retrieveSmsCampaigns(String paramValue){ List smsCampaigns = smsCampaignRepository.findActiveSmsCampaigns("%"+paramValue+"%", SmsCampaignTriggerType.TRIGGERED.getValue()); @@ -337,9 +337,9 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { smsParams.put("officeId", client.getOffice().getId()); if(client.getStaff() != null) { - smsParams.put("loanOfficerId", client.getStaff().getId()); + smsParams.put("loanOfficerId", client.getStaff().getId()); }else { - smsParams.put("loanOfficerId", -1); + smsParams.put("loanOfficerId", -1); } smsParams.put("repaymentAmount", loanTransaction.getAmount(loan.getCurrency())); @@ -347,18 +347,18 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { smsParams.put("RepaymentTime", loanTransaction.getCreatedDateTime().toLocalTime().toString(timeFormatter)); if(loanTransaction.getPaymentDetail() != null) { - smsParams.put("receiptNumber", loanTransaction.getPaymentDetail().getReceiptNumber()); + smsParams.put("receiptNumber", loanTransaction.getPaymentDetail().getReceiptNumber()); }else { - smsParams.put("receiptNumber", -1); + smsParams.put("receiptNumber", -1); } return smsParams; } private HashMap processSavingsTransactionDataForSms(final SavingsAccountTransaction savingsAccountTransaction, Client client){ - // {{savingsId}} {{id}} {{firstname}} {{middlename}} {{lastname}} {{FullName}} {{mobileNo}} {{savingsAccountId}} {{depositAmount}} {{balance}} - - //transactionDate + // {{savingsId}} {{id}} {{firstname}} {{middlename}} {{lastname}} {{FullName}} {{mobileNo}} {{savingsAccountId}} {{depositAmount}} {{balance}} + + //transactionDate HashMap smsParams = new HashMap(); SavingsAccount savingsAccount = savingsAccountTransaction.getSavingsAccount() ; DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("MMM:d:yyyy"); @@ -378,25 +378,25 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { smsParams.put("savingsTransactionId", savingsAccountTransaction.getId()) ; if(client.getStaff() != null) { - smsParams.put("loanOfficerId", client.getStaff().getId()); + smsParams.put("loanOfficerId", client.getStaff().getId()); }else { - smsParams.put("loanOfficerId", -1); + smsParams.put("loanOfficerId", -1); } if(savingsAccountTransaction.getPaymentDetail() != null) { - smsParams.put("receiptNumber", savingsAccountTransaction.getPaymentDetail().getReceiptNumber()); + smsParams.put("receiptNumber", savingsAccountTransaction.getPaymentDetail().getReceiptNumber()); }else { - smsParams.put("receiptNumber", -1); + smsParams.put("receiptNumber", -1); } return smsParams; } private abstract class SmsBusinessEventAdapter implements BusinessEventListner { - @Override - public void businessEventToBeExecuted(Map businessEventEntity) { - //Nothing to do - } + @Override + public void businessEventToBeExecuted(Map businessEventEntity) { + //Nothing to do + } } private class SendSmsOnLoanApproved extends SmsBusinessEventAdapter{ @@ -437,79 +437,79 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { private class ClientActivatedListener extends SmsBusinessEventAdapter { - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT); - if(entity instanceof Client) { - notifyClientActivated((Client)entity); - } - } + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT); + if(entity instanceof Client) { + notifyClientActivated((Client)entity); + } + } } private class ClientRejectedListener extends SmsBusinessEventAdapter { - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT); - if(entity instanceof Client) { - notifyClientRejected((Client)entity); - } - - } + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT); + if(entity instanceof Client) { + notifyClientRejected((Client)entity); + } + + } } private class SavingsAccountActivatedListener extends SmsBusinessEventAdapter{ - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVING); - if(entity instanceof SavingsAccount) { - notifySavingsAccountActivated((SavingsAccount)entity); - } - - } + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVING); + if(entity instanceof SavingsAccount) { + notifySavingsAccountActivated((SavingsAccount)entity); + } + + } } private class SavingsAccountRejectedListener extends SmsBusinessEventAdapter { - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVING); - if(entity instanceof SavingsAccount) { - notifySavingsAccountRejected((SavingsAccount)entity); - } - } + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVING); + if(entity instanceof SavingsAccount) { + notifySavingsAccountRejected((SavingsAccount)entity); + } + } } private class SavingsAccountTransactionListener extends SmsBusinessEventAdapter { - final boolean isDeposit ; - - public SavingsAccountTransactionListener(final boolean isDeposit) { - this.isDeposit = isDeposit ; - } + final boolean isDeposit ; + + public SavingsAccountTransactionListener(final boolean isDeposit) { + this.isDeposit = isDeposit ; + } - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVINGS_TRANSACTION); - if(entity instanceof SavingsAccountTransaction) { - sendSmsForSavingsTransaction((SavingsAccountTransaction)entity, this.isDeposit); - } - } + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVINGS_TRANSACTION); + 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) { + + 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/SmsCampaignWritePlatformServiceJpaImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignWritePlatformServiceJpaImpl.java index a777572da..96a0db344 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 @@ -232,10 +232,10 @@ 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 mobileNumber = null; - if(mobileNo != null){ - mobileNumber = mobileNo.toString(); - } + String mobileNumber = null; + if(mobileNo != null){ + mobileNumber = mobileNo.toString(); + } SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber, smsCampaign, smsCampaign.isNotification()); this.smsMessageRepository.save(smsMessage); @@ -243,7 +243,7 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP } } } catch (final IOException e) { - logger.error(e.getMessage()); + logger.error(e.getMessage()); } } @@ -287,10 +287,10 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP Object mobileNo = entry.get("mobileNo"); if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) { - String mobileNumber = null; - if(mobileNo != null){ - mobileNumber = mobileNo.toString(); - } + String mobileNumber = null; + if(mobileNo != null){ + mobileNumber = mobileNo.toString(); + } SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber, smsCampaign, smsCampaign.isNotification()); smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); @@ -305,9 +305,9 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP } } } catch (final IOException e) { - logger.error(e.getMessage()) ; + logger.error(e.getMessage()) ; } catch (final RuntimeException e) { - logger.error(e.getMessage()) ; + logger.error(e.getMessage()) ; } } @@ -320,39 +320,39 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP HashMap queryParamForRunReport = new ObjectMapper().readValue(smsCampaign.getParamValue(), new TypeReference>() {}); - campaignParams.put("clientId", client.getId().toString()); - queryParamForRunReport.put("clientId", client.getId().toString()); - - List> runReportObject = this - .getRunReportByServiceImpl(campaignParams.get("reportName"), queryParamForRunReport); + campaignParams.put("clientId", client.getId().toString()); + queryParamForRunReport.put("clientId", client.getId().toString()); + + 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); - Object mobileNo = entry.get("mobileNo"); + if (runReportObject != null && runReportObject.size() > 0) { + for (HashMap entry : runReportObject) { + 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){ - mobileNumber = mobileNo.toString(); - } - 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); - } - } - } + if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) { + String mobileNumber = null; + if(mobileNo != null){ + mobileNumber = mobileNo.toString(); + } + 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); + } + } + } } catch (final IOException e) { - logger.error(e.getMessage()) ; + logger.error(e.getMessage()) ; } catch (final RuntimeException e) { - logger.error(e.getMessage()) ; + logger.error(e.getMessage()) ; } } @@ -367,36 +367,36 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP queryParamForRunReport.put("savingsId", savingsAccount.getId().toString()); Client client = savingsAccount.getClient() ; - 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); - Object mobileNo = entry.get("mobileNo"); + if (runReportObject != null && runReportObject.size() > 0) { + for (HashMap entry : runReportObject) { + 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){ - mobileNumber = mobileNo.toString(); - } - 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); - } - } - } + if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) { + String mobileNumber = null; + if(mobileNo != null){ + mobileNumber = mobileNo.toString(); + } + 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); + } + } + } } catch (final IOException e) { - logger.error(e.getMessage()) ; + logger.error(e.getMessage()) ; } catch (final RuntimeException e) { - logger.error(e.getMessage()) ; + logger.error(e.getMessage()) ; } } 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 e443a2080..ec6aeb6a9 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 @@ -76,9 +76,9 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf handleCodeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; - handleCodeDataIntegrityIssues(command, throwable, ee); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + handleCodeDataIntegrityIssues(command, throwable, ee); + return CommandProcessingResult.empty(); } } @@ -108,9 +108,9 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf handleCodeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; - handleCodeDataIntegrityIssues(command, throwable, ee); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + handleCodeDataIntegrityIssues(command, throwable, ee); + return CommandProcessingResult.empty(); } } 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 500ffc170..719a78a7a 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 @@ -45,10 +45,10 @@ import com.google.gson.reflect.TypeToken; 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) { @@ -63,29 +63,29 @@ public class GlobalConfigurationDataValidator { this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, UPDATE_CONFIGURATION_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(GlobalConfigurationApiConstant.CONFIGURATION_RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(GlobalConfigurationApiConstant.CONFIGURATION_RESOURCE_NAME); 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(); - } + if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.ENABLED, element)) { + 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(); - } + if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.VALUE, element)) { + 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); - baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.DATE_VALUE).value(dateValue).notNull(); - } + if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.DATE_VALUE, element)) { + final LocalDate dateValue = this.fromApiJsonHelper + .extractLocalDateNamed(GlobalConfigurationApiConstant.DATE_VALUE, element); + baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.DATE_VALUE).value(dateValue).notNull(); + } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } 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 index 40aede7d2..19ce05005 100755 --- 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 @@ -61,33 +61,33 @@ public class GlobalConfigurationPropertyData { this.trapDoor = isTrapDoor; } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public boolean isEnabled() { - return this.enabled; - } + public boolean isEnabled() { + return this.enabled; + } - public Long getValue() { - return this.value; - } + public Long getValue() { + return this.value; + } - public Date getDateValue() { - return this.dateValue; - } + public Date getDateValue() { + return this.dateValue; + } - public Long getId() { - return this.id; - } + public Long getId() { + return this.id; + } - public String getDescription() { - return this.description; - } + public String getDescription() { + return this.description; + } - public boolean isTrapDoor() { - return this.trapDoor; - } + public boolean isTrapDoor() { + return this.trapDoor; + } } \ 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 99d7ae556..3f9c1dad2 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 @@ -232,13 +232,13 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService return property.getDateValue(); } - @Override - public boolean isPaymnetypeApplicableforDisbursementCharge() { - final String propertyName = "paymenttype-applicable-for-disbursement-charges"; + @Override + public boolean isPaymnetypeApplicableforDisbursementCharge() { + final String propertyName = "paymenttype-applicable-for-disbursement-charges"; final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName); return property.isEnabled(); - } - + } + @Override public boolean isSkippingMeetingOnFirstDayOfMonthEnabled() { return getGlobalConfigurationPropertyData("skip-repayment-on-first-day-of-month").isEnabled(); @@ -266,19 +266,19 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService return property.isEnabled(); } - @Override - public boolean isDailyTPTLimitEnabled() { + @Override + public boolean isDailyTPTLimitEnabled() { final String propertyName = "daily-tpt-limit"; final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName); return property.isEnabled(); - } + } - @Override - public Long getDailyTPTLimit() { + @Override + public Long getDailyTPTLimit() { final String propertyName = "daily-tpt-limit"; final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName); return property.getValue(); - } + } @Override public void removeGlobalConfigurationPropertyDataFromCache(final String propertyName) { 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 4e60badad..4bf8454ad 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 @@ -53,22 +53,22 @@ public class ExternalServicePropertiesPK implements Serializable { } @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj.getClass() != getClass()) { - return false; - } - final ExternalServicePropertiesPK rhs = (ExternalServicePropertiesPK) obj; - return new EqualsBuilder() // - .append(this.externalServiceId, rhs.externalServiceId) // - .append(this.name, rhs.name) // - .isEquals(); - } + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (obj == this) { + return true; + } + if (obj.getClass() != getClass()) { + return false; + } + final ExternalServicePropertiesPK rhs = (ExternalServicePropertiesPK) obj; + return new EqualsBuilder() // + .append(this.externalServiceId, rhs.externalServiceId) // + .append(this.name, rhs.name) // + .isEquals(); + } @Override public int hashCode() { 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 6db62a383..e5fc15b57 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 @@ -26,6 +26,6 @@ import org.springframework.data.repository.query.Param; public interface ExternalServicesPropertiesRepository extends JpaRepository, JpaSpecificationExecutor { - @Query("SELECT ep from ExternalServicesProperties ep where ep.externalServicePropertiesPK.name=:name and ep.externalServicePropertiesPK.externalServiceId=:externalServiceId") + @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 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 1f18a7d3f..2255c3a05 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 @@ -209,11 +209,11 @@ public class ExternalServicesPropertiesReadPlatformServiceImpl implements Extern String fcmEndPoint = null; while (rs.next()) { if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.NOTIFICATION_SERVER_KEY )) { - serverKey = rs.getString("value"); + serverKey = rs.getString("value"); } else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.NOTIFICATION_GCM_END_POINT )) { - gcmEndPoint = rs.getString("value"); + gcmEndPoint = rs.getString("value"); } else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.NOTIFICATION_FCM_END_POINT )) { - fcmEndPoint = rs.getString("value"); + fcmEndPoint = rs.getString("value"); } } return new NotificationConfigurationData(null, serverKey, gcmEndPoint, fcmEndPoint); @@ -221,13 +221,13 @@ public class ExternalServicesPropertiesReadPlatformServiceImpl implements Extern } - @Override - public NotificationConfigurationData getNotificationConfiguration() { - final ResultSetExtractor resultSetExtractor = new NotificationDataExtractor(); + @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[] {}); return notificationConfigurationData; - } + } } 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 2cef44fa7..c846b3279 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 @@ -46,15 +46,15 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; */ @Configuration @Import({ WebXmlConfiguration.class, WebXmlOauthConfiguration.class, WebFrontEndConfiguration.class, - MessagingConfiguration.class, WebTwoFactorXmlConfiguration.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}) + 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/JDBCDriverConfig.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/JDBCDriverConfig.java index 854f1209d..64de7aff1 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 @@ -28,45 +28,45 @@ import org.springframework.stereotype.Service; @Service public class JDBCDriverConfig { - private final static String DRIVER_CLASS_PROPERTYNAME = "DRIVERCLASS_NAME" ; - private final static String PROTOCOL_PROPERTYNAME = "PROTOCOL" ; - private final static String SUBPROTOCOL_PROPERTYNAME = "SUB_PROTOCOL" ; - private final static String PORT_PROPERTYNAME = "PORT" ; - - private String driverClassName ; - private String protocol ; - private String subProtocol ; - private Integer port ; - - @Autowired ApplicationContext context ; - - @PostConstruct - protected void init() { - Environment environment = context.getEnvironment() ; - driverClassName = (String)environment.getProperty(DRIVER_CLASS_PROPERTYNAME) ; - protocol = (String) environment.getProperty(PROTOCOL_PROPERTYNAME) ; - subProtocol = (String) environment.getProperty(SUBPROTOCOL_PROPERTYNAME) ; - port = Integer.parseInt((String) environment.getProperty(PORT_PROPERTYNAME)) ; - } - + private final static String DRIVER_CLASS_PROPERTYNAME = "DRIVERCLASS_NAME" ; + private final static String PROTOCOL_PROPERTYNAME = "PROTOCOL" ; + private final static String SUBPROTOCOL_PROPERTYNAME = "SUB_PROTOCOL" ; + private final static String PORT_PROPERTYNAME = "PORT" ; + + private String driverClassName ; + private String protocol ; + private String subProtocol ; + private Integer port ; + + @Autowired ApplicationContext context ; + + @PostConstruct + protected void init() { + Environment environment = context.getEnvironment() ; + driverClassName = (String)environment.getProperty(DRIVER_CLASS_PROPERTYNAME) ; + protocol = (String) environment.getProperty(PROTOCOL_PROPERTYNAME) ; + subProtocol = (String) environment.getProperty(SUBPROTOCOL_PROPERTYNAME) ; + port = Integer.parseInt((String) environment.getProperty(PORT_PROPERTYNAME)) ; + } + public String getDriverClassName() { - return this.driverClassName ; + return this.driverClassName ; } public String getProtocol() { - return this.protocol ; + return this.protocol ; } public String getSubProtocol() { - return this.subProtocol ; + return this.subProtocol ; } public Integer getPort() { - return this.port ; + return this.port ; } public String constructProtocol(String schemaServer, String schemaServerPort, String schemaName) { - final String url = new StringBuilder(protocol).append(":").append(subProtocol).append("://").append(schemaServer).append(':').append(schemaServerPort) + 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/WarWebApplicationInitializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WarWebApplicationInitializer.java index a38102fa3..c842949f8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WarWebApplicationInitializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WarWebApplicationInitializer.java @@ -39,15 +39,15 @@ import org.springframework.context.annotation.ImportResource; */ public class WarWebApplicationInitializer extends SpringBootServletInitializer { - @ImportResource({ "classpath*:META-INF/spring/jndi.xml" }) - private static class Configuration extends AbstractApplicationConfiguration { - } + @ImportResource({ "classpath*:META-INF/spring/jndi.xml" }) + private static class Configuration extends AbstractApplicationConfiguration { + } - @Override - protected SpringApplicationBuilder configure( - SpringApplicationBuilder application) { - // let's share Spring Boot Love, so no showBanner(false) - return application.sources(Configuration.class); - } + @Override + protected SpringApplicationBuilder configure( + SpringApplicationBuilder application) { + // let's share Spring Boot Love, so no showBanner(false) + return application.sources(Configuration.class); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/DataSourceConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/DataSourceConfiguration.java index fe5f9bb09..703f0f795 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/DataSourceConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/DataSourceConfiguration.java @@ -34,18 +34,18 @@ import org.springframework.context.annotation.Configuration; */ @Configuration public class DataSourceConfiguration { - private static final Logger logger = LoggerFactory.getLogger(DataSourceConfiguration.class); - - @Autowired JDBCDriverConfig config ; - + private static final Logger logger = LoggerFactory.getLogger(DataSourceConfiguration.class); + + @Autowired JDBCDriverConfig config ; + @Bean public DataSourceProperties dataSourceProperties() { - return new DataSourceProperties(config.getDriverClassName(), config.getProtocol(), config.getSubProtocol(), config.getPort()); + return new DataSourceProperties(config.getDriverClassName(), config.getProtocol(), config.getSubProtocol(), config.getPort()); } @Bean public DataSource tenantDataSourceJndi() { - PoolConfiguration p = getProperties(); + PoolConfiguration p = getProperties(); org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource(p); logger.info("Created new DataSource; url=" + p.getUrl()); return ds; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/DataSourceProperties.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/DataSourceProperties.java index 24276f782..a9d8b7566 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/DataSourceProperties.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/DataSourceProperties.java @@ -98,60 +98,60 @@ public class DataSourceProperties extends PoolProperties { @Override public void setUrl(@SuppressWarnings("unused") String url) { - throw new UnsupportedOperationException("Use setHost/Port/DB() instead of setURL()"); + throw new UnsupportedOperationException("Use setHost/Port/DB() instead of setURL()"); } - @Override - public String getUrl() { - String url = super.getUrl(); - if (StringUtils.hasText(url)) { - throw new IllegalStateException(); - } - return jdbcProtocol + ":" + jdbcSubprotocol + "://" + getHost() + ":" + getPort() + "/" + getDBName(); - } + @Override + public String getUrl() { + String url = super.getUrl(); + if (StringUtils.hasText(url)) { + throw new IllegalStateException(); + } + return jdbcProtocol + ":" + jdbcSubprotocol + "://" + getHost() + ":" + getPort() + "/" + getDBName(); + } - public String getHost() { - return hostname; - } + public String getHost() { + return hostname; + } - public int getPort() { - return port; - } + public int getPort() { + return port; + } - public String getDBName() { - return dbName; - } + public String getDBName() { + return dbName; + } - public void setPort(int port) { - this.port = port; - } + public void setPort(int port) { + this.port = port; + } - public void setHost(String hostname) { - this.hostname = hostname; - } + public void setHost(String hostname) { + this.hostname = hostname; + } - public void setDBName(String dbName) { - this.dbName = dbName; - } + public void setDBName(String dbName) { + this.dbName = dbName; + } - @Override - public String getUsername() { - return this.username; - } + @Override + public String getUsername() { + return this.username; + } - @Override - public void setUsername(String username) { - this.username = username; - } + @Override + public void setUsername(String username) { + this.username = username; + } - @Override - public String getPassword() { - return this.password; - } + @Override + public String getPassword() { + return this.password; + } - @Override - public void setPassword(String password) { - this.password = password; - } + @Override + public void setPassword(String password) { + this.password = password; + } } \ No newline at end of file diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/MariaDB4jDataSourceConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/MariaDB4jDataSourceConfiguration.java index ce32ac296..f1992fd3d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/MariaDB4jDataSourceConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/MariaDB4jDataSourceConfiguration.java @@ -26,37 +26,37 @@ import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService; @Configuration public class MariaDB4jDataSourceConfiguration extends DataSourceConfiguration { - @Bean - public MariaDB4jSetupService mariaDB4jSetUp() { - return new MariaDB4jSetupService(mariaDB4j().getDB()); - } + @Bean + public MariaDB4jSetupService mariaDB4jSetUp() { + return new MariaDB4jSetupService(mariaDB4j().getDB()); + } - @Bean - public MariaDB4jSpringService mariaDB4j() { - MariaDB4jSpringService mariaDB4jSpringService = new MariaDB4jSpringService(); - mariaDB4jSpringService.setDefaultBaseDir("build/db/bin"); - mariaDB4jSpringService.setDefaultDataDir("build/db/data"); - return mariaDB4jSpringService; - } + @Bean + public MariaDB4jSpringService mariaDB4j() { + MariaDB4jSpringService mariaDB4jSpringService = new MariaDB4jSpringService(); + mariaDB4jSpringService.setDefaultBaseDir("build/db/bin"); + mariaDB4jSpringService.setDefaultDataDir("build/db/data"); + return mariaDB4jSpringService; + } - @Override + @Override // NOT @Bean @Override dataSourceProperties() - doesn't work :( - protected DataSourceProperties getProperties() { - DataSourceProperties p = super.getProperties(); - String dbName = mariaDB4jSetUp().getTenantDBName(); - // Do not use p.setUrl(mariaDB4j().getConfiguration().getURL(dbName)); - // Because TenantDataSourcePortFixService needs separate - // host/port/db/uid/pwd: - // (DataSourceProperties getUrl() creates the correct JDBC URL from it) - // This intentionally overrides any fineract.datasource.* settings, because - // in this configuration, logically the mariaDB4j settings take - // precedence: - p.setHost("localhost"); - p.setPort(mariaDB4j().getConfiguration().getPort()); - p.setDBName(dbName); - // TODO p.setUsername(mariaDB4j().getConfiguration().getUsername()); - // TODO p.setPassword(mariaDB4j().getConfiguration().getPassword()); - return p; - } + protected DataSourceProperties getProperties() { + DataSourceProperties p = super.getProperties(); + String dbName = mariaDB4jSetUp().getTenantDBName(); + // Do not use p.setUrl(mariaDB4j().getConfiguration().getURL(dbName)); + // Because TenantDataSourcePortFixService needs separate + // host/port/db/uid/pwd: + // (DataSourceProperties getUrl() creates the correct JDBC URL from it) + // This intentionally overrides any fineract.datasource.* settings, because + // in this configuration, logically the mariaDB4j settings take + // precedence: + p.setHost("localhost"); + p.setPort(mariaDB4j().getConfiguration().getPort()); + p.setDBName(dbName); + // TODO p.setUsername(mariaDB4j().getConfiguration().getUsername()); + // TODO p.setPassword(mariaDB4j().getConfiguration().getPassword()); + return p; + } } \ No newline at end of file diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/TenantDataSourcePortFixService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/TenantDataSourcePortFixService.java index 5ca3dfe75..d6180c5aa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/TenantDataSourcePortFixService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/db/TenantDataSourcePortFixService.java @@ -46,25 +46,25 @@ import org.springframework.stereotype.Service; */ @Service public class TenantDataSourcePortFixService { - private static final Logger logger = LoggerFactory.getLogger(TenantDataSourcePortFixService.class); + private static final Logger logger = LoggerFactory.getLogger(TenantDataSourcePortFixService.class); - /** - * While what this class does is convenient in 96% you may would like to - * completely disable it if you've hand tuned your tenants table for an - * advanced configuration and use e.g. different databases maybe on - * different hosts for different tenants. - */ + /** + * While what this class does is convenient in 96% you may would like to + * completely disable it if you've hand tuned your tenants table for an + * advanced configuration and use e.g. different databases maybe on + * different hosts for different tenants. + */ public final static String ENABLED = "fineract.tenantdb.fixup"; @Value("${" + ENABLED + ":true}") private boolean enabled; - // required=false is important here, because in - // WebApplicationInitializerConfiguration for classic WAR there - // is (intentionally) no MariaDB4j nor a DataSourceProperties - // bean (because in the WAR we're using a DS from JNDI) - private @Autowired(required = false) DataSourceProperties dsp; + // required=false is important here, because in + // WebApplicationInitializerConfiguration for classic WAR there + // is (intentionally) no MariaDB4j nor a DataSourceProperties + // bean (because in the WAR we're using a DS from JNDI) + private @Autowired(required = false) DataSourceProperties dsp; - private JdbcTemplate jdbcTemplate; + private JdbcTemplate jdbcTemplate; @Autowired public TenantDataSourcePortFixService(@Qualifier("tenantDataSourceJndi") final DataSource dataSource) { @@ -72,25 +72,25 @@ public class TenantDataSourcePortFixService { } public void fixUpTenantsSchemaServerPort() { - if (!enabled) { - logger.info("No schema_server_port UPDATE made to tenant_server_connections table of the mifosplatform-tenants schema, because " + ENABLED + " = false"); - return; - } - if (dsp == null) { - // we don't have any generic mechanism to know the DB port, given just a tenant DataSource - logger.debug("No schema_server_port UPDATE made to tenant_server_connections table of the mifosplatform-tenants schema (because neither MariaDB4j nor our own Spring Boot DataSourceConfiguration is used in a traditional WAR)"); - return; - } - int r = jdbcTemplate - .update("UPDATE tenant_server_connections SET schema_server = ?, schema_server_port = ?, schema_username = ?, schema_password = ?", - dsp.getHost(), dsp.getPort(), dsp.getUsername(), dsp.getPassword()); - if ( r == 0 ) - logger.warn("UPDATE tenant_server_connections SET ... did not update ANY rows - something is probably wrong"); - else - logger.info("Upated " - + r - + " rows in the tenant_server_connections table of the mifosplatform-tenants schema to the real current host: " - + dsp.getHost() + ", port: " + dsp.getPort()); + if (!enabled) { + logger.info("No schema_server_port UPDATE made to tenant_server_connections table of the mifosplatform-tenants schema, because " + ENABLED + " = false"); + return; + } + if (dsp == null) { + // we don't have any generic mechanism to know the DB port, given just a tenant DataSource + logger.debug("No schema_server_port UPDATE made to tenant_server_connections table of the mifosplatform-tenants schema (because neither MariaDB4j nor our own Spring Boot DataSourceConfiguration is used in a traditional WAR)"); + return; + } + int r = jdbcTemplate + .update("UPDATE tenant_server_connections SET schema_server = ?, schema_server_port = ?, schema_username = ?, schema_password = ?", + dsp.getHost(), dsp.getPort(), dsp.getUsername(), dsp.getPassword()); + if ( r == 0 ) + logger.warn("UPDATE tenant_server_connections SET ... did not update ANY rows - something is probably wrong"); + else + logger.info("Upated " + + r + + " rows in the tenant_server_connections table of the mifosplatform-tenants schema to the real current host: " + + dsp.getHost() + ", port: " + dsp.getPort()); } } 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 0a073d044..d09b48b6b 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 @@ -173,22 +173,22 @@ public class DataValidatorBuilder { 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); - } - } - - return this; + + 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; } public DataValidatorBuilder notNull() { 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 ce4d15a29..80bdf2d02 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 @@ -45,7 +45,7 @@ public class AbandonedConnectionCleanupShutdownListener implements ApplicationLi private void shutDowncleanUpThreadAndDeregisterJDBCDriver() { /*try { - + AbandonedConnectionCleanupThread.shutdown(); tomcat memoroy leak with mysql connector. With Drizzle not required logger.info("Shut-down of AbandonedConnectionCleanupThread successful"); } catch (Throwable t) { @@ -67,7 +67,7 @@ public class AbandonedConnectionCleanupShutdownListener implements ApplicationLi try { Thread.sleep(2000L); } catch (Exception e) { - logger.error("Exception Occcured while trying to sleep.", e); + logger.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/GmailBackedPlatformEmailService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/GmailBackedPlatformEmailService.java index d35a9122d..0af09c0ef 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 @@ -30,20 +30,20 @@ import org.springframework.stereotype.Service; @Service public class GmailBackedPlatformEmailService implements PlatformEmailService { - - private final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService; - - @Autowired - public GmailBackedPlatformEmailService(final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService){ - this.externalServicesReadPlatformService = externalServicesReadPlatformService; - } + + private final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService; + + @Autowired + public GmailBackedPlatformEmailService(final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService){ + this.externalServicesReadPlatformService = externalServicesReadPlatformService; + } @Override 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: " + + 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" + @@ -51,8 +51,8 @@ public class GmailBackedPlatformEmailService implements PlatformEmailService { "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); + final EmailDetail emailDetail = new EmailDetail(subject, body, address, contactName); + sendDefinedEmail(emailDetail); } 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 index a3b14fb89..900f194dc 100755 --- 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 @@ -239,7 +239,7 @@ public final class SearchParameters { return new SearchParameters(sqlSearch, null, externalId, null, null, null, null, offset, maxLimitAllowed, orderBy, sortOrder, staffId, accountNo, loanId, savingsId, orphansOnly, isSelfUser); } - + private 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, 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 c831945cd..dce5f07de 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 @@ -47,7 +47,7 @@ import com.googlecode.flyway.core.util.jdbc.DriverDataSource; @Service public class TenantDatabaseUpgradeService { - private final static Logger LOG = LoggerFactory.getLogger(TenantDatabaseUpgradeService.class); + private final static Logger LOG = LoggerFactory.getLogger(TenantDatabaseUpgradeService.class); private final TenantDetailsService tenantDetailsService; protected final DataSource tenantDataSource; @@ -92,9 +92,9 @@ public class TenantDatabaseUpgradeService { * itself. */ private void upgradeTenantDB() { - String dbHostname = getEnvVar("FINERACT_DEFAULT_TENANTDB_HOSTNAME", "localhost"); - String dbPort = getEnvVar("FINERACT_DEFAULT_TENANTDB_PORT", "3306"); - LOG.info("upgradeTenantDB: FINERACT_DEFAULT_TENANTDB_HOSTNAME = {}, FINERACT_DEFAULT_TENANTDB_PORT = {}", dbHostname, dbPort); + String dbHostname = getEnvVar("FINERACT_DEFAULT_TENANTDB_HOSTNAME", "localhost"); + String dbPort = getEnvVar("FINERACT_DEFAULT_TENANTDB_PORT", "3306"); + LOG.info("upgradeTenantDB: FINERACT_DEFAULT_TENANTDB_HOSTNAME = {}, FINERACT_DEFAULT_TENANTDB_PORT = {}", dbHostname, dbPort); final Flyway flyway = new Flyway(); flyway.setDataSource(tenantDataSource); @@ -108,11 +108,11 @@ public class TenantDatabaseUpgradeService { tenantDataSourcePortFixService.fixUpTenantsSchemaServerPort(); } - private String getEnvVar(String name, String defaultValue) { - String value = System.getenv(name); - if (value == null) { - return defaultValue; - } - return value; - } + private String getEnvVar(String name, String defaultValue) { + String value = System.getenv(name); + if (value == null) { + return defaultValue; + } + return value; + } } 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 80b3ba8fe..5950517f6 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 @@ -60,7 +60,7 @@ public class ThreadLocalContextUtil { } public static void setAuthToken(final String authToken) { - authTokenContext.set(authToken); + authTokenContext.set(authToken); } public static String getAuthToken() { 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 7f9be7199..ad5b49212 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 @@ -87,7 +87,7 @@ public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceSe // http://www.tomcatexpert.com/blog/2010/04/01/configuring-jdbc-pool-high-concurrency // see also org.apache.fineract.DataSourceProperties.setDefaults() - String jdbcUrl = this.driverConfig.constructProtocol(tenantConnectionObj.getSchemaServer(), tenantConnectionObj.getSchemaServerPort(), tenantConnectionObj.getSchemaName()) ; + String jdbcUrl = this.driverConfig.constructProtocol(tenantConnectionObj.getSchemaServer(), tenantConnectionObj.getSchemaServerPort(), tenantConnectionObj.getSchemaName()) ; //final String jdbcUrl = tenantConnectionObj.databaseURL(); final PoolConfiguration poolConfiguration = new PoolProperties(); poolConfiguration.setDriverClassName(this.driverConfig.getDriverClassName()); 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 4b3a8fb7d..d9fe5b480 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 @@ -61,180 +61,180 @@ 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"; - private final PlatformSecurityContext context; - private final CreditBureauReadPlatformService readPlatformService; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final CreditBureauLoanProductMappingReadPlatformService readPlatformServiceCreditBureauLoanProduct; - private final OrganisationCreditBureauReadPlatformService readPlatformServiceOrganisationCreditBureau; - private final DefaultToApiJsonSerializer toApiJsonSerializerCreditBureauLoanProduct; - private final DefaultToApiJsonSerializer toApiJsonSerializerOrganisationCreditBureau; - private final DefaultToApiJsonSerializer toApiJsonSerializerReport; - private final ApiRequestParameterHelper apiRequestParameterHelper; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - private final CreditBureauReadConfigurationService creditBureauConfiguration; + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("creditBureauId", "alias", "country", "creditBureauProductId", "startDate", "endDate", "isActive")); + private final String resourceNameForPermissions = "CreditBureau"; + private final PlatformSecurityContext context; + private final CreditBureauReadPlatformService readPlatformService; + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final CreditBureauLoanProductMappingReadPlatformService readPlatformServiceCreditBureauLoanProduct; + private final OrganisationCreditBureauReadPlatformService readPlatformServiceOrganisationCreditBureau; + private final DefaultToApiJsonSerializer toApiJsonSerializerCreditBureauLoanProduct; + private final DefaultToApiJsonSerializer toApiJsonSerializerOrganisationCreditBureau; + private final DefaultToApiJsonSerializer toApiJsonSerializerReport; + private final ApiRequestParameterHelper apiRequestParameterHelper; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final CreditBureauReadConfigurationService creditBureauConfiguration; - @Autowired - public CreditBureauConfigurationAPI(final PlatformSecurityContext context, - final CreditBureauReadPlatformService readPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final CreditBureauLoanProductMappingReadPlatformService readPlatformServiceCreditBureauLoanProduct, - final DefaultToApiJsonSerializer toApiJsonSerializerCreditBureauLoanProduct, - final OrganisationCreditBureauReadPlatformService readPlatformServiceOrganisationCreditBureau, - final DefaultToApiJsonSerializer toApiJsonSerializerOrganisationCreditBureau, - final ApiRequestParameterHelper apiRequestParameterHelper, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializerReport, - final CreditBureauReadConfigurationService creditBureauConfiguration) { - this.context = context; - this.readPlatformService = readPlatformService; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.readPlatformServiceCreditBureauLoanProduct = readPlatformServiceCreditBureauLoanProduct; - this.toApiJsonSerializerCreditBureauLoanProduct = toApiJsonSerializerCreditBureauLoanProduct; - this.readPlatformServiceOrganisationCreditBureau = readPlatformServiceOrganisationCreditBureau; - this.toApiJsonSerializerOrganisationCreditBureau = toApiJsonSerializerOrganisationCreditBureau; - this.toApiJsonSerializer = toApiJsonSerializer; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - this.toApiJsonSerializerReport = toApiJsonSerializerReport; - this.creditBureauConfiguration = creditBureauConfiguration; + @Autowired + public CreditBureauConfigurationAPI(final PlatformSecurityContext context, + final CreditBureauReadPlatformService readPlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final CreditBureauLoanProductMappingReadPlatformService readPlatformServiceCreditBureauLoanProduct, + final DefaultToApiJsonSerializer toApiJsonSerializerCreditBureauLoanProduct, + final OrganisationCreditBureauReadPlatformService readPlatformServiceOrganisationCreditBureau, + final DefaultToApiJsonSerializer toApiJsonSerializerOrganisationCreditBureau, + final ApiRequestParameterHelper apiRequestParameterHelper, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializerReport, + final CreditBureauReadConfigurationService creditBureauConfiguration) { + this.context = context; + this.readPlatformService = readPlatformService; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.readPlatformServiceCreditBureauLoanProduct = readPlatformServiceCreditBureauLoanProduct; + this.toApiJsonSerializerCreditBureauLoanProduct = toApiJsonSerializerCreditBureauLoanProduct; + this.readPlatformServiceOrganisationCreditBureau = readPlatformServiceOrganisationCreditBureau; + this.toApiJsonSerializerOrganisationCreditBureau = toApiJsonSerializerOrganisationCreditBureau; + this.toApiJsonSerializer = toApiJsonSerializer; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.toApiJsonSerializerReport = toApiJsonSerializerReport; + this.creditBureauConfiguration = creditBureauConfiguration; - } + } - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String getCreditBureau(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String getCreditBureau(@Context final UriInfo uriInfo) { + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final Collection creditBureau = this.readPlatformService.retrieveCreditBureau(); + final Collection creditBureau = this.readPlatformService.retrieveCreditBureau(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, creditBureau, this.RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper + .process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, creditBureau, this.RESPONSE_DATA_PARAMETERS); - } + } - @GET - @Path("/mappings") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String getCreditBureauLoanProductMapping(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + @GET + @Path("/mappings") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String getCreditBureauLoanProductMapping(@Context final UriInfo uriInfo) { + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final Collection creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct - .readCreditBureauLoanProductMapping(); + 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); - } + } - @GET - @Path("/organisationCreditBureau") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String getOrganisationCreditBureau(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + @GET + @Path("/organisationCreditBureau") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String getOrganisationCreditBureau(@Context final UriInfo uriInfo) { + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final Collection organisationCreditBureau = this.readPlatformServiceOrganisationCreditBureau - .retrieveOrgCreditBureau(); + final Collection organisationCreditBureau = this.readPlatformServiceOrganisationCreditBureau + .retrieveOrgCreditBureau(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializerOrganisationCreditBureau.serialize(settings, organisationCreditBureau, - this.RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper + .process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializerOrganisationCreditBureau.serialize(settings, organisationCreditBureau, + this.RESPONSE_DATA_PARAMETERS); - } + } - @GET - @Path("/config/{organisationCreditBureauId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String getConfiguration(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId, @Context final UriInfo uriInfo) { + @GET + @Path("/config/{organisationCreditBureauId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String getConfiguration(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId, @Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final Collection configurationData = this.creditBureauConfiguration - .readConfigurationByOrganisationCreditBureauId(organisationCreditBureauId); + final Collection configurationData = this.creditBureauConfiguration + .readConfigurationByOrganisationCreditBureauId(organisationCreditBureauId); - return this.toApiJsonSerializerReport.serialize(configurationData); - } - - - @GET - @Path("/loanProduct") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String fetchLoanProducts(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + return this.toApiJsonSerializerReport.serialize(configurationData); + } + + + @GET + @Path("/loanProduct") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String fetchLoanProducts(@Context final UriInfo uriInfo) { + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final Collection creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct - .fetchLoanProducts(); + 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 - @Path("/organisationCreditBureau") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String updateCreditBureau(final String apiRequestBodyAsJson) { + @PUT + @Path("/organisationCreditBureau") + @Consumes({ MediaType.APPLICATION_JSON }) + @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); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } + return this.toApiJsonSerializer.serialize(result); + } - @PUT - @Path("/mappings") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String updateCreditBureauLoanProductMapping(final String apiRequestBodyAsJson) { + @PUT + @Path("/mappings") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String updateCreditBureauLoanProductMapping(final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCreditBureauLoanProductMapping() - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCreditBureauLoanProductMapping() + .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); + } - @POST - @Path("/organisationCreditBureau/{organisationCreditBureauId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String addOrganisationCreditBureau(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId, final String apiRequestBodyAsJson) { + @POST + @Path("/organisationCreditBureau/{organisationCreditBureauId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String addOrganisationCreditBureau(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().addOrganisationCreditBureau(organisationCreditBureauId) - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().addOrganisationCreditBureau(organisationCreditBureauId) + .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); + } - @POST - @Path("/mappings/{CreditBureauId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String createCreditBureauLoanProductMapping(@PathParam("CreditBureauId") final Long CreditBureauId, final String apiRequestBodyAsJson) { + @POST + @Path("/mappings/{CreditBureauId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String createCreditBureauLoanProductMapping(@PathParam("CreditBureauId") final Long CreditBureauId, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().createCreditBureauLoanProductMapping(CreditBureauId) - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().createCreditBureauLoanProductMapping(CreditBureauId) + .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); + } - + } 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 ad47d1c77..868707190 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,50 +19,50 @@ package org.apache.fineract.infrastructure.creditbureau.data; public class CreditBureauConfigurationData { - private final long creditBureauConfigurationId; + private final long creditBureauConfigurationId; - private final String configurationKey; + private final String configurationKey; - private final String value; + private final String value; - private final long organizationCreditBureauId; + private final long organizationCreditBureauId; - private final String description; + private 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; - this.organizationCreditBureauId = organizationCreditBureauId; - this.description = 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; + this.organizationCreditBureauId = organizationCreditBureauId; + this.description = description; - } + } - 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); - } + 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); + } - public long getCreditBureauConfigurationId() { - return this.creditBureauConfigurationId; - } + public long getCreditBureauConfigurationId() { + return this.creditBureauConfigurationId; + } - public String getConfigurationKey() { - return this.configurationKey; - } + public String getConfigurationKey() { + return this.configurationKey; + } - public String getValue() { - return this.value; - } + public String getValue() { + return this.value; + } - public long getOrganizationCreditBureauId() { - return this.organizationCreditBureauId; - } + public long getOrganizationCreditBureauId() { + return this.organizationCreditBureauId; + } - public String getDescription() { - return this.description; - } + public String getDescription() { + return this.description; + } } 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 d1cf2ead2..9106d53ff 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 @@ -20,58 +20,58 @@ package org.apache.fineract.infrastructure.creditbureau.data; public class CreditBureauData { - private final long creditBureauId; + private final long creditBureauId; - private final String creditBureauName; + private final String creditBureauName; - private final String country; + private final String country; - private final String productName; + private final String productName; - private final String creditBureauSummary; + private final String creditBureauSummary; - private final long implementationKey; + private 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; - this.productName = productName; - this.creditBureauSummary = creditBureauSummary; - this.implementationKey = 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; + this.productName = productName; + this.creditBureauSummary = creditBureauSummary; + this.implementationKey = implementationKey; - } + } - 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() { - return this.creditBureauSummary; - } + public String getCreditBureauSummary() { + return this.creditBureauSummary; + } - public long getCreditBureauId() { - return this.creditBureauId; - } + public long getCreditBureauId() { + return this.creditBureauId; + } - public String getCreditBureauName() { - return this.creditBureauName; - } + public String getCreditBureauName() { + return this.creditBureauName; + } - public String getCountry() { - return this.country; - } + public String getCountry() { + return this.country; + } - public String getProductName() { - return this.productName; - } + public String getProductName() { + return this.productName; + } - public long getImplementationKey() { - return this.implementationKey; - } + public long getImplementationKey() { + return this.implementationKey; + } } 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 356e003fe..2969010da 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 @@ -20,93 +20,93 @@ package org.apache.fineract.infrastructure.creditbureau.data; public class CreditBureauLoanProductMappingData { - private final long creditbureauLoanProductMappingId; + private final long creditbureauLoanProductMappingId; - private final long organisationCreditBureauId; + private final long organisationCreditBureauId; - private final String alias; + private final String alias; - private final String creditbureauSummary; + private final String creditbureauSummary; - private final String loanProductName; + private final String loanProductName; - private final long loanProductId; + private final long loanProductId; - private final boolean isCreditCheckMandatory; + private final boolean isCreditCheckMandatory; - private final boolean skipCrediCheckInFailure; + private final boolean skipCrediCheckInFailure; - private final long stalePeriod; + private final long stalePeriod; - private final boolean is_active; + 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) { - this.creditbureauLoanProductMappingId = creditbureauLoanProductMappingId; - this.organisationCreditBureauId = organisationCreditBureauId; - this.alias = alias; - this.creditbureauSummary = creditbureauSummary; - this.loanProductName = loanProductName; - this.loanProductId = loanProductId; - this.isCreditCheckMandatory = isCreditCheckMandatory; - this.skipCrediCheckInFailure = skipCrediCheckInFailure; - this.stalePeriod = stalePeriod; - this.is_active = 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; + this.creditbureauSummary = creditbureauSummary; + this.loanProductName = loanProductName; + this.loanProductId = loanProductId; + this.isCreditCheckMandatory = isCreditCheckMandatory; + this.skipCrediCheckInFailure = skipCrediCheckInFailure; + this.stalePeriod = stalePeriod; + this.is_active = is_active; + } - 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) { - return new CreditBureauLoanProductMappingData(creditbureauLoanProductMappingId, organisationCreditBureauId, alias, - creditbureauSummary, loanProductName, loanProductId, isCreditCheckMandatory, skipCrediCheckInFailure, - stalePeriod, is_active); - } + 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) { + return new CreditBureauLoanProductMappingData(creditbureauLoanProductMappingId, organisationCreditBureauId, alias, + creditbureauSummary, loanProductName, loanProductId, isCreditCheckMandatory, skipCrediCheckInFailure, + stalePeriod, is_active); + } - public static CreditBureauLoanProductMappingData instance1(final String loanProductName, final long loanProductId) { - return new CreditBureauLoanProductMappingData(0, 0, "", "", loanProductName, loanProductId, false, false, 0, false); - } + public static CreditBureauLoanProductMappingData instance1(final String loanProductName, final long loanProductId) { + return new CreditBureauLoanProductMappingData(0, 0, "", "", loanProductName, loanProductId, false, false, 0, false); + } - public long getCreditbureauLoanProductMappingId() { - return this.creditbureauLoanProductMappingId; - } + public long getCreditbureauLoanProductMappingId() { + return this.creditbureauLoanProductMappingId; + } - public String getAlias() { - return this.alias; - } + public String getAlias() { + return this.alias; + } - public String getCreditbureauSummary() { - return this.creditbureauSummary; - } + public String getCreditbureauSummary() { + return this.creditbureauSummary; + } - public String getLoanProductName() { - return this.loanProductName; - } + public String getLoanProductName() { + return this.loanProductName; + } - public long getOrganisationCreditBureauId() { - return this.organisationCreditBureauId; - } + public long getOrganisationCreditBureauId() { + return this.organisationCreditBureauId; + } - public long getLoanProductId() { - return this.loanProductId; - } + public long getLoanProductId() { + return this.loanProductId; + } - public boolean isCreditCheckMandatory() { - return this.isCreditCheckMandatory; - } + public boolean isCreditCheckMandatory() { + return this.isCreditCheckMandatory; + } - public boolean isSkipCrediCheckInFailure() { - return this.skipCrediCheckInFailure; - } + public boolean isSkipCrediCheckInFailure() { + return this.skipCrediCheckInFailure; + } - public long getStalePeriod() { - return this.stalePeriod; - } + public long getStalePeriod() { + return this.stalePeriod; + } - public boolean isIs_active() { - return this.is_active; - } + public boolean isIs_active() { + return this.is_active; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauMasterData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauMasterData.java index bf73b810a..bef1e61e6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauMasterData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauMasterData.java @@ -20,33 +20,33 @@ package org.apache.fineract.infrastructure.creditbureau.data; public class CreditBureauMasterData { - private final long creditBureauId; + private final long creditBureauId; - private final String creditBureauName; + private final String creditBureauName; - private final String country; + private final String country; - public static CreditBureauMasterData instance(final Long creditBureauId, final String creditBureauName, final String country) { - return new CreditBureauMasterData(creditBureauId, creditBureauName, country); - } + public static CreditBureauMasterData instance(final Long creditBureauId, final String creditBureauName, final String country) { + return new CreditBureauMasterData(creditBureauId, creditBureauName, country); + } - private CreditBureauMasterData(final Long creditBureauId, final String creditBureauName, final String country) { - this.creditBureauId = creditBureauId; - this.creditBureauName = creditBureauName; - this.country = country; + private CreditBureauMasterData(final Long creditBureauId, final String creditBureauName, final String country) { + this.creditBureauId = creditBureauId; + this.creditBureauName = creditBureauName; + this.country = country; - } + } - public String getCreditBureauName() { - return this.creditBureauName; - } + public String getCreditBureauName() { + return this.creditBureauName; + } - public String getCountry() { - return this.country; - } + public String getCountry() { + return this.country; + } - public Long getCreditBureauId() { - return this.creditBureauId; - } + public Long getCreditBureauId() { + return this.creditBureauId; + } } 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 d5f88fdd1..253be4296 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 @@ -20,34 +20,34 @@ package org.apache.fineract.infrastructure.creditbureau.data; public class CreditBureauProduct { - private final long creditBureauProductId; + private final long creditBureauProductId; - private final String creditBureauProductName; + private final String creditBureauProductName; - private final long creditBureauMasterId; + private final long creditBureauMasterId; - private CreditBureauProduct(final long creditBureauProductId, final String creditBureauProductName, - final long creditBureauMasterId) { - this.creditBureauProductId = creditBureauProductId; - this.creditBureauProductName = creditBureauProductName; - this.creditBureauMasterId = creditBureauMasterId; - } + private CreditBureauProduct(final long creditBureauProductId, final String creditBureauProductName, + final long creditBureauMasterId) { + this.creditBureauProductId = creditBureauProductId; + this.creditBureauProductName = creditBureauProductName; + this.creditBureauMasterId = creditBureauMasterId; + } - public static CreditBureauProduct instance(final long creditBureauProductId, final String creditBureauProductName, - final long creditBureauMasterId) { - return new CreditBureauProduct(creditBureauProductId, creditBureauProductName, creditBureauMasterId); - } + public static CreditBureauProduct instance(final long creditBureauProductId, final String creditBureauProductName, + final long creditBureauMasterId) { + return new CreditBureauProduct(creditBureauProductId, creditBureauProductName, creditBureauMasterId); + } - public long getCreditBureauProductId() { - return this.creditBureauProductId; - } + public long getCreditBureauProductId() { + return this.creditBureauProductId; + } - public String getCreditBureauProductName() { - return this.creditBureauProductName; - } + public String getCreditBureauProductName() { + return this.creditBureauProductName; + } - public long getCreditBureauMasterId() { - return this.creditBureauMasterId; - } + public long getCreditBureauMasterId() { + return this.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 c08c2be6e..1bc9ac6e2 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 @@ -20,72 +20,72 @@ package org.apache.fineract.infrastructure.creditbureau.data; public class OrganisationCreditBureauData { - private final long organisationCreditBureauId; + private final long organisationCreditBureauId; - private final String alias; + private final String alias; - private final long creditBureauId; + private final long creditBureauId; - private final String creditBureauName; + private final String creditBureauName; - private final String creditBureauProduct; + private final String creditBureauProduct; - private final String creditBureauCountry; + private final String creditBureauCountry; - private final String creditBureauSummary; + private final String creditBureauSummary; - private final boolean is_active; + 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) { - this.organisationCreditBureauId = organisationCreditBureauId; - this.alias = alias; - this.creditBureauId = creditBureauId; - this.creditBureauName = creditBureauName; - this.creditBureauProduct = creditBureauProduct; - this.creditBureauCountry = creditBureauCountry; - this.creditBureauSummary = creditBureauSummary; - this.is_active = 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; + this.creditBureauName = creditBureauName; + this.creditBureauProduct = creditBureauProduct; + this.creditBureauCountry = creditBureauCountry; + this.creditBureauSummary = creditBureauSummary; + this.is_active = is_active; + } - 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); - } + 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); + } - public long getOrganisationCreditBureauId() { - return this.organisationCreditBureauId; - } + public long getOrganisationCreditBureauId() { + return this.organisationCreditBureauId; + } - public String getCreditBureauName() { - return this.creditBureauName; - } + public String getCreditBureauName() { + return this.creditBureauName; + } - public String getCreditBureauProduct() { - return this.creditBureauProduct; - } + public String getCreditBureauProduct() { + return this.creditBureauProduct; + } - public String getCreditBureauCountry() { - return this.creditBureauCountry; - } + public String getCreditBureauCountry() { + return this.creditBureauCountry; + } - public String getCreditBureauSummary() { - return this.creditBureauSummary; - } + public String getCreditBureauSummary() { + return this.creditBureauSummary; + } - public String getAlias() { - return this.alias; - } + public String getAlias() { + return this.alias; + } - public long getCreditBureauId() { - return this.creditBureauId; - } + public long getCreditBureauId() { + return this.creditBureauId; + } - public boolean isActive() { - return this.is_active; - } + public boolean isActive() { + return this.is_active; + } } 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 ad3fab76a..82b2921ae 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 @@ -34,79 +34,79 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; public class CreditBureau extends AbstractPersistableCustom { - private String name; + private String name; - private String product; + private String product; - private String country; + private String country; - private String implementationKey; + private String implementationKey; - @OneToMany(mappedBy = "organisation_creditbureau", cascade = CascadeType.ALL) - private List CreditBureauLoanProductMapping = new ArrayList<>(); + @OneToMany(mappedBy = "organisation_creditbureau", cascade = CascadeType.ALL) + private List CreditBureauLoanProductMapping = new ArrayList<>(); - public CreditBureau(String name, String product, String country, String implementationKey, - List CreditBureauLoanProductMapping) { - this.name = name; - this.product = product; - this.country = country; - this.implementationKey = implementationKey; - this.CreditBureauLoanProductMapping = CreditBureauLoanProductMapping; - } + public CreditBureau(String name, String product, String country, String implementationKey, + List CreditBureauLoanProductMapping) { + this.name = name; + this.product = product; + this.country = country; + this.implementationKey = implementationKey; + this.CreditBureauLoanProductMapping = CreditBureauLoanProductMapping; + } - public CreditBureau() { + public CreditBureau() { - } + } - public static CreditBureau fromJson(final JsonCommand command) { + public static CreditBureau fromJson(final JsonCommand command) { - final String tname = command.stringValueOfParameterNamed("name"); - final String tproduct = command.stringValueOfParameterNamed("product"); - final String tcountry = command.stringValueOfParameterNamed("country"); - final String timplementationKey = command.stringValueOfParameterNamed("implementationKey"); + final String tname = command.stringValueOfParameterNamed("name"); + final String tproduct = command.stringValueOfParameterNamed("product"); + final String tcountry = command.stringValueOfParameterNamed("country"); + final String timplementationKey = command.stringValueOfParameterNamed("implementationKey"); - return new CreditBureau(tname, tproduct, tcountry, timplementationKey, null); + return new CreditBureau(tname, tproduct, tcountry, timplementationKey, null); - } + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getProduct() { - return this.product; - } + public String getProduct() { + return this.product; + } - public void setProduct(String product) { - this.product = product; - } + public void setProduct(String product) { + this.product = product; + } - public String getCountry() { - return this.country; - } + public String getCountry() { + return this.country; + } - public void setCountry(String country) { - this.country = country; - } + public void setCountry(String country) { + this.country = country; + } - public String getImplementationKey() { - return this.implementationKey; - } + public String getImplementationKey() { + return this.implementationKey; + } - public void setImplementationKey(String implementationKey) { - this.implementationKey = implementationKey; - } + public void setImplementationKey(String implementationKey) { + this.implementationKey = implementationKey; + } - public List getCreditBureauLpMapping() { - return this.CreditBureauLoanProductMapping; - } + public List getCreditBureauLpMapping() { + return this.CreditBureauLoanProductMapping; + } - public void setCreditBureauLpMapping(List CreditBureauLoanProductMapping) { - this.CreditBureauLoanProductMapping = CreditBureauLoanProductMapping; - } + public void setCreditBureauLpMapping(List CreditBureauLoanProductMapping) { + this.CreditBureauLoanProductMapping = CreditBureauLoanProductMapping; + } } 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 bdd7f6f9a..e5e015605 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 @@ -31,71 +31,71 @@ 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; + @Column(name = "configkey") + private String configurationKey; - @Column(name = "value") - private String value; + @Column(name = "value") + private String value; - @Column(name = "description") - private String description; + @Column(name = "description") + private String description; - @ManyToOne - @JoinColumn(name = "organisation_creditbureau_id") - private OrganisationCreditBureau organisationCreditbureau; + @ManyToOne + @JoinColumn(name = "organisation_creditbureau_id") + private OrganisationCreditBureau organisationCreditbureau; - public CreditBureauConfiguration() { + public CreditBureauConfiguration() { - } + } - public CreditBureauConfiguration(String configkey, String value, String description, - OrganisationCreditBureau organisationCreditbureau) { - this.configurationKey = configkey; - this.value = value; - this.description = description; - this.organisationCreditbureau = organisationCreditbureau; + public CreditBureauConfiguration(String configkey, String value, String description, + OrganisationCreditBureau organisationCreditbureau) { + this.configurationKey = configkey; + this.value = value; + this.description = description; + this.organisationCreditbureau = organisationCreditbureau; - } + } - public CreditBureauConfiguration fromJson(JsonCommand command, OrganisationCreditBureau organisation_creditbureau) { - final String configkey = command.stringValueOfParameterNamed("configkey"); - final String value = command.stringValueOfParameterNamed("value"); - final String description = command.stringValueOfParameterNamed("description"); + public CreditBureauConfiguration fromJson(JsonCommand command, OrganisationCreditBureau organisation_creditbureau) { + final String configkey = command.stringValueOfParameterNamed("configkey"); + final String value = command.stringValueOfParameterNamed("value"); + final String description = command.stringValueOfParameterNamed("description"); - return new CreditBureauConfiguration(configkey, value, description, organisation_creditbureau); + return new CreditBureauConfiguration(configkey, value, description, organisation_creditbureau); - } + } - public String getConfigkey() { - return this.configurationKey; - } + public String getConfigkey() { + return this.configurationKey; + } - public void setConfigkey(String configkey) { - this.configurationKey = configkey; - } + public void setConfigkey(String configkey) { + this.configurationKey = configkey; + } - public String getValue() { - return this.value; - } + public String getValue() { + return this.value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } - public String getDescription() { - return this.description; - } + public String getDescription() { + return this.description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public OrganisationCreditBureau getOrganisation_creditbureau() { - return this.organisationCreditbureau; - } + public OrganisationCreditBureau getOrganisation_creditbureau() { + return this.organisationCreditbureau; + } - public void setOrganisation_creditbureau(OrganisationCreditBureau organisation_creditbureau) { - this.organisationCreditbureau = organisation_creditbureau; - } + public void setOrganisation_creditbureau(OrganisationCreditBureau organisation_creditbureau) { + this.organisationCreditbureau = organisation_creditbureau; + } } 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 8c3cdb423..2ec8ae1b8 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 @@ -32,119 +32,119 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity @Table(name = "m_creditbureau_loanproduct_mapping") public class CreditBureauLoanProductMapping extends AbstractPersistableCustom { - - @Column(name = "is_CreditCheck_Mandatory") - private boolean isCreditCheckMandatory; - - @Column(name = "skip_CreditCheck_in_Failure") - private boolean skipCreditCheckInFailure; - - @Column(name = "stale_Period") - private int stalePeriod; + + @Column(name = "is_CreditCheck_Mandatory") + private boolean isCreditCheckMandatory; + + @Column(name = "skip_CreditCheck_in_Failure") + private boolean skipCreditCheckInFailure; + + @Column(name = "stale_Period") + private int stalePeriod; - private boolean is_active; + private boolean is_active; - @ManyToOne - private OrganisationCreditBureau organisation_creditbureau; + @ManyToOne + private OrganisationCreditBureau organisation_creditbureau; - @OneToOne - @JoinColumn(name="loan_product_id") - private LoanProduct loanProduct; - - public CreditBureauLoanProductMapping() { + @OneToOne + @JoinColumn(name="loan_product_id") + private LoanProduct loanProduct; + + public CreditBureauLoanProductMapping() { - } + } - public CreditBureauLoanProductMapping(boolean isCreditCheckMandatory, boolean skipCreditCheckInFailure, int stalePeriod, - boolean is_active, OrganisationCreditBureau organisationCreditbureau, LoanProduct loanProduct) { - this.isCreditCheckMandatory = isCreditCheckMandatory; - this.skipCreditCheckInFailure = skipCreditCheckInFailure; - this.stalePeriod = stalePeriod; - this.is_active = is_active; - this.organisation_creditbureau = organisationCreditbureau; - this.loanProduct = loanProduct; - } + public CreditBureauLoanProductMapping(boolean isCreditCheckMandatory, boolean skipCreditCheckInFailure, int stalePeriod, + boolean is_active, OrganisationCreditBureau organisationCreditbureau, LoanProduct loanProduct) { + this.isCreditCheckMandatory = isCreditCheckMandatory; + this.skipCreditCheckInFailure = skipCreditCheckInFailure; + this.stalePeriod = stalePeriod; + this.is_active = is_active; + this.organisation_creditbureau = organisationCreditbureau; + 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"); - } - - if((Boolean)command.booleanPrimitiveValueOfParameterNamed("skipCreditcheckInFailure")!=null) - { - skipCreditCheckInFailure = command.booleanPrimitiveValueOfParameterNamed("skipCreditcheckInFailure"); - } - - if((Integer)command.integerValueOfParameterNamed("stalePeriod")!=null) - { - stalePeriod = command.integerValueOfParameterNamed("stalePeriod"); - } - - if((Boolean) command.booleanPrimitiveValueOfParameterNamed("is_active")) - { - is_active = command.booleanPrimitiveValueOfParameterNamed("is_active"); - } - + 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((Integer)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); + return new CreditBureauLoanProductMapping(isCreditCheckMandatory, skipCreditCheckInFailure, stalePeriod, is_active, + organisation_creditbureau, loanProduct); - } + } - public boolean isCreditCheckMandatory() { - return this.isCreditCheckMandatory; - } + public boolean isCreditCheckMandatory() { + return this.isCreditCheckMandatory; + } - public void setCreditCheckMandatory(boolean isCreditCheckMandatory) { - this.isCreditCheckMandatory = isCreditCheckMandatory; - } + public void setCreditCheckMandatory(boolean isCreditCheckMandatory) { + this.isCreditCheckMandatory = isCreditCheckMandatory; + } - public boolean isSkipCreditCheckInFailure() { - return this.skipCreditCheckInFailure; - } + public boolean isSkipCreditCheckInFailure() { + return this.skipCreditCheckInFailure; + } - public void setSkipCreditCheckInFailure(boolean skipCreditCheckInFailure) { - this.skipCreditCheckInFailure = skipCreditCheckInFailure; - } + public void setSkipCreditCheckInFailure(boolean skipCreditCheckInFailure) { + this.skipCreditCheckInFailure = skipCreditCheckInFailure; + } - public int getStalePeriod() { - return this.stalePeriod; - } + public int getStalePeriod() { + return this.stalePeriod; + } - public void setStalePeriod(int stalePeriod) { - this.stalePeriod = stalePeriod; - } + public void setStalePeriod(int stalePeriod) { + this.stalePeriod = stalePeriod; + } - public boolean isIs_active() { - return this.is_active; - } + public boolean isIs_active() { + return this.is_active; + } - public void setIs_active(boolean is_active) { - this.is_active = is_active; - } + public void setIs_active(boolean is_active) { + this.is_active = is_active; + } - public OrganisationCreditBureau getOrganisationCreditbureau() { - return this.organisation_creditbureau; - } + public OrganisationCreditBureau getOrganisationCreditbureau() { + return this.organisation_creditbureau; + } - public void setOrganisationCreditbureau(OrganisationCreditBureau organisationCreditbureau) { - this.organisation_creditbureau = organisationCreditbureau; - } + public void setOrganisationCreditbureau(OrganisationCreditBureau organisationCreditbureau) { + this.organisation_creditbureau = organisationCreditbureau; + } - public LoanProduct getLoanProduct() { - return this.loanProduct; - } + public LoanProduct getLoanProduct() { + return this.loanProduct; + } - public void setLoanProduct(LoanProduct loanProduct) { - this.loanProduct = loanProduct; - } + public void setLoanProduct(LoanProduct loanProduct) { + this.loanProduct = loanProduct; + } - + } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauLoanProductMappingRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauLoanProductMappingRepository.java index 3280b83ee..4ac6f801f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauLoanProductMappingRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauLoanProductMappingRepository.java @@ -22,6 +22,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface CreditBureauLoanProductMappingRepository - extends JpaRepository, JpaSpecificationExecutor { + extends JpaRepository, JpaSpecificationExecutor { } 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 03dee5b58..26287ef35 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 @@ -23,8 +23,8 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface CreditBureauRepository - extends JpaRepository, JpaSpecificationExecutor { + extends JpaRepository, JpaSpecificationExecutor { - // CreditBureau findOne(long id); + // 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 8a88ed5b9..b164f299d 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 @@ -34,67 +34,67 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_organisation_creditbureau") public class OrganisationCreditBureau extends AbstractPersistableCustom { - private String alias; + private String alias; - @OneToOne - private CreditBureau creditbureau; + @OneToOne + private CreditBureau creditbureau; - private boolean is_active; + private boolean is_active; - @OneToMany(mappedBy = "organisation_creditbureau", cascade = CascadeType.ALL) - private List creditBureauLoanProductMapping = new ArrayList<>(); + @OneToMany(mappedBy = "organisation_creditbureau", cascade = CascadeType.ALL) + private List creditBureauLoanProductMapping = new ArrayList<>(); - public OrganisationCreditBureau(String alias, CreditBureau creditBureau, boolean is_active, - List creditBureauLoanProductMapping) { - this.alias = alias; - this.creditbureau = creditBureau; - this.is_active = is_active; - this.creditBureauLoanProductMapping = creditBureauLoanProductMapping; - } + public OrganisationCreditBureau(String alias, CreditBureau creditBureau, boolean is_active, + List creditBureauLoanProductMapping) { + this.alias = alias; + this.creditbureau = creditBureau; + this.is_active = is_active; + this.creditBureauLoanProductMapping = creditBureauLoanProductMapping; + } - public OrganisationCreditBureau() { + public OrganisationCreditBureau() { - } + } - public static OrganisationCreditBureau fromJson(final JsonCommand command, CreditBureau creditBureau) { - final String alias = command.stringValueOfParameterNamed("alias"); - final boolean is_active = command.booleanPrimitiveValueOfParameterNamed("is_active"); + public static OrganisationCreditBureau fromJson(final JsonCommand command, CreditBureau creditBureau) { + final String alias = command.stringValueOfParameterNamed("alias"); + final boolean is_active = command.booleanPrimitiveValueOfParameterNamed("is_active"); - return new OrganisationCreditBureau(alias, creditBureau, is_active, null); - } + return new OrganisationCreditBureau(alias, creditBureau, is_active, null); + } - public String getAlias() { - return this.alias; - } + public String getAlias() { + return this.alias; + } - public void setAlias(String alias) { - this.alias = alias; - } + public void setAlias(String alias) { + this.alias = alias; + } - public CreditBureau getCreditBureau() { - return this.creditbureau; - } + public CreditBureau getCreditBureau() { + return this.creditbureau; + } - public void setCreditBureau(CreditBureau creditBureau) { - this.creditbureau = creditBureau; - } + public void setCreditBureau(CreditBureau creditBureau) { + this.creditbureau = creditBureau; + } - public boolean isActive() { - return this.is_active; - } + public boolean isActive() { + return this.is_active; + } - public void setIsActive(boolean is_active) { - this.is_active = is_active; - } + public void setIsActive(boolean is_active) { + this.is_active = is_active; + } - public List getCreditBureauLoanProductMapping() { - return this.creditBureauLoanProductMapping; - } + public List getCreditBureauLoanProductMapping() { + return this.creditBureauLoanProductMapping; + } - public void setCreditBureauLoanProductMapping(List creditBureauLoanProductMapping) { - this.creditBureauLoanProductMapping = creditBureauLoanProductMapping; - } + public void setCreditBureauLoanProductMapping(List creditBureauLoanProductMapping) { + this.creditBureauLoanProductMapping = creditBureauLoanProductMapping; + } - + } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/OrganisationCreditBureauRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/OrganisationCreditBureauRepository.java index b0b05c93b..881d55239 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/OrganisationCreditBureauRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/OrganisationCreditBureauRepository.java @@ -22,6 +22,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface OrganisationCreditBureauRepository - extends JpaRepository, JpaSpecificationExecutor { + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/AddOrganisationCreditBureauCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/AddOrganisationCreditBureauCommandHandler.java index f9b0851e9..dbd953e1d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/AddOrganisationCreditBureauCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/AddOrganisationCreditBureauCommandHandler.java @@ -30,16 +30,16 @@ import org.springframework.stereotype.Service; @CommandType(entity = "ORGANISATIONCREDITBUREAU", action = "CREATE") public class AddOrganisationCreditBureauCommandHandler implements NewCommandSourceHandler { - private final OrganisationCreditBureauWritePlatflormService writePlatformService; + private final OrganisationCreditBureauWritePlatflormService writePlatformService; - @Autowired - public AddOrganisationCreditBureauCommandHandler(final OrganisationCreditBureauWritePlatflormService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public AddOrganisationCreditBureauCommandHandler(final OrganisationCreditBureauWritePlatflormService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Override - public CommandProcessingResult processCommand(JsonCommand command) { + @Override + public CommandProcessingResult processCommand(JsonCommand command) { - return this.writePlatformService.addOrganisationCreditBureau(command.getOrganisationCreditBureauId(), command); - } + return this.writePlatformService.addOrganisationCreditBureau(command.getOrganisationCreditBureauId(), command); + } } 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 2b68b3ed7..a96e62f8d 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 @@ -30,17 +30,17 @@ import org.springframework.stereotype.Service; @CommandType(entity = "CREDITBUREAU_LOANPRODUCT_MAPPING", action = "CREATE") public class CreateCreditBureauLoanProductMappingCommandHandler implements NewCommandSourceHandler { - private final CreditBureauLoanProductMappingWritePlatformService writePlatformService; + private final CreditBureauLoanProductMappingWritePlatformService writePlatformService; - @Autowired - public CreateCreditBureauLoanProductMappingCommandHandler(final CreditBureauLoanProductMappingWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public CreateCreditBureauLoanProductMappingCommandHandler(final CreditBureauLoanProductMappingWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Override - public CommandProcessingResult processCommand(JsonCommand command) { + @Override + public CommandProcessingResult processCommand(JsonCommand command) { - return this.writePlatformService.addCreditBureauLoanProductMapping(command.getCreditBureauId(), command); - } + return this.writePlatformService.addCreditBureauLoanProductMapping(command.getCreditBureauId(), command); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/UpdateCreditBureauCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/UpdateCreditBureauCommandHandler.java index 0af556053..acefb839c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/UpdateCreditBureauCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/UpdateCreditBureauCommandHandler.java @@ -31,18 +31,18 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "ORGANISATIONCREDITBUREAU", action = "UPDATE") public class UpdateCreditBureauCommandHandler implements NewCommandSourceHandler { - private final OrganisationCreditBureauWritePlatflormService writePlatformService; + private final OrganisationCreditBureauWritePlatflormService writePlatformService; - @Autowired - public UpdateCreditBureauCommandHandler(final OrganisationCreditBureauWritePlatflormService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public UpdateCreditBureauCommandHandler(final OrganisationCreditBureauWritePlatflormService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.updateCreditBureau(command); - } + return this.writePlatformService.updateCreditBureau(command); + } } 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 aa3d8450c..a7ed740e1 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 @@ -31,19 +31,19 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "CREDITBUREAU_LOANPRODUCT_MAPPING", action = "UPDATE") public class UpdateCreditBureauLoanProductMappingCommandHandler implements NewCommandSourceHandler { - private final CreditBureauLoanProductMappingWritePlatformService writePlatformService; + private final CreditBureauLoanProductMappingWritePlatformService writePlatformService; - @Autowired - public UpdateCreditBureauLoanProductMappingCommandHandler(final CreditBureauLoanProductMappingWritePlatformService writePlatformService) { + @Autowired + public UpdateCreditBureauLoanProductMappingCommandHandler(final CreditBureauLoanProductMappingWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.updateCreditBureauLoanProductMapping(command); - } + return this.writePlatformService.updateCreditBureauLoanProductMapping(command); + } } 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 895ea7757..6645c4978 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 @@ -42,85 +42,85 @@ import com.google.gson.reflect.TypeToken; @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; + private final FromJsonHelper fromApiJsonHelper; - @Autowired - public CreditBureauCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } + @Autowired + public CreditBureauCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } - public void validateForCreate(final String json, final Long creditBureauId) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public void validateForCreate(final String json, final Long creditBureauId) { + 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("CreditBureau"); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource("CreditBureau"); - final JsonElement element = this.fromApiJsonHelper.parse(json); - - baseDataValidator.reset().value(creditBureauId).notBlank().integerGreaterThanZero(); + final JsonElement element = this.fromApiJsonHelper.parse(json); + + baseDataValidator.reset().value(creditBureauId).notBlank().integerGreaterThanZero(); - final String alias = this.fromApiJsonHelper.extractStringNamed("alias", element); - baseDataValidator.reset().parameter("alias").value(alias).notNull().notBlank().notExceedingLengthOf(100); + final String alias = this.fromApiJsonHelper.extractStringNamed("alias", element); + baseDataValidator.reset().parameter("alias").value(alias).notNull().notBlank().notExceedingLengthOf(100); - final String is_activeParameter = "is_active"; - if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) { - final boolean is_active = this.fromApiJsonHelper.extractBooleanNamed("is_active", element); - baseDataValidator.reset().parameter("is_active").value(is_active).notNull().notBlank().trueOrFalseRequired(is_active); - } + final String is_activeParameter = "is_active"; + if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) { + final boolean is_active = this.fromApiJsonHelper.extractBooleanNamed("is_active", element); + baseDataValidator.reset().parameter("is_active").value(is_active).notNull().notBlank().trueOrFalseRequired(is_active); + } - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - - - public void validateForUpdate(final String json) - { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - 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"); + throwExceptionIfValidationWarningsExist(dataValidationErrors); + } + + + + public void validateForUpdate(final String json) + { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + 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 JsonElement element = this.fromApiJsonHelper.parse(json); - - - final String creditBureauIdParameter = "creditBureauId"; - if (this.fromApiJsonHelper.parameterExists(creditBureauIdParameter, element)) { - final Long creditBureauId = this.fromApiJsonHelper.extractLongNamed("creditBureauId", element); - baseDataValidator.reset().parameter("creditBureauId").value(creditBureauId).notNull().notBlank().longGreaterThanZero(); - } - - final String is_activeParameter = "is_active"; - if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) { - final boolean is_active = this.fromApiJsonHelper.extractBooleanNamed("is_active", element); - baseDataValidator.reset().parameter("is_active").value(is_active).notNull().notBlank().trueOrFalseRequired(is_active); - } - - - throwExceptionIfValidationWarningsExist(dataValidationErrors); + 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); + baseDataValidator.reset().parameter("creditBureauId").value(creditBureauId).notNull().notBlank().longGreaterThanZero(); + } + + final String is_activeParameter = "is_active"; + if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) { + final boolean is_active = this.fromApiJsonHelper.extractBooleanNamed("is_active", element); + 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); - } - } + private void throwExceptionIfValidationWarningsExist(final List 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/creditbureau/serialization/CreditBureauLoanProductCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/serialization/CreditBureauLoanProductCommandFromApiJsonDeserializer.java index 76e7fa5a0..e256c0a60 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 @@ -40,134 +40,134 @@ import com.google.gson.reflect.TypeToken; @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; + private final FromJsonHelper fromApiJsonHelper; - @Autowired - public CreditBureauLoanProductCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } + @Autowired + public CreditBureauLoanProductCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } - public void validateForCreate(final String json, final Long cb_id) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public void validateForCreate(final String json, final Long cb_id) { + 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("CREDITBUREAU_LOANPRODUCT_MAPPING"); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource("CREDITBUREAU_LOANPRODUCT_MAPPING"); - final JsonElement element = this.fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - baseDataValidator.reset().value(cb_id).notBlank().integerGreaterThanZero(); + baseDataValidator.reset().value(cb_id).notBlank().integerGreaterThanZero(); - final long loanProductId = this.fromApiJsonHelper.extractLongNamed("loanProductId", element); - baseDataValidator.reset().parameter("loanProductId").value(loanProductId).notBlank() - .integerGreaterThanZero(); - - - 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)); - } - - - if( this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element)!=null) - { - final boolean skipCreditcheckInFailure = this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element); - 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)); - } - + final long loanProductId = this.fromApiJsonHelper.extractLongNamed("loanProductId", element); + baseDataValidator.reset().parameter("loanProductId").value(loanProductId).notBlank() + .integerGreaterThanZero(); + + + 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)); + } + + + if( this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element)!=null) + { + final boolean skipCreditcheckInFailure = this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element); + 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)); + } + - 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(); - } + 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(); + } - - if(this.fromApiJsonHelper.extractBooleanNamed("is_active", element)!=null) - { - Boolean is_active = this.fromApiJsonHelper.extractBooleanNamed("is_active", element); - if (is_active == null) { - is_active = false; - } else { + + if(this.fromApiJsonHelper.extractBooleanNamed("is_active", element)!=null) + { + Boolean is_active = this.fromApiJsonHelper.extractBooleanNamed("is_active", element); + if (is_active == null) { + is_active = false; + } else { - baseDataValidator.reset().parameter("is_active").value(is_active).notBlank().trueOrFalseRequired(is_active); - } - } + baseDataValidator.reset().parameter("is_active").value(is_active).notBlank().trueOrFalseRequired(is_active); + } + } - + - throwExceptionIfValidationWarningsExist(dataValidationErrors); + 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(); - 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("CREDITBUREAU_LOANPRODUCT_MAPPING"); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource("CREDITBUREAU_LOANPRODUCT_MAPPING"); - 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 String is_activeParameter = "is_active"; - if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) { - final boolean is_active = this.fromApiJsonHelper.extractBooleanNamed("is_active", element); - baseDataValidator.reset().parameter("is_active").value(is_active).notNull().notBlank().trueOrFalseRequired(is_active); - } - - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - - } + 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 String is_activeParameter = "is_active"; + if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) { + final boolean is_active = this.fromApiJsonHelper.extractBooleanNamed("is_active", element); + 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); - } - } + private void throwExceptionIfValidationWarningsExist(final List 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/creditbureau/service/CreditBureauLoanProductMappingReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingReadPlatformService.java index d5a74f26f..ad5465322 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingReadPlatformService.java @@ -24,10 +24,10 @@ import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauLoanProd public interface CreditBureauLoanProductMappingReadPlatformService { - Collection readCreditBureauLoanProductMapping(); + Collection readCreditBureauLoanProductMapping(); - Collection fetchLoanProducts(); + Collection fetchLoanProducts(); - CreditBureauLoanProductMappingData readMappingByLoanId(long loanProductId); + CreditBureauLoanProductMappingData readMappingByLoanId(long loanProductId); } 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 b5f7145e2..072e46fed 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 @@ -32,91 +32,91 @@ import org.springframework.stereotype.Service; @Service public class CreditBureauLoanProductMappingReadPlatformServiceImpl implements CreditBureauLoanProductMappingReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public CreditBureauLoanProductMappingReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + public CreditBureauLoanProductMappingReadPlatformServiceImpl(final PlatformSecurityContext context, + final RoutingDataSource dataSource) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); + } - private static final class CreditBureauLoanProductMapper implements RowMapper { + private static final class CreditBureauLoanProductMapper implements RowMapper { - public String schema() { - return "cblp.id as mappingId, cblp.organisation_creditbureau_id as orgcbId," - + "orgcb.alias as alias,concat( cb.product,' - ' ,cb.name,' - ',cb.country) as creditbureau," - + "cblp.loan_product_id as lpId,lp.name as loan_product_name,cblp.is_creditcheck_mandatory as crCheck,cblp.skip_creditcheck_in_failure as skipcheck," - + "cblp.stale_period as staleperiod,cblp.is_active as is_active from" - + " m_creditbureau_loanproduct_mapping cblp, m_organisation_creditbureau orgcb,m_product_loan lp,m_creditbureau cb" - + " where cblp.organisation_creditbureau_id=orgcb.id and cblp.loan_product_id=lp.id and orgcb.creditbureau_id=cb.id"; - } + public String schema() { + return "cblp.id as mappingId, cblp.organisation_creditbureau_id as orgcbId," + + "orgcb.alias as alias,concat( cb.product,' - ' ,cb.name,' - ',cb.country) as creditbureau," + + "cblp.loan_product_id as lpId,lp.name as loan_product_name,cblp.is_creditcheck_mandatory as crCheck,cblp.skip_creditcheck_in_failure as skipcheck," + + "cblp.stale_period as staleperiod,cblp.is_active as is_active from" + + " m_creditbureau_loanproduct_mapping cblp, m_organisation_creditbureau orgcb,m_product_loan lp,m_creditbureau cb" + + " where cblp.organisation_creditbureau_id=orgcb.id and cblp.loan_product_id=lp.id and orgcb.creditbureau_id=cb.id"; + } - @Override - public CreditBureauLoanProductMappingData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { - final Long mapping_id = rs.getLong("mappingId"); - final Long orgcbID = rs.getLong("orgcbId"); - final String alias = rs.getString("alias"); - final String credit_bureau_name = rs.getString("creditbureau"); - final String loan_product_name = rs.getString("loan_product_name"); - final Long lpId = rs.getLong("lpId"); - final boolean is_creditcheck_mandatory = rs.getBoolean("crCheck"); - final boolean skip_credit_check_in_failure = rs.getBoolean("skipcheck"); - final int stale_period = rs.getInt("staleperiod"); - final boolean is_active = rs.getBoolean("is_active"); + @Override + public CreditBureauLoanProductMappingData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) + throws SQLException { + final Long mapping_id = rs.getLong("mappingId"); + final Long orgcbID = rs.getLong("orgcbId"); + final String alias = rs.getString("alias"); + final String credit_bureau_name = rs.getString("creditbureau"); + final String loan_product_name = rs.getString("loan_product_name"); + final Long lpId = rs.getLong("lpId"); + final boolean is_creditcheck_mandatory = rs.getBoolean("crCheck"); + final boolean skip_credit_check_in_failure = rs.getBoolean("skipcheck"); + 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); + } + } - private static final class LoanProductMapper implements RowMapper { + private static final class LoanProductMapper implements RowMapper { - public String schema() { - return "lp.name as loan_product_name,lp.id as loanid from m_product_loan lp"; - } + public String schema() { + return "lp.name as loan_product_name,lp.id as loanid from m_product_loan lp"; + } - @Override - public CreditBureauLoanProductMappingData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { - final Long loanid = rs.getLong("loanid"); + @Override + public CreditBureauLoanProductMappingData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) + throws SQLException { + final Long loanid = rs.getLong("loanid"); - final String loan_product_name = rs.getString("loan_product_name"); + final String loan_product_name = rs.getString("loan_product_name"); - return CreditBureauLoanProductMappingData.instance1(loan_product_name, loanid); - } - } + return CreditBureauLoanProductMappingData.instance1(loan_product_name, loanid); + } + } - @Override - public Collection readCreditBureauLoanProductMapping() { - this.context.authenticatedUser(); + @Override + public Collection readCreditBureauLoanProductMapping() { + this.context.authenticatedUser(); - final CreditBureauLoanProductMapper rm = new CreditBureauLoanProductMapper(); - final String sql = "select " + rm.schema() + " order by cblp.id"; + final CreditBureauLoanProductMapper rm = new CreditBureauLoanProductMapper(); + final String sql = "select " + rm.schema() + " order by cblp.id"; - return this.jdbcTemplate.query(sql, rm, new Object[] {}); - } + return this.jdbcTemplate.query(sql, rm, new Object[] {}); + } - @Override - public CreditBureauLoanProductMappingData readMappingByLoanId(long loanProductId) { - this.context.authenticatedUser(); + @Override + public CreditBureauLoanProductMappingData readMappingByLoanId(long loanProductId) { + this.context.authenticatedUser(); - final CreditBureauLoanProductMapper rm = new CreditBureauLoanProductMapper(); - final String sql = "select " + rm.schema() + " and cblp.loan_product_id=?"; + final CreditBureauLoanProductMapper rm = new CreditBureauLoanProductMapper(); + final String sql = "select " + rm.schema() + " and cblp.loan_product_id=?"; - return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { loanProductId }); - } + return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { loanProductId }); + } - @Override - public Collection fetchLoanProducts() { - this.context.authenticatedUser(); + @Override + public Collection fetchLoanProducts() { + this.context.authenticatedUser(); - final LoanProductMapper rm = new LoanProductMapper(); - final String sql = "select " + rm.schema() + " order by lp.id"; + final LoanProductMapper rm = new LoanProductMapper(); + final String sql = "select " + rm.schema() + " order by lp.id"; - return this.jdbcTemplate.query(sql, rm, new Object[] {}); - } + return this.jdbcTemplate.query(sql, rm, new Object[] {}); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingWritePlatformService.java index 41e29770f..458dc17c4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingWritePlatformService.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface CreditBureauLoanProductMappingWritePlatformService { - CommandProcessingResult addCreditBureauLoanProductMapping(Long creditBureauId, JsonCommand command); + CommandProcessingResult addCreditBureauLoanProductMapping(Long creditBureauId, JsonCommand command); - CommandProcessingResult updateCreditBureauLoanProductMapping(JsonCommand command); + CommandProcessingResult updateCreditBureauLoanProductMapping(JsonCommand command); } 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 2440699ba..adca299ff 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 @@ -36,63 +36,63 @@ import org.springframework.transaction.annotation.Transactional; @Service public class CreditBureauLoanProductMappingWritePlatformServiceImpl implements CreditBureauLoanProductMappingWritePlatformService { - private final PlatformSecurityContext context; + private final PlatformSecurityContext context; - private final CreditBureauLoanProductMappingRepository creditBureauLoanProductMappingRepository; + private final CreditBureauLoanProductMappingRepository creditBureauLoanProductMappingRepository; - private final OrganisationCreditBureauRepository organisationCreditBureauRepository; + private final OrganisationCreditBureauRepository organisationCreditBureauRepository; - private final LoanProductRepository loanProductRepository; + private final LoanProductRepository loanProductRepository; - private final CreditBureauLoanProductCommandFromApiJsonDeserializer fromApiJsonDeserializer; + private final CreditBureauLoanProductCommandFromApiJsonDeserializer fromApiJsonDeserializer; - @Autowired - public CreditBureauLoanProductMappingWritePlatformServiceImpl(final PlatformSecurityContext context, - final CreditBureauLoanProductMappingRepository creditbureauLoanProductMappingRepository, - final OrganisationCreditBureauRepository organisationCreditBureauRepository, LoanProductRepository loanProductRepository, - final CreditBureauLoanProductCommandFromApiJsonDeserializer fromApiJsonDeserializer) { - this.context = context; - this.creditBureauLoanProductMappingRepository = creditbureauLoanProductMappingRepository; - this.organisationCreditBureauRepository = organisationCreditBureauRepository; - this.loanProductRepository = loanProductRepository; - this.fromApiJsonDeserializer = fromApiJsonDeserializer; + @Autowired + public CreditBureauLoanProductMappingWritePlatformServiceImpl(final PlatformSecurityContext context, + final CreditBureauLoanProductMappingRepository creditbureauLoanProductMappingRepository, + final OrganisationCreditBureauRepository organisationCreditBureauRepository, LoanProductRepository loanProductRepository, + final CreditBureauLoanProductCommandFromApiJsonDeserializer fromApiJsonDeserializer) { + this.context = context; + this.creditBureauLoanProductMappingRepository = creditbureauLoanProductMappingRepository; + this.organisationCreditBureauRepository = organisationCreditBureauRepository; + this.loanProductRepository = loanProductRepository; + this.fromApiJsonDeserializer = fromApiJsonDeserializer; - } + } - @Transactional - @Override - public CommandProcessingResult addCreditBureauLoanProductMapping(Long creditBureau_id, JsonCommand command) { - this.context.authenticatedUser(); - - this.fromApiJsonDeserializer.validateForCreate(command.json(), creditBureau_id); + @Transactional + @Override + public CommandProcessingResult addCreditBureauLoanProductMapping(Long creditBureau_id, JsonCommand command) { + this.context.authenticatedUser(); + + this.fromApiJsonDeserializer.validateForCreate(command.json(), creditBureau_id); - final long lpid = command.longValueOfParameterNamed("loanProductId"); + final long lpid = command.longValueOfParameterNamed("loanProductId"); - final OrganisationCreditBureau orgcb = this.organisationCreditBureauRepository.getOne(creditBureau_id); + final OrganisationCreditBureau orgcb = this.organisationCreditBureauRepository.getOne(creditBureau_id); - final LoanProduct lp = this.loanProductRepository.getOne(lpid); + final LoanProduct lp = this.loanProductRepository.getOne(lpid); - final CreditBureauLoanProductMapping cb_lp = CreditBureauLoanProductMapping.fromJson(command, orgcb, lp); + final CreditBureauLoanProductMapping cb_lp = CreditBureauLoanProductMapping.fromJson(command, orgcb, lp); - this.creditBureauLoanProductMappingRepository.save(cb_lp); + 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(); - } + } - @Override - public CommandProcessingResult updateCreditBureauLoanProductMapping(JsonCommand command) { - - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForUpdate(command.json()); + @Override + public CommandProcessingResult updateCreditBureauLoanProductMapping(JsonCommand command) { + + this.context.authenticatedUser(); + this.fromApiJsonDeserializer.validateForUpdate(command.json()); - final Long mappingid = command.longValueOfParameterNamed("creditbureauLoanProductMappingId"); - final boolean is_active = command.booleanPrimitiveValueOfParameterNamed("is_active"); - 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(); - } + final Long mappingid = command.longValueOfParameterNamed("creditbureauLoanProductMappingId"); + final boolean is_active = command.booleanPrimitiveValueOfParameterNamed("is_active"); + 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(); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauMasterReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauMasterReadPlatformService.java index ef295a83d..9545bdf67 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauMasterReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauMasterReadPlatformService.java @@ -24,8 +24,8 @@ import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauMasterDa public interface CreditBureauMasterReadPlatformService { - Collection retrieveCreditBureauByCountry(String country); + Collection retrieveCreditBureauByCountry(String country); - Collection retrieveCreditBureauByCountry(); + Collection retrieveCreditBureauByCountry(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadConfigurationService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadConfigurationService.java index 5cdd959dc..45c5a86fc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadConfigurationService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadConfigurationService.java @@ -26,8 +26,8 @@ import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauConfigur public interface CreditBureauReadConfigurationService { - Collection readConfigurationByOrganisationCreditBureauId(long id); + Collection readConfigurationByOrganisationCreditBureauId(long id); - Map retrieveConfigMap(long id); + Map retrieveConfigMap(long id); } 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 132954488..879ce28df 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 @@ -36,67 +36,67 @@ import org.springframework.stereotype.Service; @Service public class CreditBureauReadConfigurationServiceImpl implements CreditBureauReadConfigurationService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public CreditBureauReadConfigurationServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + 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() { + private static final class CbConfigMapper implements RowMapper { + public String schema() { - return "cbconfig.id as configId,cbconfig.configkey,cbconfig.value as configValue," - + "cbconfig.organisation_creditbureau_id as orgCBId,cbconfig.description as description from m_creditbureau_configuration cbconfig "; + return "cbconfig.id as configId,cbconfig.configkey,cbconfig.value as configValue," + + "cbconfig.organisation_creditbureau_id as orgCBId,cbconfig.description as description from m_creditbureau_configuration cbconfig "; - } + } - @Override - 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"); - final long orgCBId = rs.getLong("orgCBId"); - final String desc = rs.getString("description"); + @Override + 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"); + final long orgCBId = rs.getLong("orgCBId"); + final String desc = rs.getString("description"); - return CreditBureauConfigurationData.instance(configId, configkey, configValue, orgCBId, desc); + return CreditBureauConfigurationData.instance(configId, configkey, configValue, orgCBId, desc); - } - } + } + } - @Override - public Collection readConfigurationByOrganisationCreditBureauId(long id) { + @Override + public Collection readConfigurationByOrganisationCreditBureauId(long id) { - this.context.authenticatedUser(); + this.context.authenticatedUser(); - final CbConfigMapper rm = new CbConfigMapper(); - final String sql = "select " + rm.schema() + " where cbconfig.organisation_creditbureau_id=?"; + final CbConfigMapper rm = new CbConfigMapper(); + final String sql = "select " + rm.schema() + " where cbconfig.organisation_creditbureau_id=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { id }); + return this.jdbcTemplate.query(sql, rm, new Object[] { id }); - } + } - @Override - public Map retrieveConfigMap(long id) { - this.context.authenticatedUser(); + @Override + public Map retrieveConfigMap(long id) { + this.context.authenticatedUser(); - final CbConfigMapper rm = new CbConfigMapper(); - final String sql = "select " + rm.schema() + " where cbconfig.organisation_creditbureau_id= ?"; + final CbConfigMapper rm = new CbConfigMapper(); + final String sql = "select " + rm.schema() + " where cbconfig.organisation_creditbureau_id= ?"; - List config = (List) this.jdbcTemplate.query(sql, - rm, new Object[] {id}); - Map configuration = new HashMap(); - for (CreditBureauConfigurationData data : config) { - configuration.put(data.getConfigurationKey(), data.getValue()); + List config = (List) this.jdbcTemplate.query(sql, + rm, new Object[] {id}); + Map configuration = new HashMap(); + for (CreditBureauConfigurationData data : config) { + configuration.put(data.getConfigurationKey(), data.getValue()); - } + } - return configuration; + return configuration; - } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadPlatformService.java index ebc64f0de..4dd156e39 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadPlatformService.java @@ -24,6 +24,6 @@ import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauData; public interface CreditBureauReadPlatformService { - Collection retrieveCreditBureau(); + Collection retrieveCreditBureau(); } 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 ea90f8017..493eff0bb 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 @@ -33,45 +33,45 @@ import org.springframework.stereotype.Service; @Service public class CreditBureauReadPlatformServiceImpl implements CreditBureauReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public CreditBureauReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + 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"; - } + 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 { - final long id = rs.getLong("creditBureauID"); - final String name = rs.getString("creditBureauName"); - final String product = rs.getString("creditBureauProduct"); - final String country = rs.getString("country"); - final String cbSummary = rs.getString("cbSummary"); - final long implementationKey = rs.getLong("implementationKey"); + @Override + 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"); + final String country = rs.getString("country"); + final String cbSummary = rs.getString("cbSummary"); + final long implementationKey = rs.getLong("implementationKey"); - return CreditBureauData.instance(id, name, product, country, cbSummary, implementationKey); + return CreditBureauData.instance(id, name, product, country, cbSummary, implementationKey); - } - } + } + } - @Override - public Collection retrieveCreditBureau() { - this.context.authenticatedUser(); + @Override + public Collection retrieveCreditBureau() { + this.context.authenticatedUser(); - final CBMapper rm = new CBMapper(); - final String sql = "select " + rm.schema() + " order by id"; + final CBMapper rm = new CBMapper(); + final String sql = "select " + rm.schema() + " order by id"; - return this.jdbcTemplate.query(sql, rm, new Object[] {}); - } + return this.jdbcTemplate.query(sql, rm, new Object[] {}); + } } 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 bb74b08a2..aa5409abd 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 @@ -23,7 +23,7 @@ import java.util.Collection; import org.apache.fineract.infrastructure.creditbureau.data.OrganisationCreditBureauData; public interface OrganisationCreditBureauReadPlatformService { - Collection retrieveOrgCreditBureau(); + Collection retrieveOrgCreditBureau(); - OrganisationCreditBureauData retrieveOrgCreditBureauById(long orgCbId); + 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 f71166326..c145fc5d7 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 @@ -33,61 +33,61 @@ import org.springframework.stereotype.Service; @Service public class OrganisationCreditBureauReadPlatformServiceImpl implements OrganisationCreditBureauReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public OrganisationCreditBureauReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + 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," - + "ocb.creditbureau_id as cbid,ocb.is_active as is_active" - + " from m_organisation_creditbureau ocb,m_creditbureau cb where ocb.creditbureau_id=cb.id"; + 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," + + "ocb.creditbureau_id as cbid,ocb.is_active as is_active" + + " from m_organisation_creditbureau ocb,m_creditbureau cb where ocb.creditbureau_id=cb.id"; - } + } - @Override - 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"); - final String creditbureauProduct = rs.getString("creditbureauProduct"); - final String creditbureauCountry = rs.getString("creditbureauCountry"); - final String CreditBureauSummary = rs.getString("CreditBureauSummary"); - final long cbid = rs.getLong("cbid"); - final boolean is_active = rs.getBoolean("is_active"); + @Override + 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"); + final String creditbureauProduct = rs.getString("creditbureauProduct"); + final String creditbureauCountry = rs.getString("creditbureauCountry"); + final String CreditBureauSummary = rs.getString("CreditBureauSummary"); + 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); - } - } + } + } - @Override - public Collection retrieveOrgCreditBureau() { - this.context.authenticatedUser(); + @Override + public Collection retrieveOrgCreditBureau() { + this.context.authenticatedUser(); - final OrganisationCreditBureauMapper rm = new OrganisationCreditBureauMapper(); - final String sql = "select " + rm.schema() + " order by ocb.id"; + final OrganisationCreditBureauMapper rm = new OrganisationCreditBureauMapper(); + final String sql = "select " + rm.schema() + " order by ocb.id"; - return this.jdbcTemplate.query(sql, rm, new Object[] {}); - } + return this.jdbcTemplate.query(sql, rm, new Object[] {}); + } - @Override - public OrganisationCreditBureauData retrieveOrgCreditBureauById(long orgCbId) { - this.context.authenticatedUser(); + @Override + public OrganisationCreditBureauData retrieveOrgCreditBureauById(long orgCbId) { + this.context.authenticatedUser(); - final OrganisationCreditBureauMapper rm = new OrganisationCreditBureauMapper(); - final String sql = "select " + rm.schema() + " and ocb.id=?"; + final OrganisationCreditBureauMapper rm = new OrganisationCreditBureauMapper(); + final String sql = "select " + rm.schema() + " and ocb.id=?"; - return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { orgCbId }); - } + return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { orgCbId }); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauWritePlatflormService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauWritePlatflormService.java index 21ffc7414..de46057cf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauWritePlatflormService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauWritePlatflormService.java @@ -23,7 +23,7 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface OrganisationCreditBureauWritePlatflormService { - CommandProcessingResult addOrganisationCreditBureau(Long ocb_id, JsonCommand command); + CommandProcessingResult addOrganisationCreditBureau(Long ocb_id, JsonCommand command); - CommandProcessingResult updateCreditBureau(JsonCommand command); + CommandProcessingResult updateCreditBureau(JsonCommand command); } 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 f6bceb7a3..d0c5ed0c6 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 @@ -33,61 +33,61 @@ import org.springframework.transaction.annotation.Transactional; @Service public class OrganisationCreditBureauWritePlatflormServiceImpl - implements OrganisationCreditBureauWritePlatflormService { + implements OrganisationCreditBureauWritePlatflormService { - private final PlatformSecurityContext context; + private final PlatformSecurityContext context; - private final OrganisationCreditBureauRepository organisationCreditBureauRepository; + private final OrganisationCreditBureauRepository organisationCreditBureauRepository; - private final CreditBureauRepository creditBureauRepository; + private final CreditBureauRepository creditBureauRepository; - private final CreditBureauCommandFromApiJsonDeserializer fromApiJsonDeserializer; + private final CreditBureauCommandFromApiJsonDeserializer fromApiJsonDeserializer; - @Autowired - public OrganisationCreditBureauWritePlatflormServiceImpl(final PlatformSecurityContext context, - final OrganisationCreditBureauRepository organisationCreditBureauRepository, final CreditBureauRepository creditBureauRepository, - final CreditBureauCommandFromApiJsonDeserializer fromApiJsonDeserializer) { - this.context = context; - this.organisationCreditBureauRepository = organisationCreditBureauRepository; - this.creditBureauRepository = creditBureauRepository; - this.fromApiJsonDeserializer = fromApiJsonDeserializer; + @Autowired + public OrganisationCreditBureauWritePlatflormServiceImpl(final PlatformSecurityContext context, + final OrganisationCreditBureauRepository organisationCreditBureauRepository, final CreditBureauRepository creditBureauRepository, + final CreditBureauCommandFromApiJsonDeserializer fromApiJsonDeserializer) { + this.context = context; + this.organisationCreditBureauRepository = organisationCreditBureauRepository; + this.creditBureauRepository = creditBureauRepository; + this.fromApiJsonDeserializer = fromApiJsonDeserializer; - } + } - @Override - public CommandProcessingResult addOrganisationCreditBureau(Long creditBureauId, JsonCommand command) { - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForCreate(command.json(), creditBureauId); + @Override + public CommandProcessingResult addOrganisationCreditBureau(Long creditBureauId, JsonCommand command) { + this.context.authenticatedUser(); + this.fromApiJsonDeserializer.validateForCreate(command.json(), creditBureauId); - final CreditBureau creditBureau = this.creditBureauRepository.getOne(creditBureauId); + final CreditBureau creditBureau = this.creditBureauRepository.getOne(creditBureauId); - final OrganisationCreditBureau organisationCreditBureau = OrganisationCreditBureau.fromJson(command, creditBureau); + final OrganisationCreditBureau organisationCreditBureau = OrganisationCreditBureau.fromJson(command, creditBureau); - this.organisationCreditBureauRepository.save(organisationCreditBureau); + this.organisationCreditBureauRepository.save(organisationCreditBureau); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(organisationCreditBureau.getId()) - .build(); - } + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(organisationCreditBureau.getId()) + .build(); + } - @Transactional - @Override - public CommandProcessingResult updateCreditBureau(JsonCommand command) { - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForUpdate(command.json()); + @Transactional + @Override + public CommandProcessingResult updateCreditBureau(JsonCommand command) { + this.context.authenticatedUser(); + this.fromApiJsonDeserializer.validateForUpdate(command.json()); - final long creditbureauID = command.longValueOfParameterNamed("creditBureauId"); - - final boolean is_active = command.booleanPrimitiveValueOfParameterNamed("is_active"); + final long creditbureauID = command.longValueOfParameterNamed("creditBureauId"); + + final boolean is_active = command.booleanPrimitiveValueOfParameterNamed("is_active"); - final OrganisationCreditBureau orgcb = organisationCreditBureauRepository.getOne(creditbureauID); + final OrganisationCreditBureau orgcb = organisationCreditBureauRepository.getOne(creditbureauID); - orgcb.setIsActive(is_active); + orgcb.setIsActive(is_active); - organisationCreditBureauRepository.saveAndFlush(orgcb); + 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/RunreportsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/RunreportsApiResource.java index 8de37ef77..7874f260f 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 @@ -88,11 +88,11 @@ public class RunreportsApiResource { @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) { + 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) { - final MultivaluedMap queryParams = uriInfo.getQueryParameters(); + final MultivaluedMap queryParams = uriInfo.getQueryParameters(); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean exportCsv = ApiParameterHelper.exportCsv(uriInfo.getQueryParameters()); 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 f26a722fc..ab4bd81d6 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 @@ -41,8 +41,8 @@ import com.google.gson.reflect.TypeToken; public class DataTableValidator { private final FromJsonHelper fromApiJsonHelper; - private final Set REGISTER_PARAMS = new HashSet<>( - Arrays.asList(DataTableApiConstant.categoryParamName, DataTableApiConstant.localParamName)); + private final Set REGISTER_PARAMS = new HashSet<>( + Arrays.asList(DataTableApiConstant.categoryParamName, DataTableApiConstant.localParamName)); @Autowired public DataTableValidator(final FromJsonHelper fromApiJsonHelper) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableCheckStatusData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableCheckStatusData.java index 72f9a9c18..d491226b4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableCheckStatusData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableCheckStatusData.java @@ -22,12 +22,12 @@ import java.io.Serializable; public class DatatableCheckStatusData implements Serializable { - private final String name; - private final int code; + private final String name; + private final int code; - public DatatableCheckStatusData(final String name, final int code) { - this.name = name; - this.code = code; - } + public DatatableCheckStatusData(final String name, final int code) { + this.name = name; + this.code = code; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableChecksData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableChecksData.java index 361e847f2..01f08519d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableChecksData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableChecksData.java @@ -22,12 +22,12 @@ import java.io.Serializable; public class DatatableChecksData implements Serializable { - private static final long serialVersionUID = 3113568562509206452L; - private final String entity; - private final String dataTableName; + private static final long serialVersionUID = 3113568562509206452L; + private final String entity; + private final String dataTableName; - public DatatableChecksData(final String entity, final String dataTableName) { - this.entity = entity; - this.dataTableName = dataTableName; - } + public DatatableChecksData(final String entity, final String dataTableName) { + this.entity = entity; + this.dataTableName = dataTableName; + } } 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 4b559b764..794435c84 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 @@ -33,50 +33,50 @@ import java.util.Objects; */ public class EntityDataTableChecksTemplateData implements Serializable { - private final List entities; - private final List statusClient; - private final List statusGroup; - private final List statusSavings; - private final List statusLoans; - private final List datatables; - private final Collection loanProductDatas; - private final Collection savingsProductDatas; + private final List entities; + private final List statusClient; + private final List statusGroup; + private final List statusSavings; + private final List statusLoans; + private final List datatables; + private final Collection loanProductDatas; + private final Collection savingsProductDatas; - public EntityDataTableChecksTemplateData(final List entities, List statusClient, - List statusGroup, List statusSavings, - List statusLoans, List datatables, - Collection loanProductDatas, Collection savingsProductDatas) { + public EntityDataTableChecksTemplateData(final List entities, List statusClient, + List statusGroup, List statusSavings, + List statusLoans, List datatables, + Collection loanProductDatas, Collection savingsProductDatas) { - this.entities = entities; - this.statusClient = statusClient; - this.statusGroup = statusGroup; - this.statusSavings = statusSavings; - this.statusLoans = statusLoans; - this.datatables = datatables; - this.loanProductDatas = loanProductDatas; - this.savingsProductDatas = savingsProductDatas; - } + this.entities = entities; + this.statusClient = statusClient; + this.statusGroup = statusGroup; + this.statusSavings = statusSavings; + this.statusLoans = statusLoans; + this.datatables = datatables; + this.loanProductDatas = loanProductDatas; + this.savingsProductDatas = savingsProductDatas; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; + @Override + public boolean equals(Object o) { + if (this == o) return true; - if (!(o instanceof EntityDataTableChecksTemplateData)) return false; + if (!(o instanceof EntityDataTableChecksTemplateData)) return false; - EntityDataTableChecksTemplateData that = (EntityDataTableChecksTemplateData) o; + 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); - } + @Override + public int hashCode() { + 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 349670efc..b0ea4bfc5 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 @@ -25,7 +25,7 @@ import java.util.Map; public enum EntityTables { - CLIENT("m_client", + CLIENT("m_client", new Integer[]{StatusEnum.CREATE.getCode(), StatusEnum.ACTIVATE.getCode(), StatusEnum.CLOSE.getCode()}, @@ -52,57 +52,57 @@ public enum EntityTables { StatusEnum.CLOSE.getCode()}, "savings_account_id"); - private static final Map lookup = new HashMap(); - static { - for (EntityTables d : EntityTables.values()) - lookup.put(d.getName(), d); - } + private static final Map lookup = new HashMap(); + static { + for (EntityTables d : EntityTables.values()) + lookup.put(d.getName(), d); + } - private String name; + private String name; - private Integer[] codes; + private Integer[] codes; - private String foreignKeyColumnNameOnDatatable; + private String foreignKeyColumnNameOnDatatable; - private EntityTables(String name, Integer[] codes, String foreignKeyColumnNameOnDatatable) { - this.name = name; - this.codes = codes; - this.foreignKeyColumnNameOnDatatable = foreignKeyColumnNameOnDatatable; - } + private EntityTables(String name, Integer[] codes, String foreignKeyColumnNameOnDatatable) { + this.name = name; + this.codes = codes; + this.foreignKeyColumnNameOnDatatable = foreignKeyColumnNameOnDatatable; + } - public static List getEntitiesList() { + public static List getEntitiesList() { - List data = new ArrayList(); + List data = new ArrayList(); - for (EntityTables entity : EntityTables.values()) { - data.add(entity.name); - } + for (EntityTables entity : EntityTables.values()) { + data.add(entity.name); + } - return data; + return data; - } + } - public static Integer[] getStatus(String name) { - if (lookup.get(name) != null) { - return lookup.get(name).getCodes(); - } - return new Integer[]{}; - } + public static Integer[] getStatus(String name) { + if (lookup.get(name) != null) { + return lookup.get(name).getCodes(); + } + return new Integer[]{}; + } - public Integer[] getCodes() { - return this.codes; - } + public Integer[] getCodes() { + return this.codes; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getForeignKeyColumnNameOnDatatable() { - return this.foreignKeyColumnNameOnDatatable; - } + public String getForeignKeyColumnNameOnDatatable() { + return this.foreignKeyColumnNameOnDatatable; + } - public static String getForeignKeyColumnNameOnDatatable(String name) { - return lookup.get(name).foreignKeyColumnNameOnDatatable; - } + public static String getForeignKeyColumnNameOnDatatable(String name) { + return lookup.get(name).foreignKeyColumnNameOnDatatable; + } } 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 9aef5b6de..7d7a69fdd 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 @@ -30,73 +30,73 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; public class EntityDatatableChecks extends AbstractPersistableCustom { - @Column(name = "application_table_name", nullable = false) - private String entity; + @Column(name = "application_table_name", nullable = false) + private String entity; - @Column(name = "x_registered_table_name", nullable = false) - private String datatableName; + @Column(name = "x_registered_table_name", nullable = false) + private String datatableName; - @Column(name = "status_enum", nullable = false) - private Long status; + @Column(name = "status_enum", nullable = false) + private Long status; - @Column(name = "system_defined") - private boolean systemDefined = false; + @Column(name = "system_defined") + private boolean systemDefined = false; - @Column(name = "product_id", nullable = true) - private Long productId; + @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; - this.datatableName = datatableName; - this.systemDefined = systemDefined; - this.productId = productId; - } + this.entity = entity; + this.status = status; + this.datatableName = datatableName; + this.systemDefined = systemDefined; + this.productId = productId; + } - public static EntityDatatableChecks fromJson(final JsonCommand command) { + public static EntityDatatableChecks fromJson(final JsonCommand command) { - final String entity = command.stringValueOfParameterNamed("entity"); - final Long status = command.longValueOfParameterNamed("status"); - final String datatableName = command.stringValueOfParameterNamed("datatableName"); + final String entity = command.stringValueOfParameterNamed("entity"); + final Long status = command.longValueOfParameterNamed("status"); + final String datatableName = command.stringValueOfParameterNamed("datatableName"); - boolean systemDefined = false; - if (command.parameterExists("systemDefined")) { - systemDefined = command.booleanObjectValueOfParameterNamed("systemDefined"); - } else { - systemDefined = false; - } + boolean systemDefined = false; + if (command.parameterExists("systemDefined")) { + systemDefined = command.booleanObjectValueOfParameterNamed("systemDefined"); + } else { + systemDefined = false; + } - Long productId = null; - if (command.parameterExists("productId")) { - productId = command.longValueOfParameterNamed("productId"); - } + Long productId = null; + if (command.parameterExists("productId")) { + productId = command.longValueOfParameterNamed("productId"); + } - return new EntityDatatableChecks(entity, datatableName, status, systemDefined, productId); + return new EntityDatatableChecks(entity, datatableName, status, systemDefined, productId); - } + } - public String getEntity() { - return this.entity; - } + public String getEntity() { + return this.entity; + } - public Long getStatus() { - return this.status; - } + public Long getStatus() { + return this.status; + } - public String getDatatableName() { - return this.datatableName; - } + public String getDatatableName() { + return this.datatableName; + } - public boolean isSystemDefined() { - return this.systemDefined; - } + public boolean isSystemDefined() { + return this.systemDefined; + } - public Long getProductId() { - return productId; - } + public Long getProductId() { + return productId; + } } 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 0560f8fe1..413783151 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 @@ -26,29 +26,29 @@ 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); + 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); + @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); - @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); + @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); - @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); + @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); - @Query("select t from EntityDatatableChecks t WHERE t.status =:status and t.entity=:entity " + @Query("select t from EntityDatatableChecks t WHERE t.status =:status and t.entity=:entity " + " and t.datatableName = :datatableName AND t.productId IS NULL") - public List findByEntityStatusAndDatatableIdAndNoProduct(@Param("entity") String entityName, - @Param("status") Long status, @Param("datatableName") String datatableName); + public List findByEntityStatusAndDatatableIdAndNoProduct(@Param("entity") String entityName, + @Param("status") Long status, @Param("datatableName") String datatableName); } 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 95965ab79..82c5028c1 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 @@ -279,9 +279,9 @@ public final class Report extends AbstractPersistableCustom { return false; } - - public Set getReportParameterUsages() { - return this.reportParameterUsages; - } + + public Set getReportParameterUsages() { + return this.reportParameterUsages; + } } \ 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 7228e9c7a..9fab40139 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 @@ -86,8 +86,8 @@ public final class ReportParameterUsage extends AbstractPersistableCustom public void updateParameterName(final String parameterName) { this.reportParameterName = parameterName; } - - public String getReportParameterName() { - return this.reportParameterName; - } + + 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 2d47db2fb..d70071a5a 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 @@ -26,6 +26,6 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ReportParameterUsageRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour - - List findByReport(Report report); + + List findByReport(Report report); } \ 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 e941f0528..5a8decb92 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,19 @@ 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) { - super("error.msg.entityDatatableCheck.duplicate.entry", - "the entity datatable check for status: '" + status + "' and datatable name '" + datatableName + 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", - "status", "datatableName", "entity", "productId", status, datatableName, entityName, productId); - } + "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 e04153c5c..d92172557 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 @@ -25,11 +25,11 @@ 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); - } + 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); + } } \ 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 5380099cb..daaa15265 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 @@ -25,15 +25,15 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc */ public class EntityDatatableCheckNotSupportedException extends AbstractPlatformResourceNotFoundException { - 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, - entityName); - } + 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, + 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); - } + 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); + } } \ 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 0e61617a0..3a7432653 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 @@ -25,8 +25,8 @@ 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); - } + public EntityDatatableChecksNotFoundException(final Long 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/handler/CreateEntityDatatableChecksCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateEntityDatatableChecksCommandHandler.java index e7caed1af..847c71a93 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 @@ -31,18 +31,18 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "ENTITY_DATATABLE_CHECK", action = "CREATE") public class CreateEntityDatatableChecksCommandHandler implements NewCommandSourceHandler { - private final EntityDatatableChecksWritePlatformService writePlatformService; + private final EntityDatatableChecksWritePlatformService writePlatformService; - @Autowired - public CreateEntityDatatableChecksCommandHandler( - final EntityDatatableChecksWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public CreateEntityDatatableChecksCommandHandler( + final EntityDatatableChecksWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.createCheck(command); - } + 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/DeleteEntityDatatableChecksCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteEntityDatatableChecksCommandHandler.java index f4301714c..9009b476a 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 @@ -31,18 +31,18 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "ENTITY_DATATABLE_CHECK", action = "DELETE") public class DeleteEntityDatatableChecksCommandHandler implements NewCommandSourceHandler { - private final EntityDatatableChecksWritePlatformService writePlatformService; + private final EntityDatatableChecksWritePlatformService writePlatformService; - @Autowired - public DeleteEntityDatatableChecksCommandHandler( - final EntityDatatableChecksWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public DeleteEntityDatatableChecksCommandHandler( + final EntityDatatableChecksWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(JsonCommand command) { - return this.writePlatformService.deleteCheck(command.entityId()); - } + 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/service/EntityDatatableChecksDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksDataValidator.java index 81b54be78..98ced39c9 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 @@ -37,62 +37,62 @@ import com.google.gson.reflect.TypeToken; @Component public final class EntityDatatableChecksDataValidator { - /** - * The parameters supported for this command. - */ - private final Set supportedParameters = new HashSet<>( - Arrays.asList("entity", "datatableName", "status", "systemDefined", "productId")); + /** + * The parameters supported for this command. + */ + private final Set supportedParameters = new HashSet<>( + Arrays.asList("entity", "datatableName", "status", "systemDefined", "productId")); - private final FromJsonHelper fromApiJsonHelper; + private final FromJsonHelper fromApiJsonHelper; - @Autowired - public EntityDatatableChecksDataValidator(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } + @Autowired + public EntityDatatableChecksDataValidator(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } - public void validateForCreate(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public void validateForCreate(final String json) { + 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("entityDatatableChecks"); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource("entityDatatableChecks"); - final JsonElement element = this.fromApiJsonHelper.parse(json); + 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()); + final String entity = this.fromApiJsonHelper.extractStringNamed("entity", element); + baseDataValidator.reset().parameter("entity").value(entity).notBlank() + .isOneOfTheseStringValues(EntityTables.getEntitiesList()); - final Integer status = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("status", element); - final Object[] entityTablesStatuses = EntityTables.getStatus(entity); + final Integer status = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("status", element); + final Object[] entityTablesStatuses = EntityTables.getStatus(entity); - baseDataValidator.reset().parameter("status").value(status).isOneOfTheseValues(entityTablesStatuses); + baseDataValidator.reset().parameter("status").value(status).isOneOfTheseValues(entityTablesStatuses); - final String datatableName = this.fromApiJsonHelper.extractStringNamed("datatableName", element); - baseDataValidator.reset().parameter("datatableName").value(datatableName).notBlank(); + final String datatableName = this.fromApiJsonHelper.extractStringNamed("datatableName", element); + baseDataValidator.reset().parameter("datatableName").value(datatableName).notBlank(); - if (this.fromApiJsonHelper.parameterExists("systemDefined", element)) { - final String systemDefined = this.fromApiJsonHelper.extractStringNamed("systemDefined", element); - baseDataValidator.reset().parameter("systemDefined").value(systemDefined).validateForBooleanValue(); - } + if (this.fromApiJsonHelper.parameterExists("systemDefined", element)) { + final String systemDefined = this.fromApiJsonHelper.extractStringNamed("systemDefined", element); + baseDataValidator.reset().parameter("systemDefined").value(systemDefined).validateForBooleanValue(); + } - if (this.fromApiJsonHelper.parameterExists("productId", element)) { - final long productId = this.fromApiJsonHelper.extractLongNamed("productId", element); - baseDataValidator.reset().parameter("productId").value(productId).integerZeroOrGreater(); - } + if (this.fromApiJsonHelper.parameterExists("productId", element)) { + final long productId = this.fromApiJsonHelper.extractLongNamed("productId", element); + baseDataValidator.reset().parameter("productId").value(productId).integerZeroOrGreater(); + } - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } + 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); + } + } } \ 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 d20b48eab..053bea36b 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 @@ -24,11 +24,11 @@ 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); - boolean saveDatatables(Long status, String entity, Long entityId, Long productId, JsonArray data); + 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); + 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/GenericDataServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/GenericDataServiceImpl.java index e325d9a5a..861d28533 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 @@ -57,40 +57,40 @@ 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++) { + for (int i = 0; i < rsmd.getColumnCount(); i++) { - final String columnName = rsmd.getColumnName(i + 1); - final String columnType = rsmd.getColumnTypeName(i + 1); + 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 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 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) { - throw new PlatformDataIntegrityException("error.msg.report.unknown.data.integrity.issue", e.getClass().getName()); - } - } + return new GenericResultsetData(columnHeaders, resultsetDataRows); + } catch (DataAccessException e) { + throw new PlatformDataIntegrityException("error.msg.report.unknown.data.integrity.issue", e.getClass().getName()); + } + } @Override public String replace(final String str, final String pattern, final String replace) { 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 bc8b9a68b..b668636b7 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 @@ -53,6 +53,6 @@ public interface ReadReportingService { String sqlToRunForSmsEmailCampaign(String name, String type, Map queryParams); - ByteArrayOutputStream generatePentahoReportAsOutputStream(String reportName, String outputTypeParam, + ByteArrayOutputStream generatePentahoReportAsOutputStream(String reportName, String outputTypeParam, Map queryParams, Locale locale, AppUser runReportAsUser, StringBuilder errorLog); } \ No newline at end of file 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 634220613..977374d3d 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 @@ -93,10 +93,10 @@ 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() { + return new StreamingOutput() { @Override public void write(final OutputStream out) { @@ -175,8 +175,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(); logger.info("STARTING REPORT: " + name + " Type: " + type); @@ -190,8 +190,8 @@ public class ReadReportingServiceImpl implements ReadReportingService { return result; } - private String getSQLtoRun(final String name, final String type, final Map queryParams, - final boolean isSelfServiceUserReport) { + private String getSQLtoRun(final String name, final String type, final Map queryParams, + final boolean isSelfServiceUserReport) { String sql = getSql(name, type); @@ -210,14 +210,14 @@ 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); + sql = this.genericDataService.wrapSQL(sql); - return sql; + return sql; - } + } private String getSql(final String name, final String type) { @@ -249,8 +249,8 @@ public class ReadReportingServiceImpl implements ReadReportingService { } @Override - public String retrieveReportPDF(final String reportName, final String type, final Map queryParams, - final boolean isSelfServiceUserReport) { + public String retrieveReportPDF(final String reportName, final String type, final Map queryParams, + final boolean isSelfServiceUserReport) { final String fileLocation = FileSystemContentRepository.FINERACT_BASE_DIR + File.separator + ""; if (!new File(fileLocation).isDirectory()) { @@ -617,10 +617,10 @@ public class ReadReportingServiceImpl implements ReadReportingService { return null ; } - private void validateReportName(final String name) { + 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/ReadWriteNonCoreDataServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java index ed4f0b754..eb93877f9 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 @@ -141,8 +141,8 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (appTable == null) { andClause = ""; } else { - validateAppTable(appTable); - SQLInjectionValidator.validateSQLInput(appTable); + validateAppTable(appTable); + SQLInjectionValidator.validateSQLInput(appTable); andClause = " and application_table_name = '" + appTable + "'"; } @@ -173,7 +173,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ public DatatableData retrieveDatatable(final String datatable) { // PERMITTED datatables - SQLInjectionValidator.validateSQLInput(datatable); + SQLInjectionValidator.validateSQLInput(datatable); final String sql = "select application_table_name, registered_table_name" + " from x_registered_table " + " 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" @@ -228,7 +228,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ @Transactional @Override - public void registerDatatable(final JsonCommand command, final String permissionSql) { + public void registerDatatable(final JsonCommand command, final String permissionSql) { final String applicationTableName = this.getTableName(command.getUrl()); final String dataTableName = this.getDataTableName(command.getUrl()); @@ -240,7 +240,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } - @Transactional + @Transactional private void _registerDataTable(final String applicationTableName, final String dataTableName, final Integer category, final String permissionsSql) { @@ -272,17 +272,17 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (realCause.getMessage() .contains("Duplicate entry") || cause.getMessage() .contains("Duplicate entry")) { - throw new PlatformDataIntegrityException("error.msg.datatable.registered", + throw new PlatformDataIntegrityException("error.msg.datatable.registered", "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() + final Throwable cause = dve.getCause() ; + if (cause.getMessage() .contains("Duplicate entry")) { - throw new PlatformDataIntegrityException("error.msg.datatable.registered", + throw new PlatformDataIntegrityException("error.msg.datatable.registered", "Datatable `" + dataTableName + "` is already registered against an application table.", "dataTableName", dataTableName); } logAsErrorUnexpectedDataIntegrityException(dve); @@ -339,7 +339,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ @Transactional @Override public void deregisterDatatable(final String datatable) { - validateDatatableName(datatable); + validateDatatableName(datatable); final String permissionList = "('CREATE_" + datatable + "', 'CREATE_" + datatable + "_CHECKER', 'READ_" + datatable + "', 'UPDATE_" + datatable + "', 'UPDATE_" + datatable + "_CHECKER', 'DELETE_" + datatable + "', 'DELETE_" + datatable + "_CHECKER')"; @@ -627,8 +627,8 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ throwExceptionIfValidationWarningsExist(dataValidationErrors); }catch (final PersistenceException | BadSqlGrammarException ee) { - Throwable realCause = ExceptionUtils.getRootCause(ee.getCause()) ; - final List dataValidationErrors = new ArrayList<>(); + 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"); @@ -920,7 +920,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (dropColumns != null) { if(rowCount>0){ - throw new GeneralPlatformDomainRuleException("error.msg.non.empty.datatable.column.cannot.be.deleted", + throw new GeneralPlatformDomainRuleException("error.msg.non.empty.datatable.column.cannot.be.deleted", "Non-empty datatable columns can not be deleted."); } StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); @@ -945,11 +945,11 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final StringBuilder constrainBuilder = new StringBuilder(); final Map codeMappings = new HashMap<>(); for (final JsonElement column : addColumns) { - JsonObject columnAsJson = column.getAsJsonObject(); - if(rowCount>0 && columnAsJson.has("mandatory") && columnAsJson.get("mandatory").getAsBoolean()){ - throw new GeneralPlatformDomainRuleException("error.msg.non.empty.datatable.mandatory.column.cannot.be.added", + JsonObject columnAsJson = column.getAsJsonObject(); + 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."); - } + } parseDatatableColumnForAdd(columnAsJson, sqlBuilder, datatableName.toLowerCase().replaceAll("\\s", "_"), constrainBuilder, codeMappings, isConstraintApproach); } @@ -1017,8 +1017,8 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ throwExceptionIfValidationWarningsExist(dataValidationErrors); }catch (final PersistenceException ee) { - Throwable realCause = ExceptionUtils.getRootCause(ee.getCause()) ; - final List dataValidationErrors = new ArrayList<>(); + 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"); @@ -1075,7 +1075,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } private int getRowCount(final String datatableName){ - final String sql = "select count(*) from `" + datatableName + "`"; + final String sql = "select count(*) from `" + datatableName + "`"; return this.jdbcTemplate.queryForObject(sql, Integer.class); } @@ -1148,7 +1148,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ @Override public CommandProcessingResult deleteDatatableEntries(final String dataTableName, final Long appTableId) { - validateDatatableName(dataTableName); + validateDatatableName(dataTableName); if (isDatatableAttachedToEntityDatatableCheck(dataTableName)) { throw new DatatableEntryRequiredException(dataTableName, appTableId); } final String appTable = queryForApplicationTableName(dataTableName); final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); @@ -1163,7 +1163,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ @Transactional @Override public CommandProcessingResult deleteDatatableEntry(final String dataTableName, final Long appTableId, final Long datatableId) { - validateDatatableName(dataTableName); + validateDatatableName(dataTableName); if (isDatatableAttachedToEntityDatatableCheck(dataTableName)) { throw new DatatableEntryRequiredException(dataTableName, appTableId); } final String appTable = queryForApplicationTableName(dataTableName); final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); @@ -1189,8 +1189,8 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ // id only used for reading a specific entry in a one to many datatable // (when updating) if (id == null) { - String whereClause = getFKField(appTable) + " = " + appTableId; - SQLInjectionValidator.validateSQLInput(whereClause); + String whereClause = getFKField(appTable) + " = " + appTableId; + SQLInjectionValidator.validateSQLInput(whereClause); sql = sql + "select * from `" + dataTableName + "` where " + whereClause; } else { sql = sql + "select * from `" + dataTableName + "` where id = " + id; @@ -1216,8 +1216,8 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ // id only used for reading a specific entry in a one to many datatable // (when updating) if (id == null) { - String whereClause = getFKField(appTable) + " = " + appTableId; - SQLInjectionValidator.validateSQLInput(whereClause); + String whereClause = getFKField(appTable) + " = " + appTableId; + SQLInjectionValidator.validateSQLInput(whereClause); sql = sql + "select * from `" + dataTableName + "` where " + whereClause; } else { sql = sql + "select * from `" + dataTableName + "` where id = " + id; @@ -1366,7 +1366,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } private String queryForApplicationTableName(final String datatable) { - SQLInjectionValidator.validateSQLInput(datatable); + SQLInjectionValidator.validateSQLInput(datatable); final String sql = "SELECT application_table_name FROM x_registered_table where registered_table_name = '" + datatable + "'"; final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); 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 dc142c576..e30c127e7 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 @@ -106,9 +106,9 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic handleReportDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleReportDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleReportDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -147,9 +147,9 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic handleReportDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleReportDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleReportDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } 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 2ea700a04..ba365260a 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 @@ -138,12 +138,12 @@ public class S3ContentRepository implements ContentRepository { @Override public ImageData fetchImage(final ImageData imageData) { - try { - final S3Object s3object = this.s3Client.getObject(new GetObjectRequest(this.s3BucketName, imageData.location())); - imageData.updateContent(s3object.getObjectContent()); - }catch(AmazonS3Exception e) { - logger.error(e.getMessage()); - } + try { + final S3Object s3object = this.s3Client.getObject(new GetObjectRequest(this.s3BucketName, imageData.location())); + imageData.updateContent(s3object.getObjectContent()); + }catch(AmazonS3Exception e) { + logger.error(e.getMessage()); + } return imageData; } 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 330c059c3..a91ddfa33 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 @@ -20,8 +20,8 @@ package org.apache.fineract.infrastructure.entityaccess; public class FineractEntityAccessConstants { - public static final String GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS = "office-specific-products-enabled"; - public static final String GLOBAL_CONFIG_FOR_RESTRICT_PRODUCTS_TO_USER_OFFICE = "restrict-products-to-user-office"; + public static final String GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS = "office-specific-products-enabled"; + public static final String GLOBAL_CONFIG_FOR_RESTRICT_PRODUCTS_TO_USER_OFFICE = "restrict-products-to-user-office"; public static final String ENTITY_ACCESS_CODENAME = "Entity to Entity Access Types"; /*** @@ -29,10 +29,10 @@ public class FineractEntityAccessConstants { ***/ public static enum ENTITY_ACCESS_JSON_INPUT_PARAMS { ENTITY_TYPE("entityType"), - ENTITY_ID("entityId"), + ENTITY_ID("entityId"), ENTITY_ACCESS_TYPE_ID("entityAccessTypeId"), SECOND_ENTITY_TYPE("secondEntityType"), - SECOND_ENTITY_ID("secondEntityId") + SECOND_ENTITY_ID("secondEntityId") ; private final String value; 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 d7808f7fa..492827b8a 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,30 +22,30 @@ 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 - ) { - this.firstEntity = firstEntity; - this.accessType = accessType; - this.secondEntity = secondEntity; - } - - public FineractEntity getFirstEntity() { - return this.firstEntity; - } - - public FineractEntityAccessType getAccessType() { - return this.accessType; - } - - public FineractEntity getSecondEntity() { - return this.secondEntity; - } + private FineractEntity firstEntity; + private FineractEntityAccessType accessType; + private FineractEntity secondEntity; + + public FineractEntityAccessData ( + FineractEntity firstEntity, + FineractEntityAccessType accessType, + FineractEntity secondEntity + ) { + this.firstEntity = firstEntity; + this.accessType = accessType; + this.secondEntity = secondEntity; + } + + public FineractEntity getFirstEntity() { + return this.firstEntity; + } + + public FineractEntityAccessType getAccessType() { + return this.accessType; + } + + public FineractEntity getSecondEntity() { + return this.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 c55105f1c..0cecc1fc6 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 @@ -63,16 +63,16 @@ 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, - 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, + FineractEntityApiResourceConstants.toEntityType, FineractEntityApiResourceConstants.startDate, + FineractEntityApiResourceConstants.LOCALE, FineractEntityApiResourceConstants.DATE_FORMAT, + FineractEntityApiResourceConstants.endDate)); @Autowired public FineractEntityDataValidator(final FromJsonHelper fromApiJsonHelper, final OfficeRepositoryWrapper officeRepositoryWrapper, @@ -91,8 +91,8 @@ 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<>(); @@ -188,8 +188,8 @@ 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<>(); 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 37a07586b..f24b86e55 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 @@ -77,17 +77,17 @@ public class FineractEntityToEntityMappingData implements Serializable { } - public Long getRelationId() { - return relationId; - } + public Long getRelationId() { + return relationId; + } - public Long getToId() { - return toId; - } + public Long getToId() { + return toId; + } - public String getFromEntity() { - return fromEntity; - } + public String getFromEntity() { + 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 89a28408b..da2a29c70 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() { - } - - public FineractEntity(Long entityId, FineractEntityType type) { - this.entityId = entityId; - this.type = type; - } - - public Long getId () { - return this.entityId; - } - - public FineractEntityType getType () { - return this.type; - } + private Long entityId; + private FineractEntityType type; + + @SuppressWarnings("unused") + private FineractEntity() { + } + + public FineractEntity(Long entityId, FineractEntityType type) { + this.entityId = entityId; + this.type = type; + } + + public Long getId () { + return this.entityId; + } + + 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 93e87d9e6..33a158d4f 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 @@ -35,21 +35,21 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity @Table(name = "m_entity_to_entity_access") public class FineractEntityAccess extends AbstractPersistableCustom { - - @Column(name = "entity_type", length = 50) + + @Column(name = "entity_type", length = 50) private String entityType; - - @Column(name = "entity_id") + + @Column(name = "entity_id") private Long entityId; - + @ManyToOne @JoinColumn(name = "access_type_code_value_id", nullable = false) private CodeValue accessType; - @Column(name = "second_entity_type", length = 50) + @Column(name = "second_entity_type", length = 50) private String secondEntityType; - - @Column(name = "second_entity_id") + + @Column(name = "second_entity_id") private Long secondEntityId; protected FineractEntityAccess () { @@ -57,34 +57,34 @@ public class FineractEntityAccess extends AbstractPersistableCustom { } public static FineractEntityAccess createNew(final String entityType, final Long entityId, - final CodeValue accessType, - final String secondEntityType, final Long secondEntityId) { + final CodeValue accessType, + final String secondEntityType, final Long secondEntityId) { return new FineractEntityAccess(entityType, entityId, accessType, - secondEntityType, secondEntityId); + secondEntityType, 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; - this.secondEntityType = secondEntityType; - this.secondEntityId = secondEntityId; + final CodeValue accessType, + final String secondEntityType, final Long secondEntityId) { + this.entityType = entityType; + this.entityId = entityId; + this.accessType = accessType; + this.secondEntityType = secondEntityType; + this.secondEntityId = secondEntityId; } public static FineractEntityAccess fromJson(final CodeValue accessType, final JsonCommand command) { final String entityType = command.stringValueOfParameterNamed( - FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.ENTITY_TYPE.getValue()); + FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.ENTITY_TYPE.getValue()); final Long entityId = command.longValueOfParameterNamed( - FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.ENTITY_ID.getValue()); + FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.ENTITY_ID.getValue()); final String secondEntityType = command.stringValueOfParameterNamed( - FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.SECOND_ENTITY_ID.getValue()); + FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.SECOND_ENTITY_ID.getValue()); final Long secondEntityId = command.longValueOfParameterNamed( - FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.SECOND_ENTITY_ID.getValue()); + FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.SECOND_ENTITY_ID.getValue()); return new FineractEntityAccess (entityType, entityId, accessType, - secondEntityType, secondEntityId); + secondEntityType, secondEntityId); } @@ -103,7 +103,7 @@ public class FineractEntityAccess extends AbstractPersistableCustom { paramName = FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.ENTITY_ID.getValue(); if (command.isChangeInLongParameterNamed(paramName, getEntityId())) { - this.entityId = command.longValueOfParameterNamed(paramName); + this.entityId = command.longValueOfParameterNamed(paramName); actualChanges.put(paramName, this.entityId); } @@ -114,7 +114,7 @@ public class FineractEntityAccess extends AbstractPersistableCustom { paramName = FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.ENTITY_ACCESS_TYPE_ID.getValue(); if (command.isChangeInLongParameterNamed(paramName, existingAccessTypeId)) { - final Long newValue = command.longValueOfParameterNamed(paramName); + final Long newValue = command.longValueOfParameterNamed(paramName); actualChanges.put(paramName, newValue); } @@ -127,7 +127,7 @@ public class FineractEntityAccess extends AbstractPersistableCustom { paramName = FineractEntityAccessConstants.ENTITY_ACCESS_JSON_INPUT_PARAMS.SECOND_ENTITY_ID.getValue(); if (command.isChangeInLongParameterNamed(paramName, getSecondEntityId())) { - this.secondEntityId = command.longValueOfParameterNamed(paramName); + this.secondEntityId = command.longValueOfParameterNamed(paramName); actualChanges.put(paramName, this.secondEntityId); } 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 fda0d61bf..e23dd9bd6 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 @@ -19,33 +19,33 @@ package org.apache.fineract.infrastructure.entityaccess.domain; 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_CHARGES = new FineractEntityAccessType("office_access_to_fees/charges"); + + 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_CHARGES = new FineractEntityAccessType("office_access_to_fees/charges"); private FineractEntityAccessType (String str) { - this.str = str; + this.str = str; } public String toStr () { - return this.str; + return this.str; } public static FineractEntityAccessType get (String type) { - - FineractEntityAccessType retType = null; - - if (type.equals(OFFICE_ACCESS_TO_LOAN_PRODUCTS.str)) { - 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; - } - - return retType; + + FineractEntityAccessType retType = null; + + if (type.equals(OFFICE_ACCESS_TO_LOAN_PRODUCTS.str)) { + 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; + } + + return retType; } } 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 ed409b173..f148f4549 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 @@ -24,6 +24,6 @@ import org.springframework.data.repository.query.Param; public interface FineractEntityRelationRepository extends JpaRepository{ - @Query("select fea from FineractEntityRelation fea where fea.codeName= :codeName") - FineractEntityRelation findOneByCodeName(@Param("codeName") String codeName); + @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 19d64ae6a..41a2b2767 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 @@ -39,9 +39,9 @@ public class FineractEntityRelationRepositoryWrapper { } 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/FineractEntityToEntityMappingRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMappingRepository.java index b67f6e16e..c58319c01 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 @@ -27,6 +27,6 @@ public interface FineractEntityToEntityMappingRepository extends JpaRepository 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 6234a941d..79952242f 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 @@ -55,7 +55,7 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess @Autowired public FineractEntityAccessReadServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, - final FineractEntityRelationRepositoryWrapper fineractEntityRelationRepository) { + final FineractEntityRelationRepositoryWrapper fineractEntityRelationRepository) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); this.fineractEntityRelationRepository = fineractEntityRelationRepository; @@ -78,27 +78,27 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess */ @Override public String getSQLQueryInClause_WithListOfIDsForEntityAccess( FineractEntityType firstEntityType, - final Long relId, final Long fromEntityId, boolean includeAllOffices) { - Collection accesslist = retrieveEntityAccessFor(firstEntityType, relId, fromEntityId, - includeAllOffices); + final Long relId, final Long fromEntityId, boolean includeAllOffices) { + Collection accesslist = retrieveEntityAccessFor(firstEntityType, relId, fromEntityId, + includeAllOffices); String returnIdListStr = null; StringBuffer accessListCSVStrBuf = null; if ((accesslist != null) && (accesslist.size() > 0)) { - for(FineractEntityToEntityMappingData accessData: accesslist){ - if (accessData == null) { - throw new FineractEntityMappingConfigurationException(); - } - - if(accessListCSVStrBuf == null){ - accessListCSVStrBuf = new StringBuffer() ; - }else{ - accessListCSVStrBuf.append(","); - } - accessListCSVStrBuf.append(accessData.getToId()); - if(accessData.getToId() == 0){ - accessListCSVStrBuf =null; - break; - } + for(FineractEntityToEntityMappingData accessData: accesslist){ + if (accessData == null) { + throw new FineractEntityMappingConfigurationException(); + } + + if(accessListCSVStrBuf == null){ + accessListCSVStrBuf = new StringBuffer() ; + }else{ + accessListCSVStrBuf.append(","); + } + accessListCSVStrBuf.append(accessData.getToId()); + if(accessData.getToId() == 0){ + accessListCSVStrBuf =null; + break; + } } } else { @@ -116,7 +116,7 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess @Override public Collection retrieveEntityAccessFor(FineractEntityType firstEntityType, - final Long relId, final Long fromEntityId,boolean includeAllSubOffices) { + final Long relId, final Long fromEntityId,boolean includeAllSubOffices) { final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); @@ -135,18 +135,18 @@ 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; } private String getSQLForRetriveEntityAccessFor() { - StringBuffer str = new StringBuffer("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 = ? "); + StringBuffer str = new StringBuffer("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 = ? "); logger.debug(str.toString()); return str.toString(); } @@ -196,7 +196,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); } @@ -206,7 +206,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); @@ -217,7 +217,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); 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 8da407f0d..c7ece69ad 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 @@ -57,15 +57,15 @@ public class FineractEntityAccessUtil { @Autowired public FineractEntityAccessUtil ( - final PlatformSecurityContext context, - final GlobalConfigurationRepositoryWrapper globalConfigurationRepository, + final PlatformSecurityContext context, + final GlobalConfigurationRepositoryWrapper globalConfigurationRepository, final FineractEntityAccessWriteService fineractEntityAccessWriteService, final CodeValueReadPlatformService codeValueReadPlatformService, final CodeValueRepositoryWrapper codeValueRepository, final FineractEntityAccessReadService fineractEntityAccessReadService, final FineractEntityRelationRepositoryWrapper fineractEntityRelationRepositoryWrapper, final FineractEntityToEntityMappingRepository fineractEntityToEntityMappingRepository) { - this.context = context; + this.context = context; this.globalConfigurationRepository = globalConfigurationRepository; this.fineractEntityAccessWriteService = fineractEntityAccessWriteService; this.codeValueReadPlatformService = codeValueReadPlatformService; @@ -75,68 +75,68 @@ public class FineractEntityAccessUtil { this.fineractEntityToEntityMappingRepository = fineractEntityToEntityMappingRepository; } - - @Transactional - 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 + + @Transactional + 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 // i.e. this product or charge is specific for this office. - + final GlobalConfigurationProperty property = this.globalConfigurationRepository - .findOneByNameWithNotFoundDetection( - FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS); + .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 + // 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() ) { - 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); - } + 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); + } } - - } - - public String getSQLWhereClauseForProductIDsForUserOffice_ifGlobalConfigEnabled ( - FineractEntityType fineractEntityType) { - String inClause = ""; - - final GlobalConfigurationProperty property = this.globalConfigurationRepository - .findOneByNameWithNotFoundDetection( - FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS); - + + } + + public String getSQLWhereClauseForProductIDsForUserOffice_ifGlobalConfigEnabled ( + FineractEntityType fineractEntityType) { + String inClause = ""; + + final GlobalConfigurationProperty property = this.globalConfigurationRepository + .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 (fineractEntityType.equals(FineractEntityType.SAVINGS_PRODUCT)) { - 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); - } else if (fineractEntityType.equals(FineractEntityType.CHARGE)) { - inClause = fineractEntityAccessReadService. - getSQLQueryInClauseIDList_ForChargesForOffice( - this.context.authenticatedUser().getOffice().getId(), false); - } + // 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); + } else if (fineractEntityType.equals(FineractEntityType.LOAN_PRODUCT)) { + 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); + } } - return inClause; - } - + return inClause; + } + } \ 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 eb86eaf43..e008cd4e2 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 @@ -113,9 +113,9 @@ public class FineractEntityAccessWriteServiceImpl implements FineractEntityAcces handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -146,9 +146,9 @@ public class FineractEntityAccessWriteServiceImpl implements FineractEntityAcces handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } 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 fa3b9bb65..8ff0e375b 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 @@ -22,221 +22,221 @@ package org.apache.fineract.infrastructure.gcm; * Constants used on GCM service communication. */ public final class GcmConstants { - - - /** - * Title for notification - */ - public static final String title = "Hello !"; - - /** - * icon for notification. - */ - public static final String defaultIcon = "default"; + + + /** + * Title for notification + */ + public static final String title = "Hello !"; + + /** + * icon for notification. + */ + public static final String defaultIcon = "default"; - - /** - * Parameter for to field. - */ - public static final String PARAM_TO = "to"; + + /** + * Parameter for to field. + */ + public static final String PARAM_TO = "to"; - /** - * Prefix of the topic. - */ - public static final String TOPIC_PREFIX = "/topics/"; + /** + * Prefix of the topic. + */ + public static final String TOPIC_PREFIX = "/topics/"; - /** - * HTTP parameter for registration id. - */ - //public static final String PARAM_REGISTRATION_ID = "registration_id"; + /** + * HTTP parameter for registration id. + */ + //public static final String PARAM_REGISTRATION_ID = "registration_id"; - /** - * HTTP parameter for collapse key. - */ - public static final String PARAM_COLLAPSE_KEY = "collapse_key"; + /** + * HTTP parameter for collapse key. + */ + public static final String PARAM_COLLAPSE_KEY = "collapse_key"; - /** - * HTTP parameter for delaying the message delivery if the device is idle. - */ - public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle"; + /** + * HTTP parameter for delaying the message delivery if the device is idle. + */ + public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle"; - /** - * HTTP parameter for telling gcm to validate the message without actually - * sending it. - */ - public static final String PARAM_DRY_RUN = "dry_run"; + /** + * HTTP parameter for telling gcm to validate the message without actually + * sending it. + */ + public static final String PARAM_DRY_RUN = "dry_run"; - /** - * HTTP parameter for package name that can be used to restrict message - * delivery by matching against the package name used to generate the - * registration id. - */ - public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name"; + /** + * HTTP parameter for package name that can be used to restrict message + * delivery by matching against the package name used to generate the + * registration id. + */ + public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name"; - /** - * Parameter used to set the message time-to-live. - */ - public static final String PARAM_TIME_TO_LIVE = "time_to_live"; + /** + * Parameter used to set the message time-to-live. + */ + public static final String PARAM_TIME_TO_LIVE = "time_to_live"; - /** - * Parameter used to set the message priority. - */ - public static final String PARAM_PRIORITY = "priority"; + /** + * Parameter used to set the message priority. + */ + public static final String PARAM_PRIORITY = "priority"; - /** - * Parameter used to set the content available (iOS only) - */ - public static final String PARAM_CONTENT_AVAILABLE = "content_available"; + /** + * Parameter used to set the content available (iOS only) + */ + public static final String PARAM_CONTENT_AVAILABLE = "content_available"; - /** - * Value used to set message priority to normal. - */ - public static final String MESSAGE_PRIORITY_NORMAL = "normal"; + /** + * Value used to set message priority to normal. + */ + public static final String MESSAGE_PRIORITY_NORMAL = "normal"; - /** - * Value used to set message priority to high. - */ - public static final String MESSAGE_PRIORITY_HIGH = "high"; - - /** - * A particular message could not be sent because the GCM servers were not - * available. Used only on JSON requests, as in plain text requests - * unavailability is indicated by a 503 response. - */ - public static final String ERROR_UNAVAILABLE = "Unavailable"; + /** + * Value used to set message priority to high. + */ + public static final String MESSAGE_PRIORITY_HIGH = "high"; + + /** + * A particular message could not be sent because the GCM servers were not + * available. Used only on JSON requests, as in plain text requests + * unavailability is indicated by a 503 response. + */ + public static final String ERROR_UNAVAILABLE = "Unavailable"; - /** - * A particular message could not be sent because the GCM servers - * encountered an error. Used only on JSON requests, as in plain text - * requests internal errors are indicated by a 500 response. - */ - public static final String ERROR_INTERNAL_SERVER_ERROR = "InternalServerError"; + /** + * A particular message could not be sent because the GCM servers + * encountered an error. Used only on JSON requests, as in plain text + * requests internal errors are indicated by a 500 response. + */ + public static final String ERROR_INTERNAL_SERVER_ERROR = "InternalServerError"; - /** - * Token returned by GCM when the requested registration id has a canonical - * value. - */ - public static final String TOKEN_CANONICAL_REG_ID = "registration_id"; + /** + * Token returned by GCM when the requested registration id has a canonical + * value. + */ + public static final String TOKEN_CANONICAL_REG_ID = "registration_id"; - /** - * JSON-only field representing the registration ids. - */ - public static final String JSON_REGISTRATION_IDS = "registration_ids"; + /** + * JSON-only field representing the registration ids. + */ + public static final String JSON_REGISTRATION_IDS = "registration_ids"; - /** - * JSON-only field representing the to recipient. - */ - public static final String JSON_TO = "to"; + /** + * JSON-only field representing the to recipient. + */ + public static final String JSON_TO = "to"; - /** - * JSON-only field representing the payload data. - */ - public static final String JSON_PAYLOAD = "data"; + /** + * JSON-only field representing the payload data. + */ + public static final String JSON_PAYLOAD = "data"; - /** - * JSON-only field representing the notification payload. - */ - public static final String JSON_NOTIFICATION = "notification"; + /** + * JSON-only field representing the notification payload. + */ + public static final String JSON_NOTIFICATION = "notification"; - /** - * JSON-only field representing the notification title. - */ - public static final String JSON_NOTIFICATION_TITLE = "title"; + /** + * JSON-only field representing the notification title. + */ + public static final String JSON_NOTIFICATION_TITLE = "title"; - /** - * JSON-only field representing the notification body. - */ - public static final String JSON_NOTIFICATION_BODY = "body"; + /** + * JSON-only field representing the notification body. + */ + public static final String JSON_NOTIFICATION_BODY = "body"; - /** - * JSON-only field representing the notification icon. - */ - public static final String JSON_NOTIFICATION_ICON = "icon"; + /** + * JSON-only field representing the notification icon. + */ + public static final String JSON_NOTIFICATION_ICON = "icon"; - /** - * JSON-only field representing the notification sound. - */ - public static final String JSON_NOTIFICATION_SOUND = "sound"; + /** + * JSON-only field representing the notification sound. + */ + public static final String JSON_NOTIFICATION_SOUND = "sound"; - /** - * JSON-only field representing the notification badge. - */ - public static final String JSON_NOTIFICATION_BADGE = "badge"; + /** + * JSON-only field representing the notification badge. + */ + public static final String JSON_NOTIFICATION_BADGE = "badge"; - /** - * JSON-only field representing the notification tag. - */ - public static final String JSON_NOTIFICATION_TAG = "tag"; + /** + * JSON-only field representing the notification tag. + */ + public static final String JSON_NOTIFICATION_TAG = "tag"; - /** - * JSON-only field representing the notification color. - */ - public static final String JSON_NOTIFICATION_COLOR = "color"; + /** + * JSON-only field representing the notification color. + */ + public static final String JSON_NOTIFICATION_COLOR = "color"; - /** - * JSON-only field representing the notification click action. - */ - public static final String JSON_NOTIFICATION_CLICK_ACTION = "click_action"; + /** + * JSON-only field representing the notification click action. + */ + public static final String JSON_NOTIFICATION_CLICK_ACTION = "click_action"; - /** - * JSON-only field representing the notification body localization key. - */ - public static final String JSON_NOTIFICATION_BODY_LOC_KEY = "body_loc_key"; + /** + * JSON-only field representing the notification body localization key. + */ + public static final String JSON_NOTIFICATION_BODY_LOC_KEY = "body_loc_key"; - /** - * JSON-only field representing the notification body localization values. - */ - public static final String JSON_NOTIFICATION_BODY_LOC_ARGS = "body_loc_args"; + /** + * JSON-only field representing the notification body localization values. + */ + public static final String JSON_NOTIFICATION_BODY_LOC_ARGS = "body_loc_args"; - /** - * JSON-only field representing the notification title localization key. - */ - public static final String JSON_NOTIFICATION_TITLE_LOC_KEY = "title_loc_key"; + /** + * JSON-only field representing the notification title localization key. + */ + public static final String JSON_NOTIFICATION_TITLE_LOC_KEY = "title_loc_key"; - /** - * JSON-only field representing the notification title localization values. - */ - public static final String JSON_NOTIFICATION_TITLE_LOC_ARGS = "title_loc_args"; + /** + * JSON-only field representing the notification title localization values. + */ + public static final String JSON_NOTIFICATION_TITLE_LOC_ARGS = "title_loc_args"; - /** - * JSON-only field representing the number of successful messages. - */ - public static final String JSON_SUCCESS = "success"; + /** + * JSON-only field representing the number of successful messages. + */ + public static final String JSON_SUCCESS = "success"; - /** - * JSON-only field representing the number of failed messages. - */ - public static final String JSON_FAILURE = "failure"; + /** + * JSON-only field representing the number of failed messages. + */ + public static final String JSON_FAILURE = "failure"; - /** - * JSON-only field representing the number of messages with a canonical - * registration id. - */ - public static final String JSON_CANONICAL_IDS = "canonical_ids"; + /** + * JSON-only field representing the number of messages with a canonical + * registration id. + */ + public static final String JSON_CANONICAL_IDS = "canonical_ids"; - /** - * JSON-only field representing the id of the multicast request. - */ - public static final String JSON_MULTICAST_ID = "multicast_id"; + /** + * JSON-only field representing the id of the multicast request. + */ + public static final String JSON_MULTICAST_ID = "multicast_id"; - /** - * JSON-only field representing the result of each individual request. - */ - public static final String JSON_RESULTS = "results"; + /** + * JSON-only field representing the result of each individual request. + */ + public static final String JSON_RESULTS = "results"; - /** - * JSON-only field representing the error field of an individual request. - */ - public static final String JSON_ERROR = "error"; + /** + * JSON-only field representing the error field of an individual request. + */ + public static final String JSON_ERROR = "error"; - /** - * JSON-only field sent by GCM when a message was successfully sent. - */ - public static final String JSON_MESSAGE_ID = "message_id"; + /** + * JSON-only field sent by GCM when a message was successfully sent. + */ + public static final String JSON_MESSAGE_ID = "message_id"; - private GcmConstants() { - throw new UnsupportedOperationException(); - } - - public static final Integer TIME_TO_LIVE = 30; + private GcmConstants() { + throw new UnsupportedOperationException(); + } + + public static final Integer TIME_TO_LIVE = 30; } 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 0b675cb47..e00286c9f 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,7 +19,7 @@ package org.apache.fineract.infrastructure.gcm.api; public class DeviceRegistrationApiConstants { - public static final String clientIdParamName = "clientId"; - public static final String registrationIdParamName = "registrationId"; + 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/domain/DeviceRegistration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistration.java index c4ba7b330..a5e82f90a 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 @@ -36,50 +36,50 @@ import org.apache.fineract.portfolio.client.domain.Client; @Table(name = "client_device_registration") public class DeviceRegistration extends AbstractPersistableCustom { - @OneToOne - @JoinColumn(name = "client_id", nullable = false, unique = true) - private Client client; + @OneToOne + @JoinColumn(name = "client_id", nullable = false, unique = true) + private Client client; - @Column(name = "registration_id", nullable = false, unique = true) - private String registrationId; + @Column(name = "registration_id", nullable = false, unique = true) + private String registrationId; - @Column(name = "updatedon_date", nullable = false) - @Temporal(TemporalType.TIMESTAMP) - private Date updatedOnDate; + @Column(name = "updatedon_date", nullable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date updatedOnDate; - private DeviceRegistration(final Client client, final String registrationId) { - this.client = client; - this.registrationId = registrationId; - this.updatedOnDate = DateUtils.getLocalDateTimeOfTenant().toDate(); - } + private DeviceRegistration(final Client client, final String registrationId) { + this.client = client; + this.registrationId = registrationId; + this.updatedOnDate = DateUtils.getLocalDateTimeOfTenant().toDate(); + } - public static DeviceRegistration instance(final Client client, - final String registrationId) { - return new DeviceRegistration(client, registrationId); - } + public static DeviceRegistration instance(final Client client, + final String registrationId) { + return new DeviceRegistration(client, registrationId); + } - 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 getRegistrationId() { - return this.registrationId; - } + public String getRegistrationId() { + return this.registrationId; + } - public void setRegistrationId(String registrationId) { - this.registrationId = registrationId; - } + public void setRegistrationId(String registrationId) { + this.registrationId = registrationId; + } - public Date getUpdatedOnDate() { - return this.updatedOnDate; - } + public Date getUpdatedOnDate() { + return this.updatedOnDate; + } - public void setUpdatedOnDate(Date updatedOnDate) { - this.updatedOnDate = updatedOnDate; - } + public void setUpdatedOnDate(Date updatedOnDate) { + this.updatedOnDate = updatedOnDate; + } } 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 3397a9bd3..f86d6fcd6 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 @@ -24,24 +24,24 @@ import org.apache.fineract.portfolio.client.data.ClientData; public class DeviceRegistrationData { - public Long id; - public ClientData clientData; - public String registrationId; - public Date updatedOnDate; + public Long id; + public ClientData clientData; + public String registrationId; + public 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; - } + 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, - final Date updatedOnDate) { - return new DeviceRegistrationData(id, clientData, registrationId, - updatedOnDate); - } + public static DeviceRegistrationData instance(final Long id, + final ClientData clientData, final String registrationId, + final Date 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 003311762..3d7be8097 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 @@ -24,13 +24,13 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface DeviceRegistrationRepository extends - JpaRepository, - JpaSpecificationExecutor { + JpaRepository, + JpaSpecificationExecutor { - public static final String FIND_DEVICE_REGISTRATION_BY_CLIENT = "select dr from DeviceRegistration dr where dr.client.id =:clientId "; + 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); + @Query(FIND_DEVICE_REGISTRATION_BY_CLIENT) + 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 ef8d8a3b2..524a11096 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 @@ -25,33 +25,33 @@ import org.springframework.stereotype.Service; @Service public class DeviceRegistrationRepositoryWrapper { - private final DeviceRegistrationRepository repository; + private final DeviceRegistrationRepository repository; - @Autowired - public DeviceRegistrationRepositoryWrapper( - DeviceRegistrationRepository repository) { - this.repository = repository; - } + @Autowired + public DeviceRegistrationRepositoryWrapper( + DeviceRegistrationRepository repository) { + this.repository = repository; + } - public DeviceRegistration findOneWithNotFoundDetection( - final Long deviceRegistrationId) { - return this.repository.findById(deviceRegistrationId) - .orElseThrow(() -> new DeviceRegistrationNotFoundException(deviceRegistrationId)); - } + public DeviceRegistration findOneWithNotFoundDetection( + final Long deviceRegistrationId) { + return this.repository.findById(deviceRegistrationId) + .orElseThrow(() -> new DeviceRegistrationNotFoundException(deviceRegistrationId)); + } - public void save(final DeviceRegistration deviceRegistration) { - this.repository.save(deviceRegistration); - } + public void save(final DeviceRegistration deviceRegistration) { + this.repository.save(deviceRegistration); + } - public void delete(final DeviceRegistration deviceRegistration) { - this.repository.delete(deviceRegistration); - } + public void delete(final DeviceRegistration deviceRegistration) { + this.repository.delete(deviceRegistration); + } - public void saveAndFlush(final DeviceRegistration deviceRegistration) { - this.repository.saveAndFlush(deviceRegistration); - } + public void saveAndFlush(final DeviceRegistration deviceRegistration) { + this.repository.saveAndFlush(deviceRegistration); + } - public DeviceRegistration findDeviceRegistrationByClientId(Long clientId) { - return this.repository.findDeviceRegistrationByClientId(clientId); - } + public DeviceRegistration findDeviceRegistrationByClientId(Long clientId) { + return this.repository.findDeviceRegistrationByClientId(clientId); + } } 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 34234dcb8..83dc3bacb 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 @@ -76,242 +76,242 @@ import org.apache.fineract.infrastructure.gcm.GcmConstants; */ public final class Message implements Serializable { - private final String collapseKey; - private final Boolean delayWhileIdle; - private final Integer timeToLive; - private final Map data; - private final Boolean dryRun; - private final String restrictedPackageName; - private final String priority; - private final Boolean contentAvailable; - private final Notification notification; + private final String collapseKey; + private final Boolean delayWhileIdle; + private final Integer timeToLive; + private final Map data; + private final Boolean dryRun; + private final String restrictedPackageName; + private final String priority; + private final Boolean contentAvailable; + private final Notification notification; - public enum Priority { - NORMAL, HIGH - } + public enum Priority { + NORMAL, HIGH + } - public static final class Builder { + public static final class Builder { - private final Map data; + private final Map data; - // optional parameters - private String collapseKey; - private Boolean delayWhileIdle; - private Integer timeToLive; - private Boolean dryRun; - private String restrictedPackageName; - private String priority; - private Boolean contentAvailable; - private Notification notification; + // optional parameters + private String collapseKey; + private Boolean delayWhileIdle; + private Integer timeToLive; + private Boolean dryRun; + private String restrictedPackageName; + private String priority; + private Boolean contentAvailable; + private Notification notification; - public Builder() { - this.data = new LinkedHashMap<>(); - } + public Builder() { + this.data = new LinkedHashMap<>(); + } - /** - * Sets the collapseKey property. - */ - public Builder collapseKey(String value) { - collapseKey = value; - return this; - } + /** + * Sets the collapseKey property. + */ + public Builder collapseKey(String value) { + collapseKey = value; + return this; + } - /** - * Sets the delayWhileIdle property (default value is {@literal false}). - */ - public Builder delayWhileIdle(boolean value) { - delayWhileIdle = value; - return this; - } + /** + * Sets the delayWhileIdle property (default value is {@literal false}). + */ + public Builder delayWhileIdle(boolean value) { + delayWhileIdle = value; + return this; + } - /** - * Sets the time to live, in seconds. - */ - public Builder timeToLive(int value) { - timeToLive = value; - return this; - } + /** + * Sets the time to live, in seconds. + */ + public Builder timeToLive(int value) { + timeToLive = value; + return this; + } - /** - * Adds a key/value pair to the payload data. - */ - public Builder addData(String key, String value) { - data.put(key, value); - return this; - } + /** + * Adds a key/value pair to the payload data. + */ + public Builder addData(String key, String value) { + data.put(key, value); + return this; + } - /** - * Sets the dryRun property (default value is {@literal false}). - */ - public Builder dryRun(boolean value) { - dryRun = value; - return this; - } + /** + * Sets the dryRun property (default value is {@literal false}). + */ + public Builder dryRun(boolean value) { + dryRun = value; + return this; + } - /** - * Sets the restrictedPackageName property. - */ - public Builder restrictedPackageName(String value) { - restrictedPackageName = value; - return this; - } + /** + * Sets the restrictedPackageName property. + */ + public Builder restrictedPackageName(String value) { + restrictedPackageName = value; + return this; + } - /** - * Sets the priority property. - */ - public Builder priority(Priority value) { - switch (value) { - case NORMAL: - priority = GcmConstants.MESSAGE_PRIORITY_NORMAL; - break; - case HIGH: - priority = GcmConstants.MESSAGE_PRIORITY_HIGH; - break; - } - return this; - } + /** + * Sets the priority property. + */ + public Builder priority(Priority value) { + switch (value) { + case NORMAL: + priority = GcmConstants.MESSAGE_PRIORITY_NORMAL; + break; + case HIGH: + priority = GcmConstants.MESSAGE_PRIORITY_HIGH; + break; + } + return this; + } - /** - * Sets the notification property. - */ - public Builder notification(Notification value) { - notification = value; - return this; - } + /** + * Sets the notification property. + */ + public Builder notification(Notification value) { + notification = value; + return this; + } - /** - * Sets the contentAvailable property - */ - public Builder contentAvailable(Boolean value) { - contentAvailable = value; - return this; - } + /** + * Sets the contentAvailable property + */ + public Builder contentAvailable(Boolean value) { + contentAvailable = value; + return this; + } - public Message build() { - return new Message(this); - } + public Message build() { + return new Message(this); + } - } + } - private Message(Builder builder) { - collapseKey = builder.collapseKey; - delayWhileIdle = builder.delayWhileIdle; - data = Collections.unmodifiableMap(builder.data); - timeToLive = builder.timeToLive; - dryRun = builder.dryRun; - restrictedPackageName = builder.restrictedPackageName; - priority = builder.priority; - contentAvailable = builder.contentAvailable; - notification = builder.notification; - } + private Message(Builder builder) { + collapseKey = builder.collapseKey; + delayWhileIdle = builder.delayWhileIdle; + data = Collections.unmodifiableMap(builder.data); + timeToLive = builder.timeToLive; + dryRun = builder.dryRun; + restrictedPackageName = builder.restrictedPackageName; + priority = builder.priority; + contentAvailable = builder.contentAvailable; + notification = builder.notification; + } - /** - * Gets the collapse key. - */ - public String getCollapseKey() { - return collapseKey; - } + /** + * Gets the collapse key. + */ + public String getCollapseKey() { + return collapseKey; + } - /** - * Gets the delayWhileIdle flag. - */ - public Boolean isDelayWhileIdle() { - return delayWhileIdle; - } + /** + * Gets the delayWhileIdle flag. + */ + public Boolean isDelayWhileIdle() { + return delayWhileIdle; + } - /** - * Gets the time to live (in seconds). - */ - public Integer getTimeToLive() { - return timeToLive; - } + /** + * Gets the time to live (in seconds). + */ + public Integer getTimeToLive() { + return timeToLive; + } - /** - * Gets the dryRun flag. - */ - public Boolean isDryRun() { - return dryRun; - } + /** + * Gets the dryRun flag. + */ + public Boolean isDryRun() { + return dryRun; + } - /** - * Gets the restricted package name. - */ - public String getRestrictedPackageName() { - return restrictedPackageName; - } + /** + * Gets the restricted package name. + */ + public String getRestrictedPackageName() { + return restrictedPackageName; + } - /** - * Gets the message priority value. - */ - public String getPriority() { - return priority; - } + /** + * Gets the message priority value. + */ + public String getPriority() { + return priority; + } - /** - * Gets the contentAvailable value - */ - public Boolean getContentAvailable() { - return contentAvailable; - } + /** + * Gets the contentAvailable value + */ + public Boolean getContentAvailable() { + return contentAvailable; + } - /** - * Gets the payload data, which is immutable. - */ - public Map getData() { - return data; - } + /** + * Gets the payload data, which is immutable. + */ + public Map getData() { + return data; + } - /** - * Gets notification payload, which is immutable. - */ - public Notification getNotification() { - return notification; - } + /** + * Gets notification payload, which is immutable. + */ + public Notification getNotification() { + return notification; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder("Message("); - if (priority != null) { - builder.append("priority=").append(priority).append(", "); - } - if (contentAvailable != null) { - builder.append("contentAvailable=").append(contentAvailable) - .append(", "); - } - if (collapseKey != null) { - builder.append("collapseKey=").append(collapseKey).append(", "); - } - if (timeToLive != null) { - builder.append("timeToLive=").append(timeToLive).append(", "); - } - if (delayWhileIdle != null) { - builder.append("delayWhileIdle=").append(delayWhileIdle) - .append(", "); - } - if (dryRun != null) { - builder.append("dryRun=").append(dryRun).append(", "); - } - if (restrictedPackageName != null) { - builder.append("restrictedPackageName=") - .append(restrictedPackageName).append(", "); - } - if (notification != null) { - builder.append("notification: ").append(notification).append(", "); - } - if (!data.isEmpty()) { - builder.append("data: {"); - for (Map.Entry entry : data.entrySet()) { - builder.append(entry.getKey()).append("=") - .append(entry.getValue()).append(","); - } - builder.delete(builder.length() - 1, builder.length()); - builder.append("}"); - } - if (builder.charAt(builder.length() - 1) == ' ') { - builder.delete(builder.length() - 2, builder.length()); - } - builder.append(")"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder("Message("); + if (priority != null) { + builder.append("priority=").append(priority).append(", "); + } + if (contentAvailable != null) { + builder.append("contentAvailable=").append(contentAvailable) + .append(", "); + } + if (collapseKey != null) { + builder.append("collapseKey=").append(collapseKey).append(", "); + } + if (timeToLive != null) { + builder.append("timeToLive=").append(timeToLive).append(", "); + } + if (delayWhileIdle != null) { + builder.append("delayWhileIdle=").append(delayWhileIdle) + .append(", "); + } + if (dryRun != null) { + builder.append("dryRun=").append(dryRun).append(", "); + } + if (restrictedPackageName != null) { + builder.append("restrictedPackageName=") + .append(restrictedPackageName).append(", "); + } + if (notification != null) { + builder.append("notification: ").append(notification).append(", "); + } + if (!data.isEmpty()) { + builder.append("data: {"); + for (Map.Entry entry : data.entrySet()) { + builder.append(entry.getKey()).append("=") + .append(entry.getValue()).append(","); + } + builder.delete(builder.length() - 1, builder.length()); + builder.append("}"); + } + if (builder.charAt(builder.length() - 1) == ' ') { + builder.delete(builder.length() - 2, builder.length()); + } + builder.append(")"); + return builder.toString(); + } } 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 c58de9fe0..4abb5a87e 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 @@ -28,124 +28,124 @@ import java.util.List; */ public final class MulticastResult implements Serializable { - private final int success; - private final int failure; - private final int canonicalIds; - private final long multicastId; - private final List results; - private final List retryMulticastIds; + private final int success; + private final int failure; + private final int canonicalIds; + private final long multicastId; + private final List results; + private final List retryMulticastIds; - public static final class Builder { + public static final class Builder { - private final List results = new ArrayList<>(); + private final List results = new ArrayList<>(); - // required parameters - private final int success; - private final int failure; - private final int canonicalIds; - private final long multicastId; + // required parameters + private final int success; + private final int failure; + private final int canonicalIds; + private final long multicastId; - // optional parameters - private List retryMulticastIds; + // optional parameters + private List retryMulticastIds; - public Builder(int success, int failure, int canonicalIds, - long multicastId) { - this.success = success; - this.failure = failure; - this.canonicalIds = canonicalIds; - this.multicastId = multicastId; - } + public Builder(int success, int failure, int canonicalIds, + long multicastId) { + this.success = success; + this.failure = failure; + this.canonicalIds = canonicalIds; + this.multicastId = multicastId; + } - public Builder addResult(Result result) { - results.add(result); - return this; - } + public Builder addResult(Result result) { + results.add(result); + return this; + } - public Builder retryMulticastIds(List retryMulticastIds) { - this.retryMulticastIds = retryMulticastIds; - return this; - } + public Builder retryMulticastIds(List retryMulticastIds) { + this.retryMulticastIds = retryMulticastIds; + return this; + } - public MulticastResult build() { - return new MulticastResult(this); - } - } + public MulticastResult build() { + return new MulticastResult(this); + } + } - private MulticastResult(Builder builder) { - success = builder.success; - failure = builder.failure; - canonicalIds = builder.canonicalIds; - multicastId = builder.multicastId; - results = Collections.unmodifiableList(builder.results); - List tmpList = builder.retryMulticastIds; - if (tmpList == null) { - tmpList = Collections.emptyList(); - } - retryMulticastIds = Collections.unmodifiableList(tmpList); - } + private MulticastResult(Builder builder) { + success = builder.success; + failure = builder.failure; + canonicalIds = builder.canonicalIds; + multicastId = builder.multicastId; + results = Collections.unmodifiableList(builder.results); + List tmpList = builder.retryMulticastIds; + if (tmpList == null) { + tmpList = Collections.emptyList(); + } + retryMulticastIds = Collections.unmodifiableList(tmpList); + } - /** - * Gets the multicast id. - */ - public long getMulticastId() { - return multicastId; - } + /** + * Gets the multicast id. + */ + public long getMulticastId() { + return multicastId; + } - /** - * Gets the number of successful messages. - */ - public int getSuccess() { - return success; - } + /** + * Gets the number of successful messages. + */ + public int getSuccess() { + return success; + } - /** - * Gets the total number of messages sent, regardless of the status. - */ - public int getTotal() { - return success + failure; - } + /** + * Gets the total number of messages sent, regardless of the status. + */ + public int getTotal() { + return success + failure; + } - /** - * Gets the number of failed messages. - */ - public int getFailure() { - return failure; - } + /** + * Gets the number of failed messages. + */ + public int getFailure() { + return failure; + } - /** - * Gets the number of successful messages that also returned a canonical - * registration id. - */ - public int getCanonicalIds() { - return canonicalIds; - } + /** + * Gets the number of successful messages that also returned a canonical + * registration id. + */ + public int getCanonicalIds() { + return canonicalIds; + } - /** - * Gets the results of each individual message, which is immutable. - */ - public List getResults() { - return results; - } + /** + * Gets the results of each individual message, which is immutable. + */ + public List getResults() { + return results; + } - /** - * Gets additional ids if more than one multicast message was sent. - */ - public List getRetryMulticastIds() { - return retryMulticastIds; - } + /** + * Gets additional ids if more than one multicast message was sent. + */ + public List getRetryMulticastIds() { + return retryMulticastIds; + } - @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(","); - if (!results.isEmpty()) { - builder.append("results: " + results); - } - return builder.toString(); - } + @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(","); + if (!results.isEmpty()) { + builder.append("results: " + results); + } + return builder.toString(); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Notification.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Notification.java index 589e7725d..219f3765a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Notification.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Notification.java @@ -52,279 +52,279 @@ import java.util.List; */ public final class Notification implements Serializable { - private final String title; - private final String body; - private final String icon; - private final String sound; - private final Integer badge; - private final String tag; - private final String color; - private final String clickAction; - private final String bodyLocKey; - private final List bodyLocArgs; - private final String titleLocKey; - private final List titleLocArgs; + private final String title; + private final String body; + private final String icon; + private final String sound; + private final Integer badge; + private final String tag; + private final String color; + private final String clickAction; + private final String bodyLocKey; + private final List bodyLocArgs; + private final String titleLocKey; + private final List titleLocArgs; - public static final class Builder { + public static final class Builder { - // required parameters - private final String icon; + // required parameters + private final String icon; - // optional parameters - private String title; - private String body; - private String sound; - private Integer badge; - private String tag; - private String color; - private String clickAction; - private String bodyLocKey; - private List bodyLocArgs; - private String titleLocKey; - private List titleLocArgs; + // optional parameters + private String title; + private String body; + private String sound; + private Integer badge; + private String tag; + private String color; + private String clickAction; + private String bodyLocKey; + private List bodyLocArgs; + private String titleLocKey; + private List titleLocArgs; - public Builder(String icon) { - this.icon = icon; - this.sound = "default"; // the only currently supported value - } + public Builder(String icon) { + this.icon = icon; + this.sound = "default"; // the only currently supported value + } - /** - * Sets the title property. - */ - public Builder title(String value) { - title = value; - return this; - } + /** + * Sets the title property. + */ + public Builder title(String value) { + title = value; + return this; + } - /** - * Sets the body property. - */ - public Builder body(String value) { - body = value; - return this; - } + /** + * Sets the body property. + */ + public Builder body(String value) { + body = value; + return this; + } - /** - * Sets the sound property (default value is {@literal default}). - */ - public Builder sound(String value) { - sound = value; - return this; - } + /** + * Sets the sound property (default value is {@literal default}). + */ + public Builder sound(String value) { + sound = value; + return this; + } - /** - * Sets the badge property. - */ - public Builder badge(int value) { - badge = value; - return this; - } + /** + * Sets the badge property. + */ + public Builder badge(int value) { + badge = value; + return this; + } - /** - * Sets the tag property. - */ - public Builder tag(String value) { - tag = value; - return this; - } + /** + * Sets the tag property. + */ + public Builder tag(String value) { + tag = value; + return this; + } - /** - * Sets the color property in {@literal #rrggbb} format. - */ - public Builder color(String value) { - color = value; - return this; - } + /** + * Sets the color property in {@literal #rrggbb} format. + */ + public Builder color(String value) { + color = value; + return this; + } - /** - * Sets the click action property. - */ - public Builder clickAction(String value) { - clickAction = value; - return this; - } + /** + * Sets the click action property. + */ + public Builder clickAction(String value) { + clickAction = value; + return this; + } - /** - * Sets the body localization key property. - */ - public Builder bodyLocKey(String value) { - bodyLocKey = value; - return this; - } + /** + * Sets the body localization key property. + */ + public Builder bodyLocKey(String value) { + bodyLocKey = value; + return this; + } - /** - * Sets the body localization values property. - */ - public Builder bodyLocArgs(List value) { - bodyLocArgs = Collections.unmodifiableList(value); - return this; - } + /** + * Sets the body localization values property. + */ + public Builder bodyLocArgs(List value) { + bodyLocArgs = Collections.unmodifiableList(value); + return this; + } - /** - * Sets the title localization key property. - */ - public Builder titleLocKey(String value) { - titleLocKey = value; - return this; - } + /** + * Sets the title localization key property. + */ + public Builder titleLocKey(String value) { + titleLocKey = value; + return this; + } - /** - * Sets the title localization values property. - */ - public Builder titleLocArgs(List value) { - titleLocArgs = Collections.unmodifiableList(value); - return this; - } + /** + * Sets the title localization values property. + */ + public Builder titleLocArgs(List value) { + titleLocArgs = Collections.unmodifiableList(value); + return this; + } - public Notification build() { - return new Notification(this); - } + public Notification build() { + return new Notification(this); + } - } + } - private Notification(Builder builder) { - title = builder.title; - body = builder.body; - icon = builder.icon; - sound = builder.sound; - badge = builder.badge; - tag = builder.tag; - color = builder.color; - clickAction = builder.clickAction; - bodyLocKey = builder.bodyLocKey; - bodyLocArgs = builder.bodyLocArgs; - titleLocKey = builder.titleLocKey; - titleLocArgs = builder.titleLocArgs; - } + private Notification(Builder builder) { + title = builder.title; + body = builder.body; + icon = builder.icon; + sound = builder.sound; + badge = builder.badge; + tag = builder.tag; + color = builder.color; + clickAction = builder.clickAction; + bodyLocKey = builder.bodyLocKey; + bodyLocArgs = builder.bodyLocArgs; + titleLocKey = builder.titleLocKey; + titleLocArgs = builder.titleLocArgs; + } - /** - * Gets the title. - */ - public String getTitle() { - return title; - } + /** + * Gets the title. + */ + public String getTitle() { + return title; + } - /** - * Gets the body. - */ - public String getBody() { - return body; - } + /** + * Gets the body. + */ + public String getBody() { + return body; + } - /** - * Gets the icon. - */ - public String getIcon() { - return icon; - } + /** + * Gets the icon. + */ + public String getIcon() { + return icon; + } - /** - * Gets the sound. - */ - public String getSound() { - return sound; - } + /** + * Gets the sound. + */ + public String getSound() { + return sound; + } - /** - * Gets the badge. - */ - public Integer getBadge() { - return badge; - } + /** + * Gets the badge. + */ + public Integer getBadge() { + return badge; + } - /** - * Gets the tag. - */ - public String getTag() { - return tag; - } + /** + * Gets the tag. + */ + public String getTag() { + return tag; + } - /** - * Gets the color. - */ - public String getColor() { - return color; - } + /** + * Gets the color. + */ + public String getColor() { + return color; + } - /** - * Gets the click action. - */ - public String getClickAction() { - return clickAction; - } + /** + * Gets the click action. + */ + public String getClickAction() { + return clickAction; + } - /** - * Gets the body localization key. - */ - public String getBodyLocKey() { - return bodyLocKey; - } + /** + * Gets the body localization key. + */ + public String getBodyLocKey() { + return bodyLocKey; + } - /** - * Gets the body localization values list, which is immutable. - */ - public List getBodyLocArgs() { - return bodyLocArgs; - } + /** + * Gets the body localization values list, which is immutable. + */ + public List getBodyLocArgs() { + return bodyLocArgs; + } - /** - * Gets the title localization key. - */ - public String getTitleLocKey() { - return titleLocKey; - } + /** + * Gets the title localization key. + */ + public String getTitleLocKey() { + return titleLocKey; + } - /** - * Gets the title localization values list, which is immutable. - */ - public List getTitleLocArgs() { - return titleLocArgs; - } + /** + * Gets the title localization values list, which is immutable. + */ + public List getTitleLocArgs() { + return titleLocArgs; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder("Notification("); - if (title != null) { - builder.append("title=").append(title).append(", "); - } - if (body != null) { - builder.append("body=").append(body).append(", "); - } - if (icon != null) { - builder.append("icon=").append(icon).append(", "); - } - if (sound != null) { - builder.append("sound=").append(sound).append(", "); - } - if (badge != null) { - builder.append("badge=").append(badge).append(", "); - } - if (tag != null) { - builder.append("tag=").append(tag).append(", "); - } - if (color != null) { - builder.append("color=").append(color).append(", "); - } - if (clickAction != null) { - builder.append("clickAction=").append(clickAction).append(", "); - } - if (bodyLocKey != null) { - builder.append("bodyLocKey=").append(bodyLocKey).append(", "); - } - if (bodyLocArgs != null) { - builder.append("bodyLocArgs=").append(bodyLocArgs).append(", "); - } - if (titleLocKey != null) { - builder.append("titleLocKey=").append(titleLocKey).append(", "); - } - if (titleLocArgs != null) { - builder.append("titleLocArgs=").append(titleLocArgs).append(", "); - } - if (builder.charAt(builder.length() - 1) == ' ') { - builder.delete(builder.length() - 2, builder.length()); - } - builder.append(")"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder("Notification("); + if (title != null) { + builder.append("title=").append(title).append(", "); + } + if (body != null) { + builder.append("body=").append(body).append(", "); + } + if (icon != null) { + builder.append("icon=").append(icon).append(", "); + } + if (sound != null) { + builder.append("sound=").append(sound).append(", "); + } + if (badge != null) { + builder.append("badge=").append(badge).append(", "); + } + if (tag != null) { + builder.append("tag=").append(tag).append(", "); + } + if (color != null) { + builder.append("color=").append(color).append(", "); + } + if (clickAction != null) { + builder.append("clickAction=").append(clickAction).append(", "); + } + if (bodyLocKey != null) { + builder.append("bodyLocKey=").append(bodyLocKey).append(", "); + } + if (bodyLocArgs != null) { + builder.append("bodyLocArgs=").append(bodyLocArgs).append(", "); + } + if (titleLocKey != null) { + builder.append("titleLocKey=").append(titleLocKey).append(", "); + } + if (titleLocArgs != null) { + builder.append("titleLocArgs=").append(titleLocArgs).append(", "); + } + if (builder.charAt(builder.length() - 1) == ' ') { + builder.delete(builder.length() - 2, builder.length()); + } + builder.append(")"); + return builder.toString(); + } } 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 2d4acc93f..6133cc37a 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 @@ -19,30 +19,30 @@ package org.apache.fineract.infrastructure.gcm.domain; public class NotificationConfigurationData { - - private final Long id; + + private final Long id; private final String serverKey; private final String gcmEndPoint; private 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; - } - - public String getGcmEndPoint() { - return gcmEndPoint; - } - public String getFcmEndPoint() { - return 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; + } + + 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 76aafa8ef..6f390f187 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 @@ -50,138 +50,138 @@ import java.util.List; */ public final class Result implements Serializable { - private final String messageId; - private final String canonicalRegistrationId; - private final String errorCode; - private final Integer success; - private final Integer failure; - private final List failedRegistrationIds; - private final int status; + private final String messageId; + private final String canonicalRegistrationId; + private final String errorCode; + private final Integer success; + private final Integer failure; + private final List failedRegistrationIds; + private final int status; - public static final class Builder { + public static final class Builder { - // optional parameters - private String messageId; - private String canonicalRegistrationId; - private String errorCode; - private Integer success; - private Integer failure; - private List failedRegistrationIds; - private int status; + // optional parameters + private String messageId; + private String canonicalRegistrationId; + private String errorCode; + private Integer success; + private Integer failure; + private List failedRegistrationIds; + private int status; - public Builder canonicalRegistrationId(String value) { - canonicalRegistrationId = value; - return this; - } + public Builder canonicalRegistrationId(String value) { + canonicalRegistrationId = value; + return this; + } - public Builder messageId(String value) { - messageId = value; - return this; - } + public Builder messageId(String value) { + messageId = value; + return this; + } - public Builder errorCode(String value) { - errorCode = value; - return this; - } + public Builder errorCode(String value) { + errorCode = value; + return this; + } - public Builder success(Integer value) { - success = value; - return this; - } + public Builder success(Integer value) { + success = value; + return this; + } - public Builder failure(Integer value) { - failure = value; - return this; - } - - public Builder status(int value) { - status = value; - return this; - } + public Builder failure(Integer value) { + failure = value; + return this; + } + + public Builder status(int value) { + status = value; + return this; + } - public Builder failedRegistrationIds(List value) { - failedRegistrationIds = value; - return this; - } + public Builder failedRegistrationIds(List value) { + failedRegistrationIds = value; + return this; + } - public Result build() { - return new Result(this); - } - } + public Result build() { + return new Result(this); + } + } - private Result(Builder builder) { - canonicalRegistrationId = builder.canonicalRegistrationId; - messageId = builder.messageId; - errorCode = builder.errorCode; - success = builder.success; - failure = builder.failure; - failedRegistrationIds = builder.failedRegistrationIds; - status = builder.status; - } + private Result(Builder builder) { + canonicalRegistrationId = builder.canonicalRegistrationId; + messageId = builder.messageId; + errorCode = builder.errorCode; + success = builder.success; + failure = builder.failure; + failedRegistrationIds = builder.failedRegistrationIds; + status = builder.status; + } - /** - * Gets the message id, if any. - */ - public String getMessageId() { - return messageId; - } + /** + * Gets the message id, if any. + */ + public String getMessageId() { + return messageId; + } - /** - * Gets the canonical registration id, if any. - */ - public String getCanonicalRegistrationId() { - return canonicalRegistrationId; - } + /** + * Gets the canonical registration id, if any. + */ + public String getCanonicalRegistrationId() { + return canonicalRegistrationId; + } - /** - * Gets the error code, if any. - */ - public String getErrorCodeName() { - return errorCode; - } + /** + * Gets the error code, if any. + */ + public String getErrorCodeName() { + return errorCode; + } - public Integer getSuccess() { - return success; - } + public Integer getSuccess() { + return success; + } - public Integer getFailure() { - return failure; - } + public Integer getFailure() { + return failure; + } - public List getFailedRegistrationIds() { - return failedRegistrationIds; - } + public List getFailedRegistrationIds() { + return failedRegistrationIds; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder("["); - if (messageId != null) { - builder.append(" messageId=").append(messageId); - } - if (canonicalRegistrationId != null) { - builder.append(" canonicalRegistrationId=").append( - canonicalRegistrationId); - } - if (errorCode != null) { - builder.append(" errorCode=").append(errorCode); - } - if (success != null) { - builder.append(" groupSuccess=").append(success); - } - if (failure != null) { - builder.append(" groupFailure=").append(failure); - } - if (failedRegistrationIds != null) { - builder.append(" failedRegistrationIds=").append( - failedRegistrationIds); - } - return builder.append(" ]").toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder("["); + if (messageId != null) { + builder.append(" messageId=").append(messageId); + } + if (canonicalRegistrationId != null) { + builder.append(" canonicalRegistrationId=").append( + canonicalRegistrationId); + } + if (errorCode != null) { + builder.append(" errorCode=").append(errorCode); + } + if (success != null) { + builder.append(" groupSuccess=").append(success); + } + if (failure != null) { + builder.append(" groupFailure=").append(failure); + } + if (failedRegistrationIds != null) { + builder.append(" failedRegistrationIds=").append( + failedRegistrationIds); + } + return builder.append(" ]").toString(); + } - public int getStatus() { - return this.status; - } - - + public int getStatus() { + 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 87470c20d..14e3f2411 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 @@ -41,741 +41,741 @@ import static org.apache.fineract.infrastructure.gcm.GcmConstants.*; */ public class Sender { - /** - * Initial delay before first retry, without jitter. - */ - protected static final int BACKOFF_INITIAL_DELAY = 1000; - /** - * Maximum delay before a retry. - */ - protected static final int MAX_BACKOFF_DELAY = 1024000; + /** + * Initial delay before first retry, without jitter. + */ + protected static final int BACKOFF_INITIAL_DELAY = 1000; + /** + * Maximum delay before a retry. + */ + protected static final int MAX_BACKOFF_DELAY = 1024000; - protected final Random random = new Random(); - protected static final Logger logger = Logger.getLogger(Sender.class - .getName()); + protected final Random random = new Random(); + protected static final Logger logger = Logger.getLogger(Sender.class + .getName()); - private final String key; + private final String key; - private String endpoint; + private String endpoint; - private int connectTimeout; - private int readTimeout; - - /** - * Full options constructor. - * - * @param key - * FCM Server Key obtained through the Firebase Web Console. - * @param endpoint - * Endpoint to use when sending the message. - */ - public Sender(String key, String endpoint) { - this.key = nonNull(key); - this.endpoint = nonNull(endpoint); - } + private int connectTimeout; + private int readTimeout; + + /** + * Full options constructor. + * + * @param key + * FCM Server Key obtained through the Firebase Web Console. + * @param endpoint + * Endpoint to use when sending the message. + */ + public Sender(String key, String endpoint) { + this.key = nonNull(key); + this.endpoint = nonNull(endpoint); + } - public String getEndpoint() { - return endpoint; - } + public String getEndpoint() { + return endpoint; + } - /** - * Set the underlying URLConnection's connect timeout (in milliseconds). A - * timeout value of 0 specifies an infinite timeout. - *

- * Default is the system's default timeout. - * - * @see java.net.URLConnection#setConnectTimeout(int) - */ - public final void setConnectTimeout(int connectTimeout) { - if (connectTimeout < 0) { - throw new IllegalArgumentException("timeout can not be negative"); - } - this.connectTimeout = connectTimeout; - } + /** + * Set the underlying URLConnection's connect timeout (in milliseconds). A + * timeout value of 0 specifies an infinite timeout. + *

+ * Default is the system's default timeout. + * + * @see java.net.URLConnection#setConnectTimeout(int) + */ + public final void setConnectTimeout(int connectTimeout) { + if (connectTimeout < 0) { + throw new IllegalArgumentException("timeout can not be negative"); + } + this.connectTimeout = connectTimeout; + } - /** - * Set the underlying URLConnection's read timeout (in milliseconds). A - * timeout value of 0 specifies an infinite timeout. - *

- * Default is the system's default timeout. - * - * @see java.net.URLConnection#setReadTimeout(int) - */ - public final void setReadTimeout(int readTimeout) { - if (readTimeout < 0) { - throw new IllegalArgumentException("timeout can not be negative"); - } - this.readTimeout = readTimeout; - } + /** + * Set the underlying URLConnection's read timeout (in milliseconds). A + * timeout value of 0 specifies an infinite timeout. + *

+ * Default is the system's default timeout. + * + * @see java.net.URLConnection#setReadTimeout(int) + */ + public final void setReadTimeout(int readTimeout) { + if (readTimeout < 0) { + throw new IllegalArgumentException("timeout can not be negative"); + } + this.readTimeout = readTimeout; + } - /** - * Sends a message to one device, retrying in case of unavailability. - * - *

- * Note: this method uses exponential back-off to retry in - * case of service unavailability and hence could block the calling thread - * for many seconds. - * - * @param message - * message to be sent, including the device's registration id. - * @param to - * registration token, notification key, or topic where the - * message will be sent. - * @param retries - * number of retries in case of service unavailability errors. - * - * @return result of the request (see its javadoc for more details). - * - * @throws IllegalArgumentException - * if to is {@literal null}. - * @throws InvalidRequestException - * if GCM didn't returned a 200 or 5xx status. - * @throws IOException - * if message could not be sent. - */ - public Result send(Message message, String to, int retries) - throws IOException { - int attempt = 0; - Result result; - int backoff = BACKOFF_INITIAL_DELAY; - boolean tryAgain; - do { - attempt++; - if (logger.isLoggable(Level.FINE)) { - logger.fine("Attempt #" + attempt + " to send message " - + message + " to regIds " + to); - } - result = sendNoRetry(message, to); - tryAgain = result == null && attempt <= retries; - if (tryAgain) { - int sleepTime = backoff / 2 + random.nextInt(backoff); - sleep(sleepTime); - if (2 * backoff < MAX_BACKOFF_DELAY) { - backoff *= 2; - } - } - } while (tryAgain); - if (result == null) { - throw new IOException("Could not send message after " + attempt - + " attempts"); - } - return result; - } + /** + * Sends a message to one device, retrying in case of unavailability. + * + *

+ * Note: this method uses exponential back-off to retry in + * case of service unavailability and hence could block the calling thread + * for many seconds. + * + * @param message + * message to be sent, including the device's registration id. + * @param to + * registration token, notification key, or topic where the + * message will be sent. + * @param retries + * number of retries in case of service unavailability errors. + * + * @return result of the request (see its javadoc for more details). + * + * @throws IllegalArgumentException + * if to is {@literal null}. + * @throws InvalidRequestException + * if GCM didn't returned a 200 or 5xx status. + * @throws IOException + * if message could not be sent. + */ + public Result send(Message message, String to, int retries) + throws IOException { + int attempt = 0; + Result result; + int backoff = BACKOFF_INITIAL_DELAY; + boolean tryAgain; + do { + attempt++; + if (logger.isLoggable(Level.FINE)) { + logger.fine("Attempt #" + attempt + " to send message " + + message + " to regIds " + to); + } + result = sendNoRetry(message, to); + tryAgain = result == null && attempt <= retries; + if (tryAgain) { + int sleepTime = backoff / 2 + random.nextInt(backoff); + sleep(sleepTime); + if (2 * backoff < MAX_BACKOFF_DELAY) { + backoff *= 2; + } + } + } while (tryAgain); + if (result == null) { + throw new IOException("Could not send message after " + attempt + + " attempts"); + } + return result; + } - /** - * Sends a message without retrying in case of service unavailability. See - * {@link #send(Message, String, int)} for more info. - * - * @return result of the post, or {@literal null} if the GCM service was - * unavailable or any network exception caused the request to fail, - * or if the response contains more than one result. - * - * @throws InvalidRequestException - * if GCM didn't returned a 200 status. - * @throws IllegalArgumentException - * if to is {@literal null}. - */ - public Result sendNoRetry(Message message, String to) throws IOException { - nonNull(to); - Map jsonRequest = new HashMap<>(); - messageToMap(message, jsonRequest); - jsonRequest.put(JSON_TO, to); - 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; - } - JsonParser jsonParser = new JsonParser(); - JsonObject jsonResponse; - try { - jsonResponse = (JsonObject) jsonParser.parse(responseBody); - Result.Builder resultBuilder = new Result.Builder(); - if (jsonResponse.has("results")) { - // Handle response from message sent to specific device. - JsonArray jsonResults = (JsonArray) jsonResponse.get("results"); - if (jsonResults.size() == 1) { - JsonObject jsonResult = (JsonObject) jsonResults.get(0); - String messageId = null; - String canonicalRegId = null; - String error = null; - 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(JSON_ERROR)){ - error = jsonResult.get(JSON_ERROR).getAsString(); - } - int success = 0; - int failure = 0; - if(jsonResponse.get("success") != null){ - success = Integer.parseInt(jsonResponse.get("success").toString()); - } - 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); - } else { - logger.log(Level.WARNING, - "Found null or " + jsonResults.size() - + " results, expected one"); - return null; - } - } else if (to.startsWith(TOPIC_PREFIX)) { - if (jsonResponse.has(JSON_MESSAGE_ID)) { - // message_id is expected when this is the response from a - // topic message. - Long messageId = jsonResponse.get(JSON_MESSAGE_ID).getAsLong(); - resultBuilder.messageId(messageId.toString()); - } else if (jsonResponse.has(JSON_ERROR)) { - String error = jsonResponse.get(JSON_ERROR).getAsString(); - resultBuilder.errorCode(error); - } else { - logger.log(Level.WARNING, "Expected " + JSON_MESSAGE_ID - + " or " + JSON_ERROR + " found: " + responseBody); - return null; - } - } 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(); - failedIds = new ArrayList<>(); - for (int i = 0; i < jFailedIds.size(); i++) { - failedIds.add(jFailedIds.get(i).getAsString()); - } - } - resultBuilder.success(success).failure(failure) - .failedRegistrationIds(failedIds); - } else { - logger.warning("Unrecognized response: " + responseBody); - throw newIoException(responseBody, new Exception( - "Unrecognized response.")); - } - return resultBuilder.build(); - } catch (CustomParserException e) { - throw newIoException(responseBody, e); - } - } + /** + * Sends a message without retrying in case of service unavailability. See + * {@link #send(Message, String, int)} for more info. + * + * @return result of the post, or {@literal null} if the GCM service was + * unavailable or any network exception caused the request to fail, + * or if the response contains more than one result. + * + * @throws InvalidRequestException + * if GCM didn't returned a 200 status. + * @throws IllegalArgumentException + * if to is {@literal null}. + */ + public Result sendNoRetry(Message message, String to) throws IOException { + nonNull(to); + Map jsonRequest = new HashMap<>(); + messageToMap(message, jsonRequest); + jsonRequest.put(JSON_TO, to); + 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; + } + JsonParser jsonParser = new JsonParser(); + JsonObject jsonResponse; + try { + jsonResponse = (JsonObject) jsonParser.parse(responseBody); + Result.Builder resultBuilder = new Result.Builder(); + if (jsonResponse.has("results")) { + // Handle response from message sent to specific device. + JsonArray jsonResults = (JsonArray) jsonResponse.get("results"); + if (jsonResults.size() == 1) { + JsonObject jsonResult = (JsonObject) jsonResults.get(0); + String messageId = null; + String canonicalRegId = null; + String error = null; + 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(JSON_ERROR)){ + error = jsonResult.get(JSON_ERROR).getAsString(); + } + int success = 0; + int failure = 0; + if(jsonResponse.get("success") != null){ + success = Integer.parseInt(jsonResponse.get("success").toString()); + } + 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); + } else { + logger.log(Level.WARNING, + "Found null or " + jsonResults.size() + + " results, expected one"); + return null; + } + } else if (to.startsWith(TOPIC_PREFIX)) { + if (jsonResponse.has(JSON_MESSAGE_ID)) { + // message_id is expected when this is the response from a + // topic message. + Long messageId = jsonResponse.get(JSON_MESSAGE_ID).getAsLong(); + resultBuilder.messageId(messageId.toString()); + } else if (jsonResponse.has(JSON_ERROR)) { + String error = jsonResponse.get(JSON_ERROR).getAsString(); + resultBuilder.errorCode(error); + } else { + logger.log(Level.WARNING, "Expected " + JSON_MESSAGE_ID + + " or " + JSON_ERROR + " found: " + responseBody); + return null; + } + } 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(); + failedIds = new ArrayList<>(); + for (int i = 0; i < jFailedIds.size(); i++) { + failedIds.add(jFailedIds.get(i).getAsString()); + } + } + resultBuilder.success(success).failure(failure) + .failedRegistrationIds(failedIds); + } else { + logger.warning("Unrecognized response: " + responseBody); + throw newIoException(responseBody, new Exception( + "Unrecognized response.")); + } + return resultBuilder.build(); + } catch (CustomParserException e) { + throw newIoException(responseBody, e); + } + } - /** - * Sends a message to many devices, retrying in case of unavailability. - * - *

- * Note: this method uses exponential back-off to retry in - * case of service unavailability and hence could block the calling thread - * for many seconds. - * - * @param message - * message to be sent. - * @param regIds - * registration id of the devices that will receive the message. - * @param retries - * number of retries in case of service unavailability errors. - * - * @return combined result of all requests made. - * - * @throws IllegalArgumentException - * if registrationIds is {@literal null} or empty. - * @throws InvalidRequestException - * if GCM didn't returned a 200 or 503 status. - * @throws IOException - * if message could not be sent. - */ - public MulticastResult send(Message message, List regIds, - int retries) throws IOException { - int attempt = 0; - MulticastResult multicastResult; - int backoff = BACKOFF_INITIAL_DELAY; - // Map of results by registration id, it will be updated after each - // attempt - // to send the messages - Map results = new HashMap<>(); - List unsentRegIds = new ArrayList<>(regIds); - boolean tryAgain; - List multicastIds = new ArrayList<>(); - do { - multicastResult = null; - attempt++; - if (logger.isLoggable(Level.FINE)) { - logger.fine("Attempt #" + attempt + " to send message " - + message + " to regIds " + unsentRegIds); - } - try { - multicastResult = sendNoRetry(message, unsentRegIds); - } catch (IOException e) { - // no need for WARNING since exception might be already logged - logger.log(Level.FINEST, "IOException on attempt " + attempt, e); - } - if (multicastResult != null) { - long multicastId = multicastResult.getMulticastId(); - logger.fine("multicast_id on attempt # " + attempt + ": " - + multicastId); - multicastIds.add(multicastId); - unsentRegIds = updateStatus(unsentRegIds, results, - multicastResult); - tryAgain = !unsentRegIds.isEmpty() && attempt <= retries; - } else { - tryAgain = attempt <= retries; - } - if (tryAgain) { - int sleepTime = backoff / 2 + random.nextInt(backoff); - sleep(sleepTime); - if (2 * backoff < MAX_BACKOFF_DELAY) { - backoff *= 2; - } - } - } 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"); - } - // calculate summary - int success = 0, failure = 0, canonicalIds = 0; - for (Result result : results.values()) { - if (result.getMessageId() != null) { - success++; - if (result.getCanonicalRegistrationId() != null) { - canonicalIds++; - } - } else { - failure++; - } - } - // build a new object with the overall result - long multicastId = multicastIds.remove(0); - 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) { - Result result = results.get(regId); - builder.addResult(result); - } - return builder.build(); - } + /** + * Sends a message to many devices, retrying in case of unavailability. + * + *

+ * Note: this method uses exponential back-off to retry in + * case of service unavailability and hence could block the calling thread + * for many seconds. + * + * @param message + * message to be sent. + * @param regIds + * registration id of the devices that will receive the message. + * @param retries + * number of retries in case of service unavailability errors. + * + * @return combined result of all requests made. + * + * @throws IllegalArgumentException + * if registrationIds is {@literal null} or empty. + * @throws InvalidRequestException + * if GCM didn't returned a 200 or 503 status. + * @throws IOException + * if message could not be sent. + */ + public MulticastResult send(Message message, List regIds, + int retries) throws IOException { + int attempt = 0; + MulticastResult multicastResult; + int backoff = BACKOFF_INITIAL_DELAY; + // Map of results by registration id, it will be updated after each + // attempt + // to send the messages + Map results = new HashMap<>(); + List unsentRegIds = new ArrayList<>(regIds); + boolean tryAgain; + List multicastIds = new ArrayList<>(); + do { + multicastResult = null; + attempt++; + if (logger.isLoggable(Level.FINE)) { + logger.fine("Attempt #" + attempt + " to send message " + + message + " to regIds " + unsentRegIds); + } + try { + multicastResult = sendNoRetry(message, unsentRegIds); + } catch (IOException e) { + // no need for WARNING since exception might be already logged + logger.log(Level.FINEST, "IOException on attempt " + attempt, e); + } + if (multicastResult != null) { + long multicastId = multicastResult.getMulticastId(); + logger.fine("multicast_id on attempt # " + attempt + ": " + + multicastId); + multicastIds.add(multicastId); + unsentRegIds = updateStatus(unsentRegIds, results, + multicastResult); + tryAgain = !unsentRegIds.isEmpty() && attempt <= retries; + } else { + tryAgain = attempt <= retries; + } + if (tryAgain) { + int sleepTime = backoff / 2 + random.nextInt(backoff); + sleep(sleepTime); + if (2 * backoff < MAX_BACKOFF_DELAY) { + backoff *= 2; + } + } + } 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"); + } + // calculate summary + int success = 0, failure = 0, canonicalIds = 0; + for (Result result : results.values()) { + if (result.getMessageId() != null) { + success++; + if (result.getCanonicalRegistrationId() != null) { + canonicalIds++; + } + } else { + failure++; + } + } + // build a new object with the overall result + long multicastId = multicastIds.remove(0); + 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) { + Result result = results.get(regId); + builder.addResult(result); + } + return builder.build(); + } - /** - * Updates the status of the messages sent to devices and the list of - * devices that should be retried. - * - * @param unsentRegIds - * list of devices that are still pending an update. - * @param allResults - * map of status that will be updated. - * @param multicastResult - * result of the last multicast sent. - * - * @return updated version of devices that should be retried. - */ - 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); - } - List newUnsentRegIds = new ArrayList<>(); - for (int i = 0; i < unsentRegIds.size(); i++) { - String regId = unsentRegIds.get(i); - 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))) { - newUnsentRegIds.add(regId); - } - } - return newUnsentRegIds; - } + /** + * Updates the status of the messages sent to devices and the list of + * devices that should be retried. + * + * @param unsentRegIds + * list of devices that are still pending an update. + * @param allResults + * map of status that will be updated. + * @param multicastResult + * result of the last multicast sent. + * + * @return updated version of devices that should be retried. + */ + 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); + } + List newUnsentRegIds = new ArrayList<>(); + for (int i = 0; i < unsentRegIds.size(); i++) { + String regId = unsentRegIds.get(i); + 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))) { + newUnsentRegIds.add(regId); + } + } + return newUnsentRegIds; + } - /** - * Sends a message without retrying in case of service unavailability. See - * {@link #send(Message, List, int)} for more info. - * - * @return multicast results if the message was sent successfully, - * {@literal null} if it failed but could be retried. - * - * @throws IllegalArgumentException - * if registrationIds is {@literal null} or empty. - * @throws InvalidRequestException - * if GCM didn't returned a 200 status. - * @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"); - } - Map jsonRequest = new HashMap<>(); - messageToMap(message, jsonRequest); - jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); - Map responseMap = makeGcmHttpRequest(jsonRequest); - String responseBody = null; - if (responseMap.get("responseBody") != null) { - responseBody = (String) responseMap.get("responseBody"); - } - if (responseBody == null) { - return null; - } - - JsonParser parser = new JsonParser(); - JsonObject jsonResponse; - try { - jsonResponse = (JsonObject) parser.parse(responseBody); - 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); - @SuppressWarnings("unchecked") - 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 error = (String) jsonResult.get(JSON_ERROR); - Result result = new Result.Builder().messageId(messageId) - .canonicalRegistrationId(canonicalRegId) - .errorCode(error).build(); - builder.addResult(result); - } - } - return builder.build(); - } catch (CustomParserException e) { - throw newIoException(responseBody, e); - } - } + /** + * Sends a message without retrying in case of service unavailability. See + * {@link #send(Message, List, int)} for more info. + * + * @return multicast results if the message was sent successfully, + * {@literal null} if it failed but could be retried. + * + * @throws IllegalArgumentException + * if registrationIds is {@literal null} or empty. + * @throws InvalidRequestException + * if GCM didn't returned a 200 status. + * @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"); + } + Map jsonRequest = new HashMap<>(); + messageToMap(message, jsonRequest); + jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); + Map responseMap = makeGcmHttpRequest(jsonRequest); + String responseBody = null; + if (responseMap.get("responseBody") != null) { + responseBody = (String) responseMap.get("responseBody"); + } + if (responseBody == null) { + return null; + } + + JsonParser parser = new JsonParser(); + JsonObject jsonResponse; + try { + jsonResponse = (JsonObject) parser.parse(responseBody); + 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); + @SuppressWarnings("unchecked") + 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 error = (String) jsonResult.get(JSON_ERROR); + Result result = new Result.Builder().messageId(messageId) + .canonicalRegistrationId(canonicalRegId) + .errorCode(error).build(); + builder.addResult(result); + } + } + return builder.build(); + } catch (CustomParserException e) { + throw newIoException(responseBody, e); + } + } - private Map makeGcmHttpRequest(Map jsonRequest) - throws InvalidRequestException { - String requestBody = new Gson().toJson(jsonRequest); - logger.finest("JSON request: " + requestBody); - HttpURLConnection conn; - int status; - try { - conn = post(getEndpoint(), "application/json", requestBody); - status = conn.getResponseCode(); - } catch (IOException e) { - logger.log(Level.FINE, "IOException posting to GCM", e); - return null; - } - String responseBody; - if (status != 200) { - try { - responseBody = getAndClose(conn.getErrorStream()); - logger.finest("JSON error response: " + responseBody); - } catch (IOException e) { - // ignore the exception since it will thrown an - // InvalidRequestException - // anyways - responseBody = "N/A"; - logger.log(Level.FINE, "Exception reading response: ", e); - } - throw new InvalidRequestException(status, responseBody); - } - try { - responseBody = getAndClose(conn.getInputStream()); - } catch (IOException e) { - logger.log(Level.WARNING, "IOException reading response", e); - return null; - } - logger.finest("JSON response: " + responseBody); - Map map = new HashMap<>(); - map.put("responseBody", responseBody); - map.put("status", status); - - return map; - } + private Map makeGcmHttpRequest(Map jsonRequest) + throws InvalidRequestException { + String requestBody = new Gson().toJson(jsonRequest); + logger.finest("JSON request: " + requestBody); + HttpURLConnection conn; + int status; + try { + conn = post(getEndpoint(), "application/json", requestBody); + status = conn.getResponseCode(); + } catch (IOException e) { + logger.log(Level.FINE, "IOException posting to GCM", e); + return null; + } + String responseBody; + if (status != 200) { + try { + responseBody = getAndClose(conn.getErrorStream()); + logger.finest("JSON error response: " + responseBody); + } catch (IOException e) { + // ignore the exception since it will thrown an + // InvalidRequestException + // anyways + responseBody = "N/A"; + logger.log(Level.FINE, "Exception reading response: ", e); + } + throw new InvalidRequestException(status, responseBody); + } + try { + responseBody = getAndClose(conn.getInputStream()); + } catch (IOException e) { + logger.log(Level.WARNING, "IOException reading response", e); + return null; + } + logger.finest("JSON response: " + responseBody); + Map map = new HashMap<>(); + map.put("responseBody", responseBody); + map.put("status", status); + + return map; + } - /** - * Populate Map with message. - * - * @param message - * Message used to populate Map. - * @param mapRequest - * Map populated by Message. - */ - private void messageToMap(Message message, Map mapRequest) { - if (message == null || mapRequest == null) { - return; - } - setJsonField(mapRequest, PARAM_PRIORITY, message.getPriority()); - 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_DRY_RUN, message.isDryRun()); - Map payload = message.getData(); - if (!payload.isEmpty()) { - mapRequest.put(JSON_PAYLOAD, payload); - } - if (message.getNotification() != null) { - Notification notification = message.getNotification(); - Map nMap = new HashMap<>(); - if (notification.getBadge() != null) { - 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_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()); - mapRequest.put(JSON_NOTIFICATION, nMap); - } - } + /** + * Populate Map with message. + * + * @param message + * Message used to populate Map. + * @param mapRequest + * Map populated by Message. + */ + private void messageToMap(Message message, Map mapRequest) { + if (message == null || mapRequest == null) { + return; + } + setJsonField(mapRequest, PARAM_PRIORITY, message.getPriority()); + 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_DRY_RUN, message.isDryRun()); + Map payload = message.getData(); + if (!payload.isEmpty()) { + mapRequest.put(JSON_PAYLOAD, payload); + } + if (message.getNotification() != null) { + Notification notification = message.getNotification(); + Map nMap = new HashMap<>(); + if (notification.getBadge() != null) { + 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_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()); + mapRequest.put(JSON_NOTIFICATION, nMap); + } + } - private IOException newIoException(String responseBody, Exception e) { - // log exception, as IOException constructor that takes a message and - // cause - // is only available on Java 6 - String msg = "Error parsing JSON response (" + responseBody + ")"; - logger.log(Level.WARNING, msg, e); - return new IOException(msg + ":" + e); - } + private IOException newIoException(String responseBody, Exception e) { + // log exception, as IOException constructor that takes a message and + // cause + // is only available on Java 6 + String msg = "Error parsing JSON response (" + responseBody + ")"; + logger.log(Level.WARNING, msg, e); + return new IOException(msg + ":" + e); + } - private static void close(Closeable closeable) { - if (closeable != null) { - try { - closeable.close(); - } catch (IOException e) { - // ignore error - logger.log(Level.FINEST, "IOException closing stream", e); - } - } - } + private static void close(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException e) { + // ignore error + logger.log(Level.FINEST, "IOException closing stream", e); + } + } + } - /** - * Sets a JSON field, but only if the value is not {@literal null}. - */ - private void setJsonField(Map json, String field, - Object value) { - if (value != null) { - json.put(field, value); - } - } + /** + * Sets a JSON field, but only if the value is not {@literal null}. + */ + private void setJsonField(Map json, String field, + Object value) { + if (value != null) { + json.put(field, value); + } + } - 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); - } - return (Number) value; - } + 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); + } + return (Number) value; + } - class CustomParserException extends RuntimeException { - CustomParserException(String message) { - super(message); - } - } + class CustomParserException extends RuntimeException { + CustomParserException(String message) { + super(message); + } + } - /** - * Make an HTTP post to a given URL. - * - * @return HTTP response. - */ - protected HttpURLConnection post(String url, String body) - throws IOException { - return post(url, "application/x-www-form-urlencoded;charset=UTF-8", - body); - } + /** + * Make an HTTP post to a given URL. + * + * @return HTTP response. + */ + protected HttpURLConnection post(String url, String body) + throws IOException { + return post(url, "application/x-www-form-urlencoded;charset=UTF-8", + body); + } - /** - * Makes an HTTP POST request to a given endpoint. - * - *

- * Note: the returned connected should not be - * disconnected, otherwise it would kill persistent connections made using - * Keep-Alive. - * - * @param url - * endpoint to post the request. - * @param contentType - * type of request. - * @param body - * body of the request. - * - * @return the underlying connection. - * - * @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"); - } - if (!url.startsWith("https://")) { - logger.warning("URL does not use https: " + url); - } - logger.fine("Sending POST to " + url); - logger.finest("POST body: " + body); - byte[] bytes = body.getBytes(StandardCharsets.UTF_8); - HttpURLConnection conn = getConnection(url); - conn.setDoOutput(true); - conn.setUseCaches(false); - conn.setFixedLengthStreamingMode(bytes.length); - conn.setRequestMethod("POST"); - conn.setRequestProperty("Content-Type", contentType); - conn.setRequestProperty("Authorization", "key=" + key); - OutputStream out = conn.getOutputStream(); - try { - out.write(bytes); - } finally { - close(out); - } - return conn; - } + /** + * Makes an HTTP POST request to a given endpoint. + * + *

+ * Note: the returned connected should not be + * disconnected, otherwise it would kill persistent connections made using + * Keep-Alive. + * + * @param url + * endpoint to post the request. + * @param contentType + * type of request. + * @param body + * body of the request. + * + * @return the underlying connection. + * + * @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"); + } + if (!url.startsWith("https://")) { + logger.warning("URL does not use https: " + url); + } + logger.fine("Sending POST to " + url); + logger.finest("POST body: " + body); + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + HttpURLConnection conn = getConnection(url); + conn.setDoOutput(true); + conn.setUseCaches(false); + conn.setFixedLengthStreamingMode(bytes.length); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", contentType); + conn.setRequestProperty("Authorization", "key=" + key); + OutputStream out = conn.getOutputStream(); + try { + out.write(bytes); + } finally { + close(out); + } + return conn; + } - /** - * Creates a map with just one key-value pair. - */ - protected static final Map newKeyValues(String key, - String value) { - Map keyValues = new HashMap<>(1); - keyValues.put(nonNull(key), nonNull(value)); - return keyValues; - } + /** + * Creates a map with just one key-value pair. + */ + protected static final Map newKeyValues(String key, + String value) { + Map keyValues = new HashMap<>(1); + keyValues.put(nonNull(key), nonNull(value)); + return keyValues; + } - /** - * Creates a {@link StringBuilder} to be used as the body of an HTTP POST. - * - * @param name - * initial parameter for the POST. - * @param value - * initial value for that parameter. - * @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)); - } + /** + * Creates a {@link StringBuilder} to be used as the body of an HTTP POST. + * + * @param name + * initial parameter for the POST. + * @param value + * initial value for that parameter. + * @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)); + } - /** - * Adds a new parameter to the HTTP POST body. - * - * @param body - * HTTP POST body. - * @param name - * parameter's name. - * @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)); - } + /** + * Adds a new parameter to the HTTP POST body. + * + * @param body + * HTTP POST body. + * @param name + * parameter's name. + * @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)); + } - /** - * Gets an {@link HttpURLConnection} given an URL. - */ - protected HttpURLConnection getConnection(String url) throws IOException { - HttpURLConnection conn = (HttpURLConnection) new URL(url) - .openConnection(); - conn.setConnectTimeout(connectTimeout); - conn.setReadTimeout(readTimeout); - return conn; - } + /** + * Gets an {@link HttpURLConnection} given an URL. + */ + protected HttpURLConnection getConnection(String url) throws IOException { + HttpURLConnection conn = (HttpURLConnection) new URL(url) + .openConnection(); + conn.setConnectTimeout(connectTimeout); + conn.setReadTimeout(readTimeout); + return conn; + } - /** - * Convenience method to convert an InputStream to a String. - *

- * If the stream ends in a newline character, it will be stripped. - *

- * 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)); - StringBuilder content = new StringBuilder(); - String newLine; - do { - newLine = reader.readLine(); - if (newLine != null) { - content.append(newLine).append('\n'); - } - } while (newLine != null); - if (content.length() > 0) { - // strip last newline - content.setLength(content.length() - 1); - } - return content.toString(); - } + /** + * Convenience method to convert an InputStream to a String. + *

+ * If the stream ends in a newline character, it will be stripped. + *

+ * 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)); + StringBuilder content = new StringBuilder(); + String newLine; + do { + newLine = reader.readLine(); + if (newLine != null) { + content.append(newLine).append('\n'); + } + } while (newLine != null); + if (content.length() > 0) { + // strip last newline + content.setLength(content.length() - 1); + } + return content.toString(); + } - private static String getAndClose(InputStream stream) throws IOException { - try { - return getString(stream); - } finally { - if (stream != null) { - close(stream); - } - } - } + private static String getAndClose(InputStream stream) throws IOException { + try { + return getString(stream); + } finally { + if (stream != null) { + close(stream); + } + } + } - static T nonNull(T argument) { - if (argument == null) { - throw new IllegalArgumentException("argument cannot be null"); - } - return argument; - } + static T nonNull(T argument) { + if (argument == null) { + throw new IllegalArgumentException("argument cannot be null"); + } + return argument; + } - void sleep(long millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } + void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } } 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 cc730a0ec..22bb1e6bd 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 @@ -21,18 +21,18 @@ package org.apache.fineract.infrastructure.gcm.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; public class DeviceRegistrationNotFoundException extends - AbstractPlatformResourceNotFoundException { + AbstractPlatformResourceNotFoundException { - public DeviceRegistrationNotFoundException(final Long id) { - super("error.msg.device.registration.id.invalid", - "Device registration with identifier " + id + " does not exist", - id); - } + public DeviceRegistrationNotFoundException(final Long 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); - } + public DeviceRegistrationNotFoundException(final Long clientId, String value) { + super("error.msg.device.registration." + value + ".invalid", + "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 2194b43d8..03b5eb25b 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 @@ -27,40 +27,40 @@ import java.io.IOException; */ public final class InvalidRequestException extends IOException { - private final int status; - private final String description; + private final int status; + private final String description; - public InvalidRequestException(int status) { - this(status, null); - } + public InvalidRequestException(int status) { + this(status, null); + } - public InvalidRequestException(int status, String description) { - super(getMessage(status, description)); - this.status = status; - this.description = description; - } + public InvalidRequestException(int status, String description) { + super(getMessage(status, description)); + this.status = status; + this.description = description; + } - private static String getMessage(int status, String description) { - StringBuilder base = new StringBuilder("HTTP Status Code: ") - .append(status); - if (description != null) { - base.append("(").append(description).append(")"); - } - return base.toString(); - } + private static String getMessage(int status, String description) { + StringBuilder base = new StringBuilder("HTTP Status Code: ") + .append(status); + if (description != null) { + base.append("(").append(description).append(")"); + } + return base.toString(); + } - /** - * Gets the HTTP Status Code. - */ - public int getHttpStatusCode() { - return status; - } + /** + * Gets the HTTP Status Code. + */ + public int getHttpStatusCode() { + return status; + } - /** - * Gets the error description. - */ - public String getDescription() { - return description; - } + /** + * Gets the error description. + */ + public String getDescription() { + return description; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationReadPlatformService.java index 1b4ec42c8..53dcd3d8f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationReadPlatformService.java @@ -24,9 +24,9 @@ import org.apache.fineract.infrastructure.gcm.domain.DeviceRegistrationData; public interface DeviceRegistrationReadPlatformService { - Collection retrieveAllDeviceRegiistrations(); + Collection retrieveAllDeviceRegiistrations(); - DeviceRegistrationData retrieveDeviceRegiistration(Long id); + DeviceRegistrationData retrieveDeviceRegiistration(Long id); - DeviceRegistrationData retrieveDeviceRegiistrationByClientId(Long clientId); + DeviceRegistrationData retrieveDeviceRegiistrationByClientId(Long clientId); } 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 8c64fe3b3..ddb782e81 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 @@ -37,89 +37,89 @@ import org.springframework.stereotype.Service; @Service public class DeviceRegistrationReadPlatformServiceImpl implements - DeviceRegistrationReadPlatformService { + DeviceRegistrationReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public DeviceRegistrationReadPlatformServiceImpl( - final PlatformSecurityContext context, - final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + 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; + 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(" from client_device_registration cdr "); - sqlBuilder.append(" left join m_client c on c.id = cdr.client_id "); - this.schema = sqlBuilder.toString(); - } + 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(" from client_device_registration cdr "); + sqlBuilder.append(" left join m_client c on c.id = cdr.client_id "); + this.schema = sqlBuilder.toString(); + } - public String schema() { - return this.schema; - } + public String schema() { + return this.schema; + } - @Override - public DeviceRegistrationData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + @Override + 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 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()); - } - } + final Long id = JdbcSupport.getLong(rs, "id"); + 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()); + } + } - @Override - public Collection retrieveAllDeviceRegiistrations() { - this.context.authenticatedUser(); - DeviceRegistrationDataMapper drm = new DeviceRegistrationDataMapper(); - String sql = "select " + drm.schema(); - return this.jdbcTemplate.query(sql, drm, new Object[] {}); - } + @Override + public Collection retrieveAllDeviceRegiistrations() { + this.context.authenticatedUser(); + DeviceRegistrationDataMapper drm = new DeviceRegistrationDataMapper(); + String sql = "select " + drm.schema(); + return this.jdbcTemplate.query(sql, drm, new Object[] {}); + } - @Override - public DeviceRegistrationData retrieveDeviceRegiistration(Long id) { - try { - this.context.authenticatedUser(); - DeviceRegistrationDataMapper drm = new DeviceRegistrationDataMapper(); - String sql = "select " + drm.schema() + " where cdr.id = ? "; - return this.jdbcTemplate.queryForObject(sql, drm, - new Object[] { id }); - } catch (final EmptyResultDataAccessException e) { - throw new DeviceRegistrationNotFoundException(id); - } - } + @Override + public DeviceRegistrationData retrieveDeviceRegiistration(Long id) { + try { + this.context.authenticatedUser(); + DeviceRegistrationDataMapper drm = new DeviceRegistrationDataMapper(); + String sql = "select " + drm.schema() + " where cdr.id = ? "; + return this.jdbcTemplate.queryForObject(sql, drm, + new Object[] { id }); + } catch (final EmptyResultDataAccessException e) { + throw new DeviceRegistrationNotFoundException(id); + } + } - @Override - 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 }); - } catch (final EmptyResultDataAccessException e) { - throw new DeviceRegistrationNotFoundException(clientId, "client"); - } - } + @Override + 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 }); + } 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 52653eaa2..04e1d6bbc 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 @@ -36,83 +36,83 @@ import org.springframework.transaction.annotation.Transactional; @Service public class DeviceRegistrationWritePlatformServiceImpl implements - DeviceRegistrationWritePlatformService { + DeviceRegistrationWritePlatformService { - private final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository; - private final ClientRepositoryWrapper clientRepositoryWrapper; - private final PlatformSecurityContext context; + private final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository; + private final ClientRepositoryWrapper clientRepositoryWrapper; + private final PlatformSecurityContext context; - @Autowired - public DeviceRegistrationWritePlatformServiceImpl( - final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository, - final ClientRepositoryWrapper clientRepositoryWrapper, - final PlatformSecurityContext context) { - this.deviceRegistrationRepository = deviceRegistrationRepository; - this.clientRepositoryWrapper = clientRepositoryWrapper; - this.context = context; - } + @Autowired + public DeviceRegistrationWritePlatformServiceImpl( + final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository, + final ClientRepositoryWrapper clientRepositoryWrapper, + final PlatformSecurityContext context) { + this.deviceRegistrationRepository = deviceRegistrationRepository; + this.clientRepositoryWrapper = clientRepositoryWrapper; + this.context = context; + } - @Transactional - @Override - public DeviceRegistration registerDevice(Long clientId, - String registrationId) { - this.context.authenticatedUser(); - Client client = this.clientRepositoryWrapper - .findOneWithNotFoundDetection(clientId); - try { - 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); - return null; - } catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); - handleDataIntegrityIssues(registrationId, throwable, dve); - return null; - } catch (final Exception dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); - handleDataIntegrityIssues(registrationId, throwable, dve); - return null; - } + @Transactional + @Override + public DeviceRegistration registerDevice(Long clientId, + String registrationId) { + this.context.authenticatedUser(); + Client client = this.clientRepositoryWrapper + .findOneWithNotFoundDetection(clientId); + try { + 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); + return null; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); + handleDataIntegrityIssues(registrationId, throwable, dve); + return null; + } catch (final Exception dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); + handleDataIntegrityIssues(registrationId, throwable, dve); + return null; + } - } + } - private void handleDataIntegrityIssues(final String registrationId, - final Throwable realCause, - @SuppressWarnings("unused") final Exception dve) { + 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); - } + 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.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); - deviceRegistration.setClient(client); - deviceRegistration.setRegistrationId(registrationId); - deviceRegistration.setUpdatedOnDate(DateUtils - .getLocalDateTimeOfTenant().toDate()); - return deviceRegistration; - } + @Override + 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()); + return deviceRegistration; + } @Override public void deleteDeviceRegistration(Long id) { 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 dda2ef7ef..d1957bbda 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 @@ -46,88 +46,88 @@ import org.springframework.stereotype.Service; @Service public class NotificationSenderService { - private final DeviceRegistrationRepositoryWrapper deviceRegistrationRepositoryWrapper; - private final SmsMessageRepository smsMessageRepository; - private ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService; + private final DeviceRegistrationRepositoryWrapper deviceRegistrationRepositoryWrapper; + private final SmsMessageRepository smsMessageRepository; + private ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService; - @Autowired - public NotificationSenderService( - final DeviceRegistrationRepositoryWrapper deviceRegistrationRepositoryWrapper, - final SmsMessageRepository smsMessageRepository, final ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService) { - this.deviceRegistrationRepositoryWrapper = deviceRegistrationRepositoryWrapper; - this.smsMessageRepository = smsMessageRepository; - this.propertiesReadPlatformService = propertiesReadPlatformService; - } + @Autowired + public NotificationSenderService( + final DeviceRegistrationRepositoryWrapper deviceRegistrationRepositoryWrapper, + final SmsMessageRepository smsMessageRepository, final ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService) { + this.deviceRegistrationRepositoryWrapper = deviceRegistrationRepositoryWrapper; + this.smsMessageRepository = smsMessageRepository; + this.propertiesReadPlatformService = propertiesReadPlatformService; + } - public void sendNotification(List smsMessages) { - Map> notificationByEachClient = getNotificationListByClient(smsMessages); - for (Map.Entry> entry : notificationByEachClient - .entrySet()) { - this.sendNotifiaction(entry.getKey(), entry.getValue()); - } - } + public void sendNotification(List smsMessages) { + Map> notificationByEachClient = getNotificationListByClient(smsMessages); + for (Map.Entry> entry : notificationByEachClient + .entrySet()) { + this.sendNotifiaction(entry.getKey(), entry.getValue()); + } + } - public Map> getNotificationListByClient( - List smsMessages) { - Map> notificationByEachClient = new HashMap<>(); - for (SmsMessage smsMessage : smsMessages) { - if (smsMessage.getClient() != null) { - Long clientId = smsMessage.getClient().getId(); - if (notificationByEachClient.containsKey(clientId)) { - notificationByEachClient.get(clientId).add(smsMessage); - } else { - List msgList = new ArrayList<>( - Arrays.asList(smsMessage)); - notificationByEachClient.put(clientId, msgList); - } + public Map> getNotificationListByClient( + List smsMessages) { + Map> notificationByEachClient = new HashMap<>(); + for (SmsMessage smsMessage : smsMessages) { + if (smsMessage.getClient() != null) { + Long clientId = smsMessage.getClient().getId(); + if (notificationByEachClient.containsKey(clientId)) { + notificationByEachClient.get(clientId).add(smsMessage); + } else { + List msgList = new ArrayList<>( + Arrays.asList(smsMessage)); + notificationByEachClient.put(clientId, msgList); + } - } - } - return notificationByEachClient; - } + } + } + return notificationByEachClient; + } - public void sendNotifiaction(Long clientId, List smsList) { + public void sendNotifiaction(Long clientId, List smsList) { - DeviceRegistration deviceRegistration = this.deviceRegistrationRepositoryWrapper - .findDeviceRegistrationByClientId(clientId); - NotificationConfigurationData notificationConfigurationData = this.propertiesReadPlatformService.getNotificationConfiguration(); - String registrationId = null; - if (deviceRegistration != null) { - registrationId = deviceRegistration.getRegistrationId(); - } - for (SmsMessage smsMessage : smsList) { - try { - Notification notification = new Notification.Builder( - GcmConstants.defaultIcon).title(GcmConstants.title) - .body(smsMessage.getMessage()).build(); - Builder b = new Builder(); - b.notification(notification); - b.dryRun(false); - b.contentAvailable(true); - b.timeToLive(GcmConstants.TIME_TO_LIVE); - b.priority(Priority.HIGH); - b.delayWhileIdle(true); - Message msg = b.build(); - Sender s = new Sender(notificationConfigurationData.getServerKey(),notificationConfigurationData.getFcmEndPoint()); - Result res; + DeviceRegistration deviceRegistration = this.deviceRegistrationRepositoryWrapper + .findDeviceRegistrationByClientId(clientId); + NotificationConfigurationData notificationConfigurationData = this.propertiesReadPlatformService.getNotificationConfiguration(); + String registrationId = null; + if (deviceRegistration != null) { + registrationId = deviceRegistration.getRegistrationId(); + } + for (SmsMessage smsMessage : smsList) { + try { + Notification notification = new Notification.Builder( + GcmConstants.defaultIcon).title(GcmConstants.title) + .body(smsMessage.getMessage()).build(); + Builder b = new Builder(); + b.notification(notification); + b.dryRun(false); + b.contentAvailable(true); + b.timeToLive(GcmConstants.TIME_TO_LIVE); + b.priority(Priority.HIGH); + b.delayWhileIdle(true); + Message msg = b.build(); + 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()); - smsMessage.setDeliveredOnDate(DateUtils.getLocalDateOfTenant().toDate()); - } else if (res.getFailure() != null && res.getFailure()>0) { - smsMessage.setStatusType(SmsMessageStatusType.FAILED - .getValue()); - } - } catch (IOException e) { - smsMessage - .setStatusType(SmsMessageStatusType.FAILED.getValue()); - } - } + res = s.send(msg, registrationId, 3); + 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()); + } + } catch (IOException e) { + smsMessage + .setStatusType(SmsMessageStatusType.FAILED.getValue()); + } + } - this.smsMessageRepository.saveAll(smsList); + this.smsMessageRepository.saveAll(smsList); - } + } } 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 0712a915c..7c8b81cc5 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 @@ -57,135 +57,135 @@ import org.springframework.stereotype.Component; @Scope("singleton") @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; - private final HookReadPlatformService readPlatformService; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final ApiRequestParameterHelper apiRequestParameterHelper; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final PlatformSecurityContext context; + private final HookReadPlatformService readPlatformService; + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final ApiRequestParameterHelper apiRequestParameterHelper; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - @Autowired - public HookApiResource( - final PlatformSecurityContext context, - final HookReadPlatformService readPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { - this.context = context; - this.readPlatformService = readPlatformService; - this.toApiJsonSerializer = toApiJsonSerializer; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - } + @Autowired + public HookApiResource( + final PlatformSecurityContext context, + final HookReadPlatformService readPlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final ApiRequestParameterHelper apiRequestParameterHelper, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + this.context = context; + this.readPlatformService = readPlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + } - @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")}) - public String retrieveHooks(@Context final UriInfo uriInfo) { + @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")}) + 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) { + @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) { - 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); + 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()); - } - return this.toApiJsonSerializer.serialize(settings, hook, - RESPONSE_DATA_PARAMETERS); - } + if (settings.isTemplate()) { + 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); + } - @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)}) - public String template(@Context final UriInfo uriInfo) { + @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)}) + 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)}) - public String createHook(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @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)}) + 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); - } + return this.toApiJsonSerializer.serialize(result); + } - @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)}) - public String updateHook(@PathParam("hookId") @ApiParam(value = "hookId") final Long hookId, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @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)}) + 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); - } + return this.toApiJsonSerializer.serialize(result); + } - @DELETE - @Path("{hookId}") - @ApiOperation(value = "Delete a Hook", notes = "Deletes a hook.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.DeleteHookResponse.class)}) - public String deleteHook(@PathParam("hookId") @ApiParam(value = "hookId") final Long hookId) { + @DELETE + @Path("{hookId}") + @ApiOperation(value = "Delete a Hook", notes = "Deletes a hook.") + @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); - } + return this.toApiJsonSerializer.serialize(result); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Entity.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Entity.java index fe7bdf8ea..f63d24e00 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Entity.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Entity.java @@ -24,20 +24,20 @@ import java.util.List; @SuppressWarnings("unused") public class Entity implements Serializable { - private String name; + private String name; - private List actions; + private List actions; - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - public void setActions(final List actions) { - this.actions = actions; - } + public void setActions(final List actions) { + this.actions = actions; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } } 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 8ecc9c3e4..97786e791 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 @@ -22,25 +22,25 @@ import java.io.Serializable; public class Event implements Serializable { - private final String actionName; - private final String entityName; + private final String actionName; + private final String entityName; - public static Event instance(final String actionName, - final String entityName) { - return new Event(actionName, entityName); - } + public static Event instance(final String actionName, + final String entityName) { + return new Event(actionName, entityName); + } - private Event(final String actionName, final String entityName) { - this.actionName = actionName; - this.entityName = entityName; - } + private Event(final String actionName, final String entityName) { + this.actionName = actionName; + this.entityName = entityName; + } - public String getActionName() { - return this.actionName; - } + public String getActionName() { + return this.actionName; + } - public String getEntityName() { - return this.entityName; - } + public String getEntityName() { + return this.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 01d07c88a..699c8f248 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 @@ -32,78 +32,78 @@ import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ResultSetExtractor; public class EventResultSetExtractor implements - ResultSetExtractor> { + ResultSetExtractor> { - @Override - public List extractData(final ResultSet rs) throws SQLException, - DataAccessException { - final List groupings = new ArrayList<>(); + @Override + public List extractData(final ResultSet rs) throws SQLException, + DataAccessException { + final List groupings = new ArrayList<>(); - final Map>> groupToEntityMapping = new HashMap<>(); - Map> entityToActionMapping = new HashMap<>(); + final Map>> groupToEntityMapping = new HashMap<>(); + Map> entityToActionMapping = new HashMap<>(); - while (rs.next()) { - 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); - List actions = entityToActionMapping.get(entityName); + while (rs.next()) { + 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); + List actions = entityToActionMapping.get(entityName); - if (entities == null) { - entityToActionMapping = new HashMap<>(); - } + if (entities == null) { + entityToActionMapping = new HashMap<>(); + } - if (actions == null) { - actions = new ArrayList<>(); - } - actions.add(actionName); - entityToActionMapping.put(entityName, actions); + if (actions == null) { + actions = new ArrayList<>(); + } + actions.add(actionName); + entityToActionMapping.put(entityName, actions); - if (entities == null) { - entities = new HashMap<>(); - } - entities.putAll(entityToActionMapping); - groupToEntityMapping.put(groupingName, entities); - } + if (entities == null) { + entities = new HashMap<>(); + } + entities.putAll(entityToActionMapping); + groupToEntityMapping.put(groupingName, entities); + } - 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()) { - final List actions = new ArrayList<>(); - final Entity entity = new Entity(); - entity.setName(entityEntry.getKey()); - for (final String action : entityEntry.getValue()) { - actions.add(action); - } - Collections.sort(actions); - entity.setActions(actions); - entities.add(entity); - } + 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()) { + final List actions = new ArrayList<>(); + final Entity entity = new Entity(); + entity.setName(entityEntry.getKey()); + for (final String action : entityEntry.getValue()) { + actions.add(action); + } + Collections.sort(actions); + entity.setActions(actions); + entities.add(entity); + } - Collections.sort(entities, new Comparator() { - @Override - public int compare(final Entity entity1, final Entity entity2) { - return entity1.getName().compareTo(entity2.getName()); - } - }); - group.setEntities(entities); - groupings.add(group); - } + Collections.sort(entities, new Comparator() { + @Override + public int compare(final Entity entity1, final Entity entity2) { + return entity1.getName().compareTo(entity2.getName()); + } + }); + group.setEntities(entities); + groupings.add(group); + } - Collections.sort(groupings, new Comparator() { - @Override - public int compare(final Grouping grouping1, - final Grouping grouping2) { - return grouping1.getName().compareTo(grouping2.getName()); - } - }); + Collections.sort(groupings, new Comparator() { + @Override + public int compare(final Grouping grouping1, + final Grouping grouping2) { + return grouping1.getName().compareTo(grouping2.getName()); + } + }); - return groupings; - } + return groupings; + } } 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 444e49de4..3fe03e64d 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 @@ -23,43 +23,43 @@ import java.io.Serializable; @SuppressWarnings("unused") public class Field implements Serializable { - private final String fieldName; - private final String fieldValue; - private final String fieldType; - private final Boolean optional; - private final String placeholder; + private final String fieldName; + private final String fieldValue; + private final String fieldType; + private final Boolean optional; + private final String placeholder; - public static Field fromConfig(final String fieldName, - final String fieldValue) { - return new Field(null, fieldName, fieldValue, null, null); - } + 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) { - return new Field(fieldType, fieldName, null, optional, 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, - final String placeholder) { - this.fieldType = fieldType; - this.fieldName = fieldName; - this.fieldValue = fieldValue; - this.optional = optional; - this.placeholder = placeholder; - } + private Field(final String fieldType, final String fieldName, + final String fieldValue, final Boolean optional, + final String placeholder) { + this.fieldType = fieldType; + this.fieldName = fieldName; + this.fieldValue = fieldValue; + this.optional = optional; + this.placeholder = placeholder; + } - public String getFieldName() { - return this.fieldName; - } + public String getFieldName() { + return this.fieldName; + } - public String getFieldValue() { - return this.fieldValue; - } + public String getFieldValue() { + return this.fieldValue; + } - public String getFieldType() { - return this.fieldType; - } + public String getFieldType() { + return this.fieldType; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Grouping.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Grouping.java index 416fe7b20..1892459ed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Grouping.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Grouping.java @@ -24,20 +24,20 @@ import java.util.List; @SuppressWarnings("unused") public class Grouping implements Serializable { - private String name; + private String name; - private List entities; + private List entities; - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - public void setEntities(final List entities) { - this.entities = entities; - } + public void setEntities(final List entities) { + this.entities = entities; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } } 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 01aeadc0a..f588426e2 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 @@ -24,28 +24,28 @@ import java.util.List; @SuppressWarnings("unused") public class HookTemplateData implements Serializable { - private final Long id; - private final String name; + private final Long id; + private final String name; - // associations - private final List schema; + // associations + private final List schema; - public static HookTemplateData instance(final Long id, final String name, - final List schema) { - return new HookTemplateData(id, name, 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) { - this.id = id; - this.name = name; + private HookTemplateData(final Long id, final String name, + final List schema) { + this.id = id; + this.name = name; - // associations - this.schema = schema; - } + // associations + this.schema = schema; + } - public Long getServiceId() { - return this.id; - } + public Long getServiceId() { + return this.id; + } } 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 410fa5539..8b31c9021 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 @@ -30,56 +30,56 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_hook_configuration") public class HookConfiguration extends AbstractPersistableCustom { - @ManyToOne(optional = false) - @JoinColumn(name = "hook_id", referencedColumnName = "id", nullable = false) - private Hook hook; + @ManyToOne(optional = false) + @JoinColumn(name = "hook_id", referencedColumnName = "id", nullable = false) + private Hook hook; - @Column(name = "field_type", nullable = false, length = 20) - private String fieldType; + @Column(name = "field_type", nullable = false, length = 20) + private String fieldType; - @Column(name = "field_name", nullable = false, length = 100) - private String fieldName; + @Column(name = "field_name", nullable = false, length = 100) + private String fieldName; - @Column(name = "field_value", nullable = false, length = 100) - private String fieldValue; + @Column(name = "field_value", nullable = false, length = 100) + private 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) { - return new HookConfiguration(hook, fieldType, fieldName, 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) { + return new HookConfiguration(hook, fieldType, fieldName, fieldValue); + } - protected HookConfiguration() { - // - } + protected HookConfiguration() { + // + } - private HookConfiguration(final Hook hook, final String fieldType, - final String fieldName, final String fieldValue) { - this.hook = hook; - this.fieldType = fieldType; - this.fieldName = fieldName; - this.fieldValue = fieldValue; - } + private HookConfiguration(final Hook hook, final String fieldType, + final String fieldName, final String fieldValue) { + this.hook = hook; + this.fieldType = fieldType; + this.fieldName = fieldName; + this.fieldValue = fieldValue; + } - public String getFieldName() { - return this.fieldName; - } + public String getFieldName() { + return this.fieldName; + } - public String getFieldType() { - return this.fieldType; - } + public String getFieldType() { + return this.fieldType; + } - public String getFieldValue() { - return this.fieldValue; - } + public String getFieldValue() { + return this.fieldValue; + } - public void update(final Hook hook) { - this.hook = hook; - } + public void update(final Hook hook) { + this.hook = hook; + } } 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 f59d80ea4..814cbf2b9 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 @@ -24,11 +24,11 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface HookConfigurationRepository extends - JpaRepository, - JpaSpecificationExecutor { + 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); + @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); } 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 123b194c6..320cce367 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 @@ -26,14 +26,14 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface HookRepository extends JpaRepository, - JpaSpecificationExecutor { + 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); + @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); - @Query("select hook from Hook hook where hook.template.id = :templateId ") - Hook findOneByTemplateId(@Param("templateId") Long templateId); + @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 161dbe610..d22502bde 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 @@ -30,33 +30,33 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_hook_registered_events") public class HookResource extends AbstractPersistableCustom { - @ManyToOne(optional = false) - @JoinColumn(name = "hook_id", referencedColumnName = "id", nullable = false) - private Hook hook; + @ManyToOne(optional = false) + @JoinColumn(name = "hook_id", referencedColumnName = "id", nullable = false) + private Hook hook; - @Column(name = "entity_name", nullable = false, length = 45) - private String entityName; + @Column(name = "entity_name", nullable = false, length = 45) + private String entityName; - @Column(name = "action_name", nullable = false, length = 45) - private String actionName; + @Column(name = "action_name", nullable = false, length = 45) + private String actionName; - protected HookResource() { - // - } + protected HookResource() { + // + } - public static HookResource createNewWithoutHook(final String entityName, - final String actionName) { - return new HookResource(null, entityName, 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) { - this.hook = hook; - this.entityName = entityName; - this.actionName = actionName; - } + private HookResource(final Hook hook, final String entityName, + final String actionName) { + this.hook = hook; + this.entityName = entityName; + this.actionName = actionName; + } - public void update(final Hook hook) { - this.hook = hook; - } + public void update(final Hook hook) { + this.hook = hook; + } } 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 9294ad254..9d0077d9f 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 @@ -38,35 +38,35 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_hook_templates") public class HookTemplate extends AbstractPersistableCustom { - @Column(name = "name", nullable = false, length = 100) - private String name; + @Column(name = "name", nullable = false, length = 100) + private String name; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "template", orphanRemoval = true, fetch=FetchType.EAGER) - private Set fields = new HashSet<>(); + @OneToMany(cascade = CascadeType.ALL, mappedBy = "template", orphanRemoval = true, fetch=FetchType.EAGER) + private Set fields = new HashSet<>(); - private HookTemplate(final String name) { + private HookTemplate(final String name) { - if (StringUtils.isNotBlank(name)) { - this.name = name.trim(); - } else { - this.name = null; - } - } + if (StringUtils.isNotBlank(name)) { + this.name = name.trim(); + } else { + this.name = null; + } + } - protected HookTemplate() { + protected HookTemplate() { - } + } - public static HookTemplate fromJson(final JsonCommand command) { - final String name = command.stringValueOfParameterNamed(nameParamName); - return new HookTemplate(name); - } + public static HookTemplate fromJson(final JsonCommand command) { + final String name = command.stringValueOfParameterNamed(nameParamName); + return new HookTemplate(name); + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public Set getSchema() { - return this.fields; - } + public Set getSchema() { + return this.fields; + } } 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 c0e53a700..f13c2784e 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 @@ -24,9 +24,9 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface HookTemplateRepository extends - JpaRepository, - JpaSpecificationExecutor { + JpaRepository, + JpaSpecificationExecutor { - @Query("select template from HookTemplate template where template.name = :name") - HookTemplate findOne(@Param("name") String name); + @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/domain/Schema.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/Schema.java index 223abe59e..840930e4d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/Schema.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/Schema.java @@ -30,36 +30,36 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_hook_schema") public class Schema extends AbstractPersistableCustom { - @ManyToOne(optional = false) - @JoinColumn(name = "hook_template_id", referencedColumnName = "id", nullable = false) - private HookTemplate template; + @ManyToOne(optional = false) + @JoinColumn(name = "hook_template_id", referencedColumnName = "id", nullable = false) + private HookTemplate template; - @Column(name = "field_type", nullable = false, length = 20) - private String fieldType; + @Column(name = "field_type", nullable = false, length = 20) + private String fieldType; - @Column(name = "field_name", nullable = false, length = 100) - private String fieldName; + @Column(name = "field_name", nullable = false, length = 100) + private String fieldName; - @Column(name = "placeholder", length = 100) - private String placeholder; + @Column(name = "placeholder", length = 100) + private String placeholder; - @Column(name = "optional", nullable = false) - private boolean optional = false; + @Column(name = "optional", nullable = false) + private boolean optional = false; - public Schema() { - // - } + public Schema() { + // + } - public String getFieldName() { - return this.fieldName; - } + public String getFieldName() { + return this.fieldName; + } - public String getFieldType() { - return this.fieldType; - } + public String getFieldType() { + return this.fieldType; + } - public boolean isOptional() { - return this.optional; - } + public boolean isOptional() { + return this.optional; + } } 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 63ffd6804..7e949f01b 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 @@ -23,43 +23,43 @@ import org.springframework.context.ApplicationEvent; public class HookEvent extends ApplicationEvent { - private final String payload; + private final String payload; - private final String tenantIdentifier; + private final String tenantIdentifier; - private final AppUser appUser; + private final AppUser appUser; - private final String authToken; + private final String authToken; - public HookEvent(final HookEventSource source, final String payload, - final String tenantIdentifier, final AppUser appUser, - final String authToken) { - super(source); - this.payload = payload; - this.tenantIdentifier = tenantIdentifier; - this.appUser = appUser; - this.authToken = authToken; - } + public HookEvent(final HookEventSource source, final String payload, + final String tenantIdentifier, final AppUser appUser, + final String authToken) { + super(source); + this.payload = payload; + this.tenantIdentifier = tenantIdentifier; + this.appUser = appUser; + this.authToken = authToken; + } - public String getPayload() { - return this.payload; - } + public String getPayload() { + return this.payload; + } - @Override - public HookEventSource getSource() { - return (HookEventSource) super.source; - } + @Override + public HookEventSource getSource() { + return (HookEventSource) super.source; + } - public String getTenantIdentifier() { - return this.tenantIdentifier; - } + public String getTenantIdentifier() { + return this.tenantIdentifier; + } - public AppUser getAppUser() { - return this.appUser; - } + public AppUser getAppUser() { + return this.appUser; + } - public String getAuthToken() { - return this.authToken; - } + public String getAuthToken() { + return this.authToken; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/event/HookEventSource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/event/HookEventSource.java index 283465da2..81d8a6874 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/event/HookEventSource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/event/HookEventSource.java @@ -22,22 +22,22 @@ import java.io.Serializable; public class HookEventSource implements Serializable { - private final String entityName; + private final String entityName; - private final String actionName; + private final String actionName; - public HookEventSource(final String entityName, final String actionName) { - super(); - this.entityName = entityName; - this.actionName = actionName; - } + public HookEventSource(final String entityName, final String actionName) { + super(); + this.entityName = entityName; + this.actionName = actionName; + } - public String getEntityName() { - return this.entityName; - } + public String getEntityName() { + return this.entityName; + } - public String getActionName() { - return this.actionName; - } + public String getActionName() { + return this.actionName; + } } 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 b92fa1d5f..e9339026e 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 @@ -21,15 +21,15 @@ package org.apache.fineract.infrastructure.hooks.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; public class HookNotFoundException extends - AbstractPlatformResourceNotFoundException { + AbstractPlatformResourceNotFoundException { - public HookNotFoundException(final String name) { - super("error.msg.hook.not.found", "Hook with name `" + name - + "` does not exist", name); - } + public HookNotFoundException(final String 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); - } + public HookNotFoundException(final Long 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 3bd91f690..85adb13fd 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 @@ -21,17 +21,17 @@ package org.apache.fineract.infrastructure.hooks.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; public class HookTemplateNotFoundException extends - AbstractPlatformResourceNotFoundException { + AbstractPlatformResourceNotFoundException { - public HookTemplateNotFoundException(final String name) { - super("error.msg.template.not.found", "Template with name `" + name - + "` does not exist", name); - } + public HookTemplateNotFoundException(final String 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); - } + public HookTemplateNotFoundException(final Long 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 55cd7596a..3bd01535a 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 @@ -31,19 +31,19 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "HOOK", action = "CREATE") public class CreateHookCommandHandler implements NewCommandSourceHandler { - private final HookWritePlatformService writePlatformService; + private final HookWritePlatformService writePlatformService; - @Autowired - public CreateHookCommandHandler( - final HookWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public CreateHookCommandHandler( + final HookWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.createHook(command); - } + return this.writePlatformService.createHook(command); + } } 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 01da33bcb..02057dfbd 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 @@ -31,19 +31,19 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "HOOK", action = "DELETE") public class DeleteHookCommandHandler implements NewCommandSourceHandler { - private final HookWritePlatformService writePlatformService; + private final HookWritePlatformService writePlatformService; - @Autowired - public DeleteHookCommandHandler( - final HookWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public DeleteHookCommandHandler( + final HookWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.deleteHook(command.entityId()); - } + return this.writePlatformService.deleteHook(command.entityId()); + } } 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 500eeaeba..942bab051 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 @@ -31,20 +31,20 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "HOOK", action = "UPDATE") public class UpdateHookCommandHandler implements NewCommandSourceHandler { - private final HookWritePlatformService writePlatformService; + private final HookWritePlatformService writePlatformService; - @Autowired - public UpdateHookCommandHandler( - final HookWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public UpdateHookCommandHandler( + final HookWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @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/processor/HookProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/HookProcessor.java index 1a1bacd63..da3a2f06e 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 09e102702..5869ee72f 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 @@ -30,27 +30,27 @@ import org.springframework.stereotype.Service; @Service public class HookProcessorProvider implements ApplicationContextAware { - private ApplicationContext applicationContext; + private ApplicationContext applicationContext; - @Override - public void setApplicationContext( - final ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } + @Override + public void setApplicationContext( + final ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } - public HookProcessor getProcessor(final Hook hook) { - HookProcessor processor; - final String templateName = hook.getHookTemplate().getName(); - if (templateName.equalsIgnoreCase(smsTemplateName)) { - processor = this.applicationContext.getBean("twilioHookProcessor", - TwilioHookProcessor.class); - } else if (templateName.equals(webTemplateName)) { - processor = this.applicationContext.getBean("webHookProcessor", - WebHookProcessor.class); - } else { - processor = null; - } - return processor; - } + public HookProcessor getProcessor(final Hook hook) { + HookProcessor processor; + final String templateName = hook.getHookTemplate().getName(); + if (templateName.equalsIgnoreCase(smsTemplateName)) { + processor = this.applicationContext.getBean("twilioHookProcessor", + TwilioHookProcessor.class); + } else if (templateName.equals(webTemplateName)) { + processor = this.applicationContext.getBean("webHookProcessor", + WebHookProcessor.class); + } else { + processor = null; + } + return processor; + } } 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 3770039f2..e20bf49c5 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 @@ -42,82 +42,82 @@ import com.squareup.okhttp.OkHttpClient; @SuppressWarnings("unused") public class ProcessorHelper { - private final static Logger logger = LoggerFactory - .getLogger(ProcessorHelper.class); + private final static Logger logger = LoggerFactory + .getLogger(ProcessorHelper.class); - @SuppressWarnings("null") - public static OkHttpClient configureClient(final OkHttpClient client) { - final TrustManager[] certs = new TrustManager[] { new X509TrustManager() { + @SuppressWarnings("null") + public static OkHttpClient configureClient(final OkHttpClient client) { + final TrustManager[] certs = new TrustManager[] { new X509TrustManager() { - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } - @Override - public void checkServerTrusted(final X509Certificate[] chain, - final String authType) throws CertificateException { - } + @Override + public void checkServerTrusted(final X509Certificate[] chain, + final String authType) throws CertificateException { + } - @Override - public void checkClientTrusted(final X509Certificate[] chain, - final String authType) throws CertificateException { - } - } }; + @Override + public void checkClientTrusted(final X509Certificate[] chain, + final String authType) throws CertificateException { + } + } }; - SSLContext ctx = null; - try { - ctx = SSLContext.getInstance("TLS"); - ctx.init(null, certs, new SecureRandom()); - } catch (final java.security.GeneralSecurityException ex) { - } + SSLContext ctx = null; + try { + ctx = SSLContext.getInstance("TLS"); + ctx.init(null, certs, new SecureRandom()); + } catch (final java.security.GeneralSecurityException ex) { + } - try { - final HostnameVerifier hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(final String hostname, - final SSLSession session) { - return true; - } - }; - client.setHostnameVerifier(hostnameVerifier); - client.setSslSocketFactory(ctx.getSocketFactory()); - } catch (final Exception e) { - } + try { + final HostnameVerifier hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(final String hostname, + final SSLSession session) { + return true; + } + }; + client.setHostnameVerifier(hostnameVerifier); + client.setSslSocketFactory(ctx.getSocketFactory()); + } catch (final Exception e) { + } - return client; - } + return client; + } - public static OkHttpClient createClient() { - final OkHttpClient client = new OkHttpClient(); - return configureClient(client); - } + public static OkHttpClient createClient() { + final OkHttpClient client = new OkHttpClient(); + return configureClient(client); + } - @SuppressWarnings("rawtypes") - public static Callback createCallback(final String url) { + @SuppressWarnings("rawtypes") + public static Callback createCallback(final String url) { - return new Callback() { - @Override - public void success(final Object o, final Response response) { - logger.info("URL : " + url + "\tStatus : " - + response.getStatus()); - } + return new Callback() { + @Override + public void success(final Object o, final Response response) { + logger.info("URL : " + url + "\tStatus : " + + response.getStatus()); + } - @Override - public void failure(final RetrofitError retrofitError) { - logger.info(retrofitError.getMessage()); - } - }; - } + @Override + public void failure(final RetrofitError retrofitError) { + logger.info(retrofitError.getMessage()); + } + }; + } - public static WebHookService createWebHookService(final String url) { + public static WebHookService createWebHookService(final String url) { - final OkHttpClient client = ProcessorHelper.createClient(); + 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); - } + 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/WebHookProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/WebHookProcessor.java index d4aa4d9fa..b6433f55c 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 @@ -39,59 +39,59 @@ import com.google.gson.JsonParser; @Service 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) { + @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) { - final Set config = hook.getHookConfig(); + final Set config = hook.getHookConfig(); - String url = ""; - String contentType = ""; + String url = ""; + String contentType = ""; - for (final HookConfiguration conf : config) { - final String fieldName = conf.getFieldName(); - if (fieldName.equals(payloadURLName)) { - url = conf.getFieldValue(); - } - if (fieldName.equals(contentTypeName)) { - contentType = conf.getFieldValue(); - } - } + for (final HookConfiguration conf : config) { + final String fieldName = conf.getFieldName(); + if (fieldName.equals(payloadURLName)) { + url = conf.getFieldValue(); + } + if (fieldName.equals(contentTypeName)) { + contentType = conf.getFieldValue(); + } + } - 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) { + @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) { - final String fineractEndpointUrl = System.getProperty("baseUrl"); - final WebHookService service = ProcessorHelper - .createWebHookService(url); + final String fineractEndpointUrl = System.getProperty("baseUrl"); + final WebHookService service = ProcessorHelper + .createWebHookService(url); - @SuppressWarnings("rawtypes") - final Callback callback = ProcessorHelper.createCallback(url); + @SuppressWarnings("rawtypes") + final Callback callback = ProcessorHelper.createCallback(url); - if (contentType.equalsIgnoreCase("json") - || contentType.contains("json")) { - final JsonObject json = new JsonParser().parse(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); - } + if (contentType.equalsIgnoreCase("json") + || contentType.contains("json")) { + final JsonObject json = new JsonParser().parse(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); + } - } + } } 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 62de67b63..a1c5363b4 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 @@ -35,41 +35,41 @@ import com.google.gson.JsonObject; public interface WebHookService { - final static String ENTITY_HEADER = "X-Fineract-Entity"; - final static String ACTION_HEADER = "X-Fineract-Action"; - final static String TENANT_HEADER = "Fineract-Platform-TenantId"; - final static String ENDPOINT_HEADER = "X-Fineract-Endpoint"; - final static String API_KEY_HEADER = "X-Fineract-API-Key"; + final static String ENTITY_HEADER = "X-Fineract-Entity"; + final static String ACTION_HEADER = "X-Fineract-Action"; + final static String TENANT_HEADER = "Fineract-Platform-TenantId"; + final static String ENDPOINT_HEADER = "X-Fineract-Endpoint"; + final static String API_KEY_HEADER = "X-Fineract-API-Key"; - // Ping - @GET("/") - Response sendEmptyRequest(); + // Ping + @GET("/") + Response sendEmptyRequest(); - // 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); + // 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); - @FormUrlEncoded - @POST("/") - 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); + @FormUrlEncoded + @POST("/") + 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); + // 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); - @POST("/configuration") - String sendSmsBridgeConfigRequest(@Body SmsProviderData config); + @POST("/configuration") + String sendSmsBridgeConfigRequest(@Body SmsProviderData config); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/data/SmsProviderData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/data/SmsProviderData.java index 6dca28320..2e4547555 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/data/SmsProviderData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/data/SmsProviderData.java @@ -30,83 +30,83 @@ import org.apache.fineract.infrastructure.hooks.domain.HookConfiguration; public class SmsProviderData { - private String url; - private String phoneNo; - private String smsProvider; - private String smsProviderAccountId; - private String smsProviderToken; - - private String tenantId; - private String mifosToken; - private String endpoint; - - public SmsProviderData(final Set config) { - - for (final HookConfiguration conf : config) { - final String fieldName = conf.getFieldName(); - if (fieldName.equals(payloadURLName)) { - this.url = conf.getFieldValue(); - } - if (fieldName.equals(smsProviderName)) { - this.smsProvider = conf.getFieldValue(); - } - if (fieldName.equals(smsProviderAccountIdName)) { - this.smsProviderAccountId = conf.getFieldValue(); - } - if (fieldName.equals(smsProviderTokenIdName)) { - this.smsProviderToken = conf.getFieldValue(); - } - if (fieldName.equals(phoneNumberName)) { - this.phoneNo = conf.getFieldValue(); - } - } - } + private String url; + private String phoneNo; + private String smsProvider; + private String smsProviderAccountId; + private String smsProviderToken; + + private String tenantId; + private String mifosToken; + private String endpoint; + + public SmsProviderData(final Set config) { + + for (final HookConfiguration conf : config) { + final String fieldName = conf.getFieldName(); + if (fieldName.equals(payloadURLName)) { + this.url = conf.getFieldValue(); + } + if (fieldName.equals(smsProviderName)) { + this.smsProvider = conf.getFieldValue(); + } + if (fieldName.equals(smsProviderAccountIdName)) { + this.smsProviderAccountId = conf.getFieldValue(); + } + if (fieldName.equals(smsProviderTokenIdName)) { + this.smsProviderToken = conf.getFieldValue(); + } + if (fieldName.equals(phoneNumberName)) { + this.phoneNo = conf.getFieldValue(); + } + } + } - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } - public String getPhoneNumber() { - return phoneNo; - } + public String getPhoneNumber() { + return phoneNo; + } - public String getSmsProvider() { - return smsProvider; - } + public String getSmsProvider() { + return smsProvider; + } - public String getSmsProviderAccountId() { - return smsProviderAccountId; - } + public String getSmsProviderAccountId() { + return smsProviderAccountId; + } - public String getSmsProviderTokenId() { - return smsProviderToken; - } + public String getSmsProviderTokenId() { + return smsProviderToken; + } - public String getTenantId() { - return tenantId; - } + public String getTenantId() { + return tenantId; + } - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } - public String getMifosToken() { - return mifosToken; - } + public String getMifosToken() { + return mifosToken; + } - public void setMifosToken(String mifosToken) { - this.mifosToken = mifosToken; - } + public void setMifosToken(String mifosToken) { + this.mifosToken = mifosToken; + } - public String getEndpoint() { - return endpoint; - } + public String getEndpoint() { + return endpoint; + } - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } } 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 9b1595dd3..da9af02ed 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 @@ -26,9 +26,9 @@ import org.apache.fineract.infrastructure.hooks.domain.Hook; public interface HookReadPlatformService { - Collection retrieveAllHooks(); + Collection retrieveAllHooks(); - HookData retrieveHook(Long hookId); + HookData retrieveHook(Long hookId); List retrieveHooksByEvent(final String actionName, final String entityName); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookWritePlatformService.java index 9cff741be..56d8f4096 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookWritePlatformService.java @@ -23,10 +23,10 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface HookWritePlatformService { - CommandProcessingResult createHook(JsonCommand command); + CommandProcessingResult createHook(JsonCommand command); - CommandProcessingResult updateHook(Long hookId, JsonCommand command); + CommandProcessingResult updateHook(Long hookId, JsonCommand command); - CommandProcessingResult deleteHook(Long hookId); + CommandProcessingResult deleteHook(Long hookId); } 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 74f54077f..d08a627f7 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 @@ -140,9 +140,9 @@ public class HookWritePlatformServiceJpaRepositoryImpl handleHookDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleHookDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleHookDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -207,9 +207,9 @@ public class HookWritePlatformServiceJpaRepositoryImpl handleHookDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleHookDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleHookDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } 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 index 77462e0e5..8247fb125 100755 --- 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 @@ -43,9 +43,9 @@ import com.google.gson.reflect.TypeToken; 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/service/JobName.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobName.java index 3d76a3e20..09266ce27 100755 --- 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 @@ -46,8 +46,8 @@ public enum JobName { 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"), - SEND_MESSAGES_TO_EMAIL_GATEWAY("Send messages to Email gateway"), + GENERATE_ADHOCCLIENT_SCEHDULE("Generate AdhocClient Schedule"), + SEND_MESSAGES_TO_EMAIL_GATEWAY("Send messages to Email gateway"), UPDATE_EMAIL_OUTBOUND_WITH_CAMPAIGN_MESSAGE("Update Email Outbound with campaign message"), EXECUTE_EMAIL("Execute Email"), UPDATE_TRAIL_BALANCE_DETAILS("Update Trial Balance Details"); 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 index 3874883ea..962271e66 100755 --- 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 @@ -48,7 +48,7 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead @Autowired public SchedulerJobRunnerReadServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.columnValidator = columnValidator; } @@ -115,17 +115,17 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead } private boolean isJobExist(final Long jobId) { - boolean isJobPresent = false; - try{ + boolean isJobPresent = false; + 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){ - return isJobPresent; - } + }catch(EmptyResultDataAccessException e){ + return isJobPresent; + } } 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 b10804967..f5b824bd0 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 @@ -48,114 +48,114 @@ import org.springframework.transaction.TransactionException; */ public class OpenJpaDialect extends DefaultJpaDialect { - @Override - public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition) - throws PersistenceException, SQLException, TransactionException { + @Override + public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition) + throws PersistenceException, SQLException, TransactionException { - OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager); + OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager); - if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { - // Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration - FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan(); - if (fetchPlan instanceof JDBCFetchPlan) { - IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel()); - ((JDBCFetchPlan) fetchPlan).setIsolation(isolation); - } - } + if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { + // Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration + FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan(); + if (fetchPlan instanceof JDBCFetchPlan) { + IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel()); + ((JDBCFetchPlan) fetchPlan).setIsolation(isolation); + } + } - entityManager.getTransaction().begin(); + 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. - openJpaEntityManager.beginStore(); - } + 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. + openJpaEntityManager.beginStore(); + } - // Custom implementation for OpenJPA savepoint handling - return new OpenJpaTransactionData(openJpaEntityManager); - } + // Custom implementation for OpenJPA savepoint handling + return new OpenJpaTransactionData(openJpaEntityManager); + } - @Override - public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly) - throws PersistenceException, SQLException { + @Override + public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly) + throws PersistenceException, SQLException { - return new OpenJpaConnectionHandle(getOpenJPAEntityManager(entityManager)); - } + return new OpenJpaConnectionHandle(getOpenJPAEntityManager(entityManager)); + } - /** - * Return the OpenJPA-specific variant of {@code EntityManager}. - * @param em the generic {@code EntityManager} instance - * @return the OpenJPA-specific variant of {@code EntityManager} - */ - protected OpenJPAEntityManager getOpenJPAEntityManager(EntityManager em) { - return OpenJPAPersistence.cast(em); - } + /** + * Return the OpenJPA-specific variant of {@code EntityManager}. + * @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. - */ - private static class OpenJpaTransactionData implements SavepointManager { + /** + * Transaction data Object exposed from {@code beginTransaction}, + * implementing the {@link SavepointManager} interface. + */ + private static class OpenJpaTransactionData implements SavepointManager { - private final OpenJPAEntityManager entityManager; + private final OpenJPAEntityManager entityManager; - private int savepointCounter = 0; + private int savepointCounter = 0; - public OpenJpaTransactionData(OpenJPAEntityManager entityManager) { - this.entityManager = entityManager; - } + public OpenJpaTransactionData(OpenJPAEntityManager entityManager) { + this.entityManager = entityManager; + } - @Override - public Object createSavepoint() throws TransactionException { - this.savepointCounter++; - String savepointName = ConnectionHolder.SAVEPOINT_NAME_PREFIX + this.savepointCounter; - this.entityManager.setSavepoint(savepointName); - return savepointName; - } + @Override + public Object createSavepoint() throws TransactionException { + this.savepointCounter++; + String savepointName = ConnectionHolder.SAVEPOINT_NAME_PREFIX + this.savepointCounter; + this.entityManager.setSavepoint(savepointName); + return savepointName; + } - @Override - public void rollbackToSavepoint(Object savepoint) throws TransactionException { - this.entityManager.rollbackToSavepoint((String) savepoint); - } + @Override + public void rollbackToSavepoint(Object savepoint) throws TransactionException { + this.entityManager.rollbackToSavepoint((String) savepoint); + } - @Override - 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); - } - } - } + @Override + 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); + } + } + } - /** - * {@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 { + /** + * {@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 { - private final OpenJPAEntityManager entityManager; + private final OpenJPAEntityManager entityManager; - public OpenJpaConnectionHandle(OpenJPAEntityManager entityManager) { - this.entityManager = entityManager; - } + public OpenJpaConnectionHandle(OpenJPAEntityManager entityManager) { + this.entityManager = entityManager; + } - @Override - public Connection getConnection() { - return (Connection) this.entityManager.getConnection(); - } + @Override + public Connection getConnection() { + return (Connection) this.entityManager.getConnection(); + } - @Override - public void releaseConnection(Connection con) { - JdbcUtils.closeConnection(con); - } - } + @Override + public void releaseConnection(Connection con) { + JdbcUtils.closeConnection(con); + } + } } 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 cccad74c7..ce5a30772 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 @@ -45,79 +45,79 @@ import org.springframework.orm.jpa.vendor.Database; */ public class OpenJpaVendorAdapter extends AbstractJpaVendorAdapter { - private final PersistenceProvider persistenceProvider = new PersistenceProviderImpl(); + private final PersistenceProvider persistenceProvider = new PersistenceProviderImpl(); - private final OpenJpaDialect jpaDialect = new OpenJpaDialect(); + private final OpenJpaDialect jpaDialect = new OpenJpaDialect(); - @Override - public PersistenceProvider getPersistenceProvider() { - return this.persistenceProvider; - } + @Override + public PersistenceProvider getPersistenceProvider() { + return this.persistenceProvider; + } - @Override - public String getPersistenceProviderRootPackage() { - return "org.apache.openjpa"; - } + @Override + public String getPersistenceProviderRootPackage() { + return "org.apache.openjpa"; + } - @Override - public Map getJpaPropertyMap() { - Map jpaProperties = new HashMap(); + @Override + public Map getJpaPropertyMap() { + Map jpaProperties = new HashMap(); - if (getDatabasePlatform() != null) { - jpaProperties.put("openjpa.jdbc.DBDictionary", getDatabasePlatform()); - } - else if (getDatabase() != null) { - String databaseDictonary = determineDatabaseDictionary(getDatabase()); - if (databaseDictonary != null) { - jpaProperties.put("openjpa.jdbc.DBDictionary", databaseDictonary); - } - } + if (getDatabasePlatform() != null) { + jpaProperties.put("openjpa.jdbc.DBDictionary", getDatabasePlatform()); + } + else if (getDatabase() != null) { + String databaseDictonary = determineDatabaseDictionary(getDatabase()); + if (databaseDictonary != null) { + jpaProperties.put("openjpa.jdbc.DBDictionary", databaseDictonary); + } + } - if (isGenerateDdl()) { - 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") - jpaProperties.put("openjpa.Log", "DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"); - } + if (isGenerateDdl()) { + 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") + jpaProperties.put("openjpa.Log", "DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"); + } - return jpaProperties; - } + return jpaProperties; + } - /** - * 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 - */ - 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; - } - } + /** + * 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 + */ + 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; + } + } - @Override - public OpenJpaDialect getJpaDialect() { - return this.jpaDialect; - } + @Override + public OpenJpaDialect getJpaDialect() { + return this.jpaDialect; + } - @Override - public Class getEntityManagerFactoryInterface() { - return OpenJPAEntityManagerFactorySPI.class; - } + @Override + public Class getEntityManagerFactoryInterface() { + return OpenJPAEntityManagerFactorySPI.class; + } - @Override - public Class getEntityManagerInterface() { - return OpenJPAEntityManagerSPI.class; - } + @Override + public Class getEntityManagerInterface() { + return OpenJPAEntityManagerSPI.class; + } } 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 4e20d4acf..7e208bb7c 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 @@ -52,7 +52,7 @@ public class ReportMailingJobReadPlatformServiceImpl implements ReportMailingJob @Autowired public ReportMailingJobReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.columnValidator = columnValidator; } 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 01002d64b..36c96e796 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 @@ -45,7 +45,7 @@ public class ReportMailingJobRunHistoryReadPlatformServiceImpl implements Report @Autowired public ReportMailingJobRunHistoryReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.reportMailingJobRunHistoryMapper = new ReportMailingJobRunHistoryMapper(); this.columnValidator = columnValidator; 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 338303f04..881c74247 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 @@ -422,7 +422,7 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo final MultivaluedMap reportParams, final String reportName, final StringBuilder errorLog) { try { - final boolean isSelfServiceUserReport = false; + final boolean isSelfServiceUserReport = false; final String reportType = this.readReportingService.getReportType(reportName, isSelfServiceUserReport); final ReportingProcessService reportingProcessService = this.reportingProcessServiceProvider.findReportingProcessService(reportType); 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 14be60d5d..32efda76c 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 @@ -21,9 +21,9 @@ package org.apache.fineract.infrastructure.security.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; 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/filter/TenantAwareBasicAuthenticationFilter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TenantAwareBasicAuthenticationFilter.java index 1be5437f9..0323fcf01 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 @@ -163,25 +163,25 @@ public class TenantAwareBasicAuthenticationFilter extends BasicAuthenticationFil @Override protected void onSuccessfulAuthentication(HttpServletRequest request, - HttpServletResponse response, Authentication authResult) - throws IOException { - super.onSuccessfulAuthentication(request, response, authResult); - AppUser user = (AppUser) authResult.getPrincipal(); + HttpServletResponse response, Authentication authResult) + throws IOException { + super.onSuccessfulAuthentication(request, response, authResult); + AppUser user = (AppUser) authResult.getPrincipal(); if (notificationReadPlatformService.hasUnreadNotifications(user.getId())) { response.addHeader("X-Notification-Refresh", "true"); } else { response.addHeader("X-Notification-Refresh", "false"); } - - String pathURL = request.getRequestURI(); - boolean isSelfServiceRequest = (pathURL != null && pathURL.contains("/self/")); + + String pathURL = request.getRequestURI(); + boolean isSelfServiceRequest = (pathURL != null && pathURL.contains("/self/")); - boolean notAllowed = ((isSelfServiceRequest && !user.isSelfServiceUser()) - ||(!isSelfServiceRequest && user.isSelfServiceUser())); - - if(notAllowed){ - throw new BadCredentialsException("User not authorised to use the requested resource."); - } + boolean notAllowed = ((isSelfServiceRequest && !user.isSelfServiceUser()) + ||(!isSelfServiceRequest && user.isSelfServiceUser())); + + 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/utils/ColumnValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/ColumnValidator.java index e10968722..2240d193a 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,188 +39,188 @@ import org.springframework.stereotype.Component; @Component public class ColumnValidator { - private final JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; - @Autowired - public ColumnValidator(final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + public ColumnValidator(final RoutingDataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } - private void validateColumn(Map> tableColumnMap) { - Connection connection = null ; - try { - connection = this.jdbcTemplate.getDataSource() - .getConnection() ; - DatabaseMetaData dbMetaData = connection.getMetaData(); - ResultSet resultSet = null; - for (HashMap.Entry> entry : tableColumnMap - .entrySet()) { - Set columns = entry.getValue(); - resultSet = dbMetaData.getColumns(null, null, entry.getKey(), - null); - Set tableColumns = getTableColumns(resultSet); - if (columns.size() > 0 && tableColumns.size() == 0) { - throw new SQLInjectionException(); - } - for (String requestedColumn : columns) { - if (!tableColumns.contains(requestedColumn)) { - throw new SQLInjectionException(); - } - } - } - } catch (SQLException e) { - throw new SQLInjectionException(); - }finally { - if(connection != null) { - DataSourceUtils.releaseConnection(connection, jdbcTemplate.getDataSource()); - } - connection = null ; - } - } + private void validateColumn(Map> tableColumnMap) { + Connection connection = null ; + try { + connection = this.jdbcTemplate.getDataSource() + .getConnection() ; + DatabaseMetaData dbMetaData = connection.getMetaData(); + ResultSet resultSet = null; + for (HashMap.Entry> entry : tableColumnMap + .entrySet()) { + Set columns = entry.getValue(); + resultSet = dbMetaData.getColumns(null, null, entry.getKey(), + null); + Set tableColumns = getTableColumns(resultSet); + if (columns.size() > 0 && tableColumns.size() == 0) { + throw new SQLInjectionException(); + } + for (String requestedColumn : columns) { + if (!tableColumns.contains(requestedColumn)) { + throw new SQLInjectionException(); + } + } + } + } catch (SQLException e) { + throw new SQLInjectionException(); + }finally { + if(connection != null) { + DataSourceUtils.releaseConnection(connection, jdbcTemplate.getDataSource()); + } + connection = null ; + } + } - private Set getTableColumns(final ResultSet rs) { - Set columns = new HashSet<>(); - try { - while (rs.next()) { - columns.add(rs.getString("column_name")); - } - } catch (SQLException e) { - e.printStackTrace(); - } - return columns; - } + private Set getTableColumns(final ResultSet rs) { + Set columns = new HashSet<>(); + try { + while (rs.next()) { + columns.add(rs.getString("column_name")); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return columns; + } - public void validateSqlInjection(String schema, String... conditions) { - for(String condition: conditions) { - SQLInjectionValidator.validateSQLInput(condition); - 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); - validateColumn(tableColumnMap); - } - } + public void validateSqlInjection(String schema, String... conditions) { + for(String condition: conditions) { + SQLInjectionValidator.validateSQLInput(condition); + 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); + validateColumn(tableColumnMap); + } + } - 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); - Set columns = tableColumnAliasMap.get(alias); - tableColumnMap.put(schema.substring(startPos, index).trim(), - columns); - } else { - throw new SQLInjectionException(); - } - } - return tableColumnMap; - } + 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); + Set columns = tableColumnAliasMap.get(alias); + tableColumnMap.put(schema.substring(startPos, index).trim(), + columns); + } else { + throw new SQLInjectionException(); + } + } + return tableColumnMap; + } - private static Map> getTableColumnAliasMap( - Set operands) { - Map> tableColumnMap = new HashMap<>(); - for (String operand : operands) { - String[] tableColumn = operand.split("\\."); - if (tableColumn.length == 2) { - if (tableColumnMap.containsKey(tableColumn[0])) { - Set columns = tableColumnMap.get(tableColumn[0]); - columns.add(tableColumn[1]); - } else { - Set columns = new HashSet<>(); - columns.add(tableColumn[1]); - tableColumnMap.put(tableColumn[0], columns); - } - } else { - throw new SQLInjectionException(); - } - } - return tableColumnMap; - } + private static Map> getTableColumnAliasMap( + Set operands) { + Map> tableColumnMap = new HashMap<>(); + for (String operand : operands) { + String[] tableColumn = operand.split("\\."); + if (tableColumn.length == 2) { + if (tableColumnMap.containsKey(tableColumn[0])) { + Set columns = tableColumnMap.get(tableColumn[0]); + columns.add(tableColumn[1]); + } else { + Set columns = new HashSet<>(); + columns.add(tableColumn[1]); + tableColumnMap.put(tableColumn[0], columns); + } + } else { + throw new SQLInjectionException(); + } + } + return tableColumnMap; + } - 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 ")); - for (String op : operatorList) { - int startIndex = 0; - do { - int index = condition.indexOf(op, startIndex); - 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)); - } - } else { - operandList.add(getOperand(condition, index, - currentChar)); - } + 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 ")); + for (String op : operatorList) { + int startIndex = 0; + do { + int index = condition.indexOf(op, startIndex); + 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)); + } + } else { + operandList.add(getOperand(condition, index, + currentChar)); + } - startIndex = index + op.length(); - } + startIndex = index + op.length(); + } - } while (condition.indexOf(op, startIndex) > -1); - } - return operandList; - } + } while (condition.indexOf(op, startIndex) > -1); + } + return operandList; + } - private static String getOperand(String condition, int index, - char currentChar) { - int startPos = 0; - if ((currentChar + "").equals(" ")) { - startPos = condition.substring(0, index - 1) - .lastIndexOf(' ', index); - } else { - startPos = condition.substring(0, index).lastIndexOf(' ', index); - } - String a = condition.substring(startPos == -1 ? 0 : startPos, index); - return a.trim().replace("(", "").replace(")", ""); - } + private static String getOperand(String condition, int index, + char currentChar) { + int startPos = 0; + if ((currentChar + "").equals(" ")) { + startPos = condition.substring(0, index - 1) + .lastIndexOf(' ', index); + } else { + startPos = condition.substring(0, index).lastIndexOf(' ', index); + } + String a = condition.substring(startPos == -1 ? 0 : startPos, index); + return a.trim().replace("(", "").replace(")", ""); + } - private static String replaceAll(String condition, String op) { - int startIndex = 0; - do { - 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("<"))) { - condition = condition.replace(op, " " + op + " "); - return condition; - } - startIndex = index + 2 + op.length(); + private static String replaceAll(String condition, String op) { + int startIndex = 0; + do { + 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("<"))) { + condition = condition.replace(op, " " + op + " "); + return condition; + } + startIndex = index + 2 + op.length(); - } else if (op.equals("< =") || op.equals("> =") - || op.equals("! =")) { - condition = condition.replace(op, op.replace(" ", "")); - return condition; - } else { - condition = condition.replace(op, " " + op + " "); - return condition; - } - } else { - return condition; - } + } else if (op.equals("< =") || op.equals("> =") + || op.equals("! =")) { + condition = condition.replace(op, op.replace(" ", "")); + return condition; + } else { + condition = condition.replace(op, " " + op + " "); + return condition; + } + } else { + return condition; + } - } while (condition.indexOf(op, startIndex) > -1); - return condition; - } + } while (condition.indexOf(op, startIndex) > -1); + return condition; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLInjectionException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLInjectionException.java index e87003e83..571b20e59 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLInjectionException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLInjectionException.java @@ -22,8 +22,8 @@ import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidati public class SQLInjectionException extends PlatformApiDataValidationException { - public SQLInjectionException() { - super("error.msg.found.sql.injection", "Unexpected SQL Commands found", null); - } + public SQLInjectionException() { + super("error.msg.found.sql.injection", "Unexpected SQL Commands found", null); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLInjectionValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLInjectionValidator.java index 2fd6746f0..2ccc3c1e9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLInjectionValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLInjectionValidator.java @@ -24,171 +24,171 @@ import java.util.regex.Pattern; public class SQLInjectionValidator { - private final static String[] DDL_COMMANDS = { "create", "drop", "alter", "truncate", "comment", "sleep" }; + private final static String[] DDL_COMMANDS = { "create", "drop", "alter", "truncate", "comment", "sleep" }; - private final static String[] DML_COMMANDS = { "select", "insert", "update", "delete", "merge", "upsert", "call" }; + private final static String[] DML_COMMANDS = { "select", "insert", "update", "delete", "merge", "upsert", "call" }; - private final static String[] COMMENTS = { "--", "({", "/*", "#" }; + private final static String[] COMMENTS = { "--", "({", "/*", "#" }; - private final static String SQL_PATTERN = "[a-zA-Z_=,\\-'!><.?\"`% ()0-9*\n\r]*"; + private final static String SQL_PATTERN = "[a-zA-Z_=,\\-'!><.?\"`% ()0-9*\n\r]*"; - public final static void validateSQLInput(final String sqlSearch) { - String lowerCaseSQL = sqlSearch.toLowerCase(); - for (String ddl : DDL_COMMANDS) { - if (lowerCaseSQL.contains(ddl)) { - throw new SQLInjectionException(); - } - } + public final static void validateSQLInput(final String sqlSearch) { + String lowerCaseSQL = sqlSearch.toLowerCase(); + for (String ddl : DDL_COMMANDS) { + if (lowerCaseSQL.contains(ddl)) { + throw new SQLInjectionException(); + } + } - for (String dml : DML_COMMANDS) { - if (lowerCaseSQL.contains(dml)) { - throw new SQLInjectionException(); - } - } + for (String dml : DML_COMMANDS) { + if (lowerCaseSQL.contains(dml)) { + throw new SQLInjectionException(); + } + } - for (String comments : COMMENTS) { - if (lowerCaseSQL.contains(comments)) { - throw new SQLInjectionException(); - } - } + for (String comments : COMMENTS) { + if (lowerCaseSQL.contains(comments)) { + throw new SQLInjectionException(); + } + } - //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 - inputSqlString = inputSqlString.replaceAll(" =", "="); - } + //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 + inputSqlString = inputSqlString.replaceAll(" =", "="); + } - while (inputSqlString.indexOf("= ") > 0) { //Don't remove space after = operator - inputSqlString = inputSqlString.replaceAll("= ", "="); - } + while (inputSqlString.indexOf("= ") > 0) { //Don't remove space after = operator + inputSqlString = inputSqlString.replaceAll("= ", "="); + } - StringTokenizer tokenizer = new StringTokenizer(inputSqlString, " "); - while (tokenizer.hasMoreTokens()) { - String token = tokenizer.nextToken().trim(); - if (token.equals("'")) { - if (tokenizer.hasMoreElements()) { - String nextToken = tokenizer.nextToken().trim(); - if (!nextToken.equals("'")) { - injectionFound = true; - break; - } - } else { - injectionFound = true; - break ; - } - } - if (token.equals("\"")) { - if (tokenizer.hasMoreElements()) { - String nextToken = tokenizer.nextToken().trim(); - if (!nextToken.equals("\"")) { - injectionFound = true; - break; - } - } else { - injectionFound = true; - break ; - } - } else if (token.indexOf('=') > 0) { - StringTokenizer operatorToken = new StringTokenizer(token, "="); - String operand = operatorToken.nextToken().trim(); - if (!operatorToken.hasMoreTokens()) { - injectionFound = true; - break; - } - String value = operatorToken.nextToken().trim(); - if (operand.equals(value)) { - injectionFound = true; - break; - } - } - } - if (injectionFound) { - throw new SQLInjectionException(); - } - - Pattern pattern = Pattern.compile(SQL_PATTERN); - Matcher matcher = pattern.matcher(sqlSearch); - 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(); - } - } + StringTokenizer tokenizer = new StringTokenizer(inputSqlString, " "); + while (tokenizer.hasMoreTokens()) { + String token = tokenizer.nextToken().trim(); + if (token.equals("'")) { + if (tokenizer.hasMoreElements()) { + String nextToken = tokenizer.nextToken().trim(); + if (!nextToken.equals("'")) { + injectionFound = true; + break; + } + } else { + injectionFound = true; + break ; + } + } + if (token.equals("\"")) { + if (tokenizer.hasMoreElements()) { + String nextToken = tokenizer.nextToken().trim(); + if (!nextToken.equals("\"")) { + injectionFound = true; + break; + } + } else { + injectionFound = true; + break ; + } + } else if (token.indexOf('=') > 0) { + StringTokenizer operatorToken = new StringTokenizer(token, "="); + String operand = operatorToken.nextToken().trim(); + if (!operatorToken.hasMoreTokens()) { + injectionFound = true; + break; + } + String value = operatorToken.nextToken().trim(); + if (operand.equals(value)) { + injectionFound = true; + break; + } + } + } + if (injectionFound) { + throw new SQLInjectionException(); + } + + Pattern pattern = Pattern.compile(SQL_PATTERN); + Matcher matcher = pattern.matcher(sqlSearch); + 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(); + } + } - - for (String comments : COMMENTS) { - if (lowerCaseSQL.contains(comments)) { - throw new SQLInjectionException(); - } - } + + for (String comments : COMMENTS) { + if (lowerCaseSQL.contains(comments)) { + throw new SQLInjectionException(); + } + } - //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 - inputSqlString = inputSqlString.replaceAll(" =", "="); - } + //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 + inputSqlString = inputSqlString.replaceAll(" =", "="); + } - while (inputSqlString.indexOf("= ") > 0) { //Don't remove space after = operator - inputSqlString = inputSqlString.replaceAll("= ", "="); - } + while (inputSqlString.indexOf("= ") > 0) { //Don't remove space after = operator + inputSqlString = inputSqlString.replaceAll("= ", "="); + } - StringTokenizer tokenizer = new StringTokenizer(inputSqlString, " "); - while (tokenizer.hasMoreTokens()) { - String token = tokenizer.nextToken().trim(); - if (token.equals("'")) { - if (tokenizer.hasMoreElements()) { - String nextToken = tokenizer.nextToken().trim(); - if (!nextToken.equals("'")) { - injectionFound = true; - break; - } - } else { - injectionFound = true; - break ; - } - } - if (token.equals("\"")) { - if (tokenizer.hasMoreElements()) { - String nextToken = tokenizer.nextToken().trim(); - if (!nextToken.equals("\"")) { - injectionFound = true; - break; - } - } else { - injectionFound = true; - break ; - } - } else if (token.indexOf('=') > 0) { - StringTokenizer operatorToken = new StringTokenizer(token, "="); - String operand = operatorToken.nextToken().trim(); - if (!operatorToken.hasMoreTokens()) { - injectionFound = true; - break; - } - String value = operatorToken.nextToken().trim(); - if (operand.equals(value)) { - injectionFound = true; - break; - } - } - } - if (injectionFound) { - throw new SQLInjectionException(); - } - - Pattern pattern = Pattern.compile(SQL_PATTERN); - Matcher matcher = pattern.matcher(sqlSearch); - if (!matcher.matches()) { - throw new SQLInjectionException(); - } - } + StringTokenizer tokenizer = new StringTokenizer(inputSqlString, " "); + while (tokenizer.hasMoreTokens()) { + String token = tokenizer.nextToken().trim(); + if (token.equals("'")) { + if (tokenizer.hasMoreElements()) { + String nextToken = tokenizer.nextToken().trim(); + if (!nextToken.equals("'")) { + injectionFound = true; + break; + } + } else { + injectionFound = true; + break ; + } + } + if (token.equals("\"")) { + if (tokenizer.hasMoreElements()) { + String nextToken = tokenizer.nextToken().trim(); + if (!nextToken.equals("\"")) { + injectionFound = true; + break; + } + } else { + injectionFound = true; + break ; + } + } else if (token.indexOf('=') > 0) { + StringTokenizer operatorToken = new StringTokenizer(token, "="); + String operand = operatorToken.nextToken().trim(); + if (!operatorToken.hasMoreTokens()) { + injectionFound = true; + break; + } + String value = operatorToken.nextToken().trim(); + if (operand.equals(value)) { + injectionFound = true; + break; + } + } + } + if (injectionFound) { + throw new SQLInjectionException(); + } + + Pattern pattern = Pattern.compile(SQL_PATTERN); + Matcher matcher = pattern.matcher(sqlSearch); + 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 83c89c7d6..ef5ea38a2 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 @@ -28,34 +28,34 @@ import org.springframework.security.web.FilterInvocation; public class SelfServiceUserAccessVote implements AccessDecisionVoter { - @Override - public boolean supports(@SuppressWarnings("unused") ConfigAttribute attribute) { - // This implementation supports any attribute, because it does not rely on it. - return true; - } + @Override + public boolean supports(@SuppressWarnings("unused") ConfigAttribute attribute) { + // This implementation supports any attribute, because it does not rely on it. + return true; + } - @Override - public boolean supports(Class clazz) { - return FilterInvocation.class.isAssignableFrom(clazz); - } + @Override + public boolean supports(Class clazz) { + return FilterInvocation.class.isAssignableFrom(clazz); + } - @Override - public int vote(final Authentication authentication, final FilterInvocation fi, - @SuppressWarnings("unused") final Collection attributes) { - if(!"OPTIONS".equalsIgnoreCase(fi.getHttpRequest().getMethod())){ - AppUser user = (AppUser) authentication.getPrincipal(); - - String pathURL = fi.getRequestUrl(); - boolean isSelfServiceRequest = (pathURL != null && pathURL.contains("/self/")); + @Override + public int vote(final Authentication authentication, final FilterInvocation fi, + @SuppressWarnings("unused") final Collection attributes) { + 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())); - - if(notAllowed){ - return ACCESS_DENIED; - } - } - return ACCESS_GRANTED; - } + boolean notAllowed = ((isSelfServiceRequest && !user.isSelfServiceUser()) + ||(!isSelfServiceRequest && user.isSelfServiceUser())); + + if(notAllowed){ + return ACCESS_DENIED; + } + } + return ACCESS_GRANTED; + } } 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 698226d39..bd3581afd 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 @@ -43,13 +43,13 @@ import com.google.gson.reflect.TypeToken; 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)); + public static final Set UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(SmsApiConstants.messageParamName, SmsApiConstants.campaignIdParamName)); @Autowired public SmsDataValidator(final FromJsonHelper fromApiJsonHelper) { 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 3858aaf0b..a83c6ce30 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 @@ -27,49 +27,49 @@ import com.google.gson.Gson; * the "/report" resource **/ public class SmsMessageApiReportResourceData { - private List externalIds; - private String mifosTenantIdentifier; - - /** - * SmsMessageApiReportResourceData constructor - **/ - private SmsMessageApiReportResourceData(List externalIds, String mifosTenantIdentifier) { - this.externalIds = externalIds; - this.mifosTenantIdentifier = mifosTenantIdentifier; - } - - /** - * SmsMessageApiReportResourceData constructor - **/ - protected SmsMessageApiReportResourceData() {} - - /** - * @return new instance of the SmsMessageApiReportResourceData class - **/ - public static final SmsMessageApiReportResourceData instance(List externalIds, String mifosTenantIdentifier) { - return new SmsMessageApiReportResourceData(externalIds, mifosTenantIdentifier); - } + private List externalIds; + private String mifosTenantIdentifier; + + /** + * SmsMessageApiReportResourceData constructor + **/ + private SmsMessageApiReportResourceData(List externalIds, String mifosTenantIdentifier) { + this.externalIds = externalIds; + this.mifosTenantIdentifier = mifosTenantIdentifier; + } + + /** + * SmsMessageApiReportResourceData constructor + **/ + protected SmsMessageApiReportResourceData() {} + + /** + * @return new instance of the SmsMessageApiReportResourceData class + **/ + public static final SmsMessageApiReportResourceData instance(List externalIds, String mifosTenantIdentifier) { + return new SmsMessageApiReportResourceData(externalIds, mifosTenantIdentifier); + } - /** - * @return the externalIds - */ - public List getExternalIds() { - return externalIds; - } + /** + * @return the externalIds + */ + public List getExternalIds() { + return externalIds; + } - /** - * @return the mifosTenantIdentifier - */ - public String getMifosTenantIdentifier() { - return mifosTenantIdentifier; - } - - /** - * @return JSON representation of the object - **/ - public String toJsonString() { - Gson gson = new Gson(); - - return gson.toJson(this); - } + /** + * @return the mifosTenantIdentifier + */ + public String getMifosTenantIdentifier() { + return mifosTenantIdentifier; + } + + /** + * @return JSON representation of the object + **/ + public String toJsonString() { + Gson gson = new Gson(); + + return gson.toJson(this); + } } 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 947bb3366..ea5ca42b0 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,44 +24,44 @@ import java.util.List; * Immutable data object representing an outbound SMS message API response data **/ public class SmsMessageApiResponseData { - private Integer httpStatusCode; - private List data; - - /** - * SmsMessageApiResponseData constructor - * - * - **/ - private SmsMessageApiResponseData(Integer httpStatusCode, List data) { - this.httpStatusCode = httpStatusCode; - this.data = data; - } - - /** - * Default SmsMessageApiResponseData constructor - * - * - **/ - protected SmsMessageApiResponseData() {} - - /** - * @return an instance of the SmsMessageApiResponseData class - **/ - public static SmsMessageApiResponseData getInstance(Integer httpStatusCode, List data) { - return new SmsMessageApiResponseData(httpStatusCode, data); - } + private Integer httpStatusCode; + private List data; + + /** + * SmsMessageApiResponseData constructor + * + * + **/ + private SmsMessageApiResponseData(Integer httpStatusCode, List data) { + this.httpStatusCode = httpStatusCode; + this.data = data; + } + + /** + * Default SmsMessageApiResponseData constructor + * + * + **/ + protected SmsMessageApiResponseData() {} + + /** + * @return an instance of the SmsMessageApiResponseData class + **/ + public static SmsMessageApiResponseData getInstance(Integer httpStatusCode, List data) { + return new SmsMessageApiResponseData(httpStatusCode, data); + } - /** - * @return the httpStatusCode - */ - public Integer getHttpStatusCode() { - return httpStatusCode; - } + /** + * @return the httpStatusCode + */ + public Integer getHttpStatusCode() { + return httpStatusCode; + } - /** - * @return the data - */ - public List getData() { - return data; - } + /** + * @return the data + */ + public List getData() { + return 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 d8167fec8..680fb5a52 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 @@ -22,92 +22,92 @@ package org.apache.fineract.infrastructure.sms.data; * Immutable data object representing an outbound SMS message delivery report data **/ public class SmsMessageDeliveryReportData { - private Long id; - private String externalId; - private String addedOnDate; - private String deliveredOnDate; - private Integer deliveryStatus; - private Boolean hasError; - private String errorMessage; - - /** - * SmsMessageDeliveryReportData constructor - * - * - **/ - 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; - this.deliveredOnDate = deliveredOnDate; - this.deliveryStatus = deliveryStatus; - this.hasError = hasError; - this.errorMessage = errorMessage; - } - - /** - * Default SmsMessageDeliveryReportData constructor - * - * - **/ - protected SmsMessageDeliveryReportData() {} - - /** - * @return an instance of the SmsMessageDeliveryReportData class - **/ - public static SmsMessageDeliveryReportData getInstance(Long id, String externalId, String addedOnDate, String deliveredOnDate, - Integer deliveryStatus, Boolean hasError, String errorMessage) { - - return new SmsMessageDeliveryReportData(id, externalId, addedOnDate, deliveredOnDate, deliveryStatus, hasError, errorMessage); - } + private Long id; + private String externalId; + private String addedOnDate; + private String deliveredOnDate; + private Integer deliveryStatus; + private Boolean hasError; + private String errorMessage; + + /** + * SmsMessageDeliveryReportData constructor + * + * + **/ + 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; + this.deliveredOnDate = deliveredOnDate; + this.deliveryStatus = deliveryStatus; + this.hasError = hasError; + this.errorMessage = errorMessage; + } + + /** + * Default SmsMessageDeliveryReportData constructor + * + * + **/ + protected SmsMessageDeliveryReportData() {} + + /** + * @return an instance of the SmsMessageDeliveryReportData class + **/ + public static SmsMessageDeliveryReportData getInstance(Long id, String externalId, String addedOnDate, String deliveredOnDate, + Integer deliveryStatus, Boolean hasError, String errorMessage) { + + return new SmsMessageDeliveryReportData(id, externalId, addedOnDate, deliveredOnDate, deliveryStatus, hasError, errorMessage); + } - /** - * @return the id - */ - public Long getId() { - return id; - } + /** + * @return the id + */ + public Long getId() { + return id; + } - /** - * @return the externalId - */ - public String getExternalId() { - return externalId; - } + /** + * @return the externalId + */ + public String getExternalId() { + return externalId; + } - /** - * @return the addedOnDate - */ - public String getAddedOnDate() { - return addedOnDate; - } + /** + * @return the addedOnDate + */ + public String getAddedOnDate() { + return addedOnDate; + } - /** - * @return the deliveredOnDate - */ - public String getDeliveredOnDate() { - return deliveredOnDate; - } + /** + * @return the deliveredOnDate + */ + public String getDeliveredOnDate() { + return deliveredOnDate; + } - /** - * @return the deliveryStatus - */ - public Integer getDeliveryStatus() { - return deliveryStatus; - } + /** + * @return the deliveryStatus + */ + public Integer getDeliveryStatus() { + return deliveryStatus; + } - /** - * @return the hasError - */ - public Boolean getHasError() { - return hasError; - } + /** + * @return the hasError + */ + public Boolean getHasError() { + return hasError; + } - /** - * @return the errorMessage - */ - public String getErrorMessage() { - return errorMessage; - } + /** + * @return the errorMessage + */ + public String getErrorMessage() { + return errorMessage; + } } 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 c4966040f..573098672 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 @@ -188,13 +188,13 @@ public class SmsMessage extends AbstractPersistableCustom { this.deliveredOnDate = deliveredOnDate; } - public boolean isNotification() { - return this.isNotification; - } + public boolean isNotification() { + return this.isNotification; + } - public void setNotification(boolean isNotification) { - this.isNotification = isNotification; - } + public void setNotification(boolean isNotification) { + this.isNotification = isNotification; + } } \ 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 5fa2ab8ae..6f3121d92 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 @@ -123,10 +123,10 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob while (pendingMessageIterator.hasNext()) { SmsMessage smsData = pendingMessageIterator.next(); if(smsData.isNotification()){ - smsData.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); - toSendNotificationMessages.add(smsData); + smsData.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); + toSendNotificationMessages.add(smsData); }else{ - SmsMessageApiQueueResourceData apiQueueResourceData = SmsMessageApiQueueResourceData.instance(smsData.getId(), + SmsMessageApiQueueResourceData apiQueueResourceData = SmsMessageApiQueueResourceData.instance(smsData.getId(), tenantIdentifier, null, null, smsData.getMobileNo(), smsData.getMessage(), smsData.getSmsCampaign() .getProviderId()); apiQueueResourceDatas.add(apiQueueResourceData); @@ -135,12 +135,12 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob } } if(toSaveMessages.size()>0){ - this.smsMessageRepository.saveAll(toSaveMessages); + this.smsMessageRepository.saveAll(toSaveMessages); this.smsMessageRepository.flush(); this.genericExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas)); } if(!toSendNotificationMessages.isEmpty()){ - this.notificationSenderService.sendNotification(toSendNotificationMessages); + this.notificationSenderService.sendNotification(toSendNotificationMessages); } // new MyThread(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas).start(); } @@ -176,7 +176,7 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob } private void connectAndSendToIntermediateServer(Collection apiQueueResourceDatas) { - Map hostConfig = this.smsConfigUtils.getMessageGateWayRequestURI("sms", SmsMessageApiQueueResourceData.toJsonString(apiQueueResourceDatas)) ; + 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, @@ -184,7 +184,7 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob if (responseOne != null) { // String smsResponse = responseOne.getBody(); if (!responseOne.getStatusCode().equals(HttpStatus.ACCEPTED)) { - logger.debug(responseOne.getStatusCode().name()); + logger.debug(responseOne.getStatusCode().name()); throw new ConnectionFailureException(SmsCampaignConstants.SMS); } } @@ -271,7 +271,7 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob if (smsMessageInternalIds.getPageItems().size() > 0) { // make request - Map hostConfig = this.smsConfigUtils.getMessageGateWayRequestURI("sms/report", new Gson().toJson(smsMessageInternalIds.getPageItems())) ; + 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, 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 dfd82c8fd..69fe96a11 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 @@ -54,7 +54,7 @@ public class SmsReadPlatformServiceImpl implements SmsReadPlatformService { @Autowired public SmsReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.smsRowMapper = new SmsMapper(); this.columnValidator = columnValidator; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/LikelihoodApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/LikelihoodApiConstants.java index c1d14b7bd..160349b6c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/LikelihoodApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/LikelihoodApiConstants.java @@ -30,6 +30,6 @@ public class LikelihoodApiConstants { public static final String LIKELIHOOD_RESOURCE_NAME = "likelihood"; - protected static final Set VALID_LIKELIHOOD_ENABLED_VALUES = new HashSet<>( - Arrays.asList(LikelihoodStatus.DISABLED, LikelihoodStatus.ENABLED)); + protected static final Set VALID_LIKELIHOOD_ENABLED_VALUES = new HashSet<>( + Arrays.asList(LikelihoodStatus.DISABLED, LikelihoodStatus.ENABLED)); } 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 1028d0151..5b03af00c 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 @@ -47,8 +47,8 @@ import java.util.Set; 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) { 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 fe8f87cd1..0dfc80694 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 @@ -97,7 +97,7 @@ public class ReadSurveyServiceImpl implements ReadSurveyService { @Override public SurveyDataTableData retrieveSurvey(String surveyName) { - SQLInjectionValidator.validateSQLInput(surveyName); + SQLInjectionValidator.validateSQLInput(surveyName); final String sql = "select cf.enabled, application_table_name, registered_table_name" + " from x_registered_table " + " left 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" 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 88713d0c6..24e597b19 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 @@ -36,59 +36,59 @@ import org.springframework.jms.listener.DefaultMessageListenerContainer; @Configuration public class MessagingConfiguration { - - @Autowired - private Environment env; - - @Autowired - private NotificationEventListener notificationEventListener; + + @Autowired + private Environment env; + + @Autowired + private NotificationEventListener notificationEventListener; - @Bean - public Logger loggerBean() { return LoggerFactory.getLogger(TenantDataSourcePortFixService.class); } + @Bean + public Logger loggerBean() { return LoggerFactory.getLogger(TenantDataSourcePortFixService.class); } - private static final String DEFAULT_BROKER_URL = "tcp://localhost:61616"; - + private static final String DEFAULT_BROKER_URL = "tcp://localhost:61616"; + @Bean public ActiveMQConnectionFactory amqConnectionFactory(){ ActiveMQConnectionFactory amqConnectionFactory = new ActiveMQConnectionFactory(); try { - amqConnectionFactory.setBrokerURL(DEFAULT_BROKER_URL); + amqConnectionFactory.setBrokerURL(DEFAULT_BROKER_URL); } catch(Exception e) { - amqConnectionFactory.setBrokerURL(this.env.getProperty("brokerUrl")); + amqConnectionFactory.setBrokerURL(this.env.getProperty("brokerUrl")); } return amqConnectionFactory; } @Bean public CachingConnectionFactory connectionFactory() { - CachingConnectionFactory connectionFactory = new CachingConnectionFactory(amqConnectionFactory()); - return connectionFactory; + CachingConnectionFactory connectionFactory = new CachingConnectionFactory(amqConnectionFactory()); + return connectionFactory; } @Bean public JmsTemplate jmsTemplate(){ - JmsTemplate jmsTemplate ; - jmsTemplate = new JmsTemplate(connectionFactory()); - jmsTemplate.setConnectionFactory(connectionFactory()); - return jmsTemplate; + JmsTemplate jmsTemplate ; + jmsTemplate = new JmsTemplate(connectionFactory()); + jmsTemplate.setConnectionFactory(connectionFactory()); + return jmsTemplate; } @Bean public DefaultMessageListenerContainer messageListenerContainer() { - - DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer(); - messageListenerContainer.setConnectionFactory(connectionFactory()); - messageListenerContainer.setDestinationName("NotificationQueue"); - messageListenerContainer.setMessageListener(notificationEventListener); - messageListenerContainer.setExceptionListener(new ExceptionListener() { - @Override + + DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer(); + messageListenerContainer.setConnectionFactory(connectionFactory()); + messageListenerContainer.setDestinationName("NotificationQueue"); + messageListenerContainer.setMessageListener(notificationEventListener); + messageListenerContainer.setExceptionListener(new ExceptionListener() { + @Override public void onException(JMSException jmse) { - loggerBean().error("Network Error: ActiveMQ Broker Unavailable."); - messageListenerContainer.shutdown(); + loggerBean().error("Network Error: ActiveMQ Broker Unavailable."); + messageListenerContainer.shutdown(); } - }); - return messageListenerContainer; + }); + return messageListenerContainer; } } 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 b4937abb0..9626e9ebc 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 @@ -41,7 +41,7 @@ public class NotificationData implements Serializable { } public NotificationData(String objectType, Long objectId, String action, Long actorId, String content, boolean isSystemGenerated, - boolean isRead, String tenantIdentifier, Long officeId, List userIds) { + boolean isRead, String tenantIdentifier, Long officeId, List userIds) { this.objectType = objectType; this.objectId = objectId; this.action = action; @@ -126,13 +126,13 @@ public class NotificationData implements Serializable { this.content = content; } - public boolean isRead() { - return this.isRead; - } + public boolean isRead() { + return this.isRead; + } - public void setRead(boolean isRead) { - this.isRead = isRead; - } + public void setRead(boolean isRead) { + this.isRead = isRead; + } public boolean isSystemGenerated() { return isSystemGenerated; 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 9e070fbd2..c6f957390 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 @@ -22,55 +22,55 @@ import java.io.Serializable; public class TopicData implements Serializable { - private final Long id; - private final String title; - private final boolean enabled; - private final Long entityId; - private final String entityType; - private final String memberType; + private final Long id; + private final String title; + private final boolean enabled; + private final Long entityId; + private final String entityType; + private final 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; - this.entityId = entityId; - this.entityType = entityType; - this.memberType = memberType; - } + public TopicData(Long id, String title, boolean enabled, Long entityId, String entityType, + String memberType) { + this.id = id; + this.title = title; + this.enabled = enabled; + this.entityId = entityId; + this.entityType = entityType; + this.memberType = memberType; + } - public TopicData(Long id, String title, Long entityId, String entityType, - String memberType) { - this.id = id; - this.title = title; - this.enabled = true; - this.entityId = entityId; - this.entityType = entityType; - this.memberType = memberType; - } + public TopicData(Long id, String title, Long entityId, String entityType, + String memberType) { + this.id = id; + this.title = title; + this.enabled = true; + this.entityId = entityId; + this.entityType = entityType; + this.memberType = memberType; + } - public Long getId() { - return this.id; - } + public Long getId() { + return this.id; + } - public String getTitle() { - return this.title; - } + public String getTitle() { + return this.title; + } - public boolean isEnabled() { - return this.enabled; - } + public boolean isEnabled() { + return this.enabled; + } - public Long getEntityId() { - return this.entityId; - } + public Long getEntityId() { + return this.entityId; + } - public String getEntityType() { - return this.entityType; - } + public String getEntityType() { + return this.entityType; + } - public String getMemberType() { - return this.memberType; - } + public String getMemberType() { + return this.memberType; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/data/TopicSubscriberData.java b/fineract-provider/src/main/java/org/apache/fineract/notification/data/TopicSubscriberData.java index 769169472..64009bcf6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/data/TopicSubscriberData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/data/TopicSubscriberData.java @@ -21,40 +21,40 @@ package org.apache.fineract.notification.data; import org.joda.time.LocalDate; public class TopicSubscriberData { - - private final Long id; - private final Long topicId; - private final Long userId; - private final LocalDate subscriptionDate; - - public TopicSubscriberData(Long id, Long topicId, Long userId, LocalDate subscriptionDate) { - this.id = id; - this.topicId = topicId; - this.userId = userId; - this.subscriptionDate = subscriptionDate; - } + + private final Long id; + private final Long topicId; + private final Long userId; + private final LocalDate subscriptionDate; + + public TopicSubscriberData(Long id, Long topicId, Long userId, LocalDate subscriptionDate) { + this.id = id; + this.topicId = topicId; + this.userId = userId; + this.subscriptionDate = subscriptionDate; + } - public TopicSubscriberData(Long id, Long topicId, Long userId) { - this.id = id; - this.topicId = topicId; - this.userId = userId; - this.subscriptionDate = new LocalDate(); - } + public TopicSubscriberData(Long id, Long topicId, Long userId) { + this.id = id; + this.topicId = topicId; + this.userId = userId; + this.subscriptionDate = new LocalDate(); + } - public Long getId() { - return this.id; - } + public Long getId() { + return this.id; + } - public Long getTopicId() { - return this.topicId; - } + public Long getTopicId() { + return this.topicId; + } - public Long getUserId() { - return this.userId; - } + public Long getUserId() { + return this.userId; + } - public LocalDate getSubscriptionDate() { - return this.subscriptionDate; - } - + public LocalDate getSubscriptionDate() { + return this.subscriptionDate; + } + } 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 62f1a5681..3c579f8e2 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 @@ -28,95 +28,95 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "topic") public class Topic extends AbstractPersistableCustom { - @Column(name = "title", unique = true, nullable = false, length = 100) - private String title; - - @Column(name = "enabled", nullable = false) - private Boolean enabled; - - @Column(name = "entity_id", nullable = false) - private Long entityId; - - @Column(name = "entity_type") - private String entityType; - - @Column(name = "member_type") - private String memberType; - - public Topic() { - } - - public Topic(String title, Boolean enabled, Long entityId, String entityType, String memberType) { - this.title = title.trim(); - this.enabled = enabled; - this.entityId = entityId; - this.entityType = entityType.trim(); - this.memberType = memberType.trim(); - } + @Column(name = "title", unique = true, nullable = false, length = 100) + private String title; + + @Column(name = "enabled", nullable = false) + private Boolean enabled; + + @Column(name = "entity_id", nullable = false) + private Long entityId; + + @Column(name = "entity_type") + private String entityType; + + @Column(name = "member_type") + private String memberType; + + public Topic() { + } + + public Topic(String title, Boolean enabled, Long entityId, String entityType, String memberType) { + this.title = title.trim(); + this.enabled = enabled; + this.entityId = entityId; + this.entityType = entityType.trim(); + this.memberType = memberType.trim(); + } - public static Topic fromJson(final JsonCommand command) { - String title = ""; - Boolean enabled = null; - Long entityId = 0L; - String entityType = ""; - String memberType = ""; - - if (command.hasParameter("title")) { - title = command.stringValueOfParameterNamed("title"); - } - if (command.hasParameter("enabled")) { - enabled = command.booleanPrimitiveValueOfParameterNamed("enabled"); - } - if (command.hasParameter("entityId")) { - entityId = command.longValueOfParameterNamed("entityId"); - } - if (command.hasParameter("entityType")) { - entityType = command.stringValueOfParameterNamed("entityType"); - } - if (command.hasParameter("memberType")) { - memberType = command.stringValueOfParameterNamed("memberType"); - } - return new Topic(title, enabled, entityId, entityType, memberType); - } + public static Topic fromJson(final JsonCommand command) { + String title = ""; + Boolean enabled = null; + Long entityId = 0L; + String entityType = ""; + String memberType = ""; + + if (command.hasParameter("title")) { + title = command.stringValueOfParameterNamed("title"); + } + if (command.hasParameter("enabled")) { + enabled = command.booleanPrimitiveValueOfParameterNamed("enabled"); + } + if (command.hasParameter("entityId")) { + entityId = command.longValueOfParameterNamed("entityId"); + } + if (command.hasParameter("entityType")) { + entityType = command.stringValueOfParameterNamed("entityType"); + } + if (command.hasParameter("memberType")) { + memberType = command.stringValueOfParameterNamed("memberType"); + } + return new Topic(title, enabled, entityId, entityType, memberType); + } - public String getTitle() { - return this.title; - } + public String getTitle() { + return this.title; + } - public void setTitle(String title) { - this.title = title; - } + public void setTitle(String title) { + this.title = title; + } - public Boolean getEnabled() { - return this.enabled; - } + public Boolean getEnabled() { + return this.enabled; + } - public void setEnabled(Boolean enabled) { - this.enabled = enabled; - } + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } - public Long getEntityId() { - return this.entityId; - } + public Long getEntityId() { + return this.entityId; + } - public void setEntityId(Long entityId) { - this.entityId = entityId; - } + public void setEntityId(Long entityId) { + this.entityId = entityId; + } - public String getEntityType() { - return this.entityType; - } + public String getEntityType() { + return this.entityType; + } - public void setEntityType(String entityType) { - this.entityType = entityType; - } + public void setEntityType(String entityType) { + this.entityType = entityType; + } - public String getMemberType() { - return this.memberType; - } + public String getMemberType() { + return this.memberType; + } - public void setMemberType(String memberType) { - this.memberType = memberType; - } - + public void setMemberType(String memberType) { + this.memberType = memberType; + } + } 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 c01bb7be0..3c300db2c 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 @@ -24,6 +24,6 @@ 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); + 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 74ef96021..4a39db8b3 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 @@ -33,48 +33,48 @@ import org.apache.fineract.useradministration.domain.AppUser; @Table(name = "topic_subscriber") public class TopicSubscriber extends AbstractPersistableCustom { - @ManyToOne - @JoinColumn(name = "topic_id") - private Topic topic; - - @ManyToOne - @JoinColumn(name = "user_id") - private AppUser subscriber; - - @Column(name = "subscription_date") - private Date subscriptionDate; + @ManyToOne + @JoinColumn(name = "topic_id") + private Topic topic; + + @ManyToOne + @JoinColumn(name = "user_id") + private AppUser subscriber; + + @Column(name = "subscription_date") + private Date subscriptionDate; - public TopicSubscriber() { - } + public TopicSubscriber() { + } - public TopicSubscriber(Topic topic, AppUser subscriber, Date subscriptionDate) { - this.topic = topic; - this.subscriber = subscriber; - this.subscriptionDate = subscriptionDate; - } + public TopicSubscriber(Topic topic, AppUser subscriber, Date subscriptionDate) { + this.topic = topic; + this.subscriber = subscriber; + this.subscriptionDate = subscriptionDate; + } - public Topic getTopic() { - return this.topic; - } + public Topic getTopic() { + return this.topic; + } - public void setTopic(Topic topic) { - this.topic = topic; - } + public void setTopic(Topic topic) { + this.topic = topic; + } - public AppUser getSubscriber() { - return this.subscriber; - } + public AppUser getSubscriber() { + return this.subscriber; + } - public void setSubscriber(AppUser subscriber) { - this.subscriber = subscriber; - } + public void setSubscriber(AppUser subscriber) { + this.subscriber = subscriber; + } - public Date getSubscriptionDate() { - return this.subscriptionDate; - } + public Date getSubscriptionDate() { + return this.subscriptionDate; + } - public void setSubscriptionDate(Date subscriptionDate) { - this.subscriptionDate = subscriptionDate; - } - + public void setSubscriptionDate(Date subscriptionDate) { + this.subscriptionDate = subscriptionDate; + } + } 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 cd67fb942..65d884c1f 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 @@ -25,5 +25,5 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface TopicSubscriberRepository extends JpaRepository, JpaSpecificationExecutor { - List findBySubscriber(AppUser subscriber); + List findBySubscriber(AppUser subscriber); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEvent.java b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEvent.java index 0a27cd535..9650c04b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEvent.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEvent.java @@ -24,8 +24,8 @@ import org.springframework.context.ApplicationEvent; @SuppressWarnings("serial") public class SpringEvent extends ApplicationEvent { - private NotificationData notificationData; - + private NotificationData notificationData; + public SpringEvent(Object source, NotificationData notificationData) { super(source); this.notificationData = notificationData; @@ -34,5 +34,5 @@ public class SpringEvent extends ApplicationEvent { public NotificationData getNotificationData() { return 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 c469e9cf0..6cd7a2b64 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 @@ -35,8 +35,8 @@ import org.springframework.stereotype.Component; @Component public class SpringEventListener implements ApplicationListener { - - private final BasicAuthTenantDetailsService basicAuthTenantDetailsService; + + private final BasicAuthTenantDetailsService basicAuthTenantDetailsService; private final NotificationWritePlatformService notificationWritePlatformService; @@ -51,11 +51,11 @@ public class SpringEventListener implements ApplicationListener { this.appUserRepository = appUserRepository; } - @Override - public void onApplicationEvent(SpringEvent event) { - NotificationData notificationData = event.getNotificationData(); - - final FineractPlatformTenant tenant = this.basicAuthTenantDetailsService + @Override + public void onApplicationEvent(SpringEvent event) { + NotificationData notificationData = event.getNotificationData(); + + final FineractPlatformTenant tenant = this.basicAuthTenantDetailsService .loadTenantById(notificationData.getTenantIdentifier(), false); ThreadLocalContextUtil.setTenant(tenant); @@ -86,7 +86,7 @@ public class SpringEventListener implements ApplicationListener { 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 1e7ed0625..8d4d0390f 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,10 +25,10 @@ import org.springframework.stereotype.Service; @Service public class SpringEventPublisher { - @Autowired - private ApplicationEventPublisher applicationEventPublisher; - - public void broadcastNotification(final NotificationData notificationData) { + @Autowired + private ApplicationEventPublisher applicationEventPublisher; + + public void broadcastNotification(final NotificationData notificationData) { SpringEvent event = new SpringEvent(this, notificationData); applicationEventPublisher.publishEvent(event); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/exception/TopicNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/notification/exception/TopicNotFoundException.java index 857ef4c4f..4c9b48168 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/exception/TopicNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/exception/TopicNotFoundException.java @@ -25,8 +25,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc */ public class TopicNotFoundException extends AbstractPlatformResourceNotFoundException { - public TopicNotFoundException(final Long id) { - super("error.msg.topic.id.invalid", "Topic with identifier " + id + " does not exist", id); - } + public TopicNotFoundException(final Long id) { + super("error.msg.topic.id.invalid", "Topic with identifier " + id + " does not exist", id); + } } 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 acda16d00..6dee234f5 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 @@ -59,552 +59,552 @@ import java.util.Map; @Service public class NotificationDomainServiceImpl implements NotificationDomainService { - private final BusinessEventNotifierService businessEventNotifierService; - final PlatformSecurityContext context; - private final RoleRepository roleRepository; - private final OfficeRepository officeRepository; - private final TopicSubscriberReadPlatformService topicSubscriberReadPlatformService; - private final NotificationEventService notificationEvent; - private final SpringEventPublisher springEventPublisher; - - @Autowired - public NotificationDomainServiceImpl(final BusinessEventNotifierService businessEventNotifierService, - final PlatformSecurityContext context, final RoleRepository roleRepository, - final TopicSubscriberReadPlatformService topicSubscriberReadPlatformService, - final OfficeRepository officeRepository, final NotificationEventService notificationEvent, - final SpringEventPublisher springEventPublisher) { - - this.businessEventNotifierService = businessEventNotifierService; - this.context = context; - this.roleRepository = roleRepository; - this.topicSubscriberReadPlatformService = topicSubscriberReadPlatformService; - this.officeRepository = officeRepository; - this.notificationEvent = notificationEvent; - this.springEventPublisher = springEventPublisher; - } - - @PostConstruct - public void addListeners() { - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.CLIENTS_CREATE, - new ClientCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_APPROVE, - new SavingsAccountApprovedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.CENTERS_CREATE, - new CenterCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.GROUPS_CREATE, - new GroupCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_DEPOSIT, - new SavingsAccountDepositListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SHARE_PRODUCT_DIVIDENDS_CREATE, - new ShareProductDividendCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.FIXED_DEPOSIT_ACCOUNT_CREATE, - new FixedDepositAccountCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.RECURRING_DEPOSIT_ACCOUNT_CREATE, - new RecurringDepositAccountCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_POST_INTEREST, - new SavingsPostInterestListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_CREATE, - new LoanCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_APPROVED, - new LoanApprovedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_CLOSE, - new LoanClosedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_CLOSE_AS_RESCHEDULE, - new LoanCloseAsRescheduledListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_MAKE_REPAYMENT, - new LoanMakeRepaymentListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_PRODUCT_CREATE, - new LoanProductCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_CREATE, - new SavingsAccountCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_CLOSE, - new SavingsAccountClosedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SHARE_ACCOUNT_CREATE, - new ShareAccountCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SHARE_ACCOUNT_APPROVE, - new ShareAccountApprovedListener()); - } - - private abstract class NotificationBusinessEventAdapter implements BusinessEventListner { - @Override - public void businessEventToBeExecuted(Map businessEventEntity) { - } - } - - private class ClientCreatedListener extends NotificationBusinessEventAdapter { + private final BusinessEventNotifierService businessEventNotifierService; + final PlatformSecurityContext context; + private final RoleRepository roleRepository; + private final OfficeRepository officeRepository; + private final TopicSubscriberReadPlatformService topicSubscriberReadPlatformService; + private final NotificationEventService notificationEvent; + private final SpringEventPublisher springEventPublisher; + + @Autowired + public NotificationDomainServiceImpl(final BusinessEventNotifierService businessEventNotifierService, + final PlatformSecurityContext context, final RoleRepository roleRepository, + final TopicSubscriberReadPlatformService topicSubscriberReadPlatformService, + final OfficeRepository officeRepository, final NotificationEventService notificationEvent, + final SpringEventPublisher springEventPublisher) { + + this.businessEventNotifierService = businessEventNotifierService; + this.context = context; + this.roleRepository = roleRepository; + this.topicSubscriberReadPlatformService = topicSubscriberReadPlatformService; + this.officeRepository = officeRepository; + this.notificationEvent = notificationEvent; + this.springEventPublisher = springEventPublisher; + } + + @PostConstruct + public void addListeners() { + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.CLIENTS_CREATE, + new ClientCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_APPROVE, + new SavingsAccountApprovedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.CENTERS_CREATE, + new CenterCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.GROUPS_CREATE, + new GroupCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_DEPOSIT, + new SavingsAccountDepositListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SHARE_PRODUCT_DIVIDENDS_CREATE, + new ShareProductDividendCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.FIXED_DEPOSIT_ACCOUNT_CREATE, + new FixedDepositAccountCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.RECURRING_DEPOSIT_ACCOUNT_CREATE, + new RecurringDepositAccountCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_POST_INTEREST, + new SavingsPostInterestListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_CREATE, + new LoanCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_APPROVED, + new LoanApprovedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_CLOSE, + new LoanClosedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_CLOSE_AS_RESCHEDULE, + new LoanCloseAsRescheduledListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_MAKE_REPAYMENT, + new LoanMakeRepaymentListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_PRODUCT_CREATE, + new LoanProductCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_CREATE, + new SavingsAccountCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_CLOSE, + new SavingsAccountClosedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SHARE_ACCOUNT_CREATE, + new ShareAccountCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SHARE_ACCOUNT_APPROVE, + new ShareAccountApprovedListener()); + } + + private abstract class NotificationBusinessEventAdapter implements BusinessEventListner { + @Override + public void businessEventToBeExecuted(Map businessEventEntity) { + } + } + + private class ClientCreatedListener extends NotificationBusinessEventAdapter { - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Client client; - Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT); - if (entity != null) { - client = (Client) entity; - buildNotification( - "ACTIVATE_CLIENT", - "client", - client.getId(), - "New client created", - "created", - context.authenticatedUser().getId(), - client.getOffice().getId() - ); - } - } - } - - private class CenterCreatedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - CommandProcessingResult commandProcessingResult; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.GROUP); - if (entity != null) { - commandProcessingResult = (CommandProcessingResult) entity; - buildNotification( - "ACTIVATE_CENTER", - "center", - commandProcessingResult.getGroupId(), - "New center created", - "created", - context.authenticatedUser().getId(), - commandProcessingResult.getOfficeId() - ); - } - } - } - - private class GroupCreatedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - CommandProcessingResult commandProcessingResult; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.GROUP); - if (entity != null) { - commandProcessingResult = (CommandProcessingResult) entity; - buildNotification( - "ACTIVATE_GROUP", - "group", - commandProcessingResult.getGroupId(), - "New group created", - "created", - context.authenticatedUser().getId(), - commandProcessingResult.getOfficeId() - ); - } - } - } - - private class SavingsAccountDepositListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - SavingsAccountTransaction savingsAccountTransaction; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.SAVINGS_TRANSACTION); - if (entity != null) { - savingsAccountTransaction = (SavingsAccountTransaction) entity; - buildNotification( - "READ_SAVINGSACCOUNT", - "savingsAccount", - savingsAccountTransaction.getSavingsAccount().getId(), - "Deposit made", - "depositMade", - context.authenticatedUser().getId(), - savingsAccountTransaction.getSavingsAccount().officeId() - ); - } - } - } - - private class ShareProductDividendCreatedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Long shareProductId; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() - ); - } - } - } - - private class FixedDepositAccountCreatedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - FixedDepositAccount fixedDepositAccount; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() - ); - } - } - } - - private class RecurringDepositAccountCreatedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - RecurringDepositAccount recurringDepositAccount; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() - ); - } - } - } - - private class SavingsAccountApprovedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - SavingsAccount savingsAccount; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() - ); - } else if (savingsAccount.depositAccountType().equals(DepositAccountType.RECURRING_DEPOSIT)) { - - 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() - ); - } - } - } - } - - private class SavingsPostInterestListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - SavingsAccount savingsAccount; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.SAVING); - if (entity != null) { - savingsAccount = (SavingsAccount) entity; - buildNotification( - "READ_SAVINGSACCOUNT", - "savingsAccount", - savingsAccount.getId(), - "Interest posted to account", - "interestPosted", - context.authenticatedUser().getId(), - savingsAccount.officeId() - ); - } - } - } - - private class LoanCreatedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Loan loan; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); - if (entity != null) { - loan = (Loan) entity; - buildNotification( - "APPROVE_LOAN", - "loan", - loan.getId(), - "New loan created", - "created", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); - } - - } - } - - private class LoanApprovedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Loan loan; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); - if (entity != null) { - loan = (Loan) entity; - buildNotification( - "DISBURSE_LOAN", - "loan", - loan.getId(), - "New loan approved", - "approved", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); - } - } - } - - private class LoanClosedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - - Loan loan; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); - if (entity != null) { - loan = (Loan) entity; - buildNotification( - "READ_LOAN", - "loan", - loan.getId(), - "Loan closed", - "loanClosed", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); - } - } - } - - private class LoanCloseAsRescheduledListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Loan loan; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); - if (entity != null) { - loan = (Loan) entity; - buildNotification( - "READ_Rescheduled Loans", - "loan", - loan.getId(), - "Loan has been rescheduled", - "loanRescheduled", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); - } - } - } - - private class LoanMakeRepaymentListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - Loan loan; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); - if (entity != null) { - loan = (Loan) entity; - buildNotification( - "READ_LOAN", - "loan", - loan.getId(), - "Repayment made", - "repaymentMade", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); - } - } - } - - private class LoanProductCreatedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - - LoanProduct loanProduct; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() - ); - } - } - } - - private class SavingsAccountCreatedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - SavingsAccount savingsAccount; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.SAVING); - if (entity != null) { - savingsAccount = (SavingsAccount) entity; - buildNotification( - "APPROVE_SAVINGSACCOUNT", - "savingsAccount", - savingsAccount.getId(), - "New savings account created", - "created", - context.authenticatedUser().getId(), - savingsAccount.officeId() - ); - } - } - } - - private class SavingsAccountClosedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - SavingsAccount savingsAccount; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.SAVING); - if (entity != null) { - savingsAccount = (SavingsAccount) entity; - buildNotification( - "READ_SAVINGSACCOUNT", - "savingsAccount", - savingsAccount.getId(), - "Savings has gone into dormant", - "closed", - context.authenticatedUser().getId(), - savingsAccount.officeId() - ); - } - } - } - - private class ShareAccountCreatedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - ShareAccount shareAccount; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.SHARE_ACCOUNT); - if (entity != null) { - shareAccount = (ShareAccount) entity; - buildNotification( - "APPROVE_SHAREACCOUNT", - "shareAccount", - shareAccount.getId(), - "New share account created", - "created", - context.authenticatedUser().getId(), - shareAccount.getOfficeId() - ); - } - } - } - - private class ShareAccountApprovedListener extends NotificationBusinessEventAdapter { - - @Override - public void businessEventWasExecuted(Map businessEventEntity) { - ShareAccount shareAccount; - Object entity = businessEventEntity.get(BUSINESS_ENTITY.SHARE_ACCOUNT); - if (entity != null) { - shareAccount = (ShareAccount) entity; - 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) { - - 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 - ); - try { - this.notificationEvent.broadcastNotification(queue, notificationData); - } catch(Exception e) { - this.springEventPublisher.broadcastNotification(notificationData); - } - } - - private List retrieveSubscribers(Long officeId, String permission) { - - Set topicSubscribers = new HashSet<>(); - List subscriberIds = new ArrayList<>(); - Long entityId = officeId; - String entityType= ""; - if (officeRepository.findById(entityId).get().getParent() == null) { - entityType = "OFFICE"; - } else { - entityType = "BRANCH"; - } - List allRoles = roleRepository.findAll(); - for (Role curRole : allRoles) { - if (curRole.hasPermissionTo(permission) || curRole.hasPermissionTo("ALL_FUNCTIONS")) { - String memberType = curRole.getName(); - topicSubscribers.addAll(topicSubscriberReadPlatformService.getSubscribers(entityId, entityType, memberType)); - } - } - - for (TopicSubscriberData topicSubscriber : topicSubscribers) { - subscriberIds.add(topicSubscriber.getUserId()); - } - return subscriberIds; - } + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Client client; + Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT); + if (entity != null) { + client = (Client) entity; + buildNotification( + "ACTIVATE_CLIENT", + "client", + client.getId(), + "New client created", + "created", + context.authenticatedUser().getId(), + client.getOffice().getId() + ); + } + } + } + + private class CenterCreatedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + CommandProcessingResult commandProcessingResult; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.GROUP); + if (entity != null) { + commandProcessingResult = (CommandProcessingResult) entity; + buildNotification( + "ACTIVATE_CENTER", + "center", + commandProcessingResult.getGroupId(), + "New center created", + "created", + context.authenticatedUser().getId(), + commandProcessingResult.getOfficeId() + ); + } + } + } + + private class GroupCreatedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + CommandProcessingResult commandProcessingResult; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.GROUP); + if (entity != null) { + commandProcessingResult = (CommandProcessingResult) entity; + buildNotification( + "ACTIVATE_GROUP", + "group", + commandProcessingResult.getGroupId(), + "New group created", + "created", + context.authenticatedUser().getId(), + commandProcessingResult.getOfficeId() + ); + } + } + } + + private class SavingsAccountDepositListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + SavingsAccountTransaction savingsAccountTransaction; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.SAVINGS_TRANSACTION); + if (entity != null) { + savingsAccountTransaction = (SavingsAccountTransaction) entity; + buildNotification( + "READ_SAVINGSACCOUNT", + "savingsAccount", + savingsAccountTransaction.getSavingsAccount().getId(), + "Deposit made", + "depositMade", + context.authenticatedUser().getId(), + savingsAccountTransaction.getSavingsAccount().officeId() + ); + } + } + } + + private class ShareProductDividendCreatedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Long shareProductId; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() + ); + } + } + } + + private class FixedDepositAccountCreatedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + FixedDepositAccount fixedDepositAccount; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() + ); + } + } + } + + private class RecurringDepositAccountCreatedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + RecurringDepositAccount recurringDepositAccount; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() + ); + } + } + } + + private class SavingsAccountApprovedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + SavingsAccount savingsAccount; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() + ); + } else if (savingsAccount.depositAccountType().equals(DepositAccountType.RECURRING_DEPOSIT)) { + + 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() + ); + } + } + } + } + + private class SavingsPostInterestListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + SavingsAccount savingsAccount; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.SAVING); + if (entity != null) { + savingsAccount = (SavingsAccount) entity; + buildNotification( + "READ_SAVINGSACCOUNT", + "savingsAccount", + savingsAccount.getId(), + "Interest posted to account", + "interestPosted", + context.authenticatedUser().getId(), + savingsAccount.officeId() + ); + } + } + } + + private class LoanCreatedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Loan loan; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); + if (entity != null) { + loan = (Loan) entity; + buildNotification( + "APPROVE_LOAN", + "loan", + loan.getId(), + "New loan created", + "created", + context.authenticatedUser().getId(), + loan.getOfficeId() + ); + } + + } + } + + private class LoanApprovedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Loan loan; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); + if (entity != null) { + loan = (Loan) entity; + buildNotification( + "DISBURSE_LOAN", + "loan", + loan.getId(), + "New loan approved", + "approved", + context.authenticatedUser().getId(), + loan.getOfficeId() + ); + } + } + } + + private class LoanClosedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + + Loan loan; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); + if (entity != null) { + loan = (Loan) entity; + buildNotification( + "READ_LOAN", + "loan", + loan.getId(), + "Loan closed", + "loanClosed", + context.authenticatedUser().getId(), + loan.getOfficeId() + ); + } + } + } + + private class LoanCloseAsRescheduledListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Loan loan; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); + if (entity != null) { + loan = (Loan) entity; + buildNotification( + "READ_Rescheduled Loans", + "loan", + loan.getId(), + "Loan has been rescheduled", + "loanRescheduled", + context.authenticatedUser().getId(), + loan.getOfficeId() + ); + } + } + } + + private class LoanMakeRepaymentListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + Loan loan; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN); + if (entity != null) { + loan = (Loan) entity; + buildNotification( + "READ_LOAN", + "loan", + loan.getId(), + "Repayment made", + "repaymentMade", + context.authenticatedUser().getId(), + loan.getOfficeId() + ); + } + } + } + + private class LoanProductCreatedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + + LoanProduct loanProduct; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.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() + ); + } + } + } + + private class SavingsAccountCreatedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + SavingsAccount savingsAccount; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.SAVING); + if (entity != null) { + savingsAccount = (SavingsAccount) entity; + buildNotification( + "APPROVE_SAVINGSACCOUNT", + "savingsAccount", + savingsAccount.getId(), + "New savings account created", + "created", + context.authenticatedUser().getId(), + savingsAccount.officeId() + ); + } + } + } + + private class SavingsAccountClosedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + SavingsAccount savingsAccount; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.SAVING); + if (entity != null) { + savingsAccount = (SavingsAccount) entity; + buildNotification( + "READ_SAVINGSACCOUNT", + "savingsAccount", + savingsAccount.getId(), + "Savings has gone into dormant", + "closed", + context.authenticatedUser().getId(), + savingsAccount.officeId() + ); + } + } + } + + private class ShareAccountCreatedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + ShareAccount shareAccount; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.SHARE_ACCOUNT); + if (entity != null) { + shareAccount = (ShareAccount) entity; + buildNotification( + "APPROVE_SHAREACCOUNT", + "shareAccount", + shareAccount.getId(), + "New share account created", + "created", + context.authenticatedUser().getId(), + shareAccount.getOfficeId() + ); + } + } + } + + private class ShareAccountApprovedListener extends NotificationBusinessEventAdapter { + + @Override + public void businessEventWasExecuted(Map businessEventEntity) { + ShareAccount shareAccount; + Object entity = businessEventEntity.get(BUSINESS_ENTITY.SHARE_ACCOUNT); + if (entity != null) { + shareAccount = (ShareAccount) entity; + 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) { + + 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 + ); + try { + this.notificationEvent.broadcastNotification(queue, notificationData); + } catch(Exception e) { + this.springEventPublisher.broadcastNotification(notificationData); + } + } + + private List retrieveSubscribers(Long officeId, String permission) { + + Set topicSubscribers = new HashSet<>(); + List subscriberIds = new ArrayList<>(); + Long entityId = officeId; + String entityType= ""; + if (officeRepository.findById(entityId).get().getParent() == null) { + entityType = "OFFICE"; + } else { + entityType = "BRANCH"; + } + List allRoles = roleRepository.findAll(); + for (Role curRole : allRoles) { + if (curRole.hasPermissionTo(permission) || curRole.hasPermissionTo("ALL_FUNCTIONS")) { + String memberType = curRole.getName(); + topicSubscribers.addAll(topicSubscriberReadPlatformService.getSubscribers(entityId, entityType, memberType)); + } + } + + for (TopicSubscriberData topicSubscriber : topicSubscribers) { + subscriberIds.add(topicSubscriber.getUserId()); + } + return subscriberIds; + } } 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 4d3dc6a38..5e692c8e2 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 @@ -52,8 +52,8 @@ public class NotificationReadPlatformServiceImpl implements NotificationReadPlat @Autowired public NotificationReadPlatformServiceImpl(final RoutingDataSource dataSource, - final PlatformSecurityContext context, - final ColumnValidator columnValidator) { + final PlatformSecurityContext context, + final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.context = context; this.columnValidator = columnValidator; 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 f96befd74..bc4baf0f0 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,21 +25,21 @@ import org.apache.fineract.useradministration.domain.AppUser; import org.apache.fineract.useradministration.domain.Role; public interface TopicDomainService { - - public void createTopic( Office newOffice ); - - public void createTopic( Role newRole ); - - public void updateTopic( Office updatedOffice, Map changes ); - - public void updateTopic( String previousRolename, Role updatedRole, Map changes ); - - public void deleteTopic( Role role ); - - public void subscribeUserToTopic( AppUser newUser ); - - public void updateUserSubscription( AppUser userToUpdate, Map changes ); - - public void unsubcribeUserFromTopic( AppUser user ); - + + public void createTopic( Office newOffice ); + + public void createTopic( Role newRole ); + + public void updateTopic( Office updatedOffice, Map changes ); + + public void updateTopic( String previousRolename, Role updatedRole, Map changes ); + + public void deleteTopic( Role role ); + + public void subscribeUserToTopic( AppUser newUser ); + + public void updateUserSubscription( AppUser userToUpdate, Map changes ); + + 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 77cbc69c1..8308f11ce 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 @@ -41,147 +41,147 @@ import org.springframework.util.ObjectUtils; @Service public class TopicDomainServiceImpl implements TopicDomainService { - private final RoleRepository roleRepository; - private final TopicRepository topicRepository; + private final RoleRepository roleRepository; + private final TopicRepository topicRepository; private final OfficeRepository officeRepository; private final TopicSubscriberRepository topicSubscriberRepository; - - @Autowired - public TopicDomainServiceImpl(RoleRepository roleRepository, TopicRepository topicRepository, - OfficeRepository officeRepository, TopicSubscriberRepository topicSubscriberRepository) { - - this.roleRepository = roleRepository; - this.topicRepository = topicRepository; - this.officeRepository = officeRepository; - this.topicSubscriberRepository = topicSubscriberRepository; - } - - @Override - public void createTopic( Office newOffice ) { - - Long entityId = newOffice.getId(); + + @Autowired + public TopicDomainServiceImpl(RoleRepository roleRepository, TopicRepository topicRepository, + OfficeRepository officeRepository, TopicSubscriberRepository topicSubscriberRepository) { + + this.roleRepository = roleRepository; + this.topicRepository = topicRepository; + this.officeRepository = officeRepository; + this.topicSubscriberRepository = topicSubscriberRepository; + } + + @Override + public void createTopic( Office newOffice ) { + + Long entityId = newOffice.getId(); String entityType = this.getEntityType(newOffice); List allRoles = roleRepository.findAll(); 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); - topicRepository.save(newTopic); + String memberType = role.getName().toUpperCase(); + String title = role.getName() + " of " + newOffice.getName(); + Topic newTopic = new Topic(title, true, entityId, entityType, memberType); + topicRepository.save(newTopic); } - } - - @Override - public void createTopic( Role newRole ) { - - List offices = officeRepository.findAll(); - + } + + @Override + public void createTopic( Role newRole ) { + + List offices = officeRepository.findAll(); + 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()); - topicRepository.save(newTopic); + String entityType = this.getEntityType(office); + String title = newRole.getName() + " of " + office.getName(); + Topic newTopic = new Topic(title, true, office.getId(), entityType, newRole.getName().toUpperCase()); + topicRepository.save(newTopic); } - } - - @Override - public void updateTopic( Office updatedOffice, Map changes ) { - - List entityTopics = topicRepository.findByEntityId(updatedOffice.getId()); - - if (changes.containsKey("parentId")) { - + } + + @Override + public void updateTopic( Office updatedOffice, Map changes ) { + + List entityTopics = topicRepository.findByEntityId(updatedOffice.getId()); + + if (changes.containsKey("parentId")) { + String entityType = this.getEntityType(updatedOffice); for (Topic topic : entityTopics) { - topic.setEntityType(entityType); - topicRepository.save(topic); + topic.setEntityType(entityType); + topicRepository.save(topic); } - } - if (changes.containsKey("name")) { - - for (Topic topic: entityTopics) { - Role role = roleRepository.getRoleByName(topic.getMemberType()); + } + if (changes.containsKey("name")) { + + for (Topic topic: entityTopics) { + Role role = roleRepository.getRoleByName(topic.getMemberType()); String title = role.getName() + " of " + updatedOffice.getName(); topic.setTitle(title); topicRepository.save(topic); - } + } } - } - - @Override - public void updateTopic( String previousRolename, Role updatedRole, Map changes ) { + } + + @Override + public void updateTopic( String previousRolename, Role updatedRole, Map changes ) { if (changes.containsKey("name")) { - List entityTopics = topicRepository.findByMemberType(previousRolename); - for (Topic topic : entityTopics) { - Office office = officeRepository.findById(topic.getEntityId()).get(); - String title = updatedRole.getName() + " of " + office.getName(); - topic.setTitle(title); - topic.setMemberType(updatedRole.getName().toUpperCase()); - topicRepository.save(topic); - } + List entityTopics = topicRepository.findByMemberType(previousRolename); + for (Topic topic : entityTopics) { + Office office = officeRepository.findById(topic.getEntityId()).get(); + String title = updatedRole.getName() + " of " + office.getName(); + topic.setTitle(title); + topic.setMemberType(updatedRole.getName().toUpperCase()); + topicRepository.save(topic); + } } - } - - @Override - public void deleteTopic( Role role ) { - - List topics = topicRepository.findByMemberType(role.getName().toUpperCase()); + } + + @Override + public void deleteTopic( Role role ) { + + List topics = topicRepository.findByMemberType(role.getName().toUpperCase()); for (Topic topic : topics) { - topicRepository.delete(topic); + topicRepository.delete(topic); } - } - - @Override - public void subscribeUserToTopic( AppUser newUser ) { - - List possibleTopics = topicRepository.findByEntityId(newUser.getOffice().getId()); + } + + @Override + public void subscribeUserToTopic( AppUser newUser ) { + + List possibleTopics = topicRepository.findByEntityId(newUser.getOffice().getId()); if (!possibleTopics.isEmpty()) { - Set userRoles = newUser.getRoles(); - for (Role role : userRoles) { - for (Topic topic : possibleTopics) { - if(role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { - TopicSubscriber topicSubscriber = new TopicSubscriber(topic, newUser, new Date()); - topicSubscriberRepository.save(topicSubscriber); - } - } - } + Set userRoles = newUser.getRoles(); + for (Role role : userRoles) { + for (Topic topic : possibleTopics) { + if(role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { + TopicSubscriber topicSubscriber = new TopicSubscriber(topic, newUser, new Date()); + topicSubscriberRepository.save(topicSubscriber); + } + } + } } - } - - @Override - public void updateUserSubscription( AppUser userToUpdate, Map changes ) { - - List oldSubscriptions = topicSubscriberRepository.findBySubscriber(userToUpdate); - if (changes.containsKey("officeId")) { - final Long oldOfficeId = userToUpdate.getOffice().getId(); - final Long newOfficeId = (Long) changes.get("officeId"); - List oldTopics = topicRepository.findByEntityId(oldOfficeId); + } + + @Override + public void updateUserSubscription( AppUser userToUpdate, Map changes ) { + + List oldSubscriptions = topicSubscriberRepository.findBySubscriber(userToUpdate); + if (changes.containsKey("officeId")) { + final Long oldOfficeId = userToUpdate.getOffice().getId(); + final Long newOfficeId = (Long) changes.get("officeId"); + List oldTopics = topicRepository.findByEntityId(oldOfficeId); List newTopics = topicRepository.findByEntityId(newOfficeId); for (TopicSubscriber subscriber : oldSubscriptions) { - for (Topic topic : oldTopics) { - if (subscriber.getTopic().getId().equals(topic.getId())) { - topicSubscriberRepository.delete(subscriber); - } - } + for (Topic topic : oldTopics) { + if (subscriber.getTopic().getId().equals(topic.getId())) { + topicSubscriberRepository.delete(subscriber); + } + } } Set userRoles = userToUpdate.getRoles(); - for (Role role : userRoles) { - for (Topic topic : newTopics) { - if (role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { - TopicSubscriber newSubscription = new TopicSubscriber(topic, userToUpdate, new Date()); - topicSubscriberRepository.save(newSubscription); - } - } - } - } - - if (changes.containsKey("roles")) { - - final Set oldRoles = userToUpdate.getRoles() ; + for (Role role : userRoles) { + for (Topic topic : newTopics) { + if (role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { + TopicSubscriber newSubscription = new TopicSubscriber(topic, userToUpdate, new Date()); + topicSubscriberRepository.save(newSubscription); + } + } + } + } + + if (changes.containsKey("roles")) { + + final Set oldRoles = userToUpdate.getRoles() ; final Set tempOldRoles = new HashSet<>(oldRoles); final String[] roleIds = (String[]) changes.get("roles"); @@ -190,47 +190,47 @@ public class TopicDomainServiceImpl implements TopicDomainService { tempOldRoles.removeAll(updatedRoles); for (TopicSubscriber subscriber : oldSubscriptions) { - Topic topic = subscriber.getTopic(); - for (Role role : tempOldRoles) { - if (role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { - topicSubscriberRepository.delete(subscriber); - } - } + Topic topic = subscriber.getTopic(); + for (Role role : tempOldRoles) { + if (role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { + topicSubscriberRepository.delete(subscriber); + } + } } tempUpdatedRoles.removeAll(oldRoles); List newTopics = topicRepository.findByEntityId(userToUpdate.getOffice().getId()); for (Topic topic : newTopics) { - for (Role role : tempUpdatedRoles) { - if (role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { - TopicSubscriber topicSubscriber = new TopicSubscriber(topic, userToUpdate, new Date()); - topicSubscriberRepository.save(topicSubscriber); - } - } + for (Role role : tempUpdatedRoles) { + if (role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { + TopicSubscriber topicSubscriber = new TopicSubscriber(topic, userToUpdate, new Date()); + topicSubscriberRepository.save(topicSubscriber); + } + } } - } - } - - @Override - public void unsubcribeUserFromTopic( AppUser user ) { - - List subscriptions = topicSubscriberRepository.findBySubscriber(user); + } + } + + @Override + public void unsubcribeUserFromTopic( AppUser user ) { + + List subscriptions = topicSubscriberRepository.findBySubscriber(user); for (TopicSubscriber subscription : subscriptions) { - topicSubscriberRepository.delete(subscription); + topicSubscriberRepository.delete(subscription); } - } - + } + - private String getEntityType( Office office ) { - + private String getEntityType( Office office ) { + if (office.getParent() == null) { - return "OFFICE"; + return "OFFICE"; } else { - return "BRANCH"; + return "BRANCH"; } - } - - private Set assembleSetOfRoles(final String[] rolesArray) { + } + + private Set assembleSetOfRoles(final String[] rolesArray) { final Set allRoles = new HashSet<>(); @@ -238,12 +238,12 @@ public class TopicDomainServiceImpl implements TopicDomainService { for (final String roleId : rolesArray) { final Long id = Long.valueOf(roleId); final Role role = this.roleRepository.findById(id) - .orElseThrow(() -> new RoleNotFoundException(id)); + .orElseThrow(() -> new RoleNotFoundException(id)); allRoles.add(role); } } return allRoles; } - + } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicReadPlatformService.java index e6c9ea5f8..72f47f170 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicReadPlatformService.java @@ -22,11 +22,11 @@ import java.util.Collection; import org.apache.fineract.notification.data.TopicData; public interface TopicReadPlatformService { - - Collection getAllTopics(); - - Collection getAllEnabledTopics(); + + Collection getAllTopics(); + + Collection getAllEnabledTopics(); - TopicData findById(Long id); - + TopicData findById(Long id); + } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicReadPlatformServiceImpl.java index 948f9310d..998952d65 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicReadPlatformServiceImpl.java @@ -33,15 +33,15 @@ import org.springframework.stereotype.Service; @Service public class TopicReadPlatformServiceImpl implements TopicReadPlatformService { - - private final JdbcTemplate jdbcTemplate; - - @Autowired - public TopicReadPlatformServiceImpl(final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - private static final class TopicMapper implements RowMapper { + private final JdbcTemplate jdbcTemplate; + + @Autowired + public TopicReadPlatformServiceImpl(final RoutingDataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } + + private static final class TopicMapper implements RowMapper { private final String schema; @@ -71,28 +71,28 @@ public class TopicReadPlatformServiceImpl implements TopicReadPlatformService { } - @Override - public Collection getAllTopics() { - final TopicMapper tm = new TopicMapper(); - String sql = "select " + tm.schema(); - return this.jdbcTemplate.query(sql, tm, new Object[] {}); - } + @Override + public Collection getAllTopics() { + final TopicMapper tm = new TopicMapper(); + String sql = "select " + tm.schema(); + return this.jdbcTemplate.query(sql, tm, new Object[] {}); + } - @Override - public Collection getAllEnabledTopics() { - final TopicMapper tm = new TopicMapper(); + @Override + public Collection getAllEnabledTopics() { + final TopicMapper tm = new TopicMapper(); final String sql = "select " + tm.schema() + " where t.is_active = ?"; return this.jdbcTemplate.query(sql, tm, new Object[] { true }); - } + } - @Override - public TopicData findById(Long topicId) { - try { + @Override + public TopicData findById(Long topicId) { + try { final TopicMapper tm = new TopicMapper(); final String sql = "select " + tm.schema() + " where t.id = ?"; return this.jdbcTemplate.queryForObject(sql, tm, new Object[] { topicId }); } catch (final EmptyResultDataAccessException e) { - throw new TopicNotFoundException(topicId); + throw new TopicNotFoundException(topicId); } - } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberReadPlatformService.java index 834b57479..04954910e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberReadPlatformService.java @@ -23,7 +23,7 @@ import java.util.Collection; import org.apache.fineract.notification.data.TopicSubscriberData; public interface TopicSubscriberReadPlatformService { - - Collection getSubscribers(Long entityId, String entityType, String memberType); - + + Collection getSubscribers(Long entityId, String entityType, String memberType); + } 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 4d597a015..03995ede7 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 @@ -33,46 +33,46 @@ import org.springframework.stereotype.Service; @Service public class TopicSubscriberReadPlatformServiceImpl implements TopicSubscriberReadPlatformService{ - private final JdbcTemplate jdbcTemplate; - - @Autowired - public TopicSubscriberReadPlatformServiceImpl(final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - private static final class TopicSubscriberMapper implements RowMapper { + private final JdbcTemplate jdbcTemplate; + + @Autowired + public TopicSubscriberReadPlatformServiceImpl(final RoutingDataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } + + private static final class TopicSubscriberMapper implements RowMapper { - private final String schema; + private final String schema; - public TopicSubscriberMapper() { - final StringBuilder sqlBuilder = new StringBuilder(200); - sqlBuilder.append("ts.id as id, ts.topic_id as topicId, ts.user_id as userId, "); - sqlBuilder.append("ts.subscription_date as subscriptionDate from topic_subscriber ts "); - sqlBuilder.append("WHERE ts.topic_id = ( SELECT id from topic WHERE entity_id = ? "); - sqlBuilder.append("AND entity_type = ? AND member_type = ? )"); - this.schema = sqlBuilder.toString(); - } + public TopicSubscriberMapper() { + final StringBuilder sqlBuilder = new StringBuilder(200); + sqlBuilder.append("ts.id as id, ts.topic_id as topicId, ts.user_id as userId, "); + sqlBuilder.append("ts.subscription_date as subscriptionDate from topic_subscriber ts "); + sqlBuilder.append("WHERE ts.topic_id = ( SELECT id from topic WHERE entity_id = ? "); + sqlBuilder.append("AND entity_type = ? AND member_type = ? )"); + this.schema = sqlBuilder.toString(); + } - public String schema() { - return this.schema; - } + public String schema() { + return this.schema; + } - @Override - public TopicSubscriberData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - final Long id = rs.getLong("id"); - final Long topicId = rs.getLong("topicId"); - final Long userId = rs.getLong("userId"); - final LocalDate subscriptionDate = JdbcSupport.getLocalDate(rs, "subscriptionDate"); + @Override + public TopicSubscriberData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + final Long id = rs.getLong("id"); + final Long topicId = rs.getLong("topicId"); + final Long userId = rs.getLong("userId"); + final LocalDate subscriptionDate = JdbcSupport.getLocalDate(rs, "subscriptionDate"); - return new TopicSubscriberData(id, topicId, userId, subscriptionDate); - } + return new TopicSubscriberData(id, topicId, userId, subscriptionDate); + } - } + } - @Override - public Collection getSubscribers(Long entityId, String entityType, String memberType) { - final TopicSubscriberMapper tsm = new TopicSubscriberMapper(); - String sql = "SELECT " + tsm.schema(); - return this.jdbcTemplate.query(sql, tsm, new Object[] { entityId, entityType, memberType }); - } + @Override + public Collection getSubscribers(Long entityId, String entityType, String memberType) { + final TopicSubscriberMapper tsm = new TopicSubscriberMapper(); + String sql = "SELECT " + tsm.schema(); + return this.jdbcTemplate.query(sql, tsm, new Object[] { entityId, entityType, memberType }); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberWritePlatformService.java index 95cbd9fc8..28e81e15d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberWritePlatformService.java @@ -21,7 +21,7 @@ package org.apache.fineract.notification.service; import org.apache.fineract.notification.domain.TopicSubscriber; public interface TopicSubscriberWritePlatformService { - - Long create(TopicSubscriber topicSubscriber); + + Long create(TopicSubscriber topicSubscriber); } 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 541fd1ad4..24788a54c 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 @@ -27,16 +27,16 @@ import org.springframework.stereotype.Service; public class TopicSubscriberWritePlatformServiceJpaRepositoryImpl implements TopicSubscriberWritePlatformService { private final TopicSubscriberRepository topicSubscriberRepository; - - @Autowired - public TopicSubscriberWritePlatformServiceJpaRepositoryImpl(TopicSubscriberRepository topicSubscriberRepository) { - this.topicSubscriberRepository = topicSubscriberRepository; - } - - @Override - public Long create(TopicSubscriber topicSubscriber) { - topicSubscriberRepository.save(topicSubscriber); - return topicSubscriber.getId(); - } + + @Autowired + public TopicSubscriberWritePlatformServiceJpaRepositoryImpl(TopicSubscriberRepository topicSubscriberRepository) { + this.topicSubscriberRepository = topicSubscriberRepository; + } + + @Override + public Long create(TopicSubscriber topicSubscriber) { + topicSubscriberRepository.save(topicSubscriber); + return topicSubscriber.getId(); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicWritePlatformService.java index d48206319..48bcdb0e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicWritePlatformService.java @@ -21,7 +21,7 @@ package org.apache.fineract.notification.service; import org.apache.fineract.notification.domain.Topic; public interface TopicWritePlatformService { - - Long create(Topic topic); - + + Long create(Topic topic); + } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicWritePlatformServiceJpaRepositoryImpl.java index 63cb911af..844f1b7dd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicWritePlatformServiceJpaRepositoryImpl.java @@ -26,17 +26,17 @@ import org.springframework.stereotype.Service; @Service public class TopicWritePlatformServiceJpaRepositoryImpl implements TopicWritePlatformService { - private final TopicRepository topicRepository; - - @Autowired - public TopicWritePlatformServiceJpaRepositoryImpl(TopicRepository topicRepository) { - this.topicRepository = topicRepository; - } + private final TopicRepository topicRepository; + + @Autowired + public TopicWritePlatformServiceJpaRepositoryImpl(TopicRepository topicRepository) { + this.topicRepository = topicRepository; + } - @Override - public Long create(Topic topic) { - topicRepository.save(topic); - return topic.getId(); - } + @Override + public Long create(Topic topic) { + topicRepository.save(topic); + return topic.getId(); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidayApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidayApiConstants.java index dc019a51e..694417ec4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidayApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidayApiConstants.java @@ -43,7 +43,7 @@ public class HolidayApiConstants { public static final String status = "status"; public static final String reschedulingType = "reschedulingType"; - protected static final Set HOLIDAY_RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(idParamName, nameParamName, fromDateParamName, descriptionParamName, toDateParamName, - repaymentsRescheduledToParamName, localeParamName, dateFormatParamName, status)); + protected static final Set HOLIDAY_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(idParamName, nameParamName, fromDateParamName, descriptionParamName, toDateParamName, + repaymentsRescheduledToParamName, localeParamName, dateFormatParamName, status)); } 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 755292c01..97415a75d 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 @@ -48,12 +48,12 @@ import com.google.gson.reflect.TypeToken; 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, - HolidayApiConstants.officesParamName, HolidayApiConstants.repaymentsRescheduledToParamName, - HolidayApiConstants.reschedulingType)); + 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, + HolidayApiConstants.officesParamName, HolidayApiConstants.repaymentsRescheduledToParamName, + HolidayApiConstants.reschedulingType)); @Autowired public HolidayDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -65,8 +65,8 @@ 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<>(); @@ -120,8 +120,8 @@ 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<>(); 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 6ff981862..6a6a5aadc 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 @@ -100,9 +100,9 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -134,9 +134,9 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } 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 cfc2a0e57..fb7c798f8 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 @@ -26,10 +26,10 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR */ 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); - } + public CurrencyInUseException(final String currencyCode) { + super("error.msg.currency.currencyCode.inUse", + "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/office/domain/Office.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/Office.java index 9b547d666..5e241ba8b 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 @@ -207,7 +207,7 @@ public class Office extends AbstractPersistableCustom implements Serializa } public Office getParent() { - return this.parent; + return this.parent; } public boolean hasParentOf(final Office office) { 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 8d747cf9d..76f152aaf 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 @@ -116,9 +116,9 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP handleOfficeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleOfficeDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleOfficeDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -165,9 +165,9 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP handleOfficeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleOfficeDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleOfficeDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } 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 d56b42ebb..e8c3ec167 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 @@ -66,17 +66,17 @@ public class ProvisioningCriteriaApiResource { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; 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)); + private static final Set PROVISIONING_CRITERIA_TEMPLATE_PARAMETER = new HashSet<>( + 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)); + private static final Set PROVISIONING_CRITERIA_PARAMETERS = new HashSet<>( + 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)); + private static final Set ALL_PROVISIONING_CRITERIA_PARAMETERS = new HashSet<>( + Arrays.asList(ProvisioningCriteriaConstants.CRITERIA_ID_PARAM, + ProvisioningCriteriaConstants.CRITERIA_NAME_PARAM, ProvisioningCriteriaConstants.CREATED_BY_PARAM)); @Autowired public ProvisioningCriteriaApiResource(final PlatformSecurityContext platformSecurityContext, 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 b0c789825..8f443b575 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 @@ -23,26 +23,26 @@ import java.util.HashSet; import java.util.Set; 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"; - public final static String JSON_LOANPRODUCTS_PARAM = "loanProducts"; - public final static String JSON_LOAN_PRODUCT_ID_PARAM = "id"; - public final static String JSON_LOAN_PRODUCTNAME_PARAM = "name"; - public final static String JSON_LOAN_PRODUCT_BORROWERCYCLE_PARAM = "includeInBorrowerCycle"; - public final static String JSON_PROVISIONING_DEFINITIONS_PARAM = "definitions"; - public final static String JSON_CATEOGRYID_PARAM = "categoryId"; - public final static String JSON_CATEOGRYNAME_PARAM = "categoryName"; - public final static String JSON_MINIMUM_AGE_PARAM = "minAge"; - public final static String JSON_MAXIMUM_AGE_PARAM = "maxAge"; - public final static String JSON_PROVISIONING_PERCENTAGE_PARAM = "provisioningPercentage"; - public final static String JSON_LIABILITY_ACCOUNT_PARAM = "liabilityAccount"; - public final static String JSON_EXPENSE_ACCOUNT_PARAM = "expenseAccount"; - public final static String DEFINITIONS_PARAM = "definitions"; - public final static String LOANPRODUCTS_PARAM = "loanProducts"; - public final static String GLACCOUNTS_PARAM = "glAccounts"; - public final static String CRITERIA_PARAM = "criteriaName"; - public final static String CRITERIA_ID_PARAM = "criteriaId"; - public final static String CRITERIA_NAME_PARAM = "criterianame"; - public final static String CREATED_BY_PARAM = "createdby"; + public final static String JSON_LOCALE_PARAM = "locale"; + public final static String JSON_CRITERIAID_PARAM = "criteriaId"; + public final static String JSON_CRITERIANAME_PARAM = "criteriaName"; + public final static String JSON_LOANPRODUCTS_PARAM = "loanProducts"; + public final static String JSON_LOAN_PRODUCT_ID_PARAM = "id"; + public final static String JSON_LOAN_PRODUCTNAME_PARAM = "name"; + public final static String JSON_LOAN_PRODUCT_BORROWERCYCLE_PARAM = "includeInBorrowerCycle"; + public final static String JSON_PROVISIONING_DEFINITIONS_PARAM = "definitions"; + public final static String JSON_CATEOGRYID_PARAM = "categoryId"; + public final static String JSON_CATEOGRYNAME_PARAM = "categoryName"; + public final static String JSON_MINIMUM_AGE_PARAM = "minAge"; + public final static String JSON_MAXIMUM_AGE_PARAM = "maxAge"; + public final static String JSON_PROVISIONING_PERCENTAGE_PARAM = "provisioningPercentage"; + public final static String JSON_LIABILITY_ACCOUNT_PARAM = "liabilityAccount"; + public final static String JSON_EXPENSE_ACCOUNT_PARAM = "expenseAccount"; + public final static String DEFINITIONS_PARAM = "definitions"; + public final static String LOANPRODUCTS_PARAM = "loanProducts"; + public final static String GLACCOUNTS_PARAM = "glAccounts"; + public final static String CRITERIA_PARAM = "criteriaName"; + public final static String CRITERIA_ID_PARAM = "criteriaId"; + public final static String CRITERIA_NAME_PARAM = "criterianame"; + public final static String CREATED_BY_PARAM = "createdby"; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/CreateProvisioningCategoryRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/CreateProvisioningCategoryRequestCommandHandler.java index 5da9288c1..413c70262 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/CreateProvisioningCategoryRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/CreateProvisioningCategoryRequestCommandHandler.java @@ -30,19 +30,19 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "PROVISIONCATEGORY", action = "CREATE") public class CreateProvisioningCategoryRequestCommandHandler implements NewCommandSourceHandler { - - private final ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService; - - @Autowired - public CreateProvisioningCategoryRequestCommandHandler( - ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService) { - this.provisioningCategoryWritePlatformService = provisioningCategoryWritePlatformService; - } + + private final ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService; + + @Autowired + public CreateProvisioningCategoryRequestCommandHandler( + ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService) { + this.provisioningCategoryWritePlatformService = provisioningCategoryWritePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(JsonCommand jsonCommand) { - return this.provisioningCategoryWritePlatformService.createProvisioningCateogry(jsonCommand); - } + @Transactional + @Override + public CommandProcessingResult processCommand(JsonCommand jsonCommand) { + return this.provisioningCategoryWritePlatformService.createProvisioningCateogry(jsonCommand); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/DeleteProvisioningCategoryRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/DeleteProvisioningCategoryRequestCommandHandler.java index c32cc92a4..ccee50240 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/DeleteProvisioningCategoryRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/DeleteProvisioningCategoryRequestCommandHandler.java @@ -30,19 +30,19 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "PROVISIONCATEGORY", action = "DELETE") public class DeleteProvisioningCategoryRequestCommandHandler implements NewCommandSourceHandler { - - private final ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService; - - @Autowired - public DeleteProvisioningCategoryRequestCommandHandler( - ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService) { - this.provisioningCategoryWritePlatformService = provisioningCategoryWritePlatformService; - } + + private final ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService; + + @Autowired + public DeleteProvisioningCategoryRequestCommandHandler( + ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService) { + this.provisioningCategoryWritePlatformService = provisioningCategoryWritePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(JsonCommand jsonCommand) { - return this.provisioningCategoryWritePlatformService.deleteProvisioningCateogry(jsonCommand); - } + @Transactional + @Override + public CommandProcessingResult processCommand(JsonCommand jsonCommand) { + return this.provisioningCategoryWritePlatformService.deleteProvisioningCateogry(jsonCommand); + } } 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 6c0ca78bd..5d95293bd 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,21 +46,21 @@ import com.google.gson.reflect.TypeToken; @Component public class ProvisioningCriteriaDefinitionJsonDeserializer implements ProvisioningCriteriaConstants { - private final FromJsonHelper fromApiJsonHelper; + private final FromJsonHelper fromApiJsonHelper; - 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 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)); + 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)); @Autowired public ProvisioningCriteriaDefinitionJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { 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 79e0deb74..1aeaa13e4 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 @@ -71,9 +71,9 @@ public class ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl implement handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -106,9 +106,9 @@ public class ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl implement handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } 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 cd854f2bd..a1fc12dc6 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 @@ -90,9 +90,9 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -109,8 +109,8 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement @Override public CommandProcessingResult updateProvisioningCriteria(final Long criteriaId, JsonCommand command) { - try { - this.fromApiJsonDeserializer.validateForUpdate(command.json()); + try { + this.fromApiJsonDeserializer.validateForUpdate(command.json()); ProvisioningCriteria provisioningCriteria = provisioningCriteriaRepository.findById(criteriaId).orElse(null); if(provisioningCriteria == null) { throw new ProvisioningCategoryNotFoundException(criteriaId) ; @@ -121,14 +121,14 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement updateProvisioningCriteriaDefinitions(provisioningCriteria, command) ; provisioningCriteriaRepository.saveAndFlush(provisioningCriteria) ; } - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(provisioningCriteria.getId()).build(); - } catch (final DataIntegrityViolationException dve) { + 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()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -168,10 +168,10 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement 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"); - } + throw new PlatformDataIntegrityException( + "error.msg.provisioning.product.id(s).already.associated.existing.criteria", + "The selected products already associated with another Provisioning Criteria"); + } logger.error(dve.getMessage(), dve); throw new PlatformDataIntegrityException("error.msg.provisioning.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/Staff.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/Staff.java index 175fcb797..bc1155aa9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/Staff.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/Staff.java @@ -61,7 +61,7 @@ public class Staff extends AbstractPersistableCustom { @Column(name = "external_id", length = 100, nullable = true, unique = true) private String externalId; - @Column(name = "email_address", length = 50, unique = true) + @Column(name = "email_address", length = 50, unique = true) private String emailAddress; @ManyToOne @@ -249,7 +249,7 @@ public class Staff extends AbstractPersistableCustom { return getId().equals(staff.getId()); } - public String emailAddress() { + public String emailAddress() { return emailAddress; } 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 d3bb4a96c..892e2d286 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 @@ -102,13 +102,13 @@ public final class StaffCommandFromApiJsonDeserializer { baseDataValidator.reset().parameter("joiningDate").value(joiningDate).notNull(); if (this.fromApiJsonHelper.parameterExists("dateFormat", element)) { - final String dateFormat = this.fromApiJsonHelper.extractStringNamed("dateFormat", element); - baseDataValidator.reset().parameter("dateFormat").value(dateFormat).notBlank(); + final String dateFormat = this.fromApiJsonHelper.extractStringNamed("dateFormat", element); + baseDataValidator.reset().parameter("dateFormat").value(dateFormat).notBlank(); } if (this.fromApiJsonHelper.parameterExists("locale", element)) { - final String locale = this.fromApiJsonHelper.extractStringNamed("locale", element); - baseDataValidator.reset().parameter("locale").value(locale).notBlank(); + final String locale = this.fromApiJsonHelper.extractStringNamed("locale", element); + baseDataValidator.reset().parameter("locale").value(locale).notBlank(); } throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -159,12 +159,12 @@ public final class StaffCommandFromApiJsonDeserializer { final Boolean forceStatus = this.fromApiJsonHelper.extractBooleanNamed("forceStatus", element); 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); - } - + Object[] result = staffReadPlatformService.hasAssociatedItems(staffId); + + if (result != null && result.length > 0) { + baseDataValidator.reset().parameter("isactive").failWithCode("staff.is.assigned",result); + } + } baseDataValidator.reset().parameter("isActive").value(activeFlag).notNull(); } @@ -175,13 +175,13 @@ public final class StaffCommandFromApiJsonDeserializer { } if (this.fromApiJsonHelper.parameterExists("dateFormat", element)) { - final String dateFormat = this.fromApiJsonHelper.extractStringNamed("dateFormat", element); - baseDataValidator.reset().parameter("dateFormat").value(dateFormat).notBlank(); + final String dateFormat = this.fromApiJsonHelper.extractStringNamed("dateFormat", element); + baseDataValidator.reset().parameter("dateFormat").value(dateFormat).notBlank(); } if (this.fromApiJsonHelper.parameterExists("locale", element)) { - final String locale = this.fromApiJsonHelper.extractStringNamed("locale", element); - baseDataValidator.reset().parameter("locale").value(locale).notBlank(); + final String locale = this.fromApiJsonHelper.extractStringNamed("locale", element); + baseDataValidator.reset().parameter("locale").value(locale).notBlank(); } throwExceptionIfValidationWarningsExist(dataValidationErrors); 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 055b66235..48bc9b43a 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 @@ -54,7 +54,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { @Autowired public StaffReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + final ColumnValidator columnValidator) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); this.columnValidator = columnValidator; @@ -65,7 +65,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 " + + " s.is_active as isActive, s.joining_date as joiningDate from m_staff s " + " join m_office o on o.id = s.office_id"; } @@ -166,8 +166,8 @@ 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. + + //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,8 +187,8 @@ 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. + + //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()+ "%"; @@ -210,16 +210,16 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { } private Collection retrieveAllStaff(final String extraCriteria, Long officeId) { - + final StaffMapper rm = new StaffMapper(); String sql = "select " + rm.schema(); final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy()+"%"; if (StringUtils.isNotBlank(extraCriteria)){ - sql += " where " + 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[] {hierarchy }); } return this.jdbcTemplate.query(sql, rm, new Object[] {officeId, hierarchy }); } @@ -251,7 +251,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { 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 +272,41 @@ 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 " + + " 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/StaffWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java index 778e5d0ca..2fd197eae 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 @@ -80,9 +80,9 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla handleStaffDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleStaffDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleStaffDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -113,9 +113,9 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla handleStaffDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleStaffDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleStaffDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } 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 2c346ce78..e16704f62 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 @@ -57,9 +57,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 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; @@ -104,20 +104,20 @@ public final class CashierData implements Serializable { * @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, - final Boolean isFullDay, final String startTime, final String endTime) { + 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); + 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) { + 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); + null, null, null, null, null, null, staffOptions); } /** @@ -222,15 +222,15 @@ public final class CashierData implements Serializable { return endTime; } - public String getOfficeName() { - return officeName; - } + public String getOfficeName() { + return officeName; + } - public String getTellerName() { - return tellerName; - } - - public String getStaffName() { - return staffName; - } + public String getTellerName() { + return tellerName; + } + + public String getStaffName() { + return staffName; + } } 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 9342af1a3..89c81a9a3 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 @@ -55,10 +55,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) { + 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; @@ -83,23 +83,23 @@ public final class CashierTransactionData implements Serializable { } 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) { + 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); + 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) { + 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); + null, null, officeId, officeName, tellerId, tellerName, cashierName, cashierData, + startDate, endDate, currencyOptions); } public Long getId() { @@ -111,31 +111,31 @@ public final class CashierTransactionData implements Serializable { } public CashierTxnType getTxnType() { - return txnType; + return txnType; } public BigDecimal getTxnAmount() { - return txnAmount; + return txnAmount; } public Date getTxnDate() { - return txnDate; + return txnDate; } public String getTxnNote() { - return txnNote; + return txnNote; } public String getEntityType() { - return entityType; + return entityType; } public Long getEntityId() { - return entityId; + return entityId; } public Date getCreatedDate() { - return createdDate; + return createdDate; } public Long getOfficeId() { @@ -143,7 +143,7 @@ public final class CashierTransactionData implements Serializable { } public String getOfficeName() { - return officeName; + return officeName; } public Long getTellerId() { @@ -151,23 +151,23 @@ public final class CashierTransactionData implements Serializable { } public String getTellerName() { - return tellerName; + return tellerName; } public String getCashierName() { - return cashierName; + return cashierName; } public Date getStartDate() { - return startDate; + return startDate; } public Date getEndDate() { - return endDate; + return endDate; } public CashierData getCashierData() { - return cashierData; + return cashierData; } } 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 f36bd15c4..2dbe0015c 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 @@ -42,113 +42,113 @@ import org.springframework.stereotype.Component; @Component public class CashierTransactionDataValidator { - private final TellerManagementReadPlatformService tellerManagementReadPlatformService; - private final JdbcTemplate jdbcTemplate; + private final TellerManagementReadPlatformService tellerManagementReadPlatformService; + private final JdbcTemplate jdbcTemplate; - @Autowired - public CashierTransactionDataValidator( - final TellerManagementReadPlatformService tellerManagementReadPlatformService, - final RoutingDataSource dataSource) { - this.tellerManagementReadPlatformService = tellerManagementReadPlatformService; - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + 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; - final String orderBy = null; - final String sortOrder = null; - final Date fromDate = null; - final Date toDate = null; - 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) { - throw new CashierInsufficientAmountException(); - } - } + final Integer offset = null; + final Integer limit = null; + final String orderBy = null; + final String sortOrder = null; + final Date fromDate = null; + final Date toDate = null; + 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) { + 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) { - Long staffId = cashier.getStaff().getId(); - final LocalDate fromDate = new LocalDate(cashier.getStartDate()); - final LocalDate endDate = new LocalDate(cashier.getEndDate()); - final LocalDate tellerFromDate = teller.getStartLocalDate(); - final LocalDate tellerEndDate = teller.getEndLocalDate(); - /** - * to validate cashier date range in range of teller date range - */ - if (fromDate.isBefore(tellerFromDate) - || endDate.isBefore(tellerFromDate) - || (tellerEndDate != null && + 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()); + final LocalDate tellerFromDate = teller.getStartLocalDate(); + final LocalDate tellerEndDate = teller.getEndLocalDate(); + /** + * 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)))) { - 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 '" - + 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 + "')) "; - } - int count = this.jdbcTemplate.queryForObject(sql, Integer.class); - if (count > 0) { - throw new CashierAlreadyAlloacated(); - } - } + 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 '" + + 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 + "')) "; + } + int count = this.jdbcTemplate.queryForObject(sql, Integer.class); + if (count > 0) { + throw new CashierAlreadyAlloacated(); + } + } - 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() - + "') BETWEEN TIME(c.start_time) AND TIME(c.end_time) ) end)"; - try { - Long cashierId = this.jdbcTemplate.queryForObject(sql, - Long.class); - validateSettleCashAndCashOutTransactions(cashierId, - currencyCode, transactionAmount); - } catch (EmptyResultDataAccessException e) { + 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() + + "') BETWEEN TIME(c.start_time) AND TIME(c.end_time) ) end)"; + try { + Long cashierId = this.jdbcTemplate.queryForObject(sql, + Long.class); + validateSettleCashAndCashOutTransactions(cashierId, + currencyCode, transactionAmount); + } catch (EmptyResultDataAccessException 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 a781bd5fa..a4a576a82 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,31 +22,31 @@ import java.io.Serializable; import java.math.BigDecimal; public final class CashierTransactionTypeTotalsData implements Serializable { - private final Integer cashierTxnType; - private final BigDecimal cashTotal; + private final Integer cashierTxnType; + private final BigDecimal cashTotal; private CashierTransactionTypeTotalsData ( - final Integer cashierTxnType, - final BigDecimal cashTotal - ) { - this.cashierTxnType = cashierTxnType; - this.cashTotal = cashTotal; + final Integer cashierTxnType, + final BigDecimal cashTotal + ) { + this.cashierTxnType = cashierTxnType; + this.cashTotal = cashTotal; } public static CashierTransactionTypeTotalsData instance( - final Integer cashierTxnType, - final BigDecimal cashTotal - ) { + final Integer cashierTxnType, + final BigDecimal cashTotal + ) { return new CashierTransactionTypeTotalsData( - cashierTxnType, cashTotal); + cashierTxnType, cashTotal); } public Integer getCashierTxnType() { - return cashierTxnType; - } + return cashierTxnType; + } public BigDecimal getCashTotal() { - return cashTotal; - } + return cashTotal; + } } 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 10baa8398..9854eee40 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 @@ -24,113 +24,113 @@ import java.math.BigDecimal; import org.apache.fineract.infrastructure.core.service.Page; public final class CashierTransactionsWithSummaryData implements Serializable { - - private final BigDecimal sumCashAllocation; - private final BigDecimal sumInwardCash; - private final BigDecimal sumOutwardCash; - private final BigDecimal sumCashSettlement; - private final BigDecimal netCash; - private final String officeName; - private final long tellerId; - private final String tellerName; - private final long cashierId; - private final String cashierName; + + private final BigDecimal sumCashAllocation; + private final BigDecimal sumInwardCash; + private final BigDecimal sumOutwardCash; + private final BigDecimal sumCashSettlement; + private final BigDecimal netCash; + private final String officeName; + private final long tellerId; + private final String tellerName; + private final long cashierId; + private final String cashierName; 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 - ) { - this.cashierTransactions = cashierTransactions; - this.sumCashAllocation = sumCashAllocation; - this.sumInwardCash = sumInwardCash; - this.sumOutwardCash = sumOutwardCash; - this.sumCashSettlement = sumCashSettlement; - this.netCash = netCash; - this.officeName = officeName; - this.tellerId = tellerId; - this.tellerName = tellerName; - this.cashierId = cashierId; - this.cashierName = cashierName; + 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; + this.sumOutwardCash = sumOutwardCash; + this.sumCashSettlement = sumCashSettlement; + this.netCash = netCash; + this.officeName = officeName; + this.tellerId = tellerId; + this.tellerName = tellerName; + this.cashierId = cashierId; + 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 - ) { - - final BigDecimal netCash = - sumCashAllocation.add(sumInwardCash). - subtract(sumOutwardCash). - subtract(sumCashSettlement); + 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); + cashierTransactions, + sumCashAllocation, + sumInwardCash, + sumOutwardCash, + sumCashSettlement, netCash, + officeName, tellerId, tellerName, cashierId, cashierName); } - public BigDecimal getSumCashAllocation() { - return sumCashAllocation; - } + public BigDecimal getSumCashAllocation() { + return sumCashAllocation; + } - public BigDecimal getSumInwardCash() { - return sumInwardCash; - } + public BigDecimal getSumInwardCash() { + return sumInwardCash; + } - public BigDecimal getSumOutwardCash() { - return sumOutwardCash; - } + public BigDecimal getSumOutwardCash() { + return sumOutwardCash; + } - public BigDecimal getSumCashSettlement() { - return sumCashSettlement; - } + public BigDecimal getSumCashSettlement() { + return sumCashSettlement; + } - public BigDecimal getNetCash() { - return netCash; - } - - public String getOfficeName() { - return officeName; - } - - public Long getTellerId() { - return tellerId; - } - - public String getTellerName() { - return tellerName; - } + public BigDecimal getNetCash() { + return netCash; + } + + public String getOfficeName() { + return officeName; + } + + public Long getTellerId() { + return tellerId; + } + + public String getTellerName() { + return tellerName; + } - public Long getCashierId() { - return cashierId; - } - - public String getCashierName() { - return cashierName; - } - public Page getCashierTransactions() { - return cashierTransactions; - } + public Long getCashierId() { + return cashierId; + } + + public String getCashierName() { + return cashierName; + } + public Page getCashierTransactions() { + return cashierTransactions; + } } 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 dbffe3837..aa57d1d7d 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 @@ -35,12 +35,12 @@ import java.util.Map; @Table(name = "m_cashier_transactions") public class CashierTransaction extends AbstractPersistableCustom { - @Transient + @Transient private Office office; - - @Transient + + @Transient private Teller teller; - + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "cashier_id", nullable = false) private Cashier cashier; @@ -79,8 +79,8 @@ public class CashierTransaction extends AbstractPersistableCustom { } public static CashierTransaction fromJson( - final Cashier cashier, - final JsonCommand command) { + final Cashier cashier, + final JsonCommand command) { final Integer txnType = command.integerValueOfParameterNamed("txnType"); final BigDecimal txnAmount = command.bigDecimalValueOfParameterNamed("txnAmount"); final LocalDate txnDate = command.localDateValueOfParameterNamed("txnDate"); @@ -91,23 +91,23 @@ public class CashierTransaction extends AbstractPersistableCustom { // TODO: get client/loan/savings details return new CashierTransaction (cashier, txnType, txnAmount, txnDate, - entityType, entityId, txnNote, currencyCode); + entityType, entityId, txnNote, 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) { - this.txnDate = txnDate.toDate(); - } - this.txnAmount = txnAmount; - this.entityType = entityType; - this.entityId = entityId; - this.txnNote = txnNote; - this.createdDate = new Date(); - this.currencyCode = currencyCode; + LocalDate txnDate, String entityType, Long entityId, String txnNote, String currencyCode) { + this.cashier = cashier; + this.txnType = txnType; + if (txnDate != null) { + this.txnDate = txnDate.toDate(); + } + this.txnAmount = txnAmount; + this.entityType = entityType; + this.entityId = entityId; + this.txnNote = txnNote; + this.createdDate = new Date(); + this.currencyCode = currencyCode; } public Map update(final JsonCommand command) { 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 c8f39cd7f..8883efa5c 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 @@ -21,46 +21,46 @@ package org.apache.fineract.organisation.teller.domain; import java.io.Serializable; 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"); - - private CashierTxnType () { - } - - private CashierTxnType (Integer id, String value) { - this.id = id; - this.value = value; - } - - public Integer getId () { - return id; - } - - public String getValue () { - return value; - } - - public static CashierTxnType getCashierTxnType (Integer id) { - CashierTxnType retVal = null; - - switch(id) { - case 101: - retVal = ALLOCATE; break; - case 102: - retVal = SETTLE; break; - case 103: - retVal = INWARD_CASH_TXN; break; - case 104: - retVal = OUTWARD_CASH_TXN; break; - default: - break; - } - return retVal; - } + + 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"); + + private CashierTxnType () { + } + + private CashierTxnType (Integer id, String value) { + this.id = id; + this.value = value; + } + + public Integer getId () { + return id; + } + + public String getValue () { + return value; + } + + public static CashierTxnType getCashierTxnType (Integer id) { + CashierTxnType retVal = null; + + switch(id) { + case 101: + retVal = ALLOCATE; break; + case 102: + retVal = SETTLE; break; + case 103: + retVal = INWARD_CASH_TXN; break; + case 104: + retVal = OUTWARD_CASH_TXN; break; + 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 b1fc196c5..53152bf4e 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 @@ -84,22 +84,22 @@ public class Teller extends AbstractPersistableCustom { } 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); - this.description = StringUtils.defaultIfEmpty(description, null); - if (startDate != null) { - this.startDate = startDate.toDateTimeAtStartOfDay().toDate(); - } - if (endDate != null) { - this.endDate = endDate.toDateTimeAtStartOfDay().toDate(); - } - if (status != null) { - this.status = status.getValue(); - } - this.office = staffOffice; - - /* + final LocalDate endDate, final TellerStatus status) { + + this.name = StringUtils.defaultIfEmpty(name, null); + this.description = StringUtils.defaultIfEmpty(description, null); + if (startDate != null) { + this.startDate = startDate.toDateTimeAtStartOfDay().toDate(); + } + if (endDate != null) { + this.endDate = endDate.toDateTimeAtStartOfDay().toDate(); + } + if (status != null) { + this.status = status.getValue(); + } + this.office = staffOffice; + + /* if (StringUtils.isNotBlank(name)) { this.name = name.trim(); } else { @@ -183,7 +183,7 @@ public class Teller extends AbstractPersistableCustom { final Integer newValue = command.integerValueOfParameterNamed(statusParamName); final TellerStatus status = TellerStatus.fromInt(newValue); if (status != TellerStatus.INVALID) { - this.status = status.getValue(); + this.status = status.getValue(); } } @@ -284,8 +284,8 @@ public class Teller extends AbstractPersistableCustom { this.cashiers = cashiers; } - public void initializeLazyCollections() { - this.office.getId(); - this.cashiers.size(); - } + public void initializeLazyCollections() { + this.office.getId(); + this.cashiers.size(); + } } 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 9b37d361a..6b7f4ef5a 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 @@ -42,14 +42,14 @@ public class TellerRepositoryWrapper { } 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) { - this.repository.delete(teller); + this.repository.delete(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 33815353d..566bb86d1 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 @@ -23,7 +23,7 @@ package org.apache.fineract.organisation.teller.domain; */ public enum TellerStatus { - + INVALID(0, "tellerStatusType.invalid"), PENDING(100, "tellerStatusType.pending"), ACTIVE(300, "tellerStatusType.active"), @@ -38,16 +38,16 @@ public enum TellerStatus { TellerStatus status = TellerStatus.INVALID; switch (statusValue) { case 100: - status = TellerStatus.PENDING; + status = TellerStatus.PENDING; break; case 300: - status = TellerStatus.ACTIVE; + status = TellerStatus.ACTIVE; break; case 400: - status = TellerStatus.INACTIVE; + status = TellerStatus.INACTIVE; break; case 600: - status = TellerStatus.CLOSED; + status = TellerStatus.CLOSED; break; } return status; 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 183f1315a..7002cf5f9 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 @@ -22,11 +22,11 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR @SuppressWarnings("serial") public class CashierAlreadyAlloacated extends - AbstractPlatformDomainRuleException { + AbstractPlatformDomainRuleException { - public CashierAlreadyAlloacated() { - super("cashier.already.allocated.for.given.data.and.time.exception", - "Cashier already allocated for given date and time range."); - } + public CashierAlreadyAlloacated() { + 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 71ea0abaf..45c70c0c8 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 @@ -22,11 +22,11 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR @SuppressWarnings("serial") public class CashierDateRangeOutOfTellerDateRangeException extends - AbstractPlatformDomainRuleException { + AbstractPlatformDomainRuleException { - public CashierDateRangeOutOfTellerDateRangeException() { - super("cashier.date.range.out.of.teller.date.range.exception", - "Cashier date range should be in teller date range."); - } + public CashierDateRangeOutOfTellerDateRangeException() { + 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/CashierInsufficientAmountException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierInsufficientAmountException.java index f9e168137..7c5520a01 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 @@ -22,11 +22,11 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR @SuppressWarnings("serial") public class CashierInsufficientAmountException extends - AbstractPlatformDomainRuleException { + AbstractPlatformDomainRuleException { - public CashierInsufficientAmountException() { - super("cashier.insufficient.amount.exception", - "Cashier do not have sufficient amount for this transaction."); - } + public CashierInsufficientAmountException() { + 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/handler/AllocateCashToCashierCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/AllocateCashToCashierCommandHandler.java index 5b2e544b3..c033bc1f1 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 @@ -45,7 +45,7 @@ public class AllocateCashToCashierCommandHandler implements NewCommandSourceHand @Override public CommandProcessingResult processCommand(final JsonCommand command) { - + return this.writePlatformService.allocateCashToCashier(command.subentityId(), command); } } 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 131b64181..3076462e1 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 @@ -45,8 +45,8 @@ public class AllocateCashierToTellerCommandHandler implements NewCommandSourceHa @Override public CommandProcessingResult processCommand(final JsonCommand command) { - + return this.writePlatformService.allocateCashierToTeller( - command.entityId(), command); + command.entityId(), 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 1ada3cb60..0d52592c9 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 @@ -53,6 +53,6 @@ public class DeleteCashierAllocationCommandHandler implements NewCommandSourceHa @Override public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.deleteCashierAllocation(command.entityId(), - command.subentityId(), command); + command.subentityId(), 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 afaaddcc6..4f705ec66 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 @@ -45,7 +45,7 @@ public class SettleCashFromCashierCommandHandler implements NewCommandSourceHand @Override public CommandProcessingResult processCommand(final JsonCommand command) { - + return this.writePlatformService.settleCashFromCashier(command.subentityId(), command); } } 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 7840a96b2..f8136dac3 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 @@ -53,6 +53,6 @@ public class UpdateCashierAllocationCommandHandler implements NewCommandSourceHa @Override public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.updateCashierAllocation(command.entityId(), - command.subentityId(), command); + command.subentityId(), command); } } 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 aea242ee9..8462a7e5d 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 @@ -23,20 +23,20 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public class CashierWritePlatformService { - public CommandProcessingResult allocateCashierToTeller(JsonCommand command) { - // TODO Auto-generated method stub - return null; - } + public CommandProcessingResult allocateCashierToTeller(JsonCommand command) { + // TODO Auto-generated method stub + return null; + } - public CommandProcessingResult deleteCashier(Long entityId) { - // TODO Auto-generated method stub - return null; - } + public CommandProcessingResult deleteCashier(Long entityId) { + // TODO Auto-generated method stub + return null; + } - public CommandProcessingResult modifyCashier(Long entityId, - JsonCommand command) { - // TODO Auto-generated method stub - return null; - } + 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/TellerManagementReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerManagementReadPlatformServiceImpl.java index a3ccd5ec5..0fb5aa034 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 @@ -220,7 +220,7 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement @Override public Collection retrieveAllTellers(final String sqlSearch, final Long officeId, final String status) { - final String extraCriteria = getTellerCriteria(sqlSearch, officeId, status); + final String extraCriteria = getTellerCriteria(sqlSearch, officeId, status); return retrieveAllTeller(extraCriteria, officeId); } @@ -233,7 +233,7 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement } sql = sql + " order by t.teller_name"; if(officeId!=null){ - return this.jdbcTemplate.query(sql, tm, new Object[] {officeId}); + return this.jdbcTemplate.query(sql, tm, new Object[] {officeId}); } return this.jdbcTemplate.query(sql, tm, new Object[] {}); } @@ -280,7 +280,7 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement @Override public Collection retrieveCashiersForTellers(final String sqlSearch, final Long tellerId) { - final String extraCriteria = getTellerCriteria(sqlSearch, tellerId); + final String extraCriteria = getTellerCriteria(sqlSearch, tellerId); return fetchCashiers(extraCriteria); } @@ -291,8 +291,8 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement if (sqlSearch != null) { extraCriteria.append(" and (").append(sqlSearch).append(")"); final CashierMapper cm = new CashierMapper(); - this.columnValidator.validateSqlInjection(cm.schema(), sqlSearch); - + this.columnValidator.validateSqlInjection(cm.schema(), sqlSearch); + } if (tellerId != null) { extraCriteria.append(" and teller_id = ").append(tellerId).append(" "); @@ -520,9 +520,9 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement 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 " + + "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() + " 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) " @@ -627,12 +627,12 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" sav_txn.id as txn_id, null as cashier_id, "); 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(" then 104 "); - sqlBuilder.append(" else "); - sqlBuilder.append(" 105 "); + 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(" 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 @@ -664,12 +664,12 @@ 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(" then 103 "); - sqlBuilder.append(" when renum.enum_value in ('DISBURSEMENT', 'WAIVE_INTEREST', 'WRITEOFF', 'WAIVE_CHARGES') "); - sqlBuilder.append(" then 104 "); - sqlBuilder.append(" else "); - sqlBuilder.append(" 105 "); + 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 "); + sqlBuilder.append(" else "); + 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 @@ -771,133 +771,133 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" cash_txn_type, sum(txn_amount) as txn_total from "); sqlBuilder.append(" (select * from "); sqlBuilder.append(" (select txn.id as txn_id, txn.cashier_id as cashier_id, "); - 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(" 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(" 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) "); + .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 txn.currency_code = ? "); - sqlBuilder.append(" and o.hierarchy like ? ) cashier_txns "); - sqlBuilder.append(" UNION "); - sqlBuilder.append(" (select sav_txn.id as txn_id, c.id as cashier_id, "); - 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(" then 104 "); - sqlBuilder.append(" else "); - 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(" and o.hierarchy like ? ) cashier_txns "); + sqlBuilder.append(" UNION "); + sqlBuilder.append(" (select sav_txn.id as txn_id, c.id as cashier_id, "); + 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(" then 104 "); + sqlBuilder.append(" else "); + 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(" 'savings' as entity_type, sav.id as entity_id, sav_txn.created_date as created_date, "); + .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(" from m_savings_account_transaction sav_txn "); + .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 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 "); - sqlBuilder.append(" left join m_appuser user on sav_txn.appuser_id = user.id "); - sqlBuilder.append(" left join m_staff staff on user.staff_id = staff.id "); - sqlBuilder.append(" left join m_cashiers c on c.staff_id = staff.id "); + .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 "); + sqlBuilder.append(" left join m_appuser user on sav_txn.appuser_id = user.id "); + sqlBuilder.append(" left join m_staff staff on user.staff_id = staff.id "); + sqlBuilder.append(" left join m_cashiers c on c.staff_id = staff.id "); sqlBuilder.append(" left join m_payment_detail payDetails on payDetails.id = sav_txn.payment_detail_id "); sqlBuilder.append(" left join m_payment_type payType on payType.id = payDetails.payment_type_id "); sqlBuilder.append(" left join m_account_transfer_transaction acnttrans "); sqlBuilder.append(" on (acnttrans.from_savings_transaction_id = sav_txn.id "); sqlBuilder.append(" or acnttrans.to_savings_transaction_id = sav_txn.id) "); - sqlBuilder.append(" where sav_txn.is_reversed = 0 and c.id = ? "); + sqlBuilder.append(" where sav_txn.is_reversed = 0 and c.id = ? "); sqlBuilder.append(" and sav.currency_code = ? "); - sqlBuilder.append(" and o.hierarchy like ? "); - sqlBuilder.append(" and sav_txn.transaction_date between c.start_date and date_add(c.end_date, interval 1 day) "); - sqlBuilder.append(" and (sav_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) "); - sqlBuilder.append(" AND acnttrans.id IS NULL "); - sqlBuilder.append(" ) "); - sqlBuilder.append(" UNION "); - 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(" then 103 "); - sqlBuilder.append(" when renum.enum_value in ('DISBURSEMENT', 'WAIVE_INTEREST', 'WRITEOFF', 'WAIVE_CHARGES') "); - sqlBuilder.append(" then 104 "); - sqlBuilder.append(" else "); - 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(" and o.hierarchy like ? "); + sqlBuilder.append(" and sav_txn.transaction_date between c.start_date and date_add(c.end_date, interval 1 day) "); + sqlBuilder.append(" and (sav_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) "); + sqlBuilder.append(" AND acnttrans.id IS NULL "); + sqlBuilder.append(" ) "); + sqlBuilder.append(" UNION "); + 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(" then 103 "); + sqlBuilder.append(" when renum.enum_value in ('DISBURSEMENT', 'WAIVE_INTEREST', 'WRITEOFF', 'WAIVE_CHARGES') "); + sqlBuilder.append(" then 104 "); + sqlBuilder.append(" else "); + 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(" 'loans' as entity_type, loan.id as entity_id, loan_txn.created_date as created_date, "); + .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(" from m_loan_transaction loan_txn "); + .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 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 "); - sqlBuilder.append(" left join m_appuser user on loan_txn.appuser_id = user.id "); - sqlBuilder.append(" left join m_staff staff on user.staff_id = staff.id "); - sqlBuilder.append(" left join m_cashiers c on c.staff_id = staff.id "); + .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 "); + sqlBuilder.append(" left join m_appuser user on loan_txn.appuser_id = user.id "); + sqlBuilder.append(" left join m_staff staff on user.staff_id = staff.id "); + sqlBuilder.append(" left join m_cashiers c on c.staff_id = staff.id "); sqlBuilder.append(" left join m_payment_detail payDetails on payDetails.id = loan_txn.payment_detail_id "); sqlBuilder.append(" left join m_payment_type payType on payType.id = payDetails.payment_type_id "); sqlBuilder.append(" left join m_account_transfer_transaction acnttrans "); sqlBuilder.append(" on (acnttrans.from_loan_transaction_id = loan_txn.id "); sqlBuilder.append(" or acnttrans.to_loan_transaction_id = loan_txn.id) "); - sqlBuilder.append(" where loan_txn.is_reversed = 0 and c.id = ? "); + sqlBuilder.append(" where loan_txn.is_reversed = 0 and c.id = ? "); sqlBuilder.append(" and loan.currency_code = ? "); - sqlBuilder.append(" and o.hierarchy like ? "); - sqlBuilder.append(" and loan_txn.transaction_date between c.start_date and date_add(c.end_date, interval 1 day) "); - sqlBuilder.append(" and (loan_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) "); - sqlBuilder.append(" AND acnttrans.id IS NULL "); - sqlBuilder.append(" ) "); - sqlBuilder.append(" UNION "); - sqlBuilder.append(" ( "); - sqlBuilder.append(" SELECT cli_txn.id AS txn_id, c.id AS cashier_id, "); - sqlBuilder.append(" case "); - sqlBuilder.append(" WHEN renum.enum_value IN ('PAY_CHARGE') "); - sqlBuilder.append(" then 103 "); - sqlBuilder.append(" WHEN renum.enum_value IN ('WAIVE_CHARGE') "); - sqlBuilder.append(" then 104 "); - sqlBuilder.append(" else "); - 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(" and o.hierarchy like ? "); + sqlBuilder.append(" and loan_txn.transaction_date between c.start_date and date_add(c.end_date, interval 1 day) "); + sqlBuilder.append(" and (loan_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) "); + sqlBuilder.append(" AND acnttrans.id IS NULL "); + sqlBuilder.append(" ) "); + sqlBuilder.append(" UNION "); + sqlBuilder.append(" ( "); + sqlBuilder.append(" SELECT cli_txn.id AS txn_id, c.id AS cashier_id, "); + sqlBuilder.append(" case "); + sqlBuilder.append(" WHEN renum.enum_value IN ('PAY_CHARGE') "); + sqlBuilder.append(" then 103 "); + sqlBuilder.append(" WHEN renum.enum_value IN ('WAIVE_CHARGE') "); + sqlBuilder.append(" then 104 "); + sqlBuilder.append(" else "); + 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(" 'client' as entity_type, cl.id as entity_id, cli_txn.created_date as created_date, "); + .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(" from m_client_transaction cli_txn "); + .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 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 "); - sqlBuilder.append(" left join m_staff staff ON user.staff_id = staff.id "); - sqlBuilder.append(" left join m_cashiers c ON c.staff_id = staff.id "); + .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 "); + sqlBuilder.append(" left join m_staff staff ON user.staff_id = staff.id "); + sqlBuilder.append(" left join m_cashiers c ON c.staff_id = staff.id "); sqlBuilder.append(" left join m_payment_detail payDetails on payDetails.id = cli_txn.payment_detail_id "); sqlBuilder.append(" left join m_payment_type payType on payType.id = payDetails.payment_type_id "); - sqlBuilder.append(" where cli_txn.is_reversed = 0 AND c.id = ? "); + sqlBuilder.append(" where cli_txn.is_reversed = 0 AND c.id = ? "); sqlBuilder.append(" and cli_txn.currency_code = ? "); - sqlBuilder.append(" and o.hierarchy LIKE ? "); - sqlBuilder.append(" and cli_txn.transaction_date between c.start_date and date_add(c.end_date, interval 1 day) "); + sqlBuilder.append(" and o.hierarchy LIKE ? "); + sqlBuilder.append(" and cli_txn.transaction_date between c.start_date and date_add(c.end_date, interval 1 day) "); sqlBuilder.append(" and (cli_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) "); - sqlBuilder.append(" ) "); - sqlBuilder.append(" ) txns "); - sqlBuilder.append(" group by cash_txn_type "); + sqlBuilder.append(" ) "); + sqlBuilder.append(" ) txns "); + sqlBuilder.append(" group by cash_txn_type "); return sqlBuilder.toString(); } 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 8a08bdb63..09aac457e 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 @@ -67,22 +67,22 @@ public interface TellerWritePlatformService { * 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 a2092fc71..efa09e681 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 @@ -127,9 +127,9 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleTellerDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleTellerDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -162,9 +162,9 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleTellerDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleTellerDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -271,9 +271,9 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleTellerDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleTellerDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -311,9 +311,9 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleTellerDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleTellerDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -336,9 +336,9 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleTellerDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleTellerDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } return new CommandProcessingResultBuilder() // @@ -355,7 +355,7 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer @Override public CommandProcessingResult allocateCashToCashier(final Long cashierId, JsonCommand command) { - return doTransactionForCashier(cashierId, CashierTxnType.ALLOCATE, command); // For + return doTransactionForCashier(cashierId, CashierTxnType.ALLOCATE, command); // For // fund // allocation // to @@ -364,10 +364,10 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer @Override public CommandProcessingResult settleCashFromCashier(final Long cashierId, JsonCommand command) { - - this.cashierTransactionDataValidator.validateSettleCashAndCashOutTransactions(cashierId, command); - - return doTransactionForCashier(cashierId, CashierTxnType.SETTLE, command); // For + + this.cashierTransactionDataValidator.validateSettleCashAndCashOutTransactions(cashierId, command); + + return doTransactionForCashier(cashierId, CashierTxnType.SETTLE, command); // For // fund // settlement // from @@ -466,9 +466,9 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleTellerDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + 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/workingdays/data/WorkingDayValidator.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDayValidator.java index fd59e5f9e..9d2dba5e2 100755 --- 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 @@ -43,10 +43,10 @@ import com.google.gson.reflect.TypeToken; public class WorkingDayValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set WORKING_DAYS_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(WorkingDaysApiConstants.recurrence, WorkingDaysApiConstants.repayment_rescheduling_enum, - WorkingDaysApiConstants.localeParamName, WorkingDaysApiConstants.extendTermForDailyRepayments, - WorkingDaysApiConstants.extendTermForRepaymentsOnHolidays)); + private static final Set WORKING_DAYS_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(WorkingDaysApiConstants.recurrence, WorkingDaysApiConstants.repayment_rescheduling_enum, + WorkingDaysApiConstants.localeParamName, WorkingDaysApiConstants.extendTermForDailyRepayments, + WorkingDaysApiConstants.extendTermForRepaymentsOnHolidays)); @Autowired public WorkingDayValidator(FromJsonHelper fromApiJsonHelper) { @@ -57,8 +57,8 @@ 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<>(); 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 index 6ca8c5664..6dca1e079 100755 --- 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 @@ -79,7 +79,7 @@ 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(); @@ -98,7 +98,7 @@ public class WorkingDaysReadPlatformServiceImpl implements WorkingDaysReadPlatfo } private Collection repaymentRescheduleTypeOptions() { - return Arrays.asList( + 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), 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 84eeba628..ee824c234 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 @@ -40,6 +40,6 @@ public class AccountTransfersApiConstants { * {@link AccountTransferData}. Where possible, we try to get response * parameters to match those of request parameters. */ - protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(AccountDetailConstants.idParamName, transferDescriptionParamName, currencyParamName)); + 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/data/AccountTransfersDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDataValidator.java index f7002d134..1755fcb9d 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 @@ -48,14 +48,14 @@ 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 @@ -82,8 +82,8 @@ public class AccountTransfersDataValidator { this.accountTransfersDetailDataValidator.validate(command, baseDataValidator); - final LocalDate transactionDate = this.fromApiJsonHelper - .extractLocalDateNamed(AccountTransfersApiConstants.transferDateParamName, element); + final LocalDate transactionDate = this.fromApiJsonHelper + .extractLocalDateNamed(AccountTransfersApiConstants.transferDateParamName, element); baseDataValidator.reset().parameter(AccountTransfersApiConstants.transferDateParamName).value (transactionDate).notNull(); 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 index ccdba4ce9..e29fa7d59 100755 --- 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 @@ -59,31 +59,31 @@ import com.google.gson.reflect.TypeToken; 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 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, - StandingInstructionApiConstants.priorityParamName, StandingInstructionApiConstants.instructionTypeParamName, - StandingInstructionApiConstants.statusParamName, StandingInstructionApiConstants.amountParamName, - StandingInstructionApiConstants.validFromParamName, StandingInstructionApiConstants.validTillParamName, - StandingInstructionApiConstants.recurrenceTypeParamName, - StandingInstructionApiConstants.recurrenceFrequencyParamName, - StandingInstructionApiConstants.recurrenceIntervalParamName, - StandingInstructionApiConstants.recurrenceOnMonthDayParamName, - 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 @@ -108,18 +108,18 @@ import com.google.gson.reflect.TypeToken; final JsonElement element = command.parsedJson(); - final Integer status = this.fromApiJsonHelper - .extractIntegerNamed(StandingInstructionApiConstants.statusParamName, element, Locale.getDefault()); + 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); @@ -143,24 +143,24 @@ import com.google.gson.reflect.TypeToken; isPeriodic = AccountTransferRecurrenceType.fromInt(recurrenceType).isPeriodicRecurrence(); } - final Integer recurrenceFrequency = this.fromApiJsonHelper.extractIntegerNamed( - StandingInstructionApiConstants.recurrenceFrequencyParamName, element, + final Integer recurrenceFrequency = this.fromApiJsonHelper.extractIntegerNamed( + StandingInstructionApiConstants.recurrenceFrequencyParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceFrequencyParamName) - .value(recurrenceFrequency).inMinMaxRange(0, 3); + 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(); + final MonthDay monthDay = this.fromApiJsonHelper + .extractMonthDayNamed(StandingInstructionApiConstants.recurrenceOnMonthDayParamName, element); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceOnMonthDayParamName) + .value(monthDay).notNull(); } } - final Integer recurrenceInterval = this.fromApiJsonHelper.extractIntegerNamed( - StandingInstructionApiConstants.recurrenceIntervalParamName, element, + final Integer recurrenceInterval = this.fromApiJsonHelper.extractIntegerNamed( + StandingInstructionApiConstants.recurrenceIntervalParamName, element, Locale.getDefault()); if (isPeriodic) { baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceIntervalParamName).value(recurrenceInterval).notNull(); @@ -216,75 +216,75 @@ import com.google.gson.reflect.TypeToken; 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(); + final BigDecimal transferAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(StandingInstructionApiConstants.amountParamName, element); + 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); - } + 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); + } - 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); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.nameParamName).value(name).notNull(); - } + if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.nameParamName, element)) { + final String name = this.fromApiJsonHelper.extractStringNamed(StandingInstructionApiConstants.nameParamName, + element); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.nameParamName).value(name).notNull(); + } throwExceptionIfValidationWarningsExist(dataValidationErrors); } 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 0434261b3..924b885a1 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 @@ -45,6 +45,6 @@ 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); + BigDecimal getTotalTransactionAmount(Long accountId, Integer accountType, + LocalDate transactionDate); } \ No newline at end of file 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 e66d4a231..89814468f 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 @@ -57,646 +57,646 @@ import org.springframework.util.CollectionUtils; @Service public class AccountTransfersReadPlatformServiceImpl implements - AccountTransfersReadPlatformService { - - private final JdbcTemplate jdbcTemplate; - private final ClientReadPlatformService clientReadPlatformService; - private final OfficeReadPlatformService officeReadPlatformService; - private final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService; - private final ColumnValidator columnValidator; - - // mapper - private final AccountTransfersMapper accountTransfersMapper; - - // pagination - private final PaginationHelper paginationHelper = new PaginationHelper<>(); - 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) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.clientReadPlatformService = clientReadPlatformService; - this.officeReadPlatformService = officeReadPlatformService; - this.portfolioAccountReadPlatformService = portfolioAccountReadPlatformService; - this.columnValidator = columnValidator; - - this.accountTransfersMapper = new AccountTransfersMapper(); - } - - @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, - final Integer toAccountType) { - - 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 toAccountTypeOptions; - if (mostRelevantFromAccountType != null - && mostRelevantFromAccountType == 1) { - // overpaid loan amt transfer to savings account - toAccountTypeOptions = Arrays.asList(savingsAccountType); - } else { - toAccountTypeOptions = Arrays.asList(loanAccountType, - savingsAccountType); - } - final Integer mostRelevantToAccountType = toAccountType; - - final EnumOptionData fromAccountTypeData = AccountTransferEnumerations - .accountType(mostRelevantFromAccountType); - final EnumOptionData toAccountTypeData = AccountTransferEnumerations - .accountType(mostRelevantToAccountType); - - // from settings - OfficeData fromOffice = null; - ClientData fromClient = null; - PortfolioAccountData fromAccount = null; - - OfficeData toOffice = null; - ClientData toClient = null; - PortfolioAccountData toAccount = null; - - // template - Collection fromAccountOptions = null; - Collection toAccountOptions = null; - - Long mostRelevantFromOfficeId = fromOfficeId; - Long mostRelevantFromClientId = fromClientId; - - Long mostRelevantToOfficeId = toOfficeId; - Long mostRelevantToClientId = toClientId; - - if (fromAccountId != null) { - Integer accountType; - if (mostRelevantFromAccountType == 1) { - accountType = PortfolioAccountType.LOAN.getValue(); - } else { - accountType = PortfolioAccountType.SAVINGS.getValue(); - } - fromAccount = this.portfolioAccountReadPlatformService.retrieveOne( - fromAccountId, accountType); - - // override provided fromClient with client of account - mostRelevantFromClientId = fromAccount.clientId(); - } - - if (mostRelevantFromClientId != null) { - 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, - loanStatus); - 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); - } - - // defaults - final LocalDate transferDate = DateUtils.getLocalDateOfTenant(); - Collection toOfficeOptions = fromOfficeOptions; - Collection toClientOptions = null; - - if (toAccountId != null && fromAccount != null) { - toAccount = this.portfolioAccountReadPlatformService.retrieveOne( - toAccountId, mostRelevantToAccountType, - fromAccount.currencyCode()); - mostRelevantToClientId = toAccount.clientId(); - } - - if (mostRelevantToClientId != null) { - toClient = this.clientReadPlatformService - .retrieveOne(mostRelevantToClientId); - mostRelevantToOfficeId = toClient.officeId(); - - toClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); - - toAccountOptions = retrieveToAccounts(fromAccount, - mostRelevantToAccountType, mostRelevantToClientId); - } - - if (mostRelevantToOfficeId != null) { - toOffice = this.officeReadPlatformService - .retrieveOffice(mostRelevantToOfficeId); - toOfficeOptions = this.officeReadPlatformService - .retrieveAllOfficesForDropdown(); - - toClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); - if (toClientOptions != null && toClientOptions.size() == 1) { - toClient = new ArrayList<>(toClientOptions).get(0); - - 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); - } - - private Collection retrieveToAccounts( - final PortfolioAccountData excludeThisAccountFromOptions, - final Integer toAccountType, final Long toClientId) { - - final String currencyCode = excludeThisAccountFromOptions != null ? excludeThisAccountFromOptions - .currencyCode() : null; - - PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO( - toAccountType, toClientId, currencyCode, null, null); - Collection accountOptions = this.portfolioAccountReadPlatformService - .retrieveAllForLookup(portfolioAccountDTO); - if (!CollectionUtils.isEmpty(accountOptions)) { - accountOptions.remove(excludeThisAccountFromOptions); - } else { - accountOptions = null; - } - - return accountOptions; - } - - @Override - public Page retrieveAll( - final SearchParameters searchParameters, final Long accountDetailId) { - - final StringBuilder sqlBuilder = new StringBuilder(200); - sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); - sqlBuilder.append(this.accountTransfersMapper.schema()); - Object[] finalObjectArray = {}; - if (accountDetailId != null) { - sqlBuilder.append(" where att.account_transfer_details_id=?"); - finalObjectArray = new Object[] { accountDetailId }; - } - - if (searchParameters.isOrderByRequested()) { - sqlBuilder.append(" order by ").append( - searchParameters.getOrderBy()); - this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy()); - if (searchParameters.isSortOrderProvided()) { - sqlBuilder.append(' ').append(searchParameters.getSortOrder()); - this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getSortOrder()); - } - } - - if (searchParameters.isLimited()) { - sqlBuilder.append(" limit ").append(searchParameters.getLimit()); - if (searchParameters.isOffset()) { - sqlBuilder.append(" offset ").append( - searchParameters.getOffset()); - } - } - - final String sqlCountRows = "SELECT FOUND_ROWS()"; - return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, - sqlBuilder.toString(), finalObjectArray, - this.accountTransfersMapper); - } - - @Override - public AccountTransferData retrieveOne(final Long transferId) { - - try { - final String sql = "select " + this.accountTransfersMapper.schema() - + " where att.id = ?"; - - return this.jdbcTemplate.queryForObject(sql, - this.accountTransfersMapper, new Object[] { transferId }); - } catch (final EmptyResultDataAccessException e) { - throw new AccountTransferNotFoundException(transferId); - } - } - - @Override - 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, - AccountTransferType.INTEREST_TRANSFER.getValue()); - - return transactionId; - } - - 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.description as transferDescription,"); - 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.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("tosavtran.id as toSavingsAccountTransactionId,"); - 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 "); - - this.schemaSql = sqlBuilder.toString(); - } - - public String schema() { - return this.schemaSql; - } - - @Override - 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 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 Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId"); - final String fromOfficeName = rs.getString("fromOfficeName"); - 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 Long fromClientId = JdbcSupport.getLong(rs, "fromClientId"); - final String fromClientName = rs.getString("fromClientName"); - 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 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); - } else if (fromLoanAccountId != null) { - 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 String toLoanAccountNo = rs.getString("toLoanAccountNo"); - - if (toSavingsAccountId != null) { - toAccount = PortfolioAccountData.lookup(toSavingsAccountId, - toSavingsAccountNo); - toAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.SAVINGS); - } else if (toLoanAccountId != null) { - 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); - } - } - - @Override - 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); - } else { - sql.append("at.from_savings_transaction_id=").append(transactionId) - .append(" or at.to_savings_transaction_id=") - .append(transactionId); - } - - final int count = this.jdbcTemplate.queryForObject(sql.toString(), Integer.class); - return count > 0; - } - - @Override - 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(" where atsi.id = ?"); - - if (searchParameters != null) { - if (searchParameters.isOrderByRequested()) { - sqlBuilder.append(" order by ").append( - searchParameters.getOrderBy()); - this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy()); - if (searchParameters.isSortOrderProvided()) { - sqlBuilder.append(' ').append( - searchParameters.getSortOrder()); - this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getSortOrder()); - } - } - - if (searchParameters.isLimited()) { - sqlBuilder.append(" limit ") - .append(searchParameters.getLimit()); - if (searchParameters.isOffset()) { - 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, - 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) { - // TODO Auto-generated method stub - 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 toAccountTypeOptions; - if (mostRelevantFromAccountType == 1) { - // overpaid loan amt transfer to savings account - toAccountTypeOptions = Arrays.asList(savingsAccountType); - } else { - toAccountTypeOptions = Arrays.asList(loanAccountType, - savingsAccountType); - } - final Integer mostRelevantToAccountType = toAccountType; - - final EnumOptionData fromAccountTypeData = AccountTransferEnumerations - .accountType(mostRelevantFromAccountType); - final EnumOptionData toAccountTypeData = AccountTransferEnumerations - .accountType(mostRelevantToAccountType); - - // from settings - OfficeData fromOffice = null; - ClientData fromClient = null; - PortfolioAccountData fromAccount = null; - - OfficeData toOffice = null; - ClientData toClient = null; - PortfolioAccountData toAccount = null; - - // template - Collection fromAccountOptions = null; - Collection toAccountOptions = null; - - Long mostRelevantFromOfficeId = fromOfficeId; - Long mostRelevantFromClientId = fromClientId; - - Long mostRelevantToOfficeId = toOfficeId; - Long mostRelevantToClientId = toClientId; - - if (fromAccountId != null) { - Integer accountType; - if (mostRelevantFromAccountType == 1) { - accountType = PortfolioAccountType.LOAN.getValue(); - } else { - accountType = PortfolioAccountType.SAVINGS.getValue(); - } - fromAccount = this.portfolioAccountReadPlatformService - .retrieveOneByPaidInAdvance(fromAccountId, accountType); - - // override provided fromClient with client of account - mostRelevantFromClientId = fromAccount.clientId(); - } - - if (mostRelevantFromClientId != null) { - 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, - loanStatus); - 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); - } - - // defaults - final LocalDate transferDate = DateUtils.getLocalDateOfTenant(); - Collection toOfficeOptions = fromOfficeOptions; - Collection toClientOptions = null; - - if (toAccountId != null && fromAccount != null) { - toAccount = this.portfolioAccountReadPlatformService.retrieveOne( - toAccountId, mostRelevantToAccountType, - fromAccount.currencyCode()); - mostRelevantToClientId = toAccount.clientId(); - } - - if (mostRelevantToClientId != null) { - toClient = this.clientReadPlatformService - .retrieveOne(mostRelevantToClientId); - mostRelevantToOfficeId = toClient.officeId(); - - toClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); - - toAccountOptions = retrieveToAccounts(fromAccount, - mostRelevantToAccountType, mostRelevantToClientId); - } - - if (mostRelevantToOfficeId != null) { - toOffice = this.officeReadPlatformService - .retrieveOffice(mostRelevantToOfficeId); - toOfficeOptions = this.officeReadPlatformService - .retrieveAllOfficesForDropdown(); - - toClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); - if (toClientOptions != null && toClientOptions.size() == 1) { - toClient = new ArrayList<>(toClientOptions).get(0); - - 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); - } - - @Override - 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(" 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 = ?) "); - - return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), - new Object[] { this.formatter.print(transactionDate), - accountType, accountId, accountId }, BigDecimal.class); - } + AccountTransfersReadPlatformService { + + private final JdbcTemplate jdbcTemplate; + private final ClientReadPlatformService clientReadPlatformService; + private final OfficeReadPlatformService officeReadPlatformService; + private final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService; + private final ColumnValidator columnValidator; + + // mapper + private final AccountTransfersMapper accountTransfersMapper; + + // pagination + private final PaginationHelper paginationHelper = new PaginationHelper<>(); + 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) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.clientReadPlatformService = clientReadPlatformService; + this.officeReadPlatformService = officeReadPlatformService; + this.portfolioAccountReadPlatformService = portfolioAccountReadPlatformService; + this.columnValidator = columnValidator; + + this.accountTransfersMapper = new AccountTransfersMapper(); + } + + @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, + final Integer toAccountType) { + + 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 toAccountTypeOptions; + if (mostRelevantFromAccountType != null + && mostRelevantFromAccountType == 1) { + // overpaid loan amt transfer to savings account + toAccountTypeOptions = Arrays.asList(savingsAccountType); + } else { + toAccountTypeOptions = Arrays.asList(loanAccountType, + savingsAccountType); + } + final Integer mostRelevantToAccountType = toAccountType; + + final EnumOptionData fromAccountTypeData = AccountTransferEnumerations + .accountType(mostRelevantFromAccountType); + final EnumOptionData toAccountTypeData = AccountTransferEnumerations + .accountType(mostRelevantToAccountType); + + // from settings + OfficeData fromOffice = null; + ClientData fromClient = null; + PortfolioAccountData fromAccount = null; + + OfficeData toOffice = null; + ClientData toClient = null; + PortfolioAccountData toAccount = null; + + // template + Collection fromAccountOptions = null; + Collection toAccountOptions = null; + + Long mostRelevantFromOfficeId = fromOfficeId; + Long mostRelevantFromClientId = fromClientId; + + Long mostRelevantToOfficeId = toOfficeId; + Long mostRelevantToClientId = toClientId; + + if (fromAccountId != null) { + Integer accountType; + if (mostRelevantFromAccountType == 1) { + accountType = PortfolioAccountType.LOAN.getValue(); + } else { + accountType = PortfolioAccountType.SAVINGS.getValue(); + } + fromAccount = this.portfolioAccountReadPlatformService.retrieveOne( + fromAccountId, accountType); + + // override provided fromClient with client of account + mostRelevantFromClientId = fromAccount.clientId(); + } + + if (mostRelevantFromClientId != null) { + 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, + loanStatus); + 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); + } + + // defaults + final LocalDate transferDate = DateUtils.getLocalDateOfTenant(); + Collection toOfficeOptions = fromOfficeOptions; + Collection toClientOptions = null; + + if (toAccountId != null && fromAccount != null) { + toAccount = this.portfolioAccountReadPlatformService.retrieveOne( + toAccountId, mostRelevantToAccountType, + fromAccount.currencyCode()); + mostRelevantToClientId = toAccount.clientId(); + } + + if (mostRelevantToClientId != null) { + toClient = this.clientReadPlatformService + .retrieveOne(mostRelevantToClientId); + mostRelevantToOfficeId = toClient.officeId(); + + toClientOptions = this.clientReadPlatformService + .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); + + toAccountOptions = retrieveToAccounts(fromAccount, + mostRelevantToAccountType, mostRelevantToClientId); + } + + if (mostRelevantToOfficeId != null) { + toOffice = this.officeReadPlatformService + .retrieveOffice(mostRelevantToOfficeId); + toOfficeOptions = this.officeReadPlatformService + .retrieveAllOfficesForDropdown(); + + toClientOptions = this.clientReadPlatformService + .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); + if (toClientOptions != null && toClientOptions.size() == 1) { + toClient = new ArrayList<>(toClientOptions).get(0); + + 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); + } + + private Collection retrieveToAccounts( + final PortfolioAccountData excludeThisAccountFromOptions, + final Integer toAccountType, final Long toClientId) { + + final String currencyCode = excludeThisAccountFromOptions != null ? excludeThisAccountFromOptions + .currencyCode() : null; + + PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO( + toAccountType, toClientId, currencyCode, null, null); + Collection accountOptions = this.portfolioAccountReadPlatformService + .retrieveAllForLookup(portfolioAccountDTO); + if (!CollectionUtils.isEmpty(accountOptions)) { + accountOptions.remove(excludeThisAccountFromOptions); + } else { + accountOptions = null; + } + + return accountOptions; + } + + @Override + public Page retrieveAll( + final SearchParameters searchParameters, final Long accountDetailId) { + + final StringBuilder sqlBuilder = new StringBuilder(200); + sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); + sqlBuilder.append(this.accountTransfersMapper.schema()); + Object[] finalObjectArray = {}; + if (accountDetailId != null) { + sqlBuilder.append(" where att.account_transfer_details_id=?"); + finalObjectArray = new Object[] { accountDetailId }; + } + + if (searchParameters.isOrderByRequested()) { + sqlBuilder.append(" order by ").append( + searchParameters.getOrderBy()); + this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy()); + if (searchParameters.isSortOrderProvided()) { + sqlBuilder.append(' ').append(searchParameters.getSortOrder()); + this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getSortOrder()); + } + } + + if (searchParameters.isLimited()) { + sqlBuilder.append(" limit ").append(searchParameters.getLimit()); + if (searchParameters.isOffset()) { + sqlBuilder.append(" offset ").append( + searchParameters.getOffset()); + } + } + + final String sqlCountRows = "SELECT FOUND_ROWS()"; + return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, + sqlBuilder.toString(), finalObjectArray, + this.accountTransfersMapper); + } + + @Override + public AccountTransferData retrieveOne(final Long transferId) { + + try { + final String sql = "select " + this.accountTransfersMapper.schema() + + " where att.id = ?"; + + return this.jdbcTemplate.queryForObject(sql, + this.accountTransfersMapper, new Object[] { transferId }); + } catch (final EmptyResultDataAccessException e) { + throw new AccountTransferNotFoundException(transferId); + } + } + + @Override + 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, + AccountTransferType.INTEREST_TRANSFER.getValue()); + + return transactionId; + } + + 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.description as transferDescription,"); + 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.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("tosavtran.id as toSavingsAccountTransactionId,"); + 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 "); + + this.schemaSql = sqlBuilder.toString(); + } + + public String schema() { + return this.schemaSql; + } + + @Override + 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 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 Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId"); + final String fromOfficeName = rs.getString("fromOfficeName"); + 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 Long fromClientId = JdbcSupport.getLong(rs, "fromClientId"); + final String fromClientName = rs.getString("fromClientName"); + 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 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); + } else if (fromLoanAccountId != null) { + 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 String toLoanAccountNo = rs.getString("toLoanAccountNo"); + + if (toSavingsAccountId != null) { + toAccount = PortfolioAccountData.lookup(toSavingsAccountId, + toSavingsAccountNo); + toAccountType = AccountTransferEnumerations + .accountType(PortfolioAccountType.SAVINGS); + } else if (toLoanAccountId != null) { + 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); + } + } + + @Override + 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); + } else { + sql.append("at.from_savings_transaction_id=").append(transactionId) + .append(" or at.to_savings_transaction_id=") + .append(transactionId); + } + + final int count = this.jdbcTemplate.queryForObject(sql.toString(), Integer.class); + return count > 0; + } + + @Override + 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(" where atsi.id = ?"); + + if (searchParameters != null) { + if (searchParameters.isOrderByRequested()) { + sqlBuilder.append(" order by ").append( + searchParameters.getOrderBy()); + this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy()); + if (searchParameters.isSortOrderProvided()) { + sqlBuilder.append(' ').append( + searchParameters.getSortOrder()); + this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getSortOrder()); + } + } + + if (searchParameters.isLimited()) { + sqlBuilder.append(" limit ") + .append(searchParameters.getLimit()); + if (searchParameters.isOffset()) { + 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, + 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) { + // TODO Auto-generated method stub + 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 toAccountTypeOptions; + if (mostRelevantFromAccountType == 1) { + // overpaid loan amt transfer to savings account + toAccountTypeOptions = Arrays.asList(savingsAccountType); + } else { + toAccountTypeOptions = Arrays.asList(loanAccountType, + savingsAccountType); + } + final Integer mostRelevantToAccountType = toAccountType; + + final EnumOptionData fromAccountTypeData = AccountTransferEnumerations + .accountType(mostRelevantFromAccountType); + final EnumOptionData toAccountTypeData = AccountTransferEnumerations + .accountType(mostRelevantToAccountType); + + // from settings + OfficeData fromOffice = null; + ClientData fromClient = null; + PortfolioAccountData fromAccount = null; + + OfficeData toOffice = null; + ClientData toClient = null; + PortfolioAccountData toAccount = null; + + // template + Collection fromAccountOptions = null; + Collection toAccountOptions = null; + + Long mostRelevantFromOfficeId = fromOfficeId; + Long mostRelevantFromClientId = fromClientId; + + Long mostRelevantToOfficeId = toOfficeId; + Long mostRelevantToClientId = toClientId; + + if (fromAccountId != null) { + Integer accountType; + if (mostRelevantFromAccountType == 1) { + accountType = PortfolioAccountType.LOAN.getValue(); + } else { + accountType = PortfolioAccountType.SAVINGS.getValue(); + } + fromAccount = this.portfolioAccountReadPlatformService + .retrieveOneByPaidInAdvance(fromAccountId, accountType); + + // override provided fromClient with client of account + mostRelevantFromClientId = fromAccount.clientId(); + } + + if (mostRelevantFromClientId != null) { + 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, + loanStatus); + 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); + } + + // defaults + final LocalDate transferDate = DateUtils.getLocalDateOfTenant(); + Collection toOfficeOptions = fromOfficeOptions; + Collection toClientOptions = null; + + if (toAccountId != null && fromAccount != null) { + toAccount = this.portfolioAccountReadPlatformService.retrieveOne( + toAccountId, mostRelevantToAccountType, + fromAccount.currencyCode()); + mostRelevantToClientId = toAccount.clientId(); + } + + if (mostRelevantToClientId != null) { + toClient = this.clientReadPlatformService + .retrieveOne(mostRelevantToClientId); + mostRelevantToOfficeId = toClient.officeId(); + + toClientOptions = this.clientReadPlatformService + .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); + + toAccountOptions = retrieveToAccounts(fromAccount, + mostRelevantToAccountType, mostRelevantToClientId); + } + + if (mostRelevantToOfficeId != null) { + toOffice = this.officeReadPlatformService + .retrieveOffice(mostRelevantToOfficeId); + toOfficeOptions = this.officeReadPlatformService + .retrieveAllOfficesForDropdown(); + + toClientOptions = this.clientReadPlatformService + .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); + if (toClientOptions != null && toClientOptions.size() == 1) { + toClient = new ArrayList<>(toClientOptions).get(0); + + 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); + } + + @Override + 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(" 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 = ?) "); + + return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), + 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/StandingInstructionHistoryReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformServiceImpl.java index 0307b4779..ff2070130 100755 --- 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 @@ -61,7 +61,7 @@ public class StandingInstructionHistoryReadPlatformServiceImpl implements Standi @Autowired public StandingInstructionHistoryReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + 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/accountdetails/data/ShareAccountSummaryData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/ShareAccountSummaryData.java index ef5f49a9f..034b2ff56 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 @@ -27,45 +27,45 @@ import java.io.Serializable; @SuppressWarnings("unused") public class ShareAccountSummaryData implements Serializable { - private final Long id; - private final String accountNo; - private final Long totalApprovedShares; - private final Long totalPendingForApprovalShares; - private final String externalId; - private final Long productId; - private final String productName; - private final String shortProductName; - private final ShareAccountStatusEnumData status; - private final CurrencyData currency; - private final ShareAccountApplicationTimelineData timeline; + private final Long id; + private final String accountNo; + private final Long totalApprovedShares; + private final Long totalPendingForApprovalShares; + private final String externalId; + private final Long productId; + private final String productName; + private final String shortProductName; + private final ShareAccountStatusEnumData status; + 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) { - this.id = id; - this.accountNo = accountNo; - this.externalId = externalId; - if(approvedShares == null) { - this.totalApprovedShares = new Long(0) ; - }else { - this.totalApprovedShares = approvedShares; - } - if(pendingForApprovalShares == null) { - this.totalPendingForApprovalShares = new Long(0) ; - }else { - this.totalPendingForApprovalShares = pendingForApprovalShares; - } - this.productId = productId; - this.productName = productName; - this.shortProductName = shortProductName; - this.status = status; - this.currency = currency; - this.timeline = 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 = new Long(0) ; + }else { + this.totalApprovedShares = approvedShares; + } + if(pendingForApprovalShares == null) { + this.totalPendingForApprovalShares = new Long(0) ; + }else { + this.totalPendingForApprovalShares = pendingForApprovalShares; + } + this.productId = productId; + this.productName = productName; + this.shortProductName = shortProductName; + this.status = status; + this.currency = currency; + this.timeline = timeline; + } public String getAccountNo() { 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 index b4b1bb7e5..153616578 100755 --- 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 @@ -82,7 +82,7 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final List savingsAccounts = retrieveAccountDetails(savingswhereClause, new Object[] { clientId }); final List shareAccounts = retrieveShareAccountDetails(clientId) ; final List guarantorloanAccounts = retrieveGuarantorLoanAccountDetails( - guarantorWhereClause, new Object[] { clientId }); + guarantorWhereClause, new Object[] { clientId }); return new AccountSummaryCollectionData(loanAccounts, savingsAccounts, shareAccounts, guarantorloanAccounts); } @@ -101,13 +101,13 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final List groupSavingsAccounts = retrieveAccountDetails(savingswhereClauseForGroup, new Object[] { groupId }); final List groupGuarantorloanAccounts = retrieveGuarantorLoanAccountDetails( - guarantorWhereClauseForGroup, new Object[] { groupId }); + guarantorWhereClauseForGroup, new Object[] { groupId }); final List memberLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForMembers, new Object[] { groupId }); final List memberSavingsAccounts = retrieveAccountDetails(savingswhereClauseForMembers, new Object[] { groupId }); final List memberGuarantorloanAccounts = retrieveGuarantorLoanAccountDetails( - guarantorWhereClauseForMembers, new Object[] { groupId }); + guarantorWhereClauseForMembers, new Object[] { groupId }); return new AccountSummaryCollectionData(groupLoanAccounts, groupSavingsAccounts, groupGuarantorloanAccounts, memberLoanAccounts, memberSavingsAccounts, memberGuarantorloanAccounts); } @@ -151,56 +151,56 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou } 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) { - final GuarantorLoanAccountSummaryDataMapper rm = new GuarantorLoanAccountSummaryDataMapper(); - final String sql = "select " + rm.guarantorLoanAccountSummarySchema() - + loanwhereClause; - return this.jdbcTemplate.query(sql, rm, inputs); - } + final String loanwhereClause, final Object[] inputs) { + final GuarantorLoanAccountSummaryDataMapper rm = new GuarantorLoanAccountSummaryDataMapper(); + 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 ; - - ShareAccountSummaryDataMapper() { - final StringBuffer buff = new StringBuffer() - .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 { + private final String schema ; + + ShareAccountSummaryDataMapper() { + final StringBuffer buff = new StringBuffer() + .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 { final Long id = JdbcSupport.getLong(rs, "id"); final String accountNo = rs.getString("accountNo"); @@ -255,10 +255,10 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou return new ShareAccountSummaryData(id, accountNo, externalId, productId, productName, shortProductName, status, currency, approvedShares, pendingShares, timeline); } - - public String schema() { - return this.schema ; - } + + public String schema() { + return this.schema ; + } } private static final class SavingsAccountSummaryDataMapper implements RowMapper { @@ -516,94 +516,94 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou } private static final class GuarantorLoanAccountSummaryDataMapper implements - RowMapper { + RowMapper { - public String guarantorLoanAccountSummarySchema() { + public String guarantorLoanAccountSummarySchema() { - 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,") + 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.principal_disbursed_derived as originalLoan,") - .append("l.total_outstanding_derived as loanBalance,") - .append("l.total_repayment_derived as amountPaid,") + .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,") + .append(" l.loan_product_counter as loanCycle,") - .append(" l.submittedon_date as submittedOnDate,") + .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") + .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(); - } + return accountsSummary.toString(); + } - @Override - public GuarantorAccountSummaryData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + @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 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 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 LocalDate overdueSinceDate = JdbcSupport.getLocalDate(rs, + "overdueSinceDate"); + Boolean inArrears = true; + if (overdueSinceDate == null) { + inArrears = false; + } - final Boolean isActive = rs.getBoolean("isActive"); + 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); - } - + 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); + } + } } \ No newline at end of file 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 4cdadcafd..964716f96 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 @@ -25,88 +25,88 @@ import java.util.Set; public interface ShareAccountApiConstants { - String amountParamName = "amount"; - String dateFormatParamName = "dateFormat"; - String dueAsOfDateParamName = "dueDate"; - String feeIntervalParamName = "feeInterval"; - String feeOnMonthDayParamName = "feeOnMonthDay"; - String localeParamName = "locale"; + String amountParamName = "amount"; + String dateFormatParamName = "dateFormat"; + String dueAsOfDateParamName = "dueDate"; + String feeIntervalParamName = "feeInterval"; + String feeOnMonthDayParamName = "feeOnMonthDay"; + String localeParamName = "locale"; - // Command Strings - String APPROVE_COMMAND = "approve"; - String REJECT_COMMAND = "reject"; - String APPLY_ADDITIONALSHARES_COMMAND = "applyadditionalshares"; - String APPROVE_ADDITIONSHARES_COMMAND = "approveadditionalshares"; - String REJECT_ADDITIONSHARES_COMMAND = "rejectadditionalshares"; + // Command Strings + String APPROVE_COMMAND = "approve"; + String REJECT_COMMAND = "reject"; + String APPLY_ADDITIONALSHARES_COMMAND = "applyadditionalshares"; + String APPROVE_ADDITIONSHARES_COMMAND = "approveadditionalshares"; + String REJECT_ADDITIONSHARES_COMMAND = "rejectadditionalshares"; - // - String locale_paramname = "locale" ; - - String dateformat_paramname = "dateFormat" ; - - String id_paramname = "id"; + // + String locale_paramname = "locale" ; + + String dateformat_paramname = "dateFormat" ; + + String id_paramname = "id"; - String clientid_paramname = "clientId"; + String clientid_paramname = "clientId"; - String productid_paramname = "productId"; + String productid_paramname = "productId"; - String submitteddate_paramname = "submittedDate"; + String submitteddate_paramname = "submittedDate"; - String approveddate_paramname = "approvedDate"; + String approveddate_paramname = "approvedDate"; - String activatedate_paramname = "activatedDate" ; - - String fieldofferid_paramname = "fieldOfficerId"; + String activatedate_paramname = "activatedDate" ; + + String fieldofferid_paramname = "fieldOfficerId"; - String externalid_paramname = "externalId"; + String externalid_paramname = "externalId"; - String currency_paramname = "currencyCode"; + String currency_paramname = "currencyCode"; - String digitsafterdecimal_paramname = "digitsAfterDecimal"; + String digitsafterdecimal_paramname = "digitsAfterDecimal"; - String inmultiplesof_paramname = "inMultiplesOf"; + String inmultiplesof_paramname = "inMultiplesOf"; - String requestedshares_paramname = "requestedShares"; + String requestedshares_paramname = "requestedShares"; - String savingsaccountid_paramname = "savingsAccountId"; + String savingsaccountid_paramname = "savingsAccountId"; - String lockinperiod_paramname = "lockinPeriodFrequency"; + String lockinperiod_paramname = "lockinPeriodFrequency"; - String lockperiodfrequencytype_paramname = "lockinPeriodFrequencyType"; + String lockperiodfrequencytype_paramname = "lockinPeriodFrequencyType"; - String minimumactiveperiod_paramname = "minimumActivePeriod"; + String minimumactiveperiod_paramname = "minimumActivePeriod"; - String minimumactiveperiodfrequencytype_paramname = "minimumActivePeriodFrequencyType"; + String minimumactiveperiodfrequencytype_paramname = "minimumActivePeriodFrequencyType"; - String allowdividendcalculationforinactiveclients_paramname = "allowDividendCalculationForInactiveClients"; + String allowdividendcalculationforinactiveclients_paramname = "allowDividendCalculationForInactiveClients"; - String charges_paramname = "charges"; + String charges_paramname = "charges"; - String applicationdate_param = "applicationDate"; + String applicationdate_param = "applicationDate"; - String purchaseddate_paramname = "purchasedDate"; + String purchaseddate_paramname = "purchasedDate"; - String numberofshares_paramname = "numberOfShares"; + String numberofshares_paramname = "numberOfShares"; - String purchasedprice_paramname = "unitPrice"; - - String note_paramname = "note" ; - - String requesteddate_paramname = "requestedDate" ; - - String additionalshares_paramname = "additionalshares" ; - - String closeddate_paramname = "closedDate"; + String purchasedprice_paramname = "unitPrice"; + + String note_paramname = "note" ; + + String requesteddate_paramname = "requestedDate" ; + + 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))); + 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))); } 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 e36b9a4a5..ff964de6a 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 @@ -45,52 +45,52 @@ import java.util.Set; @Scope("singleton") @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 String resourceNameForPermissions = "Address"; - private final PlatformSecurityContext context; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final FieldConfigurationReadPlatformService readPlatformServicefld; - private final DefaultToApiJsonSerializer toApiJsonSerializerfld; - private final ApiRequestParameterHelper apiRequestParameterHelper; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + 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; + private final FieldConfigurationReadPlatformService readPlatformServicefld; + private final DefaultToApiJsonSerializer toApiJsonSerializerfld; + private final ApiRequestParameterHelper apiRequestParameterHelper; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - @Autowired - public EntityFieldConfigurationApiResources(final PlatformSecurityContext context, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final FieldConfigurationReadPlatformService readPlatformServicefld, - final DefaultToApiJsonSerializer toApiJsonSerializerfld, - final ApiRequestParameterHelper apiRequestParameterHelper, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { - this.context = context; - this.toApiJsonSerializer = toApiJsonSerializer; - this.readPlatformServicefld = readPlatformServicefld; - this.toApiJsonSerializerfld = toApiJsonSerializerfld; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - } + @Autowired + public EntityFieldConfigurationApiResources(final PlatformSecurityContext context, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final FieldConfigurationReadPlatformService readPlatformServicefld, + final DefaultToApiJsonSerializer toApiJsonSerializerfld, + final ApiRequestParameterHelper apiRequestParameterHelper, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + this.context = context; + this.toApiJsonSerializer = toApiJsonSerializer; + this.readPlatformServicefld = readPlatformServicefld; + this.toApiJsonSerializerfld = toApiJsonSerializerfld; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + } - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) + @GET + @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")}) - public String getAddresses(@PathParam("entity") @ApiParam(value = "entity") final String entityname, @Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + 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()); - return this.toApiJsonSerializerfld.serialize(settings, fldconfig, this.RESPONSE_DATA_PARAMETERS); + 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/data/AddressData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/AddressData.java index 9d3802252..a7f10aaf2 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 @@ -27,197 +27,197 @@ import java.util.Date; @SuppressWarnings("unused") public class AddressData implements Serializable { - - private final Long client_id; + + private final Long client_id; - private final String addressType; + private final String addressType; - private final Long addressId; + private final Long addressId; - private final Long addressTypeId; + private final Long addressTypeId; - private final Boolean isActive; + private final Boolean isActive; - private final String street; + private final String street; - private final String addressLine1; + private final String addressLine1; - private final String addressLine2; + private final String addressLine2; - private final String addressLine3; + private final String addressLine3; - private final String townVillage; + private final String townVillage; - private final String city; + private final String city; - private final String countyDistrict; + private final String countyDistrict; - private final Long stateProvinceId; + private final Long stateProvinceId; - private final String countryName; + private final String countryName; - private final String stateName; + private final String stateName; - private final Long countryId; + private final Long countryId; - private final String postalCode; + private final String postalCode; - private final BigDecimal latitude; + private final BigDecimal latitude; - private final BigDecimal longitude; + private final BigDecimal longitude; - private final String createdBy; + private final String createdBy; - private final Date createdOn; + private final Date createdOn; - private final String updatedBy; + private final String updatedBy; - private final Date updatedOn; + private final Date updatedOn; - // template holder - private final Collection countryIdOptions; - private final Collection stateProvinceIdOptions; - private final Collection addressTypeIdOptions; + // template holder + private final Collection countryIdOptions; + 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; - this.street = street; - this.addressLine1 = addressLine1; - this.addressLine2 = addressLine2; - this.addressLine3 = addressLine3; - this.countryId = countryId; - this.postalCode = postalCode; - this.stateProvinceId = stateProvinceId; - this.city = city; - this.townVillage = null; - this.client_id = null; - this.addressType = null; - this.addressId = null; - this.countyDistrict = null; - this.countryName = null; - this.stateName = null; - this.latitude = null; - this.longitude = null; - this.createdBy = null; - this.createdOn = null; - this.updatedBy = null; - this.updatedOn = null; - this.countryIdOptions = null; - this.stateProvinceIdOptions = null; - this.addressTypeIdOptions = null; - } + this.addressTypeId = addressTypeId; + this.isActive = isActive; + this.street = street; + this.addressLine1 = addressLine1; + this.addressLine2 = addressLine2; + this.addressLine3 = addressLine3; + this.countryId = countryId; + this.postalCode = postalCode; + this.stateProvinceId = stateProvinceId; + this.city = city; + this.townVillage = null; + this.client_id = null; + this.addressType = null; + this.addressId = null; + this.countyDistrict = null; + this.countryName = null; + this.stateName = null; + this.latitude = null; + this.longitude = null; + this.createdBy = null; + this.createdOn = null; + this.updatedBy = null; + this.updatedOn = null; + this.countryIdOptions = null; + this.stateProvinceIdOptions = null; + 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 Collection countryIdOptions, final Collection stateProvinceIdOptions, - final Collection addressTypeIdOptions) { - this.addressType = addressType; - this.client_id = client_id; - this.addressId = addressId; - this.addressTypeId = addressTypeId; - this.isActive = is_active; - this.street = street; - this.addressLine1 = addressLine1; - this.addressLine2 = addressLine2; - this.addressLine3 = addressLine3; - this.townVillage = townVillage; - this.city = city; - this.countyDistrict = countyDistrict; - this.stateProvinceId = stateProvinceId; - this.countryId = countryId; - this.stateName = stateName; - this.countryName = countryName; - this.postalCode = postalCode; - this.latitude = latitude; - this.longitude = longitude; - this.createdBy = createdBy; - this.createdOn = createdOn; - this.updatedBy = updatedBy; - this.updatedOn = updatedOn; - this.countryIdOptions = countryIdOptions; - this.stateProvinceIdOptions = stateProvinceIdOptions; - this.addressTypeIdOptions = addressTypeIdOptions; - } + 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 Collection countryIdOptions, final Collection stateProvinceIdOptions, + final Collection addressTypeIdOptions) { + this.addressType = addressType; + this.client_id = client_id; + this.addressId = addressId; + this.addressTypeId = addressTypeId; + this.isActive = is_active; + this.street = street; + this.addressLine1 = addressLine1; + this.addressLine2 = addressLine2; + this.addressLine3 = addressLine3; + this.townVillage = townVillage; + this.city = city; + this.countyDistrict = countyDistrict; + this.stateProvinceId = stateProvinceId; + this.countryId = countryId; + this.stateName = stateName; + this.countryName = countryName; + this.postalCode = postalCode; + this.latitude = latitude; + this.longitude = longitude; + this.createdBy = createdBy; + this.createdOn = createdOn; + this.updatedBy = updatedBy; + this.updatedOn = updatedOn; + this.countryIdOptions = countryIdOptions; + this.stateProvinceIdOptions = stateProvinceIdOptions; + 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, - updatedOn, null, null, null); - } + 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 Long client_idtemp = null; + public static AddressData template(final Collection countryIdOptions, + final Collection stateProvinceIdOptions, + final Collection addressTypeIdOptions) { + final Long client_idtemp = null; - final Long addressIdtemp = null; + final Long addressIdtemp = null; - final Long addressTypeIdtemp = null; + final Long addressTypeIdtemp = null; - final Boolean is_activetemp = null; + final Boolean is_activetemp = null; - final String streettemp = null; + final String streettemp = null; - final String addressLine1temp = null; + final String addressLine1temp = null; - final String addressLine2temp = null; + final String addressLine2temp = null; - final String addressLine3temp = null; + final String addressLine3temp = null; - final String townVillagetemp = null; + final String townVillagetemp = null; - final String citytemp = null; + final String citytemp = null; - final String countyDistricttemp = null; + final String countyDistricttemp = null; - final Long stateProvinceIdtemp = null; + final Long stateProvinceIdtemp = null; - final Long countryIdtemp = null; + final Long countryIdtemp = null; - final String postalCodetemp = null; + final String postalCodetemp = null; - final BigDecimal latitudetemp = null; + final BigDecimal latitudetemp = null; - final BigDecimal longitudetemp = null; + final BigDecimal longitudetemp = null; - final String createdBytemp = null; + final String createdBytemp = null; - final Date createdOntemp = null; + final Date createdOntemp = null; - final String updatedBytemp = null; + final String updatedBytemp = null; - final Date updatedOntemp = null; + 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 dc55e0538..b776ae869 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 @@ -20,27 +20,27 @@ package org.apache.fineract.portfolio.address.data; public class ClientAddressData { - private final long clientAddressId; + private final long clientAddressId; - private final long client_id; + private final long client_id; - private final long address_id; + private final long address_id; - private final long address_type_id; + private final long address_type_id; - private final boolean isActive; + 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) { - this.clientAddressId = clientAddressId; - this.client_id = client_id; - this.address_id = address_id; - this.address_type_id = address_type_id; - this.isActive = 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; + this.address_type_id = address_type_id; + this.isActive = isActive; + } - public static ClientAddressData instance(final long clientAddressId, final long client_id, final long address_id, - final long address_type_id, final boolean isActive) { - return new ClientAddressData(clientAddressId, client_id, address_id, address_type_id, isActive); - } + public static ClientAddressData instance(final long clientAddressId, final long client_id, final long address_id, + final long address_type_id, final boolean isActive) { + return new ClientAddressData(clientAddressId, client_id, address_id, address_type_id, isActive); + } } 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 ae0495d0a..1a1bd5d5d 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,64 +19,64 @@ package org.apache.fineract.portfolio.address.data; public class FieldConfigurationData { - private final long fieldConfigurationId; + private final long fieldConfigurationId; - private final String entity; + private final String entity; - private final String subentity; + private final String subentity; - private final String field; + private final String field; - private final boolean is_enabled; + private final boolean is_enabled; - private final boolean is_mandatory; + private final boolean is_mandatory; - private final String validation_regex; + 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) { - this.fieldConfigurationId = fieldConfigurationId; - this.entity = entity; - this.subentity = subentity; - this.field = field; - this.is_enabled = is_enabled; - this.is_mandatory = is_mandatory; - this.validation_regex = 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; + this.field = field; + this.is_enabled = is_enabled; + this.is_mandatory = is_mandatory; + 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() { - return this.fieldConfigurationId; - } + public long getFieldConfigurationId() { + return this.fieldConfigurationId; + } - public String getEntity() { - return this.entity; - } + public String getEntity() { + return this.entity; + } - public String getSubEntity() { - return this.subentity; - } + public String getSubEntity() { + return this.subentity; + } - public String getField() { - return this.field; - } + public String getField() { + return this.field; + } - public boolean isIs_enabled() { - return this.is_enabled; - } + public boolean isIs_enabled() { + return this.is_enabled; + } - public boolean isIs_mandatory() { - return this.is_mandatory; - } + public boolean isIs_mandatory() { + return this.is_mandatory; + } - public String getValidation_regex() { - return this.validation_regex; - } + public String getValidation_regex() { + return this.validation_regex; + } } 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 85c39a216..2d855e867 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 @@ -45,349 +45,349 @@ import com.google.gson.JsonObject; @Table(name = "m_address") public class Address extends AbstractPersistableCustom { - /* - * @OneToMany(mappedBy = "address", cascade = CascadeType.ALL) private - * List clientaddress = new ArrayList<>(); - */ + /* + * @OneToMany(mappedBy = "address", cascade = CascadeType.ALL) private + * List clientaddress = new ArrayList<>(); + */ - @OneToMany(mappedBy = "address", cascade = CascadeType.ALL) - private Set clientaddress; + @OneToMany(mappedBy = "address", cascade = CascadeType.ALL) + private Set clientaddress; - @Column(name = "street") - private String street; + @Column(name = "street") + private String street; - @Column(name = "address_line_1") - private String addressLine1; + @Column(name = "address_line_1") + private String addressLine1; - @Column(name = "address_line_2") - private String addressLine2; + @Column(name = "address_line_2") + private String addressLine2; - @Column(name = "address_line_3") - private String addressLine3; + @Column(name = "address_line_3") + private String addressLine3; - @Column(name = "town_village") - private String townVillage; + @Column(name = "town_village") + private String townVillage; - @Column(name = "city") - private String city; + @Column(name = "city") + private String city; - @Column(name = "county_district") - private String countyDistrict; + @Column(name = "county_district") + private String countyDistrict; - @ManyToOne - @JoinColumn(name = "state_province_id") - private CodeValue stateProvince; + @ManyToOne + @JoinColumn(name = "state_province_id") + private CodeValue stateProvince; - @ManyToOne - @JoinColumn(name = "country_id") - private CodeValue country; + @ManyToOne + @JoinColumn(name = "country_id") + private CodeValue country; - @Column(name = "postal_code") - private String postalCode; + @Column(name = "postal_code") + private String postalCode; - @Column(name = "latitude") - private BigDecimal latitude; + @Column(name = "latitude") + private BigDecimal latitude; - @Column(name = "longitude") - private BigDecimal longitude; + @Column(name = "longitude") + private BigDecimal longitude; - @Column(name = "created_by") - private String createdBy; + @Column(name = "created_by") + private String createdBy; - @Column(name = "created_on") - private Date createdOn; + @Column(name = "created_on") + private Date createdOn; - @Column(name = "updated_by") - private String updatedBy; + @Column(name = "updated_by") + private String updatedBy; - @Column(name = "updated_on") - private Date updatedOn; + @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) { - this.street = street; - this.addressLine1 = addressLine1; - this.addressLine2 = addressLine2; - this.addressLine3 = addressLine3; - this.townVillage = townVillage; - this.city = city; - this.countyDistrict = countyDistrict; - this.stateProvince = stateProvince; - this.country = country; - this.postalCode = postalCode; - this.latitude = latitude; - this.longitude = longitude; - this.createdBy = createdBy; - //this.createdOn = createdOn; - this.updatedBy = updatedBy; - //this.updatedOn = updatedOn; - - if (createdOn != null) { - this.createdOn = createdOn.toDate(); - - } + 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; + this.addressLine3 = addressLine3; + this.townVillage = townVillage; + this.city = city; + this.countyDistrict = countyDistrict; + this.stateProvince = stateProvince; + this.country = country; + this.postalCode = postalCode; + this.latitude = latitude; + this.longitude = longitude; + this.createdBy = createdBy; + //this.createdOn = createdOn; + this.updatedBy = updatedBy; + //this.updatedOn = updatedOn; + + if (createdOn != null) { + this.createdOn = createdOn.toDate(); + + } - if (updatedOn != null) { - this.updatedOn = updatedOn.toDate(); - } + if (updatedOn != null) { + this.updatedOn = updatedOn.toDate(); + } - } + } - public Address() { - - } + public Address() { + + } - public static Address fromJson(final JsonCommand command, final CodeValue stateProvince, final CodeValue country) { - - final String street = command.stringValueOfParameterNamed("street"); - - final String addressLine1 = command.stringValueOfParameterNamed("addressLine1"); - - final String addressLine2 = command.stringValueOfParameterNamed("addressLine2"); - - final String addressLine3 = command.stringValueOfParameterNamed("addressLine3"); - - final String townVillage = command.stringValueOfParameterNamed("townVillage"); - - final String city = command.stringValueOfParameterNamed("city"); - - final String countyDistrict = command.stringValueOfParameterNamed("countyDistrict"); - - final String postalCode = command.stringValueOfParameterNamed("postalCode"); - - final BigDecimal latitude = command.bigDecimalValueOfParameterNamed("latitude"); - - final BigDecimal longitude = command.bigDecimalValueOfParameterNamed("longitude"); - - final String createdBy = command.stringValueOfParameterNamed("createdBy"); - - final LocalDate createdOn = command.localDateValueOfParameterNamed("createdOn"); - - final String updatedBy = command.stringValueOfParameterNamed("updatedBy"); - - 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); - } - - public static Address fromJsonObject(final JsonObject jsonObject, final CodeValue state_province, - final CodeValue country) { - String street = ""; - String addressLine1 = ""; - String addressLine2 = ""; - String addressLine3 = ""; - String townVillage = ""; - String city = ""; - String countyDistrict = ""; - String postalCode = ""; - BigDecimal latitude = BigDecimal.ZERO; - BigDecimal longitude = BigDecimal.ZERO; - String createdBy = ""; - Locale locale = Locale.ENGLISH; - String updatedBy = ""; - LocalDate updatedOnDate = null; - LocalDate createdOnDate = null; - - if (jsonObject.has("street")) { - street = jsonObject.get("street").getAsString(); - - } - - if (jsonObject.has("addressLine1")) { - addressLine1 = jsonObject.get("addressLine1").getAsString(); - } - if (jsonObject.has("addressLine2")) { - - addressLine2 = jsonObject.get("addressLine2").getAsString(); - } - if (jsonObject.has("addressLine3")) { - addressLine3 = jsonObject.get("addressLine3").getAsString(); - } - if (jsonObject.has("townVillage")) { - townVillage = jsonObject.get("townVillage").getAsString(); - } - if (jsonObject.has("city")) { - city = jsonObject.get("city").getAsString(); - } - if (jsonObject.has("countyDistrict")) { - countyDistrict = jsonObject.get("countyDistrict").getAsString(); - } - if (jsonObject.has("postalCode")) { - - postalCode = jsonObject.get("postalCode").getAsString(); - } - if (jsonObject.has("latitude")) { - - latitude = jsonObject.get("latitude").getAsBigDecimal(); - } - if (jsonObject.has("longitude")) { + public static Address fromJson(final JsonCommand command, final CodeValue stateProvince, final CodeValue country) { + + final String street = command.stringValueOfParameterNamed("street"); + + final String addressLine1 = command.stringValueOfParameterNamed("addressLine1"); + + final String addressLine2 = command.stringValueOfParameterNamed("addressLine2"); + + final String addressLine3 = command.stringValueOfParameterNamed("addressLine3"); + + final String townVillage = command.stringValueOfParameterNamed("townVillage"); + + final String city = command.stringValueOfParameterNamed("city"); + + final String countyDistrict = command.stringValueOfParameterNamed("countyDistrict"); + + final String postalCode = command.stringValueOfParameterNamed("postalCode"); + + final BigDecimal latitude = command.bigDecimalValueOfParameterNamed("latitude"); + + final BigDecimal longitude = command.bigDecimalValueOfParameterNamed("longitude"); + + final String createdBy = command.stringValueOfParameterNamed("createdBy"); + + final LocalDate createdOn = command.localDateValueOfParameterNamed("createdOn"); + + final String updatedBy = command.stringValueOfParameterNamed("updatedBy"); + + 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); + } + + public static Address fromJsonObject(final JsonObject jsonObject, final CodeValue state_province, + final CodeValue country) { + String street = ""; + String addressLine1 = ""; + String addressLine2 = ""; + String addressLine3 = ""; + String townVillage = ""; + String city = ""; + String countyDistrict = ""; + String postalCode = ""; + BigDecimal latitude = BigDecimal.ZERO; + BigDecimal longitude = BigDecimal.ZERO; + String createdBy = ""; + Locale locale = Locale.ENGLISH; + String updatedBy = ""; + LocalDate updatedOnDate = null; + LocalDate createdOnDate = null; + + if (jsonObject.has("street")) { + street = jsonObject.get("street").getAsString(); + + } + + if (jsonObject.has("addressLine1")) { + addressLine1 = jsonObject.get("addressLine1").getAsString(); + } + if (jsonObject.has("addressLine2")) { + + addressLine2 = jsonObject.get("addressLine2").getAsString(); + } + if (jsonObject.has("addressLine3")) { + addressLine3 = jsonObject.get("addressLine3").getAsString(); + } + if (jsonObject.has("townVillage")) { + townVillage = jsonObject.get("townVillage").getAsString(); + } + if (jsonObject.has("city")) { + city = jsonObject.get("city").getAsString(); + } + if (jsonObject.has("countyDistrict")) { + countyDistrict = jsonObject.get("countyDistrict").getAsString(); + } + if (jsonObject.has("postalCode")) { + + postalCode = jsonObject.get("postalCode").getAsString(); + } + if (jsonObject.has("latitude")) { + + latitude = jsonObject.get("latitude").getAsBigDecimal(); + } + if (jsonObject.has("longitude")) { - longitude = jsonObject.get("longitude").getAsBigDecimal(); - } + longitude = jsonObject.get("longitude").getAsBigDecimal(); + } - if (jsonObject.has("createdBy")) { - createdBy = jsonObject.get("createdBy").getAsString(); - } - if (jsonObject.has("createdOn")) { - String createdOn = jsonObject.get("createdOn").getAsString(); - DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); - createdOnDate = LocalDate.parse(createdOn, formatter); - - } - if (jsonObject.has("updatedBy")) { - updatedBy = jsonObject.get("updatedBy").getAsString(); - } - if (jsonObject.has("updatedOn")) { - String updatedOn = jsonObject.get("updatedOn").getAsString(); - DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); - 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); - } - - public Set getClientaddress() { - return this.clientaddress; - } - - public void setClientaddress(Set clientaddress) { - this.clientaddress = clientaddress; - } - - public String getStreet() { - return this.street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getAddressLine1() { - return this.addressLine1; - } - - public void setAddressLine1(String addressLine1) { - this.addressLine1 = addressLine1; - } - - public String getAddressLine2() { - return this.addressLine2; - } - - public void setAddressLine2(String addressLine2) { - this.addressLine2 = addressLine2; - } - - public String getAddressLine3() { - return this.addressLine3; - } - - public void setAddressLine3(String addressLine3) { - this.addressLine3 = addressLine3; - } - - public String getTownVillage() { - return this.townVillage; - } - - public void setTownVillage(String townVillage) { - this.townVillage = townVillage; - } - - public String getCity() { - return this.city; - } - - public void setCity(String city) { - this.city = city; - } - - public String getCountyDistrict() { - return this.countyDistrict; - } - - public void setCountyDistrict(String countyDistrict) { - this.countyDistrict = countyDistrict; - } - - public CodeValue getStateProvince() { - return this.stateProvince; - } - - public void setStateProvince(CodeValue stateProvince) { - this.stateProvince = stateProvince; - } - - public CodeValue getCountry() { - return this.country; - } - - public void setCountry(CodeValue country) { - this.country = country; - } - - public String getPostalCode() { - return this.postalCode; - } - - public void setPostalCode(String postalCode) { - this.postalCode = postalCode; - } - - public BigDecimal getLatitude() { - return this.latitude; - } - - public void setLatitude(BigDecimal latitude) { - this.latitude = latitude; - } - - public BigDecimal getLongitude() { - return this.longitude; - } + if (jsonObject.has("createdBy")) { + createdBy = jsonObject.get("createdBy").getAsString(); + } + if (jsonObject.has("createdOn")) { + String createdOn = jsonObject.get("createdOn").getAsString(); + DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); + createdOnDate = LocalDate.parse(createdOn, formatter); + + } + if (jsonObject.has("updatedBy")) { + updatedBy = jsonObject.get("updatedBy").getAsString(); + } + if (jsonObject.has("updatedOn")) { + String updatedOn = jsonObject.get("updatedOn").getAsString(); + DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); + 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); + } + + public Set getClientaddress() { + return this.clientaddress; + } + + public void setClientaddress(Set clientaddress) { + this.clientaddress = clientaddress; + } + + public String getStreet() { + return this.street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getAddressLine1() { + return this.addressLine1; + } + + public void setAddressLine1(String addressLine1) { + this.addressLine1 = addressLine1; + } + + public String getAddressLine2() { + return this.addressLine2; + } + + public void setAddressLine2(String addressLine2) { + this.addressLine2 = addressLine2; + } + + public String getAddressLine3() { + return this.addressLine3; + } + + public void setAddressLine3(String addressLine3) { + this.addressLine3 = addressLine3; + } + + public String getTownVillage() { + return this.townVillage; + } + + public void setTownVillage(String townVillage) { + this.townVillage = townVillage; + } + + public String getCity() { + return this.city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getCountyDistrict() { + return this.countyDistrict; + } + + public void setCountyDistrict(String countyDistrict) { + this.countyDistrict = countyDistrict; + } + + public CodeValue getStateProvince() { + return this.stateProvince; + } + + public void setStateProvince(CodeValue stateProvince) { + this.stateProvince = stateProvince; + } + + public CodeValue getCountry() { + return this.country; + } + + public void setCountry(CodeValue country) { + this.country = country; + } + + public String getPostalCode() { + return this.postalCode; + } + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + public BigDecimal getLatitude() { + return this.latitude; + } + + public void setLatitude(BigDecimal latitude) { + this.latitude = latitude; + } + + public BigDecimal getLongitude() { + return this.longitude; + } - public void setLongitude(BigDecimal longitude) { - this.longitude = longitude; - } + public void setLongitude(BigDecimal longitude) { + this.longitude = longitude; + } - public String getCreatedBy() { - return this.createdBy; - } + public String getCreatedBy() { + return this.createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public Date getCreatedOn() { - return this.createdOn; - } + public Date getCreatedOn() { + return this.createdOn; + } - public void setCreatedOn(LocalDate createdOn) { - this.createdOn = createdOn.toDate(); - } + public void setCreatedOn(LocalDate createdOn) { + this.createdOn = createdOn.toDate(); + } - public String getUpdatedBy() { - return this.updatedBy; - } + public String getUpdatedBy() { + return this.updatedBy; + } - public void setUpdatedBy(String updatedBy) { - this.updatedBy = updatedBy; - } + public void setUpdatedBy(String updatedBy) { + this.updatedBy = updatedBy; + } - public Date getUpdatedOn() { - return this.updatedOn; - } + public Date getUpdatedOn() { + return this.updatedOn; + } - public void setUpdatedOn(LocalDate updatedOn) { - this.updatedOn = updatedOn.toDate();; - } + public void setUpdatedOn(LocalDate updatedOn) { + this.updatedOn = updatedOn.toDate();; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/FieldConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/FieldConfiguration.java index 7353c7ed2..2fe213194 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/FieldConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/FieldConfiguration.java @@ -28,32 +28,32 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_field_configuration") public class FieldConfiguration extends AbstractPersistableCustom { - private String entity; + private String entity; - private String table; + private String table; - private String field; + private String field; - private boolean is_enabled; + private boolean is_enabled; - public FieldConfiguration() { + public FieldConfiguration() { - } + } - private FieldConfiguration(final String entity, final String table, final String field, final boolean is_enabled) { - this.entity = entity; - this.table = table; - this.field = field; - this.is_enabled = is_enabled; + private FieldConfiguration(final String entity, final String table, final String field, final boolean is_enabled) { + this.entity = entity; + this.table = table; + this.field = field; + this.is_enabled = is_enabled; - } + } - private static FieldConfiguration fromJson(final JsonCommand command) { - final String entity = command.stringValueOfParameterNamed("entity"); - final String table = command.stringValueOfParameterNamed("table"); - final String field = command.stringValueOfParameterNamed("field"); - final boolean is_enabled = command.booleanPrimitiveValueOfParameterNamed("implementationKey"); + private static FieldConfiguration fromJson(final JsonCommand command) { + final String entity = command.stringValueOfParameterNamed("entity"); + final String table = command.stringValueOfParameterNamed("table"); + final String field = command.stringValueOfParameterNamed("field"); + final boolean is_enabled = command.booleanPrimitiveValueOfParameterNamed("implementationKey"); - return new FieldConfiguration(entity, table, field, is_enabled); - } + return new FieldConfiguration(entity, table, field, is_enabled); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/FieldConfigurationRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/FieldConfigurationRepository.java index 070373c74..ce0c3de7c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/FieldConfigurationRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/FieldConfigurationRepository.java @@ -22,6 +22,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface FieldConfigurationRepository - extends JpaRepository, JpaSpecificationExecutor { + extends JpaRepository, JpaSpecificationExecutor { } 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 99351925a..d565fd0a9 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 @@ -22,13 +22,13 @@ 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); - } + 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); + } - public AddressNotFoundException(final long clientId, final long addressTypeId) { - super("error.msg.address.client.addresstype.not.found", - "Client with client ID`" + clientId + "` does not have address" + " type with id", addressTypeId); - } + public AddressNotFoundException(final long clientId, final long addressTypeId) { + super("error.msg.address.client.addresstype.not.found", + "Client with client ID`" + clientId + "` does not have address" + " type with id", 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 dd054e1ec..243b6ed56 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 @@ -44,229 +44,229 @@ import com.google.gson.reflect.TypeToken; @Component public class AddressCommandFromApiJsonDeserializer { - private final FromJsonHelper fromApiJsonHelper; - private final FieldConfigurationReadPlatformService readservice; + private final FromJsonHelper fromApiJsonHelper; + private final FieldConfigurationReadPlatformService readservice; - @Autowired - public AddressCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper, - final FieldConfigurationReadPlatformService readservice) { - this.fromApiJsonHelper = fromApiJsonHelper; - this.readservice = readservice; - } + @Autowired + public AddressCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper, + final FieldConfigurationReadPlatformService readservice) { + this.fromApiJsonHelper = fromApiJsonHelper; + this.readservice = readservice; + } - public void validateForUpdate(final String json) { - validate(json, false); - } + public void validateForUpdate(final String json) { + validate(json, false); + } - public void validateForCreate(final String json, final boolean fromNewClient) { - validate(json, fromNewClient); - } + public void validateForCreate(final String json, final boolean fromNewClient) { + validate(json, fromNewClient); + } - public void validate(final String json, final boolean fromNewClient) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public void validate(final String json, final boolean fromNewClient) { + 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 List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource("Address"); - final JsonElement element = this.fromApiJsonHelper.parse(json); - Set supportedParameters = new HashSet<>(); + final JsonElement element = this.fromApiJsonHelper.parse(json); + Set supportedParameters = new HashSet<>(); - final List configurationData = new ArrayList<>( - this.readservice.retrieveFieldConfigurationList("ADDRESS")); - final List enabledFieldList = new ArrayList<>(); + final List configurationData = new ArrayList<>( + this.readservice.retrieveFieldConfigurationList("ADDRESS")); + final List enabledFieldList = new ArrayList<>(); - final Map madatoryFieldsMap = new HashMap(); - final Map enabledFieldsMap = new HashMap(); - final Map regexFieldsMap = new HashMap(); + final Map madatoryFieldsMap = new HashMap(); + final Map enabledFieldsMap = new HashMap(); + final Map regexFieldsMap = new HashMap(); - // validate the json fields from the configuration data fields + // validate the json fields from the configuration data fields - for (final FieldConfigurationData data : configurationData) { - madatoryFieldsMap.put(data.getField(), data.isIs_mandatory()); - enabledFieldsMap.put(data.getField(), data.isIs_enabled()); - regexFieldsMap.put(data.getField(), data.getValidation_regex()); - if (data.isIs_enabled()) { - enabledFieldList.add(data.getField()); - } - } - if (fromNewClient) { + for (final FieldConfigurationData data : configurationData) { + madatoryFieldsMap.put(data.getField(), data.isIs_mandatory()); + enabledFieldsMap.put(data.getField(), data.isIs_enabled()); + regexFieldsMap.put(data.getField(), data.getValidation_regex()); + if (data.isIs_enabled()) { + enabledFieldList.add(data.getField()); + } + } + if (fromNewClient) { - enabledFieldList.add("addressTypeId"); - enabledFieldList.add("locale"); - enabledFieldList.add("dateFormat"); - supportedParameters = new HashSet<>(enabledFieldList); - // enabledFieldList.add("address"); + enabledFieldList.add("addressTypeId"); + enabledFieldList.add("locale"); + enabledFieldList.add("dateFormat"); + supportedParameters = new HashSet<>(enabledFieldList); + // enabledFieldList.add("address"); - madatoryFieldsMap.put("addressTypeId", true); + madatoryFieldsMap.put("addressTypeId", true); - } - if (!fromNewClient) { - enabledFieldList.add("locale"); - enabledFieldList.add("dateFormat"); - enabledFieldList.add("addressId"); - madatoryFieldsMap.put("addressId", true); - supportedParameters = new HashSet<>(enabledFieldList); - } - // final Set supportedParameters = new - // HashSet<>(enabledFieldList); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + } + if (!fromNewClient) { + enabledFieldList.add("locale"); + enabledFieldList.add("dateFormat"); + enabledFieldList.add("addressId"); + madatoryFieldsMap.put("addressId", true); + supportedParameters = new HashSet<>(enabledFieldList); + } + // final Set supportedParameters = new + // HashSet<>(enabledFieldList); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); - final String street = this.fromApiJsonHelper.extractStringNamed("street", element); + final String street = this.fromApiJsonHelper.extractStringNamed("street", element); - if (enabledFieldsMap.get("street")) { - if (madatoryFieldsMap.get("street") && fromNewClient) { + if (enabledFieldsMap.get("street")) { + if (madatoryFieldsMap.get("street") && fromNewClient) { - baseDataValidator.reset().parameter("street").value(street).notBlank(); + baseDataValidator.reset().parameter("street").value(street).notBlank(); - } - if (!regexFieldsMap.get("street").isEmpty()) { - baseDataValidator.reset().parameter("street").value(street) - .matchesRegularExpression(regexFieldsMap.get("street")); - } + } + if (!regexFieldsMap.get("street").isEmpty()) { + baseDataValidator.reset().parameter("street").value(street) + .matchesRegularExpression(regexFieldsMap.get("street")); + } - } - final String addressLine1 = this.fromApiJsonHelper.extractStringNamed("addressLine1", element); - if (enabledFieldsMap.get("addressLine1")) { - if (madatoryFieldsMap.get("addressLine1") && fromNewClient) { - baseDataValidator.reset().parameter("addressLine1").value(addressLine1).notBlank(); - } - if (!regexFieldsMap.get("addressLine1").isEmpty()) { - baseDataValidator.reset().parameter("addressLine1").value(addressLine1) - .matchesRegularExpression(regexFieldsMap.get("addressLine1")); - } + } + final String addressLine1 = this.fromApiJsonHelper.extractStringNamed("addressLine1", element); + if (enabledFieldsMap.get("addressLine1")) { + if (madatoryFieldsMap.get("addressLine1") && fromNewClient) { + baseDataValidator.reset().parameter("addressLine1").value(addressLine1).notBlank(); + } + if (!regexFieldsMap.get("addressLine1").isEmpty()) { + baseDataValidator.reset().parameter("addressLine1").value(addressLine1) + .matchesRegularExpression(regexFieldsMap.get("addressLine1")); + } - } - final String addressLine2 = this.fromApiJsonHelper.extractStringNamed("addressLine2", element); - if (enabledFieldsMap.get("addressLine2")) { - if (madatoryFieldsMap.get("addressLine2") && fromNewClient) { - baseDataValidator.reset().parameter("addressLine2").value(addressLine2).notBlank(); - } - if (!regexFieldsMap.get("addressLine2").isEmpty()) { - baseDataValidator.reset().parameter("addressLine2").value(addressLine2) - .matchesRegularExpression(regexFieldsMap.get("addressLine2")); - } - } - final String addressLine3 = this.fromApiJsonHelper.extractStringNamed("addressLine3", element); - if (enabledFieldsMap.get("addressLine3")) { - if (madatoryFieldsMap.get("addressLine3") && fromNewClient) { - baseDataValidator.reset().parameter("addressLine3").value(addressLine3).notBlank(); - } - if (!regexFieldsMap.get("addressLine3").isEmpty()) { - baseDataValidator.reset().parameter("addressLine3").value(addressLine3) - .matchesRegularExpression(regexFieldsMap.get("addressLine3")); - } - } - final String townVillage = this.fromApiJsonHelper.extractStringNamed("townVillage", element); - if (enabledFieldsMap.get("townVillage")) { - if (madatoryFieldsMap.get("townVillage") && fromNewClient) { - baseDataValidator.reset().parameter("townVillage").value(townVillage).notBlank(); - } - if (!regexFieldsMap.get("townVillage").isEmpty()) { - baseDataValidator.reset().parameter("townVillage").value(townVillage) - .matchesRegularExpression(regexFieldsMap.get("townVillage")); - } - } - final String city = this.fromApiJsonHelper.extractStringNamed("city", element); + } + final String addressLine2 = this.fromApiJsonHelper.extractStringNamed("addressLine2", element); + if (enabledFieldsMap.get("addressLine2")) { + if (madatoryFieldsMap.get("addressLine2") && fromNewClient) { + baseDataValidator.reset().parameter("addressLine2").value(addressLine2).notBlank(); + } + if (!regexFieldsMap.get("addressLine2").isEmpty()) { + baseDataValidator.reset().parameter("addressLine2").value(addressLine2) + .matchesRegularExpression(regexFieldsMap.get("addressLine2")); + } + } + final String addressLine3 = this.fromApiJsonHelper.extractStringNamed("addressLine3", element); + if (enabledFieldsMap.get("addressLine3")) { + if (madatoryFieldsMap.get("addressLine3") && fromNewClient) { + baseDataValidator.reset().parameter("addressLine3").value(addressLine3).notBlank(); + } + if (!regexFieldsMap.get("addressLine3").isEmpty()) { + baseDataValidator.reset().parameter("addressLine3").value(addressLine3) + .matchesRegularExpression(regexFieldsMap.get("addressLine3")); + } + } + final String townVillage = this.fromApiJsonHelper.extractStringNamed("townVillage", element); + if (enabledFieldsMap.get("townVillage")) { + if (madatoryFieldsMap.get("townVillage") && fromNewClient) { + baseDataValidator.reset().parameter("townVillage").value(townVillage).notBlank(); + } + if (!regexFieldsMap.get("townVillage").isEmpty()) { + baseDataValidator.reset().parameter("townVillage").value(townVillage) + .matchesRegularExpression(regexFieldsMap.get("townVillage")); + } + } + final String city = this.fromApiJsonHelper.extractStringNamed("city", element); - if (enabledFieldsMap.get("city")) { - if (madatoryFieldsMap.get("city") && fromNewClient) { - baseDataValidator.reset().parameter("city").value(city).notBlank(); - } - if (!regexFieldsMap.get("city").isEmpty()) { - baseDataValidator.reset().parameter("city").value(city) - .matchesRegularExpression(regexFieldsMap.get("city")); - } - } - final String countyDistrict = this.fromApiJsonHelper.extractStringNamed("countyDistrict", element); - if (enabledFieldsMap.get("countyDistrict")) { - if (madatoryFieldsMap.get("countyDistrict") && fromNewClient) { - baseDataValidator.reset().parameter("countyDistrict").value(countyDistrict).notBlank(); - } - if (!regexFieldsMap.get("countyDistrict").isEmpty()) { - baseDataValidator.reset().parameter("countyDistrict").value(countyDistrict) - .matchesRegularExpression(regexFieldsMap.get("countyDistrict")); - } - } + if (enabledFieldsMap.get("city")) { + if (madatoryFieldsMap.get("city") && fromNewClient) { + baseDataValidator.reset().parameter("city").value(city).notBlank(); + } + if (!regexFieldsMap.get("city").isEmpty()) { + baseDataValidator.reset().parameter("city").value(city) + .matchesRegularExpression(regexFieldsMap.get("city")); + } + } + final String countyDistrict = this.fromApiJsonHelper.extractStringNamed("countyDistrict", element); + if (enabledFieldsMap.get("countyDistrict")) { + if (madatoryFieldsMap.get("countyDistrict") && fromNewClient) { + baseDataValidator.reset().parameter("countyDistrict").value(countyDistrict).notBlank(); + } + if (!regexFieldsMap.get("countyDistrict").isEmpty()) { + baseDataValidator.reset().parameter("countyDistrict").value(countyDistrict) + .matchesRegularExpression(regexFieldsMap.get("countyDistrict")); + } + } - if (this.fromApiJsonHelper.extractLongNamed("stateProvinceId", element) != null) { + if (this.fromApiJsonHelper.extractLongNamed("stateProvinceId", element) != null) { - final long stateProvinceId = this.fromApiJsonHelper.extractLongNamed("stateProvinceId", element); - if (enabledFieldsMap.get("stateProvinceId")) { - if (madatoryFieldsMap.get("stateProvinceId") && fromNewClient) { - baseDataValidator.reset().parameter("stateProvinceId").value(stateProvinceId).notBlank(); - } - if (!regexFieldsMap.get("stateProvinceId").isEmpty()) { - baseDataValidator.reset().parameter("stateProvinceId").value(stateProvinceId) - .matchesRegularExpression(regexFieldsMap.get("stateProvinceId")); - } - } - } + final long stateProvinceId = this.fromApiJsonHelper.extractLongNamed("stateProvinceId", element); + if (enabledFieldsMap.get("stateProvinceId")) { + if (madatoryFieldsMap.get("stateProvinceId") && fromNewClient) { + baseDataValidator.reset().parameter("stateProvinceId").value(stateProvinceId).notBlank(); + } + if (!regexFieldsMap.get("stateProvinceId").isEmpty()) { + baseDataValidator.reset().parameter("stateProvinceId").value(stateProvinceId) + .matchesRegularExpression(regexFieldsMap.get("stateProvinceId")); + } + } + } - if (this.fromApiJsonHelper.extractLongNamed("countryId", element) != null) { - final long countryId = this.fromApiJsonHelper.extractLongNamed("countryId", element); - if (enabledFieldsMap.get("countryId")) { - if (madatoryFieldsMap.get("countryId") && fromNewClient) { - baseDataValidator.reset().parameter("countryId").value(countryId).notBlank(); - } - if (!regexFieldsMap.get("countryId").isEmpty()) { - baseDataValidator.reset().parameter("countryId").value(countryId) - .matchesRegularExpression(regexFieldsMap.get("countryId")); - } - } - } + if (this.fromApiJsonHelper.extractLongNamed("countryId", element) != null) { + final long countryId = this.fromApiJsonHelper.extractLongNamed("countryId", element); + if (enabledFieldsMap.get("countryId")) { + if (madatoryFieldsMap.get("countryId") && fromNewClient) { + baseDataValidator.reset().parameter("countryId").value(countryId).notBlank(); + } + if (!regexFieldsMap.get("countryId").isEmpty()) { + baseDataValidator.reset().parameter("countryId").value(countryId) + .matchesRegularExpression(regexFieldsMap.get("countryId")); + } + } + } - final String postalCode = this.fromApiJsonHelper.extractStringNamed("postalCode", element); - if (enabledFieldsMap.get("postalCode")) { - if (madatoryFieldsMap.get("postalCode") && fromNewClient) { - baseDataValidator.reset().parameter("postalCode").value(postalCode).notBlank(); - } - if (!regexFieldsMap.get("postalCode").isEmpty()) { - baseDataValidator.reset().parameter("postalCode").value(postalCode) - .matchesRegularExpression(regexFieldsMap.get("postalCode")); - } - } + final String postalCode = this.fromApiJsonHelper.extractStringNamed("postalCode", element); + if (enabledFieldsMap.get("postalCode")) { + if (madatoryFieldsMap.get("postalCode") && fromNewClient) { + baseDataValidator.reset().parameter("postalCode").value(postalCode).notBlank(); + } + if (!regexFieldsMap.get("postalCode").isEmpty()) { + baseDataValidator.reset().parameter("postalCode").value(postalCode) + .matchesRegularExpression(regexFieldsMap.get("postalCode")); + } + } - if (this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("latitude", element) != null) { - final BigDecimal latitude = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("latitude", element); - if (enabledFieldsMap.get("latitude")) { - if (madatoryFieldsMap.get("latitude") && fromNewClient) { - baseDataValidator.reset().parameter("latitude").value(latitude).notBlank(); - } - if (!regexFieldsMap.get("latitude").isEmpty()) { - baseDataValidator.reset().parameter("latitude").value(latitude) - .matchesRegularExpression(regexFieldsMap.get("latitude")); - } - } - } + if (this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("latitude", element) != null) { + final BigDecimal latitude = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("latitude", element); + if (enabledFieldsMap.get("latitude")) { + if (madatoryFieldsMap.get("latitude") && fromNewClient) { + baseDataValidator.reset().parameter("latitude").value(latitude).notBlank(); + } + if (!regexFieldsMap.get("latitude").isEmpty()) { + baseDataValidator.reset().parameter("latitude").value(latitude) + .matchesRegularExpression(regexFieldsMap.get("latitude")); + } + } + } - if (this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("longitude", element) != null) { - final BigDecimal longitude = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("longitude", element); - if (enabledFieldsMap.get("longitude")) { - if (madatoryFieldsMap.get("longitude") && fromNewClient) { - baseDataValidator.reset().parameter("longitude").value(longitude).notBlank(); - } - if (!regexFieldsMap.get("longitude").isEmpty()) { - baseDataValidator.reset().parameter("longitude").value(longitude) - .matchesRegularExpression(regexFieldsMap.get("longitude")); - } - } - } + if (this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("longitude", element) != null) { + final BigDecimal longitude = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("longitude", element); + if (enabledFieldsMap.get("longitude")) { + if (madatoryFieldsMap.get("longitude") && fromNewClient) { + baseDataValidator.reset().parameter("longitude").value(longitude).notBlank(); + } + if (!regexFieldsMap.get("longitude").isEmpty()) { + baseDataValidator.reset().parameter("longitude").value(longitude) + .matchesRegularExpression(regexFieldsMap.get("longitude")); + } + } + } - throwExceptionIfValidationWarningsExist(dataValidationErrors); + throwExceptionIfValidationWarningsExist(dataValidationErrors); - } + } - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - } + private void throwExceptionIfValidationWarningsExist(final List 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/address/service/AddressReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressReadPlatformService.java index 0a45e7aa8..229fb524a 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 @@ -23,15 +23,15 @@ import java.util.Collection; import org.apache.fineract.portfolio.address.data.AddressData; public interface AddressReadPlatformService { - public Collection retrieveAddressFields(long clientid); + public Collection retrieveAddressFields(long clientid); - public Collection retrieveAllClientAddress(long clientid); + public Collection retrieveAllClientAddress(long clientid); - public Collection retrieveAddressbyType(long clientid, long typeid); + public Collection retrieveAddressbyType(long clientid, long typeid); - Collection retrieveAddressbyTypeAndStatus(long clientid, long typeid, String status); + Collection retrieveAddressbyTypeAndStatus(long clientid, long typeid, String status); - Collection retrieveAddressbyStatus(long clientid, String status); + Collection retrieveAddressbyStatus(long clientid, String status); - AddressData retrieveTemplate(); + AddressData retrieveTemplate(); } 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 ccc142500..0b17ddd0c 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 @@ -39,208 +39,208 @@ import org.springframework.stereotype.Service; @Service public class AddressReadPlatformServiceImpl implements AddressReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; - private final CodeValueReadPlatformService readService; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; + private final CodeValueReadPlatformService readService; - @Autowired - public AddressReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, - final CodeValueReadPlatformService readService) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.readService = readService; - } + @Autowired + public AddressReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, + final CodeValueReadPlatformService readService) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.readService = readService; + } - 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," - + "addr.state_province_id as state_province_id, addr.country_id as country_id,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 as addr,m_client client"; - } + 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," + + "addr.state_province_id as state_province_id, addr.country_id as country_id,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 as addr,m_client client"; + } - @Override - public AddressData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + @Override + public AddressData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) + throws SQLException { - final long addressId = rs.getLong("id"); + final long addressId = rs.getLong("id"); - final long clientId = rs.getLong("client_id"); + final long clientId = rs.getLong("client_id"); - final String street = rs.getString("street"); + final String street = rs.getString("street"); - final String address_line_1 = rs.getString("address_line_1"); + final String address_line_1 = rs.getString("address_line_1"); - final String address_line_2 = rs.getString("address_line_2"); + final String address_line_2 = rs.getString("address_line_2"); - final String address_line_3 = rs.getString("address_line_3"); + final String address_line_3 = rs.getString("address_line_3"); - final String town_village = rs.getString("town_village"); + final String town_village = rs.getString("town_village"); - final String city = rs.getString("city"); + final String city = rs.getString("city"); - final String county_district = rs.getString("county_district"); + final String county_district = rs.getString("county_district"); - final long state_province_id = rs.getLong("state_province_id"); + final long state_province_id = rs.getLong("state_province_id"); - final long country_id = rs.getLong("country_id"); + final long country_id = rs.getLong("country_id"); - final String postal_code = rs.getString("postal_code"); + final String postal_code = rs.getString("postal_code"); - final BigDecimal latitude = rs.getBigDecimal("latitude"); + final BigDecimal latitude = rs.getBigDecimal("latitude"); - final BigDecimal longitude = rs.getBigDecimal("longitude"); + final BigDecimal longitude = rs.getBigDecimal("longitude"); - final String created_by = rs.getString("created_by"); + final String created_by = rs.getString("created_by"); - final Date created_on = rs.getDate("created_on"); + final Date created_on = rs.getDate("created_on"); - final String updated_by = rs.getString("updated_by"); + final String updated_by = rs.getString("updated_by"); - final Date updated_on = rs.getDate("updated_on"); + 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" - + " join m_code_value cv2 on ca.address_type_id=cv2.id"; + 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" + + " 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 { + @Override + 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"); + final String addressType = rs.getString("addressType"); + final long addressId = rs.getLong("id"); - final long client_id = rs.getLong("client_id"); + final long client_id = rs.getLong("client_id"); - final String street = rs.getString("street"); + final String street = rs.getString("street"); - final long address_type_id = rs.getLong("addresstyp"); + final long address_type_id = rs.getLong("addresstyp"); - final boolean is_active = rs.getBoolean("is_active"); + final boolean is_active = rs.getBoolean("is_active"); - final String address_line_1 = rs.getString("address_line_1"); + final String address_line_1 = rs.getString("address_line_1"); - final String address_line_2 = rs.getString("address_line_2"); + final String address_line_2 = rs.getString("address_line_2"); - final String address_line_3 = rs.getString("address_line_3"); + final String address_line_3 = rs.getString("address_line_3"); - final String town_village = rs.getString("town_village"); + final String town_village = rs.getString("town_village"); - final String city = rs.getString("city"); + final String city = rs.getString("city"); - final String county_district = rs.getString("county_district"); + final String county_district = rs.getString("county_district"); - final long state_province_id = rs.getLong("state_province_id"); + final long state_province_id = rs.getLong("state_province_id"); - final long country_id = rs.getLong("country_id"); + final long country_id = rs.getLong("country_id"); - final String country_name = rs.getString("country_name"); + final String country_name = rs.getString("country_name"); - final String state_name = rs.getString("state_name"); + final String state_name = rs.getString("state_name"); - final String postal_code = rs.getString("postal_code"); + final String postal_code = rs.getString("postal_code"); - final BigDecimal latitude = rs.getBigDecimal("latitude"); + final BigDecimal latitude = rs.getBigDecimal("latitude"); - final BigDecimal longitude = rs.getBigDecimal("longitude"); + final BigDecimal longitude = rs.getBigDecimal("longitude"); - final String created_by = rs.getString("created_by"); + final String created_by = rs.getString("created_by"); - final Date created_on = rs.getDate("created_on"); + final Date created_on = rs.getDate("created_on"); - final String updated_by = rs.getString("updated_by"); + final String updated_by = rs.getString("updated_by"); - final Date updated_on = rs.getDate("updated_on"); + 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); - } - } + } + } - @Override - public Collection retrieveAddressFields(final long clientid) { - this.context.authenticatedUser(); + @Override + public Collection retrieveAddressFields(final long clientid) { + this.context.authenticatedUser(); - final AddFieldsMapper rm = new AddFieldsMapper(); - final String sql = "select " + rm.schema() + " where client.id=?"; + final AddFieldsMapper rm = new AddFieldsMapper(); + final String sql = "select " + rm.schema() + " where client.id=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { clientid }); - } + return this.jdbcTemplate.query(sql, rm, new Object[] { clientid }); + } - @Override - public Collection retrieveAllClientAddress(final long clientid) { - this.context.authenticatedUser(); - final AddMapper rm = new AddMapper(); - final String sql = "select " + rm.schema() + " and ca.client_id=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { clientid }); - } + @Override + public Collection retrieveAllClientAddress(final long clientid) { + this.context.authenticatedUser(); + final AddMapper rm = new AddMapper(); + final String sql = "select " + rm.schema() + " and ca.client_id=?"; + return this.jdbcTemplate.query(sql, rm, new Object[] { clientid }); + } - @Override - public Collection retrieveAddressbyType(final long clientid, final long typeid) { - this.context.authenticatedUser(); + @Override + public Collection retrieveAddressbyType(final long clientid, final long typeid) { + this.context.authenticatedUser(); - final AddMapper rm = new AddMapper(); - final String sql = "select " + rm.schema() + " and ca.client_id=? and ca.address_type_id=?"; + final AddMapper rm = new AddMapper(); + final String sql = "select " + rm.schema() + " and ca.client_id=? and ca.address_type_id=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { clientid, typeid }); - } + return this.jdbcTemplate.query(sql, rm, new Object[] { clientid, typeid }); + } - @Override - public Collection retrieveAddressbyTypeAndStatus(final long clientid, final long typeid, - final String status) { - this.context.authenticatedUser(); - Boolean temp = false; - temp = Boolean.parseBoolean(status); + @Override + public Collection retrieveAddressbyTypeAndStatus(final long clientid, final long typeid, + final String status) { + this.context.authenticatedUser(); + Boolean temp = false; + temp = Boolean.parseBoolean(status); - final AddMapper rm = new AddMapper(); - final String sql = "select " + rm.schema() + " and ca.client_id=? and ca.address_type_id=? and ca.is_active=?"; + final AddMapper rm = new AddMapper(); + final String sql = "select " + rm.schema() + " and ca.client_id=? and ca.address_type_id=? and ca.is_active=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { clientid, typeid, temp }); - } + return this.jdbcTemplate.query(sql, rm, new Object[] { clientid, typeid, temp }); + } - @Override - public Collection retrieveAddressbyStatus(final long clientid, final String status) { - this.context.authenticatedUser(); - Boolean temp = false; - temp = Boolean.parseBoolean(status); + @Override + public Collection retrieveAddressbyStatus(final long clientid, final String status) { + this.context.authenticatedUser(); + Boolean temp = false; + temp = Boolean.parseBoolean(status); - final AddMapper rm = new AddMapper(); - final String sql = "select " + rm.schema() + " and ca.client_id=? and ca.is_active=?"; + final AddMapper rm = new AddMapper(); + final String sql = "select " + rm.schema() + " and ca.client_id=? and ca.is_active=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { clientid, temp }); - } + return this.jdbcTemplate.query(sql, rm, new Object[] { clientid, temp }); + } - @Override - public AddressData retrieveTemplate() { - final List countryoptions = new ArrayList<>( - this.readService.retrieveCodeValuesByCode("COUNTRY")); + @Override + public AddressData retrieveTemplate() { + final List countryoptions = new ArrayList<>( + this.readService.retrieveCodeValuesByCode("COUNTRY")); - final List StateOptions = new ArrayList<>(this.readService.retrieveCodeValuesByCode("STATE")); + 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); - } + 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 fa1219aab..c60e6c0f4 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,9 +23,9 @@ 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 addClientAddress(Long clientId, Long addressTypeId, JsonCommand command); - CommandProcessingResult addNewClientAddress(Client client, JsonCommand command); + CommandProcessingResult addNewClientAddress(Client client, JsonCommand command); - CommandProcessingResult updateClientAddress(Long clientId, JsonCommand command); + CommandProcessingResult updateClientAddress(Long clientId, 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 b552c2518..e9169dadf 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,249 +42,249 @@ import com.google.gson.JsonObject; @Service public class AddressWritePlatformServiceImpl implements AddressWritePlatformService { - private final PlatformSecurityContext context; - private final CodeValueRepository codeValueRepository; - private final ClientAddressRepository clientAddressRepository; - private final ClientRepositoryWrapper clientRepositoryWrapper; - private final AddressRepository addressRepository; - private final ClientAddressRepositoryWrapper clientAddressRepositoryWrapper; - private final AddressCommandFromApiJsonDeserializer fromApiJsonDeserializer; + private final PlatformSecurityContext context; + private final CodeValueRepository codeValueRepository; + private final ClientAddressRepository clientAddressRepository; + private final ClientRepositoryWrapper clientRepositoryWrapper; + private final AddressRepository addressRepository; + private final ClientAddressRepositoryWrapper clientAddressRepositoryWrapper; + 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, - final AddressCommandFromApiJsonDeserializer fromApiJsonDeserializer) { - this.context = context; - this.codeValueRepository = codeValueRepository; - this.clientAddressRepository = clientAddressRepository; - this.clientRepositoryWrapper = clientRepositoryWrapper; - this.addressRepository = addressRepository; - this.clientAddressRepositoryWrapper = clientAddressRepositoryWrapper; - this.fromApiJsonDeserializer = fromApiJsonDeserializer; + @Autowired + 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; + this.clientAddressRepository = clientAddressRepository; + this.clientRepositoryWrapper = clientRepositoryWrapper; + this.addressRepository = addressRepository; + this.clientAddressRepositoryWrapper = clientAddressRepositoryWrapper; + this.fromApiJsonDeserializer = fromApiJsonDeserializer; - } + } - @Override - public CommandProcessingResult addClientAddress(final Long clientId, final Long addressTypeId, - final JsonCommand command) { - CodeValue stateIdobj = null; - CodeValue countryIdObj = null; - long stateId; - long countryId; + @Override + public CommandProcessingResult addClientAddress(final Long clientId, final Long addressTypeId, + final JsonCommand command) { + CodeValue stateIdobj = null; + CodeValue countryIdObj = null; + long stateId; + long countryId; - this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateForCreate(command.json(), true); + this.context.authenticatedUser(); + this.fromApiJsonDeserializer.validateForCreate(command.json(), true); - if (command.longValueOfParameterNamed("stateProvinceId") != null) { - stateId = command.longValueOfParameterNamed("stateProvinceId"); - stateIdobj = this.codeValueRepository.getOne(stateId); - } + if (command.longValueOfParameterNamed("stateProvinceId") != null) { + stateId = command.longValueOfParameterNamed("stateProvinceId"); + stateIdobj = this.codeValueRepository.getOne(stateId); + } - if (command.longValueOfParameterNamed("countryId") != null) { - countryId = command.longValueOfParameterNamed("countryId"); - countryIdObj = this.codeValueRepository.getOne(countryId); - } + if (command.longValueOfParameterNamed("countryId") != null) { + countryId = command.longValueOfParameterNamed("countryId"); + countryIdObj = this.codeValueRepository.getOne(countryId); + } - final CodeValue addressTypeIdObj = this.codeValueRepository.getOne(addressTypeId); + final CodeValue addressTypeIdObj = this.codeValueRepository.getOne(addressTypeId); - final Address add = Address.fromJson(command, stateIdobj, countryIdObj); - this.addressRepository.save(add); - final Long addressid = add.getId(); - final Address addobj = this.addressRepository.getOne(addressid); + final Address add = Address.fromJson(command, stateIdobj, countryIdObj); + this.addressRepository.save(add); + final Long addressid = add.getId(); + final Address addobj = this.addressRepository.getOne(addressid); - final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); - final boolean isActive = command.booleanPrimitiveValueOfParameterNamed("isActive"); + final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); + final boolean isActive = command.booleanPrimitiveValueOfParameterNamed("isActive"); - final ClientAddress clientAddressobj = ClientAddress.fromJson(isActive, client, addobj, addressTypeIdObj); - this.clientAddressRepository.save(clientAddressobj); + 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 - // client + // following method is used for adding multiple addresses while creating new + // client - @Override - public CommandProcessingResult addNewClientAddress(final Client client, final JsonCommand command) { - CodeValue stateIdobj = null; - CodeValue countryIdObj = null; - long stateId; - long countryId; - ClientAddress clientAddressobj = new ClientAddress(); - final JsonArray addressArray = command.arrayOfParameterNamed("address"); - - if(addressArray != null){ - for (int i = 0; i < addressArray.size(); i++) { - final JsonObject jsonObject = addressArray.get(i).getAsJsonObject(); + @Override + public CommandProcessingResult addNewClientAddress(final Client client, final JsonCommand command) { + CodeValue stateIdobj = null; + CodeValue countryIdObj = null; + long stateId; + long countryId; + ClientAddress clientAddressobj = new ClientAddress(); + final JsonArray addressArray = command.arrayOfParameterNamed("address"); + + if(addressArray != null){ + for (int i = 0; i < addressArray.size(); i++) { + final JsonObject jsonObject = addressArray.get(i).getAsJsonObject(); - // validate every address - this.fromApiJsonDeserializer.validateForCreate(jsonObject.toString(), true); + // validate every address + this.fromApiJsonDeserializer.validateForCreate(jsonObject.toString(), true); - if (jsonObject.get("stateProvinceId") != null) { - stateId = jsonObject.get("stateProvinceId").getAsLong(); - stateIdobj = this.codeValueRepository.getOne(stateId); - } + if (jsonObject.get("stateProvinceId") != null) { + stateId = jsonObject.get("stateProvinceId").getAsLong(); + stateIdobj = this.codeValueRepository.getOne(stateId); + } - if (jsonObject.get("countryId") != null) { - countryId = jsonObject.get("countryId").getAsLong(); - countryIdObj = this.codeValueRepository.getOne(countryId); - } + if (jsonObject.get("countryId") != null) { + countryId = jsonObject.get("countryId").getAsLong(); + countryIdObj = this.codeValueRepository.getOne(countryId); + } - final long addressTypeId = jsonObject.get("addressTypeId").getAsLong(); - final CodeValue addressTypeIdObj = this.codeValueRepository.getOne(addressTypeId); + final long addressTypeId = jsonObject.get("addressTypeId").getAsLong(); + final CodeValue addressTypeIdObj = this.codeValueRepository.getOne(addressTypeId); - final Address add = Address.fromJsonObject(jsonObject, stateIdobj, countryIdObj); - this.addressRepository.save(add); - final Long addressid = add.getId(); - final Address addobj = this.addressRepository.getOne(addressid); + final Address add = Address.fromJsonObject(jsonObject, stateIdobj, countryIdObj); + this.addressRepository.save(add); + 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); + 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 - public CommandProcessingResult updateClientAddress(final Long clientId, final JsonCommand command) { - this.context.authenticatedUser(); + @Override + public CommandProcessingResult updateClientAddress(final Long clientId, final JsonCommand command) { + this.context.authenticatedUser(); - long stateId; + long stateId; - long countryId; + long countryId; - CodeValue stateIdobj; + CodeValue stateIdobj; - CodeValue countryIdObj; + CodeValue countryIdObj; - boolean is_address_update = false; + boolean is_address_update = false; - this.fromApiJsonDeserializer.validateForUpdate(command.json()); + this.fromApiJsonDeserializer.validateForUpdate(command.json()); - final long addressId = command.longValueOfParameterNamed("addressId"); + final long addressId = command.longValueOfParameterNamed("addressId"); - final ClientAddress clientAddressObj = this.clientAddressRepositoryWrapper - .findOneByClientIdAndAddressId(clientId, addressId); + final ClientAddress clientAddressObj = this.clientAddressRepositoryWrapper + .findOneByClientIdAndAddressId(clientId, addressId); - final Address addobj = this.addressRepository.getOne(addressId); + final Address addobj = this.addressRepository.getOne(addressId); - if (!(command.stringValueOfParameterNamed("street").isEmpty())) { + if (!(command.stringValueOfParameterNamed("street").isEmpty())) { - is_address_update = true; - final String street = command.stringValueOfParameterNamed("street"); - addobj.setStreet(street); - } + is_address_update = true; + final String street = command.stringValueOfParameterNamed("street"); + addobj.setStreet(street); + } - if (!(command.stringValueOfParameterNamed("addressLine1").isEmpty())) { + if (!(command.stringValueOfParameterNamed("addressLine1").isEmpty())) { - is_address_update = true; - final String addressLine1 = command.stringValueOfParameterNamed("addressLine1"); - addobj.setAddressLine1(addressLine1); + is_address_update = true; + final String addressLine1 = command.stringValueOfParameterNamed("addressLine1"); + addobj.setAddressLine1(addressLine1); - } + } - if (!(command.stringValueOfParameterNamed("addressLine2").isEmpty())) { + if (!(command.stringValueOfParameterNamed("addressLine2").isEmpty())) { - is_address_update = true; - final String addressLine2 = command.stringValueOfParameterNamed("addressLine2"); - addobj.setAddressLine2(addressLine2); + is_address_update = true; + final String addressLine2 = command.stringValueOfParameterNamed("addressLine2"); + addobj.setAddressLine2(addressLine2); - } + } - if (!(command.stringValueOfParameterNamed("addressLine3").isEmpty())) { - is_address_update = true; - final String addressLine3 = command.stringValueOfParameterNamed("addressLine3"); - addobj.setAddressLine3(addressLine3); + if (!(command.stringValueOfParameterNamed("addressLine3").isEmpty())) { + is_address_update = true; + final String addressLine3 = command.stringValueOfParameterNamed("addressLine3"); + addobj.setAddressLine3(addressLine3); - } + } - if (!(command.stringValueOfParameterNamed("townVillage").isEmpty())) { + if (!(command.stringValueOfParameterNamed("townVillage").isEmpty())) { - is_address_update = true; - final String townVillage = command.stringValueOfParameterNamed("townVillage"); - addobj.setTownVillage(townVillage); - } + is_address_update = true; + final String townVillage = command.stringValueOfParameterNamed("townVillage"); + addobj.setTownVillage(townVillage); + } - if (!(command.stringValueOfParameterNamed("city").isEmpty())) { - is_address_update = true; - final String city = command.stringValueOfParameterNamed("city"); - addobj.setCity(city); - } + if (!(command.stringValueOfParameterNamed("city").isEmpty())) { + is_address_update = true; + final String city = command.stringValueOfParameterNamed("city"); + addobj.setCity(city); + } - if (!(command.stringValueOfParameterNamed("countyDistrict").isEmpty())) { - is_address_update = true; - final String countyDistrict = command.stringValueOfParameterNamed("countyDistrict"); - addobj.setCountyDistrict(countyDistrict); - } + if (!(command.stringValueOfParameterNamed("countyDistrict").isEmpty())) { + is_address_update = true; + final String countyDistrict = command.stringValueOfParameterNamed("countyDistrict"); + addobj.setCountyDistrict(countyDistrict); + } - if ((command.longValueOfParameterNamed("stateProvinceId") != null)) { - if ((command.longValueOfParameterNamed("stateProvinceId") != 0)) { - is_address_update = true; - stateId = command.longValueOfParameterNamed("stateProvinceId"); - stateIdobj = this.codeValueRepository.getOne(stateId); - addobj.setStateProvince(stateIdobj); - } + if ((command.longValueOfParameterNamed("stateProvinceId") != null)) { + if ((command.longValueOfParameterNamed("stateProvinceId") != 0)) { + is_address_update = true; + stateId = command.longValueOfParameterNamed("stateProvinceId"); + stateIdobj = this.codeValueRepository.getOne(stateId); + addobj.setStateProvince(stateIdobj); + } - } - if ((command.longValueOfParameterNamed("countryId") != null)) { - if ((command.longValueOfParameterNamed("countryId") != 0)) { - is_address_update = true; - countryId = command.longValueOfParameterNamed("countryId"); - countryIdObj = this.codeValueRepository.getOne(countryId); - addobj.setCountry(countryIdObj); - } + } + if ((command.longValueOfParameterNamed("countryId") != null)) { + if ((command.longValueOfParameterNamed("countryId") != 0)) { + is_address_update = true; + countryId = command.longValueOfParameterNamed("countryId"); + countryIdObj = this.codeValueRepository.getOne(countryId); + addobj.setCountry(countryIdObj); + } - } + } - if (!(command.stringValueOfParameterNamed("postalCode").isEmpty())) { - is_address_update = true; - final String postalCode = command.stringValueOfParameterNamed("postalCode"); - addobj.setPostalCode(postalCode); - } + if (!(command.stringValueOfParameterNamed("postalCode").isEmpty())) { + is_address_update = true; + final String postalCode = command.stringValueOfParameterNamed("postalCode"); + addobj.setPostalCode(postalCode); + } - if (command.bigDecimalValueOfParameterNamed("latitude") != null) { + if (command.bigDecimalValueOfParameterNamed("latitude") != null) { - is_address_update = true; - final BigDecimal latitude = command.bigDecimalValueOfParameterNamed("latitude"); + is_address_update = true; + final BigDecimal latitude = command.bigDecimalValueOfParameterNamed("latitude"); - addobj.setLatitude(latitude); - } - if (command.bigDecimalValueOfParameterNamed("longitude") != null) { - is_address_update = true; - final BigDecimal longitude = command.bigDecimalValueOfParameterNamed("longitude"); - addobj.setLongitude(longitude); + addobj.setLatitude(latitude); + } + if (command.bigDecimalValueOfParameterNamed("longitude") != null) { + is_address_update = true; + final BigDecimal longitude = command.bigDecimalValueOfParameterNamed("longitude"); + addobj.setLongitude(longitude); - } + } - if (is_address_update) { + if (is_address_update) { - this.addressRepository.save(addobj); + this.addressRepository.save(addobj); - } + } - final Boolean testActive = command.booleanPrimitiveValueOfParameterNamed("isActive"); - if (testActive != null) { + final Boolean testActive = command.booleanPrimitiveValueOfParameterNamed("isActive"); + if (testActive != null) { - final boolean active = command.booleanPrimitiveValueOfParameterNamed("isActive"); - clientAddressObj.setIs_active(active); + final boolean active = command.booleanPrimitiveValueOfParameterNamed("isActive"); + 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 c3403f455..348c096cb 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 @@ -24,7 +24,7 @@ import java.util.List; import org.apache.fineract.portfolio.address.data.FieldConfigurationData; public interface FieldConfigurationReadPlatformService { - public Collection retrieveFieldConfiguration(String entity); + public Collection retrieveFieldConfiguration(String entity); - List retrieveFieldConfigurationList(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 946a96f09..75fff0e11 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 @@ -33,57 +33,57 @@ import org.springframework.stereotype.Service; @Service public class FieldConfigurationReadPlatformServiceImpl implements FieldConfigurationReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public FieldConfigurationReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + 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"; - } + 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 { - final long fieldConfigurationId = rs.getLong("fieldConfigurationId"); - final String entity = rs.getString("entity"); - final String subentity = rs.getString("subentity"); - final String field = rs.getString("field"); - final boolean is_enabled = rs.getBoolean("is_enabled"); - final boolean is_mandatory = rs.getBoolean("is_mandatory"); - final String validation_regex = rs.getString("validation_regex"); + @Override + 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"); + final String field = rs.getString("field"); + final boolean is_enabled = rs.getBoolean("is_enabled"); + 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); - } - } + } + } - @Override - public Collection retrieveFieldConfiguration(final String entity) { - this.context.authenticatedUser(); + @Override + public Collection retrieveFieldConfiguration(final String entity) { + this.context.authenticatedUser(); - final FieldMapper rm = new FieldMapper(); - final String sql = "select " + rm.schema() + " where fld.entity=?"; + final FieldMapper rm = new FieldMapper(); + final String sql = "select " + rm.schema() + " where fld.entity=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { entity }); - } + return this.jdbcTemplate.query(sql, rm, new Object[] { entity }); + } - @Override - public List retrieveFieldConfigurationList(final String entity) { - this.context.authenticatedUser(); + @Override + public List retrieveFieldConfigurationList(final String entity) { + this.context.authenticatedUser(); - final FieldMapper rm = new FieldMapper(); - final String sql = "select " + rm.schema() + " where fld.entity=?"; + final FieldMapper rm = new FieldMapper(); + final String sql = "select " + rm.schema() + " where fld.entity=?"; - return this.jdbcTemplate.query(sql, new Object[] { entity }, rm); + return this.jdbcTemplate.query(sql, new Object[] { entity }, rm); - } + } } 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 e7f778d52..2594ee336 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 @@ -486,12 +486,12 @@ public class CalendarData implements Serializable { public EnumOptionData frequencyType(){ return this.frequency; } - public EnumOptionData getRepeatsOnDay() { - return this.repeatsOnDay; - } - public EnumOptionData getRepeatsOnNthDayOfMonth() { - return this.repeatsOnNthDayOfMonth; - } + public EnumOptionData getRepeatsOnDay() { + return this.repeatsOnDay; + } + public EnumOptionData getRepeatsOnNthDayOfMonth() { + return this.repeatsOnNthDayOfMonth; + } @Override public boolean equals(Object o) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarHistory.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarHistory.java index e9d2cf472..38e1be04b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarHistory.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarHistory.java @@ -143,8 +143,8 @@ public class CalendarHistory extends AbstractPersistableCustom { this.endDate = historyCalEndDate; } - public Calendar getCalendar() { - return this.calendar; - } + public Calendar getCalendar() { + return this.calendar; + } } 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 15c74ecb7..f3537ca2c 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 @@ -138,9 +138,9 @@ public class CalendarEnumerations { } public static List calendarFrequencyNthDayType() { final List optionDatas = Arrays.asList(calendarFrequencyNthDayType(NthDayType.ONE), - calendarFrequencyNthDayType(NthDayType.TWO), calendarFrequencyNthDayType(NthDayType.THREE), - calendarFrequencyNthDayType(NthDayType.FOUR), calendarFrequencyNthDayType(NthDayType.LAST), - calendarFrequencyNthDayType(NthDayType.ONDAY)); + calendarFrequencyNthDayType(NthDayType.TWO), calendarFrequencyNthDayType(NthDayType.THREE), + calendarFrequencyNthDayType(NthDayType.FOUR), calendarFrequencyNthDayType(NthDayType.LAST), + calendarFrequencyNthDayType(NthDayType.ONDAY)); return optionDatas; } } 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 c9e706875..4a404486d 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 @@ -244,33 +244,33 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ */ final LocalDate periodEndDate = this.getPeriodEndDate(calendarData.getEndDate(), tillDate); - Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService - .isSkippingMeetingOnFirstDayOfMonthEnabled(); - if (isSkipRepaymentOnFirstMonthEnabled) { - numberOfDays = this.configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); - } + Integer numberOfDays = 0; + boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService + .isSkippingMeetingOnFirstDayOfMonthEnabled(); + if (isSkipRepaymentOnFirstMonthEnabled) { + numberOfDays = this.configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); + } - final Collection recurringDates = CalendarUtils.getRecurringDates(rrule, seedDate, periodStartDate, - periodEndDate, maxCount, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); - return recurringDates; - } + final Collection recurringDates = CalendarUtils.getRecurringDates(rrule, seedDate, periodStartDate, + periodEndDate, maxCount, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); + return recurringDates; + } - @Override - public Boolean isCalendarAssociatedWithEntity(final Long entityId, final Long calendarId, final Long entityTypeId) { - 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; - } - return false; - } catch (final EmptyResultDataAccessException e) { - return false; - } - } + @Override + public Boolean isCalendarAssociatedWithEntity(final Long entityId, final Long calendarId, final Long entityTypeId) { + 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; + } + return false; + } catch (final EmptyResultDataAccessException e) { + return false; + } + } private LocalDate getSeedDate(LocalDate date) { return date; @@ -332,35 +332,35 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ */ - Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService - .isSkippingMeetingOnFirstDayOfMonthEnabled(); - if (isSkipRepaymentOnFirstMonthEnabled) { - numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); - } + Integer numberOfDays = 0; + boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService + .isSkippingMeetingOnFirstDayOfMonthEnabled(); + if (isSkipRepaymentOnFirstMonthEnabled) { + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); + } - if (lastMeetingDate != null && !calendarData.isBetweenStartAndEndDate(lastMeetingDate) - && !calendarData.isBetweenStartAndEndDate(DateUtils.getLocalDateOfTenant())) { - applicableCalendarData = this.retrieveApplicableCalendarFromHistory(calendarData.getId(), lastMeetingDate); - nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), - lastMeetingDate, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); - } + if (lastMeetingDate != null && !calendarData.isBetweenStartAndEndDate(lastMeetingDate) + && !calendarData.isBetweenStartAndEndDate(DateUtils.getLocalDateOfTenant())) { + applicableCalendarData = this.retrieveApplicableCalendarFromHistory(calendarData.getId(), lastMeetingDate); + nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), + lastMeetingDate, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); + } - /** - * If nextEligibleMeetingDate is on or after current calendar startdate - * then regenerate the nextEligible meeting date based on - */ - if (nextEligibleMeetingDate == null) { - final LocalDate seedDate = (lastMeetingDate != null) ? lastMeetingDate : calendarData.getStartDate(); - nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), - seedDate, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); - } else if (calendarData.isBetweenStartAndEndDate(nextEligibleMeetingDate)) { - nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), - calendarData.getStartDate(), isSkipRepaymentOnFirstMonthEnabled, numberOfDays); - } + /** + * If nextEligibleMeetingDate is on or after current calendar startdate + * then regenerate the nextEligible meeting date based on + */ + if (nextEligibleMeetingDate == null) { + final LocalDate seedDate = (lastMeetingDate != null) ? lastMeetingDate : calendarData.getStartDate(); + nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), + seedDate, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); + } else if (calendarData.isBetweenStartAndEndDate(nextEligibleMeetingDate)) { + nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), + calendarData.getStartDate(), isSkipRepaymentOnFirstMonthEnabled, numberOfDays); + } - return nextEligibleMeetingDate; - } + return nextEligibleMeetingDate; + } @Override public Collection updateWithRecurringDates(final Collection calendarsData) { 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 c7f10cb73..d29217b6f 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 @@ -469,9 +469,9 @@ public class CalendarUtils { final Recur recur = CalendarUtils.getICalRecur(recurringRule); NumberList monthDays = null; if(recur.getDayList().isEmpty()) - monthDays = recur.getMonthDayList(); + monthDays = recur.getMonthDayList(); else - monthDays = recur.getSetPosList(); + monthDays = recur.getSetPosList(); if (monthDays.isEmpty()) return NthDayType.INVALID; if (!recur.getMonthDayList().isEmpty() && recur.getSetPosList().isEmpty()) return NthDayType.ONDAY; Integer monthDay = (Integer) monthDays.get(0); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarWritePlatformServiceJpaRepositoryImpl.java index f0b203736..7a309ff41 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarWritePlatformServiceJpaRepositoryImpl.java @@ -167,50 +167,50 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr } - public void validateIsEditMeetingAllowed(Long groupId) { + public void validateIsEditMeetingAllowed(Long groupId) { - final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource("calendar"); - Group centerOrGroup = null; + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( + dataValidationErrors).resource("calendar"); + Group centerOrGroup = null; - if (groupId != null) { - 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(); - /* Check if calendar is created at center */ - final CalendarInstance collectionCalendarInstance = this.calendarInstanceRepository - .findByEntityIdAndEntityTypeIdAndCalendarTypeId( - parent.getId(), centerEntityTypeId, - CalendarType.COLLECTION.getValue()); - /* 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); - } - } + if (groupId != null) { + 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(); + /* Check if calendar is created at center */ + final CalendarInstance collectionCalendarInstance = this.calendarInstanceRepository + .findByEntityIdAndEntityTypeIdAndCalendarTypeId( + parent.getId(), centerEntityTypeId, + CalendarType.COLLECTION.getValue()); + /* 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); + } + } - } - 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); + } - } + } @Override public CommandProcessingResult updateCalendar(final JsonCommand command) { - /** Validate to check if Edit is Allowed **/ - this.validateIsEditMeetingAllowed(command.getGroupId()); + /** Validate to check if Edit is Allowed **/ + this.validateIsEditMeetingAllowed(command.getGroupId()); /* * Validate all the data for updating the calendar */ 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 index 1a79c668e..295035034 100755 --- 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 @@ -603,15 +603,15 @@ public class Charge extends AbstractPersistableCustom { 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) && + 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 && @@ -625,6 +625,6 @@ public class Charge extends AbstractPersistableCustom { @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); + 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 bc4cef038..6130ca6a4 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 @@ -57,8 +57,8 @@ public enum ChargeAppliesTo { chargeAppliesToType = CLIENT; break; case 4: - chargeAppliesToType = SHARES ; - break ; + chargeAppliesToType = SHARES ; + break ; default: chargeAppliesToType = INVALID; break; @@ -81,7 +81,7 @@ 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() }; 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 c3379e342..9bfcab166 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 @@ -66,7 +66,7 @@ public enum ChargeCalculationType { } public static Object[] validValuesForTrancheDisbursement(){ - return new Integer[] { ChargeCalculationType.FLAT.getValue(), ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue()}; + return new Integer[] { ChargeCalculationType.FLAT.getValue(), ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue()}; } public static ChargeCalculationType fromInt(final Integer chargeCalculation) { @@ -85,7 +85,7 @@ public enum ChargeCalculationType { chargeCalculationType = PERCENT_OF_INTEREST; break; case 5: - chargeCalculationType = PERCENT_OF_DISBURSEMENT_AMOUNT; + chargeCalculationType = PERCENT_OF_DISBURSEMENT_AMOUNT; break; } return chargeCalculationType; @@ -120,6 +120,6 @@ public enum ChargeCalculationType { } public boolean isPercentageOfDisbursementAmount(){ - return this.value.equals(ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue()); + 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/ChargeTimeType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeTimeType.java index b7d695acd..f2ce168fd 100755 --- 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 @@ -131,7 +131,7 @@ public enum ChargeTimeType { chargeTimeType = SHARE_REDEEM; break; case 16: - chargeTimeType = SAVINGS_NOACTIVITY_FEE; + chargeTimeType = SAVINGS_NOACTIVITY_FEE; break; default: chargeTimeType = INVALID; @@ -162,7 +162,7 @@ public enum ChargeTimeType { } public boolean isSavingsNoActivityFee() { - return this.value.equals(ChargeTimeType.SAVINGS_NOACTIVITY_FEE.getValue()); + return this.value.equals(ChargeTimeType.SAVINGS_NOACTIVITY_FEE.getValue()); } public boolean isAnnualFee() { 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 index 50a83abf6..6aae77669 100755 --- 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 @@ -117,13 +117,13 @@ public class ChargeDropdownReadPlatformServiceImpl implements ChargeDropdownRead @Override public List retrieveSharesCalculationTypes() { - return Arrays.asList(chargeCalculationType(ChargeCalculationType.FLAT), + return Arrays.asList(chargeCalculationType(ChargeCalculationType.FLAT), chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT)); } @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 index 28e48bd30..c87b47a48 100755 --- 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 @@ -86,14 +86,14 @@ public class ChargeEnumerations { break ; case SHARE_PURCHASE: - optionData = new EnumOptionData(ChargeTimeType.SHARE_PURCHASE.getValue().longValue(), ChargeTimeType.SHARE_PURCHASE.getCode(), "Share Purchase") ; + 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") ; + 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,7 +120,7 @@ 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") ; + optionData = new EnumOptionData(ChargeAppliesTo.SHARES.getValue().longValue(), ChargeAppliesTo.SHARES.getCode(), "Shares") ; break ; default: optionData = new EnumOptionData(ChargeAppliesTo.INVALID.getValue().longValue(), ChargeAppliesTo.INVALID.getCode(), @@ -154,8 +154,8 @@ public class ChargeEnumerations { ChargeCalculationType.PERCENT_OF_INTEREST.getCode(), "% Interest"); break; case PERCENT_OF_DISBURSEMENT_AMOUNT: - optionData = new EnumOptionData(ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue().longValue(), - ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getCode(), "% Disbursement Amount"); + optionData = new EnumOptionData(ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue().longValue(), + ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getCode(), "% Disbursement Amount"); break; default: optionData = new EnumOptionData(ChargeCalculationType.INVALID.getValue().longValue(), 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 fb069a560..5976c5401 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 @@ -124,7 +124,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP }catch(final PersistenceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -192,9 +192,9 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } 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 51a46dab3..56c684426 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 @@ -47,110 +47,110 @@ import java.util.Set; @Scope("singleton") @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 String resourceNameForPermissions = "Address"; - private final PlatformSecurityContext context; - private final AddressReadPlatformServiceImpl readPlatformService; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final ApiRequestParameterHelper apiRequestParameterHelper; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + 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; + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final ApiRequestParameterHelper apiRequestParameterHelper; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - @Autowired - public ClientAddressApiResources(final PlatformSecurityContext context, - final AddressReadPlatformServiceImpl readPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { - this.context = context; - this.readPlatformService = readPlatformService; - this.toApiJsonSerializer = toApiJsonSerializer; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - } + @Autowired + public ClientAddressApiResources(final PlatformSecurityContext context, + final AddressReadPlatformServiceImpl readPlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final ApiRequestParameterHelper apiRequestParameterHelper, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + this.context = context; + this.readPlatformService = readPlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + } - @GET - @Path("addresses/template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String getAddressesTemplate(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + @GET + @Path("addresses/template") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String getAddressesTemplate(@Context final UriInfo uriInfo) { + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final AddressData template = this.readPlatformService.retrieveTemplate(); + final AddressData template = this.readPlatformService.retrieveTemplate(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, template, this.RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper + .process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, template, this.RESPONSE_DATA_PARAMETERS); - } + } - @POST - @Path("/{clientid}/addresses") - @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)}) - 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) { + @POST + @Path("/{clientid}/addresses") + @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)}) + 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) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().addClientAddress(clientid, addressTypeId) - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().addClientAddress(clientid, addressTypeId) + .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 - @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) { - Collection address; + @GET + @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) { + Collection address; - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - if (addressTypeId == 0 && status == null) { - address = this.readPlatformService.retrieveAllClientAddress(clientid); - } else if (addressTypeId != 0 && status == null) { - address = this.readPlatformService.retrieveAddressbyType(clientid, addressTypeId); - } else if (addressTypeId != 0 && status != null) { - address = this.readPlatformService.retrieveAddressbyTypeAndStatus(clientid, addressTypeId, status); - } else { - address = this.readPlatformService.retrieveAddressbyStatus(clientid, status); - } + if (addressTypeId == 0 && status == null) { + address = this.readPlatformService.retrieveAllClientAddress(clientid); + } else if (addressTypeId != 0 && status == null) { + address = this.readPlatformService.retrieveAddressbyType(clientid, addressTypeId); + } else if (addressTypeId != 0 && status != null) { + address = this.readPlatformService.retrieveAddressbyTypeAndStatus(clientid, addressTypeId, status); + } else { + address = this.readPlatformService.retrieveAddressbyStatus(clientid, status); + } - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, address, this.RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper + .process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, address, this.RESPONSE_DATA_PARAMETERS); - } + } - @PUT - @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) { + @PUT + @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) { - 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); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } + return this.toApiJsonSerializer.serialize(result); + } } 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 64edab861..c7d2c414a 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 @@ -84,7 +84,7 @@ public class ClientApiConstants { public static final String accountNoParamName = "accountNo"; public static final String externalIdParamName = "externalId"; public static final String mobileNoParamName = "mobileNo"; - public static final String emailAddressParamName = "emailAddress"; + public static final String emailAddressParamName = "emailAddress"; public static final String firstnameParamName = "firstname"; public static final String middlenameParamName = "middlename"; public static final String lastnameParamName = "lastname"; @@ -96,7 +96,7 @@ public class ClientApiConstants { public static final String activationDateParamName = "activationDate"; public static final String reactivationDateParamName = "reactivationDate"; public static final String staffIdParamName = "staffId"; - public static final String isStaffParamName = "isStaff"; + public static final String isStaffParamName = "isStaff"; public static final String closureDateParamName = "closureDate"; public static final String closureReasonIdParamName = "closureReasonId"; public static final String reopenedDateParamName = "reopenedDate"; 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 92aff7134..9c1543281 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 @@ -55,118 +55,118 @@ import org.springframework.stereotype.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")); - private final String resourceNameForPermissions = "FamilyMembers"; - private final PlatformSecurityContext context; - private final ClientFamilyMembersReadPlatformService readPlatformService; - private final ToApiJsonSerializer toApiJsonSerializer; - private final ApiRequestParameterHelper apiRequestParameterHelper; - 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; - - } - - @GET - @Path("/{familyMemberId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - 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 ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, familyMembers, this.RESPONSE_DATA_PARAMETERS); + 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; + private final ToApiJsonSerializer toApiJsonSerializer; + private final ApiRequestParameterHelper apiRequestParameterHelper; + 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; + + } + + @GET + @Path("/{familyMemberId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + 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 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) { - - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - - final Collection familyMembers = this.readPlatformService.getClientFamilyMembers(clientId); - - 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) { + + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + + final Collection familyMembers = this.readPlatformService.getClientFamilyMembers(clientId); + + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, familyMembers, this.RESPONSE_DATA_PARAMETERS); - } - - @GET - @Path("/template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String getTemplate(@Context final UriInfo uriInfo,@PathParam("clientId") final long clientId) { - - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + } + + @GET + @Path("/template") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String getTemplate(@Context final UriInfo uriInfo,@PathParam("clientId") final long clientId) { + + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ClientFamilyMembersData options = this.readPlatformService.retrieveTemplate(); + final ClientFamilyMembersData options = this.readPlatformService.retrieveTemplate(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, options, this.RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, options, this.RESPONSE_DATA_PARAMETERS); - } - - - @PUT - @Path("/{familyMemberId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String updateClientFamilyMembers(@PathParam("familyMemberId") final long familyMemberId, final String apiRequestBodyAsJson) { + } + + + @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); + 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) { + 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); + 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) { + 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); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } - - - + return this.toApiJsonSerializer.serialize(result); + } + + + } 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 65d09dbe5..984ec90f5 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 @@ -102,11 +102,11 @@ public class ClientsApiResource { final AccountDetailsReadPlatformService accountDetailsReadPlatformService, final SavingsAccountReadPlatformService savingsAccountReadPlatformService, final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService, - final BulkImportWorkbookService bulkImportWorkbookService, - final GuarantorReadPlatformService guarantorReadPlatformService) { - this.context = context; - this.clientReadPlatformService = readPlatformService; - this.toApiJsonSerializer = toApiJsonSerializer; + final BulkImportWorkbookService bulkImportWorkbookService, + final GuarantorReadPlatformService guarantorReadPlatformService) { + this.context = context; + this.clientReadPlatformService = readPlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; this.clientAccountSummaryToApiJsonSerializer = clientAccountSummaryToApiJsonSerializer; this.apiRequestParameterHelper = apiRequestParameterHelper; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; @@ -160,7 +160,7 @@ public class ClientsApiResource { @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); + lastname, hierarchy, offset, limit, orderBy, sortOrder, orphansOnly, false); } public String retrieveAll(final UriInfo uriInfo, final String sqlSearch, @@ -317,16 +317,16 @@ public class ClientsApiResource { } else if (is(commandParam, "withdraw")) { commandRequest = builder.withdrawClient(clientId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "reactivate")) { - commandRequest = builder.reActivateClient(clientId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "undoRejection")) { - commandRequest = builder.undoRejection(clientId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, "undoWithdrawal")) { - commandRequest = builder.undoWithdrawal(clientId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } + } else if (is(commandParam, "reactivate")) { + commandRequest = builder.reActivateClient(clientId).build(); + result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + } else if (is(commandParam, "undoRejection")) { + commandRequest = builder.undoRejection(clientId).build(); + result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + } else if (is(commandParam, "undoWithdrawal")) { + commandRequest = builder.undoWithdrawal(clientId).build(); + result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + } if (result == null) { throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "activate", "unassignStaff", "assignStaff", "close", "proposeTransfer", "withdrawTransfer", "acceptTransfer", "rejectTransfer", @@ -379,27 +379,27 @@ public class ClientsApiResource { return this.toApiJsonSerializer.serialize(importDocumentId); } - @GET - @Path("{clientId}/obligeedetails") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveObligeeDetails(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { + @GET + @Path("{clientId}/obligeedetails") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveObligeeDetails(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); - final List ObligeeList = this.guarantorReadPlatformService.retrieveObligeeDetails(clientId); + final List ObligeeList = this.guarantorReadPlatformService.retrieveObligeeDetails(clientId); - return this.toApiJsonSerializer.serialize(ObligeeList); - } + return this.toApiJsonSerializer.serialize(ObligeeList); + } - @GET - @Path("{clientId}/transferproposaldate") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveTransferTemplate(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { + @GET + @Path("{clientId}/transferproposaldate") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveTransferTemplate(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); - final Date transferDate = this.clientReadPlatformService.retrieveClientTransferProposalDate(clientId); - return this.toApiJsonSerializer.serialize((transferDate != null ? new LocalDate(transferDate) : null)); - } + this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); + 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/command/ClientIdentifierCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/command/ClientIdentifierCommand.java index 19f831b49..dde46f34c 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,7 @@ public class ClientIdentifierCommand { private final Long documentTypeId; private final String documentKey; private final String description; - private final String status; + private final String status; public ClientIdentifierCommand(final Long documentTypeId, final String documentKey, final String statusString, final String description) { this.documentTypeId = documentTypeId; 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 7acedf348..527563d6a 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 @@ -59,7 +59,7 @@ final public class ClientData implements Comparable, Serializable { private final String fullname; private final String displayName; private final String mobileNo; - private final String emailAddress; + private final String emailAddress; private final LocalDate dateOfBirth; private final CodeValueData gender; private final CodeValueData clientType; @@ -104,10 +104,10 @@ final public class ClientData implements Comparable, Serializable { private final Collection address; - private final Boolean isAddressEnabled; + private final Boolean isAddressEnabled; - private final List datatables; + private final List datatables; //import fields private transient Integer rowIndex; @@ -124,8 +124,8 @@ final public class ClientData implements Comparable, Serializable { 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); + 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, @@ -138,7 +138,7 @@ final public class ClientData implements Comparable, Serializable { } 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, @@ -241,7 +241,7 @@ final public class ClientData implements Comparable, Serializable { final String displayName = null; final String externalId = null; final String mobileNo = null; - final String emailAddress = null; + final String emailAddress = null; final LocalDate dateOfBirth = null; final CodeValueData gender = null; final Long imageId = null; @@ -256,7 +256,7 @@ final public class ClientData implements Comparable, Serializable { final CodeValueData clientType = null; final CodeValueData clientClassification = null; final EnumOptionData legalForm = null; - final Boolean isStaff = false; + 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, @@ -308,7 +308,7 @@ final public class ClientData implements Comparable, Serializable { 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.isAddressEnabled, null, clientData.isStaff); } @@ -319,7 +319,7 @@ final public class ClientData implements Comparable, Serializable { final String transferToOfficeName = null; final String externalId = null; final String mobileNo = null; - final String emailAddress = null; + final String emailAddress = null; final LocalDate dateOfBirth = null; final CodeValueData gender = null; final LocalDate activationDate = null; @@ -348,7 +348,7 @@ final public class ClientData implements Comparable, Serializable { final EnumOptionData status = null; final CodeValueData subStatus = null; final EnumOptionData legalForm = null; - final Boolean isStaff = false; + 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, @@ -370,7 +370,7 @@ final public class ClientData implements Comparable, Serializable { final String fullname = null; final String externalId = null; final String mobileNo = null; - final String emailAddress = null; + final String emailAddress = null; final LocalDate dateOfBirth = null; final CodeValueData gender = null; final LocalDate activationDate = null; @@ -397,7 +397,7 @@ final public class ClientData implements Comparable, Serializable { final List clientLegalFormOptions = null; final ClientFamilyMembersData familyMemberOptions=null; final EnumOptionData legalForm = null; - final Boolean isStaff = false; + 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, @@ -409,9 +409,9 @@ final public class ClientData implements Comparable, Serializable { } public static ClientData instance(final Long id, final String displayName){ - final Long officeId = null; - final String officeName = null; - return lookup(id, displayName, officeId, officeName); + 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, @@ -478,7 +478,7 @@ final public class ClientData implements Comparable, Serializable { this.displayName = StringUtils.defaultIfEmpty(displayName, null); this.externalId = StringUtils.defaultIfEmpty(externalId, null); this.mobileNo = StringUtils.defaultIfEmpty(mobileNo, null); - this.emailAddress = StringUtils.defaultIfEmpty(emailAddress, null); + this.emailAddress = StringUtils.defaultIfEmpty(emailAddress, null); this.activationDate = activationDate; this.dateOfBirth = dateOfBirth; this.gender = gender; @@ -517,11 +517,11 @@ final public class ClientData implements Comparable, Serializable { this.savingsAccountId = savingsAccountId; this.savingAccountOptions = savingAccountOptions; this.legalForm = legalForm; - this.isStaff = isStaff; + this.isStaff = isStaff; this.clientNonPersonDetails = clientNonPerson; - this.address = address; - this.isAddressEnabled = isAddressEnabled; + this.address = address; + this.isAddressEnabled = isAddressEnabled; this.datatables = datatables; } @@ -535,7 +535,7 @@ final public class ClientData implements Comparable, Serializable { } public String accountNo() { - return this.accountNo; + return this.accountNo; } public Long officeId() { @@ -565,7 +565,7 @@ final public class ClientData implements Comparable, Serializable { .append(this.id, obj.id) // .append(this.displayName, obj.displayName) // .append(this.mobileNo, obj.mobileNo) // - .append(this.emailAddress, obj.emailAddress) // + .append(this.emailAddress, obj.emailAddress) // .toComparison(); } @@ -579,7 +579,7 @@ final public class ClientData implements Comparable, Serializable { .append(this.id, rhs.id) // .append(this.displayName, rhs.displayName) // .append(this.mobileNo, rhs.mobileNo) // - .append(this.emailAddress, rhs.emailAddress) // + .append(this.emailAddress, rhs.emailAddress) // .isEquals(); } @@ -608,6 +608,6 @@ final public class ClientData implements Comparable, Serializable { } public Boolean getIsAddressEnabled() { - return this.isAddressEnabled; - } + return this.isAddressEnabled; + } } \ No newline at end of file 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 ffa1dadb9..78fc4b137 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 @@ -54,11 +54,11 @@ public final class ClientDataValidator { private final ConfigurationReadPlatformService configurationReadPlatformService; @Autowired - public ClientDataValidator(final FromJsonHelper fromApiJsonHelper, - final ConfigurationReadPlatformService configurationReadPlatformService) { + public ClientDataValidator(final FromJsonHelper fromApiJsonHelper, + final ConfigurationReadPlatformService configurationReadPlatformService) { this.fromApiJsonHelper = fromApiJsonHelper; - this.configurationReadPlatformService = configurationReadPlatformService; - } + this.configurationReadPlatformService = configurationReadPlatformService; + } public void validateForCreate(final String json) { @@ -69,9 +69,9 @@ public final class ClientDataValidator { 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) - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, clientNonPersonJson, ClientApiCollectionConstants.CLIENT_NON_PERSON_CREATE_REQUEST_DATA_PARAMETERS); + 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); } final List dataValidationErrors = new ArrayList<>(); @@ -208,7 +208,7 @@ public final class ClientDataValidator { } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.legalFormIdParamName, element)) { - final Integer legalFormId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.legalFormIdParamName, element); + final Integer legalFormId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.legalFormIdParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.legalFormIdParamName).value(legalFormId).ignoreIfNull().inMinMaxRange(1, 2); } @@ -217,18 +217,18 @@ public final class ClientDataValidator { baseDataValidator.reset().parameter(ClientApiConstants.datatables).value(datatables).notNull().jsonArrayNotEmpty(); } - if (this.fromApiJsonHelper.parameterExists("isStaff", element)) { + if (this.fromApiJsonHelper.parameterExists("isStaff", element)) { final Boolean isStaffFlag = this.fromApiJsonHelper.extractBooleanNamed("isStaff", element); baseDataValidator.reset().parameter("isStaff").value(isStaffFlag).notNull(); } - - - 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(); - } - + + + 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)); dataValidationErrors.addAll(dataValidationErrorsForClientNonPerson); @@ -237,8 +237,8 @@ public final class ClientDataValidator { List getDataValidationErrorsForCreateOnClientNonPerson(JsonElement element) { - - final List dataValidationErrors = new ArrayList<>(); + + final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(ClientApiCollectionConstants.CLIENT_RESOURCE_NAME); @@ -246,7 +246,7 @@ public final class ClientDataValidator { if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.incorpNumberParamName, element)) { final String incorpNumber = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.incorpNumberParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.incorpNumberParamName).value(incorpNumber).ignoreIfNull() - .notExceedingLengthOf(50); + .notExceedingLengthOf(50); } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.remarksParamName, element)) { @@ -272,7 +272,7 @@ public final class ClientDataValidator { baseDataValidator.reset().parameter(ClientApiConstants.mainBusinessLineIdParamName).value(mainBusinessLine).integerGreaterThanZero(); } - return dataValidationErrors; + return dataValidationErrors; } private void validateIndividualNamePartsCannotBeUsedWithFullname(final JsonElement element, final DataValidatorBuilder baseDataValidator) { @@ -349,11 +349,11 @@ public final class ClientDataValidator { 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) - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, clientNonPersonJson, ClientApiCollectionConstants.CLIENT_NON_PERSON_UPDATE_REQUEST_DATA_PARAMETERS); + 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); } - + final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -491,12 +491,12 @@ public final class ClientDataValidator { } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.legalFormIdParamName, element)) { - atLeastOneParameterPassedForUpdate = true; - final Integer legalFormId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(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); } - if (this.fromApiJsonHelper.parameterExists("isStaff", element)) { + if (this.fromApiJsonHelper.parameterExists("isStaff", element)) { final Boolean isStaffFlag = this.fromApiJsonHelper.extractBooleanNamed("isStaff", element); baseDataValidator.reset().parameter("isStaff").value(isStaffFlag).notNull(); } @@ -510,7 +510,7 @@ public final class ClientDataValidator { } @SuppressWarnings("unchecked") - List dataValidationErrorsForClientNonPerson = (List) parameterUpdateStatusDetails.get("dataValidationErrors"); + List dataValidationErrorsForClientNonPerson = (List) parameterUpdateStatusDetails.get("dataValidationErrors"); dataValidationErrors.addAll(dataValidationErrorsForClientNonPerson); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -518,48 +518,48 @@ public final class ClientDataValidator { Map getParameterUpdateStatusAndDataValidationErrorsForUpdateOnClientNonPerson(JsonElement element) { - boolean atLeastOneParameterPassedForUpdate = false; - final List dataValidationErrors = new ArrayList<>(); + boolean atLeastOneParameterPassedForUpdate = false; + final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(ClientApiCollectionConstants.CLIENT_RESOURCE_NAME); - - if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.incorpNumberParamName, element)) { + + 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); } - - if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.remarksParamName, element)) { + + if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.remarksParamName, element)) { atLeastOneParameterPassedForUpdate = true; final String remarks = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.remarksParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.remarksParamName).value(remarks).notExceedingLengthOf(150); } - - if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.incorpValidityTillParamName, element)) { + + if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.incorpValidityTillParamName, element)) { atLeastOneParameterPassedForUpdate = true; final LocalDate incorpValidityTill = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.incorpValidityTillParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.incorpValidityTillParamName).value(incorpValidityTill); } - - if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.constitutionIdParamName, element)) { + + 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(); } - - if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.mainBusinessLineIdParamName, element)) { + + 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(); } - - Map parameterUpdateStatusDetails = new HashMap<>(); - parameterUpdateStatusDetails.put("parameterUpdateStatus", atLeastOneParameterPassedForUpdate); - parameterUpdateStatusDetails.put("dataValidationErrors", dataValidationErrors); - - return parameterUpdateStatusDetails; - + + Map parameterUpdateStatusDetails = new HashMap<>(); + parameterUpdateStatusDetails.put("parameterUpdateStatus", atLeastOneParameterPassedForUpdate); + parameterUpdateStatusDetails.put("dataValidationErrors", dataValidationErrors); + + return parameterUpdateStatusDetails; + } public void validateActivation(final JsonCommand command) { @@ -779,8 +779,8 @@ public final class ClientDataValidator { final LocalDate undoRejectionDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.reopenedDateParamName, element); - baseDataValidator.reset().parameter(ClientApiConstants.reopenedDateParamName).value(undoRejectionDate).notNull() - .validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()); + baseDataValidator.reset().parameter(ClientApiConstants.reopenedDateParamName).value(undoRejectionDate).notNull() + .validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -802,8 +802,8 @@ public final class ClientDataValidator { final LocalDate undoWithdrawnDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.reopenedDateParamName, element); - baseDataValidator.reset().parameter(ClientApiConstants.reopenedDateParamName).value(undoWithdrawnDate).notNull() - .validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()); + baseDataValidator.reset().parameter(ClientApiConstants.reopenedDateParamName).value(undoWithdrawnDate).notNull() + .validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()); throwExceptionIfValidationWarningsExist(dataValidationErrors); 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 a5e127f5a..8b2ad7f5e 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 @@ -27,172 +27,172 @@ import java.util.Collection; public class ClientFamilyMembersData implements Serializable { - private final Long id; + private final Long id; - private final Long clientId; + private final Long clientId; - private final String firstName; + private final String firstName; - private final String middleName; + private final String middleName; - private final String lastName; + private final String lastName; - private final String qualification; + private final String qualification; - private final Long relationshipId; + private final Long relationshipId; - private final String relationship; + private final String relationship; - private final Long maritalStatusId; + private final Long maritalStatusId; - private final String maritalStatus; + private final String maritalStatus; - private final Long genderId; + private final Long genderId; - private final String gender; + private final String gender; - private final LocalDate dateOfBirth; + private final LocalDate dateOfBirth; - private final Long professionId; + private final Long professionId; - private final String profession; - - private final String mobileNumber; - - private final Long age; - - private final Boolean isDependent; + private final String profession; + + private final String mobileNumber; + + private final Long age; + + private final Boolean isDependent; - // template holder - private final Collection relationshipIdOptions; - private final Collection genderIdOptions; - private final Collection maritalStatusIdOptions; - private final Collection professionIdOptions; + // template holder + private final Collection relationshipIdOptions; + private final Collection genderIdOptions; + private final Collection maritalStatusIdOptions; + 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) { - this.id = id; - this.clientId = clientId; - this.firstName = firstName; - this.middleName = middleName; - this.lastName = lastName; - this.qualification = qualification; - this.relationship = relationship; - this.relationshipId = relationshipId; - this.maritalStatus = maritalStatus; - this.maritalStatusId = maritalStatusId; - this.gender = gender; - this.genderId = genderId; - 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; - - } + 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) { + this.id = id; + this.clientId = clientId; + this.firstName = firstName; + this.middleName = middleName; + this.lastName = lastName; + this.qualification = qualification; + this.relationship = relationship; + this.relationshipId = relationshipId; + this.maritalStatus = maritalStatus; + this.maritalStatusId = maritalStatusId; + this.gender = gender; + this.genderId = genderId; + 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; + + } - 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 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 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 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() { - return this.id; - } + public Long getId() { + return this.id; + } - public Long getClientId() { - return this.clientId; - } + public Long getClientId() { + return this.clientId; + } - 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; - } + public String getLastName() { + return this.lastName; + } - public String getQualification() { - return this.qualification; - } + public String getQualification() { + return this.qualification; + } - public Long getRelationshipId() { - return this.relationshipId; - } + public Long getRelationshipId() { + return this.relationshipId; + } - public String getRelationship() { - return this.relationship; - } + public String getRelationship() { + return this.relationship; + } - public Long getMaritalStatusId() { - return this.maritalStatusId; - } + public Long getMaritalStatusId() { + return this.maritalStatusId; + } - public String getMaritalStatus() { - return this.maritalStatus; - } + public String getMaritalStatus() { + return this.maritalStatus; + } - public Long getGenderId() { - return this.genderId; - } + public Long getGenderId() { + return this.genderId; + } - public String getGender() { - return this.gender; - } + public String getGender() { + return this.gender; + } - public LocalDate getDateOfBirth() { - return this.dateOfBirth; - } + public LocalDate getDateOfBirth() { + return this.dateOfBirth; + } - public Long getProfessionId() { - return this.professionId; - } + public Long getProfessionId() { + return this.professionId; + } - public String getProfession() { - return this.profession; - } + public String getProfession() { + return this.profession; + } - public String getMobileNumber() { - return this.mobileNumber; - } + public String getMobileNumber() { + return this.mobileNumber; + } - public Long getAge() { - return this.age; - } + public Long getAge() { + return this.age; + } - public Boolean getIsDependent() { - return this.isDependent; - } - - + public Boolean getIsDependent() { + return this.isDependent; + } + + } 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 e3b628268..6e26f4524 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 @@ -28,46 +28,46 @@ import java.io.Serializable; */ @SuppressWarnings("unused") public class ClientNonPersonData implements Serializable { - - private final CodeValueData constitution; - private final String incorpNumber; - private final LocalDate incorpValidityTillDate; + + private final CodeValueData constitution; + private final String incorpNumber; + private final LocalDate incorpValidityTillDate; private final CodeValueData mainBusinessLine; private final String remarks; - //import fields - private Long mainBusinessLineId; - private Long constitutionId; - private String locale; - private String dateFormat; + //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); - } - private ClientNonPersonData(String incorpNumber, LocalDate incorpValidityTillDate, - String remarks, Long mainBusinessLineId, Long constitutionId,String locale,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); + } + 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.constitution = null; - this.mainBusinessLine = null; - } + this.incorpNumber = incorpNumber; + this.incorpValidityTillDate = incorpValidityTillDate; + this.remarks = remarks; + this.mainBusinessLineId = mainBusinessLineId; + this.constitutionId = constitutionId; + this.dateFormat= dateFormat; + this.locale= locale; + this.constitution = null; + this.mainBusinessLine = null; + } - public ClientNonPersonData(CodeValueData constitution, String incorpNo, LocalDate incorpValidityTillDate, - CodeValueData mainBusinessLine, String remarks) { - super(); - this.constitution = constitution; - this.incorpNumber = incorpNo; - this.incorpValidityTillDate = incorpValidityTillDate; - this.mainBusinessLine = mainBusinessLine; - this.remarks = remarks; - } + public ClientNonPersonData(CodeValueData constitution, String incorpNo, LocalDate incorpValidityTillDate, + CodeValueData mainBusinessLine, String remarks) { + super(); + this.constitution = constitution; + this.incorpNumber = incorpNo; + this.incorpValidityTillDate = incorpValidityTillDate; + this.mainBusinessLine = mainBusinessLine; + this.remarks = remarks; + } } 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 8feff41ad..99e07a8b7 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 @@ -76,10 +76,10 @@ public class AccountNumberGenerator { } public String generate(ShareAccount shareaccount, AccountNumberFormat accountNumberFormat) { - Map propertyMap = new HashMap<>(); - propertyMap.put(ID, shareaccount.getId().toString()); - propertyMap.put(SHARE_PRODUCT_SHORT_NAME, shareaccount.getShareProduct().getShortName()); - return generateAccountNumber(propertyMap, accountNumberFormat) ; + Map propertyMap = new HashMap<>(); + propertyMap.put(ID, shareaccount.getId().toString()); + propertyMap.put(SHARE_PRODUCT_SHORT_NAME, shareaccount.getShareProduct().getShortName()); + return generateAccountNumber(propertyMap, accountNumberFormat) ; } private String generateAccountNumber(Map propertyMap, AccountNumberFormat accountNumberFormat) { @@ -121,14 +121,14 @@ public class AccountNumberGenerator { } public String generateGroupAccountNumber(Group group, AccountNumberFormat accountNumberFormat) { - Map propertyMap = new HashMap<>(); + Map propertyMap = new HashMap<>(); propertyMap.put(ID, group.getId().toString()); propertyMap.put(OFFICE_NAME, group.getOffice().getName()); return generateAccountNumber(propertyMap, accountNumberFormat); } public String generateCenterAccountNumber(Group group, AccountNumberFormat accountNumberFormat) { - Map propertyMap = new HashMap<>(); + Map propertyMap = new HashMap<>(); propertyMap.put(ID, group.getId().toString()); propertyMap.put(OFFICE_NAME, group.getOffice().getName()); return generateAccountNumber(propertyMap, accountNumberFormat); 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 f6afd7d3d..a445d9a52 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 @@ -114,11 +114,11 @@ public final class Client extends AbstractPersistableCustom { @Column(name = "mobile_no", length = 50, nullable = true, unique = true) private String mobileNo; - - @Column(name = "email_address", length = 50, unique = true) + + @Column(name = "email_address", length = 50, unique = true) private String emailAddress; - @Column(name = "is_staff", nullable = false) + @Column(name = "is_staff", nullable = false) private boolean isStaff; @Column(name = "external_id", length = 100, nullable = true, unique = true) @@ -233,8 +233,8 @@ public final class Client extends AbstractPersistableCustom { private AppUser reopenedBy; @Column(name = "proposed_transfer_date", nullable = true) - @Temporal(TemporalType.DATE) - private Date proposedTransferDate; + @Temporal(TemporalType.DATE) + 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, @@ -243,14 +243,14 @@ public final class Client extends AbstractPersistableCustom { final String accountNo = command.stringValueOfParameterNamed(ClientApiConstants.accountNoParamName); final String externalId = command.stringValueOfParameterNamed(ClientApiConstants.externalIdParamName); final String mobileNo = command.stringValueOfParameterNamed(ClientApiConstants.mobileNoParamName); - final String emailAddress = command.stringValueOfParameterNamed(ClientApiConstants.emailAddressParamName); + final String emailAddress = command.stringValueOfParameterNamed(ClientApiConstants.emailAddressParamName); final String firstname = command.stringValueOfParameterNamed(ClientApiConstants.firstnameParamName); final String middlename = command.stringValueOfParameterNamed(ClientApiConstants.middlenameParamName); final String lastname = command.stringValueOfParameterNamed(ClientApiConstants.lastnameParamName); final String fullname = command.stringValueOfParameterNamed(ClientApiConstants.fullnameParamName); - - final boolean isStaff = command.booleanPrimitiveValueOfParameterNamed(ClientApiConstants.isStaffParamName); + + final boolean isStaff = command.booleanPrimitiveValueOfParameterNamed(ClientApiConstants.isStaffParamName); final LocalDate dataOfBirth = command.localDateValueOfParameterNamed(ClientApiConstants.dateOfBirthParamName); @@ -282,7 +282,7 @@ public final class Client extends AbstractPersistableCustom { } protected Client() { - this.setLegalForm(null); + this.setLegalForm(null); } private Client(final AppUser currentUser, final ClientStatus status, final Office office, final Group clientParentGroup, @@ -315,7 +315,7 @@ public final class Client extends AbstractPersistableCustom { this.mobileNo = null; } - if (StringUtils.isNotBlank(emailAddress)) { + if (StringUtils.isNotBlank(emailAddress)) { this.emailAddress = emailAddress.trim(); } else { this.emailAddress = null; @@ -512,8 +512,8 @@ public final class Client extends AbstractPersistableCustom { actualChanges.put(ClientApiConstants.mobileNoParamName, newValue); this.mobileNo = StringUtils.defaultIfEmpty(newValue, null); } - - if (command.isChangeInStringParameterNamed(ClientApiConstants.emailAddressParamName, this.emailAddress)) { + + if (command.isChangeInStringParameterNamed(ClientApiConstants.emailAddressParamName, this.emailAddress)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.emailAddressParamName); actualChanges.put(ClientApiConstants.emailAddressParamName, newValue); this.emailAddress = StringUtils.defaultIfEmpty(newValue, null); @@ -577,10 +577,10 @@ public final class Client extends AbstractPersistableCustom { final Integer newValue = command.integerValueOfParameterNamed(ClientApiConstants.legalFormIdParamName); if(newValue != null) { - LegalForm legalForm = LegalForm.fromInt(newValue); - if(legalForm != null) - { - actualChanges.put(ClientApiConstants.legalFormIdParamName, ClientEnumerations.legalForm(newValue)); + LegalForm legalForm = LegalForm.fromInt(newValue); + if(legalForm != null) + { + actualChanges.put(ClientApiConstants.legalFormIdParamName, ClientEnumerations.legalForm(newValue)); this.setLegalForm(legalForm.getValue()); if(legalForm.isPerson()){ this.fullname = null; @@ -589,16 +589,16 @@ public final class Client extends AbstractPersistableCustom { this.lastname = null; this.displayName = null; } - } - else - { - actualChanges.put(ClientApiConstants.legalFormIdParamName, null); + } + else + { + actualChanges.put(ClientApiConstants.legalFormIdParamName, null); this.setLegalForm(null); - } + } } else { - actualChanges.put(ClientApiConstants.legalFormIdParamName, null); + actualChanges.put(ClientApiConstants.legalFormIdParamName, null); this.setLegalForm(null); } } @@ -688,16 +688,16 @@ 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 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); - dataValidationErrors.add(error); - } + dataValidationErrors.add(error); + } if (getActivationLocalDate() != null && isDateInTheFuture(getActivationLocalDate())) { @@ -725,7 +725,7 @@ public final class Client extends AbstractPersistableCustom { Integer legalForm = this.getLegalForm(); if(legalForm == null || LegalForm.fromInt(legalForm).isPerson()) { - if (StringUtils.isNotBlank(this.firstname)) { + if (StringUtils.isNotBlank(this.firstname)) { nameBuilder.append(this.firstname).append(' '); } @@ -743,7 +743,7 @@ public final class Client extends AbstractPersistableCustom { } else if(LegalForm.fromInt(legalForm).isEntity()) { - if (StringUtils.isNotBlank(this.fullname)) { + if (StringUtils.isNotBlank(this.fullname)) { nameBuilder = new StringBuilder(this.fullname); } } @@ -791,7 +791,7 @@ public final class Client extends AbstractPersistableCustom { return this.mobileNo; } - public String emailAddress() { + public String emailAddress() { return this.emailAddress; } @@ -799,7 +799,7 @@ public final class Client extends AbstractPersistableCustom { this.mobileNo = mobileNo; } - public boolean isNotStaff() { + public boolean isNotStaff() { return !isStaff(); } @@ -807,11 +807,11 @@ public final class Client extends AbstractPersistableCustom { return this.isStaff; } - public String getExternalId() { - return this.externalId; - } + public String getExternalId() { + return this.externalId; + } - public void setEmailAddress(final String emailAddress) { + public void setEmailAddress(final String emailAddress) { this.emailAddress = emailAddress; } @@ -963,13 +963,13 @@ public final class Client extends AbstractPersistableCustom { } public LocalDate getWithdrawalDate() { return (LocalDate) ObjectUtils.defaultIfNull(new LocalDate(this.withdrawalDate), null); - } + } - public LocalDate getReopenedDate() { - return this.reopenedDate == null ? null : new LocalDate(this.reopenedDate); - } + public LocalDate getReopenedDate() { + return this.reopenedDate == null ? null : new LocalDate(this.reopenedDate); + } - public CodeValue gender() { + public CodeValue gender() { return this.gender; } @@ -1061,16 +1061,16 @@ public final class Client extends AbstractPersistableCustom { public String getMiddlename(){return this.middlename;} - public String getLastname() { - return this.lastname; - } + public String getLastname() { + return this.lastname; + } - public Date getProposedTransferDate() { - return proposedTransferDate; - } + public Date getProposedTransferDate() { + return proposedTransferDate; + } - public void updateProposedTransferDate(Date proposedTransferDate) { - this.proposedTransferDate = proposedTransferDate; - } + public void updateProposedTransferDate(Date proposedTransferDate) { + this.proposedTransferDate = proposedTransferDate; + } } \ No newline at end of file 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 5eff17309..77c4d9ca6 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 @@ -32,68 +32,68 @@ import org.apache.fineract.portfolio.address.domain.Address; @Table(name = "m_client_address") public class ClientAddress extends AbstractPersistableCustom { - @ManyToOne - private Client client; + @ManyToOne + private Client client; - @ManyToOne - private Address address; + @ManyToOne + private Address address; - @ManyToOne - @JoinColumn(name = "address_type_id") - private CodeValue addressType; + @ManyToOne + @JoinColumn(name = "address_type_id") + private CodeValue addressType; - @Column(name = "is_active") - private boolean isActive; + @Column(name = "is_active") + private 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; - this.isActive = isActive; + private ClientAddress(final Client client, final Address address, final CodeValue addressType, + final boolean isActive) { + this.client = client; + this.address = address; + this.addressType = addressType; + this.isActive = isActive; - } + } - public ClientAddress() { + public ClientAddress() { - } + } - 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); - } + return new ClientAddress(client, address, address_type, isActive); + } - public Client getClient() { - return this.client; - } + public Client getClient() { + return this.client; + } - public Address getAddress() { - return this.address; - } + public Address getAddress() { + return this.address; + } - public CodeValue getAddressType() { - return this.addressType; - } + public CodeValue getAddressType() { + return this.addressType; + } - public void setAddressType(final CodeValue addressType) { - this.addressType = addressType; - } + public void setAddressType(final CodeValue addressType) { + this.addressType = addressType; + } - public boolean isIs_active() { - return this.isActive; - } + public boolean isIs_active() { + return this.isActive; + } - public void setClient(final Client client) { - this.client = client; - } + public void setClient(final Client client) { + this.client = client; + } - public void setAddress(final Address address) { - this.address = address; - } + public void setAddress(final Address address) { + this.address = address; + } - public void setIs_active(final boolean isActive) { - this.isActive = isActive; - } + public void setIs_active(final boolean isActive) { + this.isActive = 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 984b2ea3a..b6add4b4c 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 @@ -23,13 +23,13 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ClientAddressRepository - extends JpaRepository, JpaSpecificationExecutor { - ClientAddress findByClientId(String clientId); + extends JpaRepository, JpaSpecificationExecutor { + ClientAddress findByClientId(String clientId); - // ClientAddress findByAddressId(long addressId); + // 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); + 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 fbe7cd2a8..8ac51ec89 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,27 +24,27 @@ import org.springframework.stereotype.Service; @Service public class ClientAddressRepositoryWrapper { - private final ClientAddressRepository clientAddressRepository; + private final ClientAddressRepository clientAddressRepository; - @Autowired - public ClientAddressRepositoryWrapper(final ClientAddressRepository clientAddressRepository) { - this.clientAddressRepository = clientAddressRepository; - } + @Autowired + public ClientAddressRepositoryWrapper(final ClientAddressRepository clientAddressRepository) { + this.clientAddressRepository = clientAddressRepository; + } - public ClientAddress findOneByClientIdAndAddressTypeAndIsActive(final long clientId, final CodeValue addressType, - final boolean isActive) { - final ClientAddress clientAddress = this.clientAddressRepository - .findByClientIdAndAddressTypeAndIsActive(clientId, addressType, isActive); - // if (clientAddress == null) { throw new - // AddressNotFoundException(clientId, addressType); } - return clientAddress; - } + public ClientAddress findOneByClientIdAndAddressTypeAndIsActive(final long clientId, final CodeValue addressType, + final boolean 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); + public ClientAddress findOneByClientIdAndAddressId(final long clientId, final long addressId) { + final ClientAddress clientAddress = this.clientAddressRepository.findByClientIdAndAddressId(clientId, + addressId); - return clientAddress; - } + return clientAddress; + } } 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 a8bffc432..2a51a55a7 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 @@ -72,7 +72,7 @@ public class ClientEnumerations { } public static EnumOptionData legalForm(final LegalForm legalForm) { - final EnumOptionData optionData = new EnumOptionData(legalForm.getValue().longValue(), legalForm.getCode(), + final EnumOptionData optionData = new EnumOptionData(legalForm.getValue().longValue(), legalForm.getCode(), legalForm.toString()); return optionData; } 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 a1419c4bd..e4084fb13 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 @@ -33,206 +33,206 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity @Table(name = "m_family_members") public class ClientFamilyMembers extends AbstractPersistableCustom { - - @ManyToOne - @JoinColumn(name="client_id") - private Client client; - - @Column(name="firstname") - private String firstName; - - @Column(name="middleName") - private String middleName; - - @Column(name="lastName") - private String lastName; - - @Column(name="qualification") - private String qualification; - - @Column(name="mobile_number") - private String mobileNumber; - - @Column(name="age") - private Long age; - - @Column(name="is_dependent") - private Boolean isDependent; - - - @ManyToOne - @JoinColumn(name = "relationship_cv_id") - private CodeValue relationship; - - @ManyToOne - @JoinColumn(name = "marital_status_cv_id") - private CodeValue maritalStatus; - - - @ManyToOne - @JoinColumn(name = "gender_cv_id") - private CodeValue gender; - - @ManyToOne - @JoinColumn(name = "profession_cv_id") - private CodeValue profession; - - @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) - { - - 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 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); - } + + @ManyToOne + @JoinColumn(name="client_id") + private Client client; + + @Column(name="firstname") + private String firstName; + + @Column(name="middleName") + private String middleName; + + @Column(name="lastName") + private String lastName; + + @Column(name="qualification") + private String qualification; + + @Column(name="mobile_number") + private String mobileNumber; + + @Column(name="age") + private Long age; + + @Column(name="is_dependent") + private Boolean isDependent; + + + @ManyToOne + @JoinColumn(name = "relationship_cv_id") + private CodeValue relationship; + + @ManyToOne + @JoinColumn(name = "marital_status_cv_id") + private CodeValue maritalStatus; + + + @ManyToOne + @JoinColumn(name = "gender_cv_id") + private CodeValue gender; + + @ManyToOne + @JoinColumn(name = "profession_cv_id") + private CodeValue profession; + + @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) + { + + 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 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 String getMobileNumber() { + return this.mobileNumber; + } - public void setMobileNumber(String mobileNumber) { - this.mobileNumber = mobileNumber; - } + public void setMobileNumber(String mobileNumber) { + this.mobileNumber = mobileNumber; + } - public Long getAge() { - return this.age; - } + public Long getAge() { + return this.age; + } - public void setAge(Long age) { - this.age = age; - } + public void setAge(Long age) { + this.age = age; + } - public Boolean getIsDependent() { - return this.isDependent; - } + public Boolean getIsDependent() { + return this.isDependent; + } - public void setIsDependent(Boolean isDependent) { - this.isDependent = isDependent; - } - - - - - + public void setIsDependent(Boolean isDependent) { + this.isDependent = isDependent; + } + + + + + } 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 2122f77e6..7c6144efe 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 @@ -79,7 +79,7 @@ public class ClientIdentifier extends AbstractAuditableCustom { ClientIdentifierStatus statusEnum = ClientIdentifierStatus.valueOf(statusName.toUpperCase()); this.active = null; if(statusEnum.isActive()){ - this.active = statusEnum.getValue(); + this.active = statusEnum.getValue(); } this.status = statusEnum.getValue(); } 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 23e18ef7e..ba2821032 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 @@ -47,78 +47,78 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity @Table(name = "m_client_non_person") public class ClientNonPerson extends AbstractPersistableCustom { - - @OneToOne(optional = false) + + @OneToOne(optional = false) @JoinColumn(name = "client_id", referencedColumnName = "id", nullable = false, unique = true) private Client client; - - @ManyToOne(fetch = FetchType.LAZY) + + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "constitution_cv_id", nullable = false) private CodeValue constitution; - - @Column(name = "incorp_no", length = 50, nullable = true) - private String incorpNumber; - - @Column(name = "incorp_validity_till", nullable = true) - @Temporal(TemporalType.DATE) - private Date incorpValidityTill; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "main_business_line_cv_id", nullable = true) + + @Column(name = "incorp_no", length = 50, nullable = true) + private String incorpNumber; + + @Column(name = "incorp_validity_till", nullable = true) + @Temporal(TemporalType.DATE) + private Date incorpValidityTill; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "main_business_line_cv_id", nullable = true) private CodeValue mainBusinessLine; - - @Column(name = "remarks", length = 150, nullable = true) - private String remarks; - + + @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) - { - return new ClientNonPerson(client, constitution, mainBusinessLine, incorpNumber, incorpValidityTill, remarks); - } - - protected ClientNonPerson() { + 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); + } + + protected ClientNonPerson() { // } - - 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) - this.constitution = constitution; - - if(mainBusinessLine != null) - this.mainBusinessLine = mainBusinessLine; - - if (StringUtils.isNotBlank(incorpNumber)) { + + 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) + this.constitution = constitution; + + if(mainBusinessLine != null) + this.mainBusinessLine = mainBusinessLine; + + if (StringUtils.isNotBlank(incorpNumber)) { this.incorpNumber = incorpNumber.trim(); } else { this.incorpNumber = null; } - - if (incorpValidityTill != null) { + + if (incorpValidityTill != null) { this.incorpValidityTill = incorpValidityTill.toDateTimeAtStartOfDay().toDate(); } - - if (StringUtils.isNotBlank(remarks)) { + + if (StringUtils.isNotBlank(remarks)) { this.remarks = remarks.trim(); } else { this.remarks = null; } - - validate(client); - } - - private void validate(final Client client) { + + validate(client); + } + + private void validate(final Client client) { final List dataValidationErrors = new ArrayList<>(); validateIncorpValidityTillDate(client, dataValidationErrors); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - - private void validateIncorpValidityTillDate(final Client client, final List dataValidationErrors) { + + private void validateIncorpValidityTillDate(final Client client, final List dataValidationErrors) { if (getIncorpValidityTillLocalDate() != null && client.dateOfBirthLocalDate() != null && client.dateOfBirthLocalDate().isAfter(getIncorpValidityTillLocalDate())) { final String defaultUserMessage = "incorpvaliditytill date cannot be after the incorporation date"; @@ -128,59 +128,59 @@ public class ClientNonPerson extends AbstractPersistableCustom { dataValidationErrors.add(error); } } - - public LocalDate getIncorpValidityTillLocalDate() { + + public LocalDate getIncorpValidityTillLocalDate() { LocalDate incorpValidityTillLocalDate = null; if (this.incorpValidityTill != null) { incorpValidityTillLocalDate = LocalDate.fromDateFields(this.incorpValidityTill); } return incorpValidityTillLocalDate; } - - public Long constitutionId() { + + public Long constitutionId() { Long constitutionId = null; if (this.constitution != null) { constitutionId = this.constitution.getId(); } return constitutionId; } - - public Long mainBusinessLineId() { + + public Long mainBusinessLineId() { Long mainBusinessLineId = null; if (this.mainBusinessLine != null) { mainBusinessLineId = this.mainBusinessLine.getId(); } return mainBusinessLineId; } - - public void updateConstitution(CodeValue constitution) { + + public void updateConstitution(CodeValue constitution) { this.constitution = constitution; } - - public void updateMainBusinessLine(CodeValue mainBusinessLine) { + + public void updateMainBusinessLine(CodeValue mainBusinessLine) { this.mainBusinessLine = mainBusinessLine; } - - public Map update(final JsonCommand command) { - - final Map actualChanges = new LinkedHashMap<>(9); - - if (command.isChangeInStringParameterNamed(ClientApiConstants.incorpNumberParamName, this.incorpNumber)) { + + public Map update(final JsonCommand command) { + + final Map actualChanges = new LinkedHashMap<>(9); + + if (command.isChangeInStringParameterNamed(ClientApiConstants.incorpNumberParamName, this.incorpNumber)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.incorpNumberParamName); actualChanges.put(ClientApiConstants.incorpNumberParamName, newValue); this.incorpNumber = StringUtils.defaultIfEmpty(newValue, null); } - - if (command.isChangeInStringParameterNamed(ClientApiConstants.remarksParamName, this.remarks)) { + + if (command.isChangeInStringParameterNamed(ClientApiConstants.remarksParamName, this.remarks)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.remarksParamName); actualChanges.put(ClientApiConstants.remarksParamName, newValue); this.remarks = StringUtils.defaultIfEmpty(newValue, null); } - - final String dateFormatAsInput = command.dateFormat(); + + final String dateFormatAsInput = command.dateFormat(); final String localeAsInput = command.locale(); - if (command.isChangeInLocalDateParameterNamed(ClientApiConstants.incorpValidityTillParamName, getIncorpValidityTillLocalDate())) { + if (command.isChangeInLocalDateParameterNamed(ClientApiConstants.incorpValidityTillParamName, getIncorpValidityTillLocalDate())) { final String valueAsInput = command.stringValueOfParameterNamed(ClientApiConstants.incorpValidityTillParamName); actualChanges.put(ClientApiConstants.incorpValidityTillParamName, valueAsInput); actualChanges.put(ClientApiConstants.dateFormatParamName, dateFormatAsInput); @@ -189,20 +189,20 @@ public class ClientNonPerson extends AbstractPersistableCustom { final LocalDate newValue = command.localDateValueOfParameterNamed(ClientApiConstants.incorpValidityTillParamName); this.incorpValidityTill = newValue.toDate(); } - - if (command.isChangeInLongParameterNamed(ClientApiConstants.constitutionIdParamName, constitutionId())) { + + if (command.isChangeInLongParameterNamed(ClientApiConstants.constitutionIdParamName, constitutionId())) { final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.constitutionIdParamName); actualChanges.put(ClientApiConstants.constitutionIdParamName, newValue); } - - if (command.isChangeInLongParameterNamed(ClientApiConstants.mainBusinessLineIdParamName, mainBusinessLineId())) { + + if (command.isChangeInLongParameterNamed(ClientApiConstants.mainBusinessLineIdParamName, mainBusinessLineId())) { final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.mainBusinessLineIdParamName); 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 d80653013..49c226be7 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 @@ -25,6 +25,6 @@ import org.springframework.data.repository.query.Param; public interface ClientNonPersonRepository extends JpaRepository, JpaSpecificationExecutor{ - @Query("select clientNonPerson from ClientNonPerson clientNonPerson where clientNonPerson.client.id = :clientId") - ClientNonPerson findByClientId(@Param("clientId") Long clientId); + @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 8a38eea67..062ea3689 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 @@ -33,10 +33,10 @@ import org.springframework.stereotype.Service; */ @Service public class ClientNonPersonRepositoryWrapper { - - private final ClientNonPersonRepository repository; + + private final ClientNonPersonRepository repository; private final PlatformSecurityContext context; - + @Autowired public ClientNonPersonRepositoryWrapper(final ClientNonPersonRepository repository, final PlatformSecurityContext context) { this.repository = repository; @@ -49,7 +49,7 @@ public class ClientNonPersonRepositoryWrapper { } public ClientNonPerson findOneByClientId(final Long clientId) { - return this.repository.findByClientId(clientId); + return this.repository.findByClientId(clientId); } public ClientNonPerson findOneByClientIdWithNotFoundDetection(final Long clientId) { 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 fbdd96d36..50506dd8a 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 @@ -56,10 +56,10 @@ public enum ClientStatus { enumeration = ClientStatus.CLOSED; break; case 700: - enumeration = ClientStatus.REJECTED; + enumeration = ClientStatus.REJECTED; break; case 800: - enumeration = ClientStatus.WITHDRAWN; + enumeration = ClientStatus.WITHDRAWN; break; } @@ -95,10 +95,10 @@ public enum ClientStatus { return this.value.equals(ClientStatus.CLOSED.getValue()); } public boolean isRejected(){ - return this.value.equals(ClientStatus.REJECTED.getValue()); + return this.value.equals(ClientStatus.REJECTED.getValue()); } public boolean isWithdrawn(){ - return this.value.equals(ClientStatus.WITHDRAWN.getValue()); + return this.value.equals(ClientStatus.WITHDRAWN.getValue()); } public boolean isTransferInProgress() { return this.value.equals(ClientStatus.TRANSFER_IN_PROGRESS.getValue()); 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 18c56f71a..daf5672a8 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 @@ -34,50 +34,50 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_client_transfer_details") public class ClientTransferDetails extends AbstractPersistableCustom { - @Column(name = "client_id", length = 20, unique = true, nullable = false) - private Long clientId; + @Column(name = "client_id", length = 20, unique = true, nullable = false) + private Long clientId; - @Column(name = "from_office_id", nullable = false) - private Long fromOfficeId; + @Column(name = "from_office_id", nullable = false) + private Long fromOfficeId; - @Column(name = "to_office_id", nullable = false) - private Long toOfficeId; + @Column(name = "to_office_id", nullable = false) + private Long toOfficeId; - @Column(name = "proposed_transfer_date", nullable = true) - @Temporal(TemporalType.DATE) - private Date proposedTransferDate; + @Column(name = "proposed_transfer_date", nullable = true) + @Temporal(TemporalType.DATE) + private Date proposedTransferDate; - @Column(name = "transfer_type", nullable = false) - private Integer transferEventType; + @Column(name = "transfer_type", nullable = false) + private Integer transferEventType; - @Column(name = "submitted_on", nullable = false) - @Temporal(TemporalType.DATE) - private Date submittedOn; + @Column(name = "submitted_on", nullable = false) + @Temporal(TemporalType.DATE) + private Date submittedOn; - @Column(name = "submitted_by", nullable = false) - private Long submittedBy; + @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) { - this.clientId = clientId; - this.fromOfficeId = fromOfficeId; - this.toOfficeId = toOfficeId; - this.proposedTransferDate = proposedTransferDate; - this.transferEventType = transferEventType; - this.submittedOn = submittedOn; - this.submittedBy = 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; + this.proposedTransferDate = proposedTransferDate; + this.transferEventType = transferEventType; + this.submittedOn = submittedOn; + this.submittedBy = submittedBy; + } - 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); + 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); - } + } } \ 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 753fab980..32675f41f 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 @@ -23,6 +23,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ClientTransferDetailsRepository - extends JpaRepository, JpaSpecificationExecutor { + 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 c2cdac364..4ec3ab75d 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 @@ -25,15 +25,15 @@ import org.springframework.stereotype.Service; @Service public class ClientTransferDetailsRepositoryWrapper { - private final ClientTransferDetailsRepository repository; + private final ClientTransferDetailsRepository repository; - @Autowired - public ClientTransferDetailsRepositoryWrapper(final ClientTransferDetailsRepository repository) { - this.repository = repository; - } + @Autowired + public ClientTransferDetailsRepositoryWrapper(final ClientTransferDetailsRepository repository) { + this.repository = repository; + } - public void save(final ClientTransferDetails clientTransferDetails) { - this.repository.save(clientTransferDetails); - } + public void save(final ClientTransferDetails clientTransferDetails) { + this.repository.save(clientTransferDetails); + } } \ No newline at end of file diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/LegalForm.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/LegalForm.java index 3a9a4ff90..0d85369f6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/LegalForm.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/LegalForm.java @@ -22,14 +22,14 @@ package org.apache.fineract.portfolio.client.domain; * Type used to differentiate the type of client */ public enum LegalForm { - - PERSON(1, "legalFormType.person"), - - ENTITY(2, "legalFormType.entity"); - - private final Integer value; + + PERSON(1, "legalFormType.person"), + + ENTITY(2, "legalFormType.entity"); + + private final Integer value; private final String code; - + private LegalForm(final Integer value, final String code) { this.value = value; this.code = code; @@ -42,10 +42,10 @@ public enum LegalForm { public String getCode() { return this.code; } - + public static LegalForm fromInt(final Integer type) { - LegalForm legalForm = null; + LegalForm legalForm = null; switch (type) { case 1: legalForm = LegalForm.PERSON; 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 ed717bdb0..860cc2d4b 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 @@ -24,8 +24,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc * A {@link RuntimeException} thrown when clientNonPerson resources are not found. */ public class ClientNonPersonNotFoundByClientIdException extends AbstractPlatformResourceNotFoundException { - - public ClientNonPersonNotFoundByClientIdException(final Long id) { + + public ClientNonPersonNotFoundByClientIdException(final Long id) { super("error.msg.clientnonperson.id.invalid", "ClientNonPerson with client identifier " + id + " does not exist", id); } } 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 15e5ada0b..82420fe47 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 @@ -24,9 +24,9 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc * A {@link RuntimeException} thrown when clientNonPerson resources are not found. */ public class ClientNonPersonNotFoundException extends AbstractPlatformResourceNotFoundException { - - public ClientNonPersonNotFoundException(final Long id) { + + public ClientNonPersonNotFoundException(final Long id) { super("error.msg.clientnonperson.id.invalid", "ClientNonPerson with identifier " + id + " does not exist", id); } - + } 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 2e9d844ba..731f4c616 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,17 +29,17 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "ADDRESS", action = "CREATE") public class AddClientAddressCommandHandler implements NewCommandSourceHandler { - private final AddressWritePlatformService writePlatformService; + private final AddressWritePlatformService writePlatformService; - @Autowired - public AddClientAddressCommandHandler(final AddressWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public AddClientAddressCommandHandler(final AddressWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.addClientAddress(command.getClientId(), command.entityId(), command); + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.writePlatformService.addClientAddress(command.getClientId(), command.entityId(), command); - } + } } 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 7ab2c587d..69be3f7d3 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 @@ -33,18 +33,18 @@ import org.springframework.stereotype.Service; public class AddClientFamilyMemberCommandHandler implements NewCommandSourceHandler { - private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; - - @Autowired - public AddClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) - { - this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - - return this.clientFamilyMembersWritePlatformService.addFamilyMember(command.getClientId(), command); - } + private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; + + @Autowired + public AddClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) + { + this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; + } + + @Override + public CommandProcessingResult processCommand(JsonCommand command) { + + return this.clientFamilyMembersWritePlatformService.addFamilyMember(command.getClientId(), command); + } } 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 484478c7b..1414ef387 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 @@ -32,16 +32,16 @@ import org.springframework.stereotype.Service; public class DeleteClientFamilyMemberCommandHandler implements NewCommandSourceHandler { private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; - - @Autowired - public DeleteClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) - { - this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - - return this.clientFamilyMembersWritePlatformService.deleteFamilyMember(command.entityId(), command); - } + + @Autowired + public DeleteClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) + { + this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; + } + + @Override + public CommandProcessingResult processCommand(JsonCommand command) { + + return this.clientFamilyMembersWritePlatformService.deleteFamilyMember(command.entityId(), command); + } } 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 86dce395f..9fb72c481 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 @@ -28,8 +28,8 @@ 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) { 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 7b5718844..f95194bec 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 @@ -32,12 +32,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 bf81e40aa..c030e17f5 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 @@ -30,12 +30,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 diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientAddressCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientAddressCommandHandler.java index a7892c9ee..8bc7005fb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientAddressCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientAddressCommandHandler.java @@ -30,22 +30,22 @@ import org.springframework.stereotype.Service; @CommandType(entity = "ADDRESS", action = "UPDATE") public class UpdateClientAddressCommandHandler implements NewCommandSourceHandler { - private final AddressWritePlatformService writePlatformService; + private final AddressWritePlatformService writePlatformService; - @Autowired - public UpdateClientAddressCommandHandler(final AddressWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public UpdateClientAddressCommandHandler(final AddressWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - /* - * return - * this.writePlatformService.updateClientAddress(command.getClientId(), - * command.entityId(), command.getStatus(), command); - */ - return this.writePlatformService.updateClientAddress(command.getClientId(), command); + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + /* + * return + * this.writePlatformService.updateClientAddress(command.getClientId(), + * command.entityId(), command.getStatus(), command); + */ + return this.writePlatformService.updateClientAddress(command.getClientId(), command); - } + } } 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 69c25f35f..3b4287933 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 @@ -32,18 +32,18 @@ import org.springframework.stereotype.Service; @CommandType(entity = "FAMILYMEMBERS", action = "UPDATE") public class UpdateClientFamilyMemberCommandHandler implements NewCommandSourceHandler { - private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; - - @Autowired - public UpdateClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) - { - this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; - } - - @Override - public CommandProcessingResult processCommand(JsonCommand command) { - - return this.clientFamilyMembersWritePlatformService.updateFamilyMember(command.entityId(), command); - } + private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; + + @Autowired + public UpdateClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) + { + this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; + } + + @Override + public CommandProcessingResult processCommand(JsonCommand command) { + + return this.clientFamilyMembersWritePlatformService.updateFamilyMember(command.entityId(), command); + } } 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 54080f550..de5515949 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 @@ -31,8 +31,8 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "CLIENT", action = "WITHDRAW") public class WithdrawClientCommandHandler implements NewCommandSourceHandler { - - private final ClientWritePlatformService clientWritePlatformService; + + private final ClientWritePlatformService clientWritePlatformService; @Autowired public WithdrawClientCommandHandler(final ClientWritePlatformService clientWritePlatformService) { 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 e5354fe9e..c0852a5fa 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 @@ -45,269 +45,269 @@ import com.google.gson.reflect.TypeToken; @Component 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")); - - @Autowired - private ClientFamilyMemberCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) - { - this.fromApiJsonHelper=fromApiJsonHelper; - } - - - public void validateForCreate(String json) - { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + 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")); + + @Autowired + private ClientFamilyMemberCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) + { + this.fromApiJsonHelper=fromApiJsonHelper; + } + + + public void validateForCreate(String json) + { + + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } - 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 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); - - } - - - - public void validateForCreate(final long clientId,String json) - { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + 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 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); + + } + + + + public void validateForCreate(final long clientId,String json) + { + + 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("FamilyMembers"); + final List dataValidationErrors = new ArrayList<>(); + 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) - { - 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); - } - - 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) - { - 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) - { - 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) - { - 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) - { - 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); - baseDataValidator.reset().parameter("relationShipId").value(relationShipId).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); - baseDataValidator.reset().parameter("maritalStatusId").value(maritalStatusId).notBlank().longGreaterThanZero(); - - } - - 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); - baseDataValidator.reset().parameter("age").value(age).notBlank().longGreaterThanZero(); - - } - - 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); - baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).value(dateOfBirth).notNull() + final JsonElement element = this.fromApiJsonHelper.parse(json); + + baseDataValidator.reset().value(clientId).notBlank().integerGreaterThanZero(); + + 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); + } + + 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) + { + 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) + { + 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) + { + 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) + { + 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); + baseDataValidator.reset().parameter("relationShipId").value(relationShipId).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); + baseDataValidator.reset().parameter("maritalStatusId").value(maritalStatusId).notBlank().longGreaterThanZero(); + + } + + 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); + baseDataValidator.reset().parameter("age").value(age).notBlank().longGreaterThanZero(); + + } + + 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); + baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).value(dateOfBirth).notNull() .validateDateBefore(DateUtils.getLocalDateOfTenant()); - - } - - - - } - - - public void validateForUpdate(final long familyMemberId,String json) - { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + + } + + + + } + + + public void validateForUpdate(final long familyMemberId,String json) + { + + 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("FamilyMembers"); + final List dataValidationErrors = new ArrayList<>(); + 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) - { - 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) - { - 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) - { - 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) - { - 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); - baseDataValidator.reset().parameter("relationShipId").value(relationShipId).notBlank().longGreaterThanZero(); - - } - - - 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); - baseDataValidator.reset().parameter("genderId").value(genderId).longGreaterThanZero(); - - } - - 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) - { - LocalDateTime currentDate = LocalDateTime.now(); - - final LocalDate dateOfBirth=this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element); - baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).validateDateBefore(currentDate.toLocalDate()); - - } - - - - } - - public void validateForDelete(final long familyMemberId) - { - + final JsonElement element = this.fromApiJsonHelper.parse(json); + + baseDataValidator.reset().value(familyMemberId).notBlank().integerGreaterThanZero(); + + 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) + { + 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) + { + 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) + { + 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); + baseDataValidator.reset().parameter("relationShipId").value(relationShipId).notBlank().longGreaterThanZero(); + + } + + + 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); + baseDataValidator.reset().parameter("genderId").value(genderId).longGreaterThanZero(); + + } + + 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) + { + LocalDateTime currentDate = LocalDateTime.now(); + + final LocalDate dateOfBirth=this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element); + baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).validateDateBefore(currentDate.toLocalDate()); + + } + + + + } + + public void validateForDelete(final long familyMemberId) + { + - + - final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("FamilyMembers"); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource("FamilyMembers"); - //final JsonElement element = this.fromApiJsonHelper.parse(json); - - baseDataValidator.reset().value(familyMemberId).notBlank().integerGreaterThanZero(); - } + //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/service/ClientAddressReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientAddressReadPlatformService.java index d33635f78..1bd992cbd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientAddressReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientAddressReadPlatformService.java @@ -24,6 +24,6 @@ import org.apache.fineract.portfolio.address.data.ClientAddressData; public interface ClientAddressReadPlatformService { - public Collection retrieveClientAddrConfiguration(String entity); + public Collection retrieveClientAddrConfiguration(String entity); } 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 63079ed1d..1e564501b 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 @@ -33,44 +33,44 @@ import org.springframework.stereotype.Service; @Service public class ClientAddressReadPlatformServiceImpl implements ClientAddressReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public ClientAddressReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + 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"; - } + 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 { - final long clientAddressId = rs.getLong("clientAddressId"); - final long client_id = rs.getLong("client_id"); - final long address_id = rs.getLong("address_id"); - final long address_type_id = rs.getLong("address_type_id"); - final boolean is_active = rs.getBoolean("is_active"); + @Override + 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"); + final long address_type_id = rs.getLong("address_type_id"); + final boolean is_active = rs.getBoolean("is_active"); - return ClientAddressData.instance(clientAddressId, client_id, address_id, address_type_id, is_active); + return ClientAddressData.instance(clientAddressId, client_id, address_id, address_type_id, is_active); - } - } + } + } - @Override - public Collection retrieveClientAddrConfiguration(final String entity) { - this.context.authenticatedUser(); + @Override + public Collection retrieveClientAddrConfiguration(final String entity) { + this.context.authenticatedUser(); - final ClientAddrMapper rm = new ClientAddrMapper(); - final String sql = "select " + rm.schema() + " where fld.entity=?"; + final ClientAddrMapper rm = new ClientAddrMapper(); + final String sql = "select " + rm.schema() + " where fld.entity=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { entity }); - } + return this.jdbcTemplate.query(sql, rm, new Object[] { entity }); + } } 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 7a916a671..dfc25641a 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 @@ -26,9 +26,9 @@ import org.apache.fineract.portfolio.client.data.ClientFamilyMembersData; public interface ClientFamilyMembersReadPlatformService { - Collection getClientFamilyMembers(long clientId); - - ClientFamilyMembersData getClientFamilyMember(long id); + Collection getClientFamilyMembers(long clientId); + + ClientFamilyMembersData getClientFamilyMember(long id); - ClientFamilyMembersData retrieveTemplate(); + ClientFamilyMembersData retrieveTemplate(); } 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 19c376ffd..a01987fcf 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 @@ -40,103 +40,103 @@ import org.springframework.stereotype.Service; @Service public class ClientFamilyMembersReadPlatformServiceImpl implements ClientFamilyMembersReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; - private final CodeValueReadPlatformService codeValueReadPlatformService; - + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; + private final CodeValueReadPlatformService codeValueReadPlatformService; + - @Autowired - public ClientFamilyMembersReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource,final CodeValueReadPlatformService codeValueReadPlatformService) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.codeValueReadPlatformService=codeValueReadPlatformService; - - } + @Autowired + public ClientFamilyMembersReadPlatformServiceImpl(final PlatformSecurityContext context, + final RoutingDataSource dataSource,final CodeValueReadPlatformService codeValueReadPlatformService) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); + 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"; - } + 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"; + } - @Override - 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 relationship = rs.getString("relationship"); - final long relationshipId = rs.getLong("relationshipId"); - final String maritalStatus = rs.getString("maritalStatus"); - final long maritalStatusId = rs.getLong("maritalStatusId"); - final String gender = rs.getString("gender"); - final long genderId = rs.getLong("genderId"); - final LocalDate dateOfBirth = JdbcSupport.getLocalDate(rs, "dateOfBirth"); - 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); - - + @Override + 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 relationship = rs.getString("relationship"); + final long relationshipId = rs.getLong("relationshipId"); + final String maritalStatus = rs.getString("maritalStatus"); + final long maritalStatusId = rs.getLong("maritalStatusId"); + final String gender = rs.getString("gender"); + final long genderId = rs.getLong("genderId"); + final LocalDate dateOfBirth = JdbcSupport.getLocalDate(rs, "dateOfBirth"); + 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); + + - } - } - - - @Override - public Collection getClientFamilyMembers(long clientId) { + } + } + + + @Override + public Collection getClientFamilyMembers(long clientId) { - this.context.authenticatedUser(); + this.context.authenticatedUser(); - final ClientFamilyMembersMapper rm = new ClientFamilyMembersMapper(); - final String sql = "select " + rm.schema() + " where fmb.client_id=?"; + final ClientFamilyMembersMapper rm = new ClientFamilyMembersMapper(); + final String sql = "select " + rm.schema() + " where fmb.client_id=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { clientId }); - } - - - @Override - public ClientFamilyMembersData getClientFamilyMember(long id) { + return this.jdbcTemplate.query(sql, rm, new Object[] { clientId }); + } + + + @Override + public ClientFamilyMembersData getClientFamilyMember(long id) { - this.context.authenticatedUser(); + this.context.authenticatedUser(); - final ClientFamilyMembersMapper rm = new ClientFamilyMembersMapper(); - final String sql = "select " + rm.schema() + " where fmb.id=? "; + final ClientFamilyMembersMapper rm = new ClientFamilyMembersMapper(); + final String sql = "select " + rm.schema() + " where fmb.id=? "; - return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { id }); - } - - @Override - public ClientFamilyMembersData retrieveTemplate() { - - final List maritalStatusOptions = new ArrayList<>( - this.codeValueReadPlatformService.retrieveCodeValuesByCode("MARITAL STATUS")); + return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { id }); + } + + @Override + public ClientFamilyMembersData retrieveTemplate() { + + final List maritalStatusOptions = new ArrayList<>( + this.codeValueReadPlatformService.retrieveCodeValuesByCode("MARITAL STATUS")); - final List genderOptions = new ArrayList<>(this.codeValueReadPlatformService.retrieveCodeValuesByCode("Gender")); + final List genderOptions = new ArrayList<>(this.codeValueReadPlatformService.retrieveCodeValuesByCode("Gender")); - final List relationshipOptions = new ArrayList<>( - this.codeValueReadPlatformService.retrieveCodeValuesByCode("RELATIONSHIP")); - - final List professionOptions = new ArrayList<>( - this.codeValueReadPlatformService.retrieveCodeValuesByCode("PROFESSION")); + final List relationshipOptions = new ArrayList<>( + this.codeValueReadPlatformService.retrieveCodeValuesByCode("RELATIONSHIP")); + + 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 2667f4df5..47d3bb51f 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 @@ -25,13 +25,13 @@ import org.apache.fineract.portfolio.client.domain.Client; public interface ClientFamilyMembersWritePlatformService { - - CommandProcessingResult addFamilyMember(final long clientId,final JsonCommand command); - - CommandProcessingResult addClientFamilyMember(final Client client,final JsonCommand command); + + CommandProcessingResult addFamilyMember(final long clientId,final JsonCommand command); + + CommandProcessingResult addClientFamilyMember(final Client client,final JsonCommand command); - CommandProcessingResult updateFamilyMember(Long familyMemberId, JsonCommand command); + CommandProcessingResult updateFamilyMember(Long familyMemberId, JsonCommand command); - CommandProcessingResult deleteFamilyMember(Long familyMemberId, JsonCommand command); + CommandProcessingResult deleteFamilyMember(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 e8b7af70e..00835e9bc 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 @@ -45,404 +45,404 @@ import com.google.gson.JsonObject; @Service public class ClientFamilyMembersWritePlatformServiceImpl implements ClientFamilyMembersWritePlatformService { - - private final PlatformSecurityContext context; - private final CodeValueRepository codeValueRepository; - private final ClientFamilyMembersRepository clientFamilyRepository; - private final ClientRepositoryWrapper clientRepositoryWrapper; - 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; - - } - - + + private final PlatformSecurityContext context; + private final CodeValueRepository codeValueRepository; + private final ClientFamilyMembersRepository clientFamilyRepository; + private final ClientRepositoryWrapper clientRepositoryWrapper; + 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; + + } + + - @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; - - - this.context.authenticatedUser(); - apiJsonDeserializer.validateForCreate(clientId, command.json()); - - - 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"); - relationship = this.codeValueRepository.getOne(relationshipId); - } - - if (command.longValueOfParameterNamed("maritalStatusId") != null) { - maritalStatusId = command.longValueOfParameterNamed("maritalStatusId"); - maritalStatus = this.codeValueRepository.getOne(maritalStatusId); - } + @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; + + + this.context.authenticatedUser(); + apiJsonDeserializer.validateForCreate(clientId, command.json()); + + + 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"); + relationship = this.codeValueRepository.getOne(relationshipId); + } + + if (command.longValueOfParameterNamed("maritalStatusId") != null) { + maritalStatusId = command.longValueOfParameterNamed("maritalStatusId"); + maritalStatus = this.codeValueRepository.getOne(maritalStatusId); + } - if (command.longValueOfParameterNamed("genderId") != null) { - genderId = command.longValueOfParameterNamed("genderId"); - gender = this.codeValueRepository.getOne(genderId); - } - - if (command.longValueOfParameterNamed("professionId") != null) { - professionId = command.longValueOfParameterNamed("professionId"); - profession = this.codeValueRepository.getOne(professionId); - } - - 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); - - this.clientFamilyRepository.save(clientFamilyMembers); - - 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; - - - - - this.context.authenticatedUser(); - - - //Client client=clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); - - ClientFamilyMembers familyMember=new ClientFamilyMembers(); - - //apiJsonDeserializer.validateForCreate(command.json()); - - - JsonArray familyMembers=command.arrayOfParameterNamed("familyMembers"); - - for(JsonElement members :familyMembers) - { - - apiJsonDeserializer.validateForCreate(members.toString()); - - 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(); - relationship = this.codeValueRepository.getOne(relationshipId); - } - - if (member.get("maritalStatusId") != null) { - maritalStatusId = member.get("maritalStatusId").getAsLong(); - maritalStatus = this.codeValueRepository.getOne(maritalStatusId); - } + if (command.longValueOfParameterNamed("genderId") != null) { + genderId = command.longValueOfParameterNamed("genderId"); + gender = this.codeValueRepository.getOne(genderId); + } + + if (command.longValueOfParameterNamed("professionId") != null) { + professionId = command.longValueOfParameterNamed("professionId"); + profession = this.codeValueRepository.getOne(professionId); + } + + 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); + + this.clientFamilyRepository.save(clientFamilyMembers); + + 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; + + + + + this.context.authenticatedUser(); + + + //Client client=clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); + + ClientFamilyMembers familyMember=new ClientFamilyMembers(); + + //apiJsonDeserializer.validateForCreate(command.json()); + + + JsonArray familyMembers=command.arrayOfParameterNamed("familyMembers"); + + for(JsonElement members :familyMembers) + { + + apiJsonDeserializer.validateForCreate(members.toString()); + + 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(); + relationship = this.codeValueRepository.getOne(relationshipId); + } + + if (member.get("maritalStatusId") != null) { + maritalStatusId = member.get("maritalStatusId").getAsLong(); + maritalStatus = this.codeValueRepository.getOne(maritalStatusId); + } - if (member.get("genderId") != null) { - genderId = member.get("genderId").getAsLong(); - gender = this.codeValueRepository.getOne(genderId); - } - - if (member.get("professionId") != null) { - professionId = member.get("professionId").getAsLong(); - profession = this.codeValueRepository.getOne(professionId); - } - - 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; - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - - /* this.fromApiJsonHelper.extractDateFormatParameter(member.get("dateOfBirth").getAsJsonObject());*/ - - - } - - 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(); - - - } + if (member.get("genderId") != null) { + genderId = member.get("genderId").getAsLong(); + gender = this.codeValueRepository.getOne(genderId); + } + + if (member.get("professionId") != null) { + professionId = member.get("professionId").getAsLong(); + profession = this.codeValueRepository.getOne(professionId); + } + + 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; + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + + /* this.fromApiJsonHelper.extractDateFormatParameter(member.get("dateOfBirth").getAsJsonObject());*/ + + + } + + 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(); + + + } - @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; - - - this.context.authenticatedUser(); - - apiJsonDeserializer.validateForUpdate(familyMemberId, command.json()); - - /*if (command.stringValueOfParameterNamed("clientFamilyMemberId") != null) { - clientFamilyMemberId = command.longValueOfParameterNamed("clientFamilyMemberId"); - }*/ - - - ClientFamilyMembers clientFamilyMember=clientFamilyRepository.getOne(familyMemberId); - - //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"); - relationship = this.codeValueRepository.getOne(relationshipId); - clientFamilyMember.setRelationship(relationship); - } - - if (command.longValueOfParameterNamed("maritalStatusId") != null) { - maritalStatusId = command.longValueOfParameterNamed("maritalStatusId"); - maritalStatus = this.codeValueRepository.getOne(maritalStatusId); - clientFamilyMember.setMaritalStatus(maritalStatus); - } + @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; + + + this.context.authenticatedUser(); + + apiJsonDeserializer.validateForUpdate(familyMemberId, command.json()); + + /*if (command.stringValueOfParameterNamed("clientFamilyMemberId") != null) { + clientFamilyMemberId = command.longValueOfParameterNamed("clientFamilyMemberId"); + }*/ + + + ClientFamilyMembers clientFamilyMember=clientFamilyRepository.getOne(familyMemberId); + + //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"); + relationship = this.codeValueRepository.getOne(relationshipId); + clientFamilyMember.setRelationship(relationship); + } + + if (command.longValueOfParameterNamed("maritalStatusId") != null) { + maritalStatusId = command.longValueOfParameterNamed("maritalStatusId"); + maritalStatus = this.codeValueRepository.getOne(maritalStatusId); + clientFamilyMember.setMaritalStatus(maritalStatus); + } - if (command.longValueOfParameterNamed("genderId") != null) { - genderId = command.longValueOfParameterNamed("genderId"); - gender = this.codeValueRepository.getOne(genderId); - clientFamilyMember.setGender(gender); - } - - if (command.longValueOfParameterNamed("professionId") != null) { - professionId = command.longValueOfParameterNamed("professionId"); - profession = this.codeValueRepository.getOne(professionId); - clientFamilyMember.setProfession(profession); - } - - 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); - - this.clientFamilyRepository.save(clientFamilyMember); - - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(clientFamilyMember.getId()).build(); - } + if (command.longValueOfParameterNamed("genderId") != null) { + genderId = command.longValueOfParameterNamed("genderId"); + gender = this.codeValueRepository.getOne(genderId); + clientFamilyMember.setGender(gender); + } + + if (command.longValueOfParameterNamed("professionId") != null) { + professionId = command.longValueOfParameterNamed("professionId"); + profession = this.codeValueRepository.getOne(professionId); + clientFamilyMember.setProfession(profession); + } + + 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); + + this.clientFamilyRepository.save(clientFamilyMember); + + return new CommandProcessingResultBuilder().withCommandId(command.commandId()) + .withEntityId(clientFamilyMember.getId()).build(); + } - @Override - public CommandProcessingResult deleteFamilyMember(Long clientFamilyMemberId, JsonCommand command) { - // TODO Auto-generated method stub - - this.context.authenticatedUser(); - - apiJsonDeserializer.validateForDelete(clientFamilyMemberId); - - ClientFamilyMembers clientFamilyMember=null; - - - - 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(); - } - - } - - - + @Override + public CommandProcessingResult deleteFamilyMember(Long clientFamilyMemberId, JsonCommand command) { + // TODO Auto-generated method stub + + this.context.authenticatedUser(); + + apiJsonDeserializer.validateForDelete(clientFamilyMemberId); + + ClientFamilyMembers clientFamilyMember=null; + + + + 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(); + } + + } + + + } 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 index 1280b4a75..1806612ad 100755 --- 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 @@ -103,9 +103,9 @@ public class ClientIdentifierWritePlatformServiceJpaRepositoryImpl implements Cl handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -165,9 +165,9 @@ public class ClientIdentifierWritePlatformServiceJpaRepositoryImpl implements Cl handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve.getMostSpecificCause(), dve); return new CommandProcessingResult(Long.valueOf(-1)); }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, throwable, dve); + return CommandProcessingResult.empty(); } } 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 c2cdb35bc..7859dff5e 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 @@ -47,7 +47,7 @@ public interface ClientReadPlatformService { ClientData retrieveAllNarrations(String clientNarrations); - Date retrieveClientTransferProposalDate(Long clientId); + Date retrieveClientTransferProposalDate(Long clientId); - void validateClient(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 1e45cc75c..d7bc1ef69 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 @@ -105,8 +105,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final AddressReadPlatformService addressReadPlatformService,final ClientFamilyMembersReadPlatformService clientFamilyMembersReadPlatformService, final ConfigurationReadPlatformService configurationReadPlatformService, final EntityDatatableChecksReadService entityDatatableChecksReadService, - final ColumnValidator columnValidator) { - this.context = context; + final ColumnValidator columnValidator) { + this.context = context; this.officeReadPlatformService = officeReadPlatformService; this.jdbcTemplate = new JdbcTemplate(dataSource); this.staffReadPlatformService = staffReadPlatformService; @@ -117,7 +117,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService this.configurationReadPlatformService=configurationReadPlatformService; this.entityDatatableChecksReadService = entityDatatableChecksReadService; this.columnValidator = columnValidator; - } + } @Override public ClientData retrieveTemplate(final Long officeId, final boolean staffInSelectedOfficeOnly) { @@ -135,7 +135,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final Boolean isAddressEnabled=configuration.isEnabled(); if(isAddressEnabled) { - address = this.addressReadPlatformService.retrieveTemplate(); + address = this.addressReadPlatformService.retrieveTemplate(); } final ClientFamilyMembersData familyMemberOptions=this.clientFamilyMembersReadPlatformService.retrieveTemplate(); @@ -174,9 +174,9 @@ 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) @@ -251,33 +251,33 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService } if (externalId != null) { - paramList.add(externalId); + paramList.add(externalId); extraCriteria += " and c.external_id like ? " ; } if (displayName != null) { //extraCriteria += " and concat(ifnull(c.firstname, ''), if(c.firstname > '',' ', '') , ifnull(c.lastname, '')) like " - paramList.add("%" + displayName + "%"); - extraCriteria += " and c.display_name like ? "; + paramList.add("%" + displayName + "%"); + extraCriteria += " and c.display_name like ? "; } if (firstname != null) { - paramList.add(firstname); + paramList.add(firstname); extraCriteria += " and c.firstname like ? " ; } if (lastname != null) { - paramList.add(lastname); + paramList.add(lastname); extraCriteria += " and c.lastname like ? "; } if (searchParameters.isScopedByOfficeHierarchy()) { - paramList.add(searchParameters.getHierarchy() + "%"); + paramList.add(searchParameters.getHierarchy() + "%"); extraCriteria += " and o.hierarchy like ? "; } if(searchParameters.isOrphansOnly()){ - extraCriteria += " and c.id NOT IN (select client_id from m_group_client) "; + extraCriteria += " and c.id NOT IN (select client_id from m_group_client) "; } if (StringUtils.isNotBlank(extraCriteria)) { @@ -370,8 +370,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService 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, "); sqlBuilder.append("c.mobile_no as mobileNo, "); - sqlBuilder.append("c.is_staff as isStaff, "); - sqlBuilder.append("c.email_address as emailAddress, "); + sqlBuilder.append("c.is_staff as isStaff, "); + sqlBuilder.append("c.email_address as emailAddress, "); sqlBuilder.append("c.date_of_birth as dateOfBirth, "); sqlBuilder.append("c.gender_cv_id as genderId, "); sqlBuilder.append("cv.code_value as genderValue, "); @@ -460,8 +460,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final String displayName = rs.getString("displayName"); final String externalId = rs.getString("externalId"); final String mobileNo = rs.getString("mobileNo"); - final boolean isStaff = rs.getBoolean("isStaff"); - final String emailAddress = rs.getString("emailAddress"); + final boolean isStaff = rs.getBoolean("isStaff"); + final String emailAddress = rs.getString("emailAddress"); final LocalDate dateOfBirth = JdbcSupport.getLocalDate(rs, "dateOfBirth"); final Long genderId = JdbcSupport.getLong(rs, "genderId"); final String genderValue = rs.getString("genderValue"); @@ -502,7 +502,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final Integer legalFormEnum = JdbcSupport.getInteger(rs, "legalFormEnum"); EnumOptionData legalForm = null; if(legalFormEnum != null) - legalForm = ClientEnumerations.legalForm(legalFormEnum); + legalForm = ClientEnumerations.legalForm(legalFormEnum); final Long constitutionId = JdbcSupport.getLong(rs, "constitutionId"); final String constitutionValue = rs.getString("constitutionValue"); @@ -556,8 +556,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService 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, "); builder.append("c.mobile_no as mobileNo, "); - builder.append("c.is_staff as isStaff, "); - builder.append("c.email_address as emailAddress, "); + builder.append("c.is_staff as isStaff, "); + builder.append("c.email_address as emailAddress, "); builder.append("c.date_of_birth as dateOfBirth, "); builder.append("c.gender_cv_id as genderId, "); builder.append("cv.code_value as genderValue, "); @@ -645,8 +645,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final String displayName = rs.getString("displayName"); final String externalId = rs.getString("externalId"); final String mobileNo = rs.getString("mobileNo"); - final boolean isStaff = rs.getBoolean("isStaff"); - final String emailAddress = rs.getString("emailAddress"); + final boolean isStaff = rs.getBoolean("isStaff"); + final String emailAddress = rs.getString("emailAddress"); final LocalDate dateOfBirth = JdbcSupport.getLocalDate(rs, "dateOfBirth"); final Long genderId = JdbcSupport.getLong(rs, "genderId"); final String genderValue = rs.getString("genderValue"); @@ -686,7 +686,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final Integer legalFormEnum = JdbcSupport.getInteger(rs, "legalFormEnum"); EnumOptionData legalForm = null; if(legalFormEnum != null) - legalForm = ClientEnumerations.legalForm(legalFormEnum); + legalForm = ClientEnumerations.legalForm(legalFormEnum); final Long constitutionId = JdbcSupport.getLong(rs, "constitutionId"); final String constitutionValue = rs.getString("constitutionValue"); @@ -819,28 +819,28 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService 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 - public Date retrieveClientTransferProposalDate(Long clientId) { - validateClient(clientId); - final String sql = "SELECT cl.proposed_transfer_date FROM m_client cl WHERE cl.id =? "; - try { - return this.jdbcTemplate.queryForObject(sql, Date.class, clientId); - } catch (final EmptyResultDataAccessException e) { - return null; - } - } + @Override + public Date retrieveClientTransferProposalDate(Long clientId) { + validateClient(clientId); + final String sql = "SELECT cl.proposed_transfer_date FROM m_client cl WHERE cl.id =? "; + try { + return this.jdbcTemplate.queryForObject(sql, Date.class, clientId); + } catch (final EmptyResultDataAccessException e) { + return null; + } + } - @Override - public void validateClient(Long clientId) { - try { - final String sql = "SELECT cl.id FROM m_client cl WHERE cl.id =? "; - this.jdbcTemplate.queryForObject(sql, Long.class, clientId); - } catch (final EmptyResultDataAccessException e) { - throw new ClientNotFoundException(clientId); - } - } + @Override + public void validateClient(Long clientId) { + try { + final String sql = "SELECT cl.id FROM m_client cl WHERE cl.id =? "; + this.jdbcTemplate.queryForObject(sql, Long.class, clientId); + } catch (final EmptyResultDataAccessException e) { + throw new ClientNotFoundException(clientId); + } + } } \ 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 c520aff1a..2c06b8ff2 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 @@ -45,9 +45,9 @@ public interface ClientWritePlatformService { CommandProcessingResult reActivateClient(Long entityId, JsonCommand command); - CommandProcessingResult undoRejection(Long entityId, JsonCommand command); - - CommandProcessingResult undoWithdrawal(Long entityId, JsonCommand command); + CommandProcessingResult undoRejection(Long entityId, JsonCommand command); + + 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 02b61bf0c..dafe44e42 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 @@ -227,12 +227,12 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP this.fromApiJsonDeserializer.validateForCreate(command.json()); - final GlobalConfigurationPropertyData configuration = this.configurationReadPlatformService - .retrieveGlobalConfiguration("Enable-Address"); + final GlobalConfigurationPropertyData configuration = this.configurationReadPlatformService + .retrieveGlobalConfiguration("Enable-Address"); - final Boolean isAddressEnabled = configuration.isEnabled(); + final Boolean isAddressEnabled = configuration.isEnabled(); - final Boolean isStaff = command.booleanObjectValueOfParameterNamed(ClientApiConstants.isStaffParamName); + final Boolean isStaff = command.booleanObjectValueOfParameterNamed(ClientApiConstants.isStaffParamName); final Long officeId = command.longValueOfParameterNamed(ClientApiConstants.officeIdParamName); @@ -284,11 +284,11 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP Integer legalFormValue = null; if(legalFormParamValue != null) { - LegalForm legalForm = LegalForm.fromInt(legalFormParamValue); - if(legalForm != null) + LegalForm legalForm = LegalForm.fromInt(legalFormParamValue); + if(legalForm != null) { - legalFormValue = legalForm.getValue(); - isEntity = legalForm.isEntity(); + legalFormValue = legalForm.getValue(); + isEntity = legalForm.isEntity(); } } @@ -333,7 +333,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP if(command.arrayOfParameterNamed("familyMembers")!=null) { - this.clientFamilyMembersWritePlatformService.addClientFamilyMember(newClient, command); + this.clientFamilyMembersWritePlatformService.addClientFamilyMember(newClient, command); } if(command.parameterExists(ClientApiConstants.datatables)){ @@ -361,9 +361,9 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -374,37 +374,37 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP */ public void extractAndCreateClientNonPerson(Client client, JsonCommand command) { - final JsonElement clientNonPersonElement = this.fromApiJsonHelper.parse(command.jsonFragment(ClientApiConstants.clientNonPersonDetailsParamName)); + final JsonElement clientNonPersonElement = this.fromApiJsonHelper.parse(command.jsonFragment(ClientApiConstants.clientNonPersonDetailsParamName)); - 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); + 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); - //JsonCommand clientNonPersonCommand = JsonCommand.fromExistingCommand(command, command.arrayOfParameterNamed(ClientApiConstants.clientNonPersonDetailsParamName).getAsJsonObject()); - CodeValue clientNonPersonConstitution = null; - final Long clientNonPersonConstitutionId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.constitutionIdParamName, clientNonPersonElement); - if (clientNonPersonConstitutionId != null) { - clientNonPersonConstitution = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_NON_PERSON_CONSTITUTION, - clientNonPersonConstitutionId); - } + //JsonCommand clientNonPersonCommand = JsonCommand.fromExistingCommand(command, command.arrayOfParameterNamed(ClientApiConstants.clientNonPersonDetailsParamName).getAsJsonObject()); + CodeValue clientNonPersonConstitution = null; + final Long clientNonPersonConstitutionId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.constitutionIdParamName, clientNonPersonElement); + if (clientNonPersonConstitutionId != null) { + clientNonPersonConstitution = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_NON_PERSON_CONSTITUTION, + clientNonPersonConstitutionId); + } - CodeValue clientNonPersonMainBusinessLine = null; - final Long clientNonPersonMainBusinessLineId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.mainBusinessLineIdParamName, clientNonPersonElement); - if (clientNonPersonMainBusinessLineId != null) { - clientNonPersonMainBusinessLine = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_NON_PERSON_MAIN_BUSINESS_LINE, - clientNonPersonMainBusinessLineId); - } + CodeValue clientNonPersonMainBusinessLine = null; + final Long clientNonPersonMainBusinessLineId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.mainBusinessLineIdParamName, clientNonPersonElement); + if (clientNonPersonMainBusinessLineId != null) { + 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); - } + this.clientNonPersonRepository.save(newClientNonPerson); + } } public boolean isEmpty(final JsonElement element){ - return element.toString().trim().length()<4; + return element.toString().trim().length()<4; } @Transactional @@ -487,32 +487,32 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP } if (changes.containsKey(ClientApiConstants.legalFormIdParamName)) { - Integer legalFormValue = clientForUpdate.getLegalForm(); - boolean isChangedToEntity = false; - if(legalFormValue != null) - { - LegalForm legalForm = LegalForm.fromInt(legalFormValue); - if(legalForm != null) - isChangedToEntity = legalForm.isEntity(); - } + Integer legalFormValue = clientForUpdate.getLegalForm(); + boolean isChangedToEntity = false; + if(legalFormValue != null) + { + LegalForm legalForm = LegalForm.fromInt(legalFormValue); + if(legalForm != null) + isChangedToEntity = legalForm.isEntity(); + } if(isChangedToEntity) { - extractAndCreateClientNonPerson(clientForUpdate, command); + extractAndCreateClientNonPerson(clientForUpdate, command); } else { - final ClientNonPerson clientNonPerson = this.clientNonPersonRepository.findOneByClientId(clientForUpdate.getId()); - if(clientNonPerson != null) - this.clientNonPersonRepository.delete(clientNonPerson); + final ClientNonPerson clientNonPerson = this.clientNonPersonRepository.findOneByClientId(clientForUpdate.getId()); + if(clientNonPerson != null) + this.clientNonPersonRepository.delete(clientNonPerson); } } final ClientNonPerson clientNonPersonForUpdate = this.clientNonPersonRepository.findOneByClientId(clientId); if(clientNonPersonForUpdate != null) { - final JsonElement clientNonPersonElement = command.jsonElement(ClientApiConstants.clientNonPersonDetailsParamName); - final Map clientNonPersonChanges = clientNonPersonForUpdate.update(JsonCommand.fromExistingCommand(command, clientNonPersonElement)); + final JsonElement clientNonPersonElement = command.jsonElement(ClientApiConstants.clientNonPersonDetailsParamName); + final Map clientNonPersonChanges = clientNonPersonForUpdate.update(JsonCommand.fromExistingCommand(command, clientNonPersonElement)); if (clientNonPersonChanges.containsKey(ClientApiConstants.constitutionIdParamName)) { @@ -563,9 +563,9 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -905,60 +905,60 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP .build(); } - @Override - public CommandProcessingResult undoRejection(Long entityId, JsonCommand command) { - final AppUser currentUser = this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateUndoRejection(command); + @Override + public CommandProcessingResult undoRejection(Long entityId, JsonCommand command) { + final AppUser currentUser = this.context.authenticatedUser(); + this.fromApiJsonDeserializer.validateUndoRejection(command); - final Client client = this.clientRepository.findOneWithNotFoundDetection(entityId); - final LocalDate undoRejectDate = command - .localDateValueOfParameterNamed(ClientApiConstants.reopenedDateParamName); + final Client client = this.clientRepository.findOneWithNotFoundDetection(entityId); + 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()); - } + 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()); + } - client.reOpened(currentUser, undoRejectDate.toDate()); - this.clientRepository.saveAndFlush(client); + client.reOpened(currentUser, undoRejectDate.toDate()); + this.clientRepository.saveAndFlush(client); - return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withClientId(entityId) // - .withEntityId(entityId) // - .build(); - } + return new CommandProcessingResultBuilder() // + .withCommandId(command.commandId()) // + .withClientId(entityId) // + .withEntityId(entityId) // + .build(); + } - @Override - public CommandProcessingResult undoWithdrawal(Long entityId, JsonCommand command) { - final AppUser currentUser = this.context.authenticatedUser(); - this.fromApiJsonDeserializer.validateUndoWithDrawn(command); + @Override + public CommandProcessingResult undoWithdrawal(Long entityId, JsonCommand command) { + final AppUser currentUser = this.context.authenticatedUser(); + this.fromApiJsonDeserializer.validateUndoWithDrawn(command); - final Client client = this.clientRepository.findOneWithNotFoundDetection(entityId); - final LocalDate undoWithdrawalDate = command - .localDateValueOfParameterNamed(ClientApiConstants.reopenedDateParamName); + final Client client = this.clientRepository.findOneWithNotFoundDetection(entityId); + 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()); - } - client.reOpened(currentUser, undoWithdrawalDate.toDate()); - this.clientRepository.saveAndFlush(client); + 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()); + } + client.reOpened(currentUser, undoWithdrawalDate.toDate()); + this.clientRepository.saveAndFlush(client); - return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withClientId(entityId) // - .withEntityId(entityId) // - .build(); - } + return new CommandProcessingResultBuilder() // + .withCommandId(command.commandId()) // + .withClientId(entityId) // + .withEntityId(entityId) // + .build(); + } private Map constructEntityMap(final BUSINESS_ENTITY entityEvent, Object entity) { Map map = new HashMap<>(1); 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 ec6192e92..ed1b681a7 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 @@ -64,17 +64,17 @@ public class CollectionSheetTransactionDataValidator { 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)); + 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)); - private static final Set PAYMENT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(PaymentDetailConstants.accountNumberParamName, PaymentDetailConstants.checkNumberParamName, - PaymentDetailConstants.routingCodeParamName, PaymentDetailConstants.receiptNumberParamName, - PaymentDetailConstants.bankNumberParamName)); + private static final Set PAYMENT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(PaymentDetailConstants.accountNumberParamName, PaymentDetailConstants.checkNumberParamName, + PaymentDetailConstants.routingCodeParamName, PaymentDetailConstants.receiptNumberParamName, + PaymentDetailConstants.bankNumberParamName)); @Autowired public CollectionSheetTransactionDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -127,8 +127,8 @@ 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) 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 e09c29079..1128a02c8 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 @@ -68,8 +68,8 @@ public class SavingsDueData { return this.productId; } - public String getDepositAccountType() { - return depositAccountType; - } + public String getDepositAccountType() { + return depositAccountType; + } } \ 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 0d16d10ad..55788a9b5 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 @@ -95,7 +95,7 @@ public final class CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer ex detail = this.paymentDetailAssembler.fetchPaymentDetail(loanTransactionElement); } if(transactionAmount != null && transactionAmount.intValue() > 0){ - loanRepaymentTransactions[i] = new SingleRepaymentCommand(loanId, transactionAmount, transactionDate, detail); + loanRepaymentTransactions[i] = new SingleRepaymentCommand(loanId, transactionAmount, transactionDate, detail); } } } 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 6f7f4d6d3..81d8e8ca8 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 @@ -52,11 +52,11 @@ public class CollectionSheetGenerateCommandFromApiJsonDeserializer { /** * The parameters supported for this command. */ - final Set supportedParameters = new HashSet<>( - Arrays.asList(transactionDateParamName, localeParamName, dateFormatParamName, calendarIdParamName)); + 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; 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 f71330ee6..bb8858c40 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 @@ -343,9 +343,9 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe Long entityId = null; if(group.isChildGroup()){ - entityId = group.getParentId(); + entityId = group.getParentId(); }else{ - entityId = group.getId(); + entityId = group.getId(); } Boolean isSkipMeetingOnFirstDay = false; @@ -354,7 +354,7 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe if(isSkipRepaymentOnFirstMonthEnabled){ numberOfDays = this.configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); isSkipMeetingOnFirstDay = this.calendarReadPlatformService.isCalendarAssociatedWithEntity(entityId, calendar.getId(), - entityType.getValue().longValue()); + entityType.getValue().longValue()); } if (!calendar.isValidRecurringDate(transactionDate, isSkipMeetingOnFirstDay, numberOfDays)) { throw new NotValidRecurringDateException("collectionsheet", "The date '" 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 index 7b445859f..e8b70e559 100755 --- 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,55 +22,55 @@ 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"); - - private final Integer value; + 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; - + private DayOfWeekType(Integer value, String code) { - this.value = value; - this.code = code; - } + this.value = value; + this.code = code; + } - public Integer getValue() { - return this.value; - } + public Integer getValue() { + return this.value; + } - public String getCode() { - return this.code; - } - - public static DayOfWeekType fromInt(final Integer dayOfWeek) { - DayOfWeekType weekDayType = INVALID; + public String getCode() { + return this.code; + } + + public static DayOfWeekType fromInt(final Integer dayOfWeek) { + DayOfWeekType weekDayType = INVALID; if (dayOfWeek != null) { switch (dayOfWeek) { case 1: - weekDayType = MONDAY; + weekDayType = MONDAY; break; case 2: - weekDayType = TUESDAY; + weekDayType = TUESDAY; break; case 3: - weekDayType = WEDNESDAY; + weekDayType = WEDNESDAY; break; case 4: - weekDayType = THURSDAY; + weekDayType = THURSDAY; break; case 5: - weekDayType = FRIDAY; + weekDayType = FRIDAY; break; case 6: - weekDayType = SATURDAY; + weekDayType = SATURDAY; break; case 7: - weekDayType = SUNDAY; + weekDayType = SUNDAY; break; default: break; 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 index 7abb4454c..8e306ba64 100755 --- 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 @@ -19,34 +19,34 @@ 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"); - - private final Integer value; + + 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; - + private NthDayType(Integer value, String code) { - this.value = value; - this.code = code; - } + this.value = value; + this.code = code; + } - public Integer getValue() { - return this.value; - } + public Integer getValue() { + return this.value; + } - public String getCode() { - return this.code; - } - - public static NthDayType fromInt(final Integer frequency) { - NthDayType repaymentFrequencyNthDayType = NthDayType.INVALID; + public String getCode() { + return this.code; + } + + public static NthDayType fromInt(final Integer frequency) { + NthDayType repaymentFrequencyNthDayType = NthDayType.INVALID; if (frequency != null) { switch (frequency) { case 1: 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 ac24534a8..36d79281a 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 @@ -47,104 +47,104 @@ import java.util.Set; @Scope("singleton") @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")); - private final PlatformSecurityContext context; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final FloatingRatesReadPlatformService floatingRatesReadPlatformService; - private final ApiRequestParameterHelper apiRequestParameterHelper; + 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")); + private final PlatformSecurityContext context; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final FloatingRatesReadPlatformService floatingRatesReadPlatformService; + private final ApiRequestParameterHelper apiRequestParameterHelper; - @Autowired - public FloatingRatesApiResource( - final PlatformSecurityContext context, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, - final FloatingRatesReadPlatformService floatingRatesReadPlatformService) { - this.context = context; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - this.toApiJsonSerializer = toApiJsonSerializer; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.floatingRatesReadPlatformService = floatingRatesReadPlatformService; - } + @Autowired + public FloatingRatesApiResource( + final PlatformSecurityContext context, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final ApiRequestParameterHelper apiRequestParameterHelper, + final FloatingRatesReadPlatformService floatingRatesReadPlatformService) { + this.context = context; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.floatingRatesReadPlatformService = floatingRatesReadPlatformService; + } - @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)}) - public String createFloatingRate(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @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)}) + 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); - return this.toApiJsonSerializer.serialize(result); - } + final CommandWrapper commandRequest = new CommandWrapperBuilder() + .createFloatingRate().withJson(apiRequestBodyAsJson).build(); + final CommandProcessingResult result = this.commandsSourceWritePlatformService + .logCommandSource(commandRequest); + return this.toApiJsonSerializer.serialize(result); + } - @GET - @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")}) - 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); - } + @GET + @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")}) + 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); + } - @GET - @Path("{floatingRateId}") - @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, - @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); - } + @GET + @Path("{floatingRateId}") + @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, + @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); + } - @PUT - @Path("{floatingRateId}") - @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, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .updateFloatingRate(floatingRateId) - .withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } + @PUT + @Path("{floatingRateId}") + @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, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + 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/data/FloatingRateData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/FloatingRateData.java index 7116a0c59..c00598981 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 @@ -29,118 +29,118 @@ import java.util.List; public class FloatingRateData implements Comparable , Serializable { - private final Long id; - private final String name; - private final boolean isBaseLendingRate; - private final boolean isActive; - private final String createdBy; - private final LocalDate createdOn; - private final String modifiedBy; - private final LocalDate modifiedOn; - private final List ratePeriods; - @SuppressWarnings("unused") - private final List interestRateFrequencyTypeOptions; + private final Long id; + private final String name; + private final boolean isBaseLendingRate; + private final boolean isActive; + private final String createdBy; + private final LocalDate createdOn; + private final String modifiedBy; + private final LocalDate modifiedOn; + private final List ratePeriods; + @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, - List interestRateFrequencyTypeOptions) { - this.id = id; - this.name = name; - this.isBaseLendingRate = isBaseLendingRate; - this.isActive = isActive; - this.createdBy = createdBy; - this.createdOn = createdOn; - this.modifiedBy = modifiedBy; - this.modifiedOn = modifiedOn; - this.ratePeriods = ratePeriods; - this.interestRateFrequencyTypeOptions = interestRateFrequencyTypeOptions; - } + 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; + this.isBaseLendingRate = isBaseLendingRate; + this.isActive = isActive; + this.createdBy = createdBy; + this.createdOn = createdOn; + this.modifiedBy = modifiedBy; + this.modifiedOn = modifiedOn; + this.ratePeriods = ratePeriods; + this.interestRateFrequencyTypeOptions = interestRateFrequencyTypeOptions; + } - public Long getId() { - return this.id; - } + public Long getId() { + return this.id; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public boolean isBaseLendingRate() { - return this.isBaseLendingRate; - } + public boolean isBaseLendingRate() { + return this.isBaseLendingRate; + } - public boolean isActive() { - return this.isActive; - } + public boolean isActive() { + return this.isActive; + } - public String getCreatedBy() { - return this.createdBy; - } + public String getCreatedBy() { + return this.createdBy; + } - public LocalDate getCreatedOn() { - return this.createdOn; - } + public LocalDate getCreatedOn() { + return this.createdOn; + } - public String getModifiedBy() { - return this.modifiedBy; - } + public String getModifiedBy() { + return this.modifiedBy; + } - public LocalDate getModifiedOn() { - return this.modifiedOn; - } + public LocalDate getModifiedOn() { + return this.modifiedOn; + } - public List getRatePeriods() { - return this.ratePeriods; - } + public List getRatePeriods() { + return this.ratePeriods; + } - @Override - public int compareTo(final FloatingRateData obj) { - if (obj == null) { - return -1; - } - return new CompareToBuilder() // - .append(this.id, obj.id) // - .append(this.name, obj.name) // - .append(this.isBaseLendingRate, obj.isBaseLendingRate) // - .append(this.isActive, obj.isActive) // - .toComparison(); - } + @Override + public int compareTo(final FloatingRateData obj) { + if (obj == null) { + return -1; + } + return new CompareToBuilder() // + .append(this.id, obj.id) // + .append(this.name, obj.name) // + .append(this.isBaseLendingRate, obj.isBaseLendingRate) // + .append(this.isActive, obj.isActive) // + .toComparison(); + } - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj.getClass() != getClass()) { - return false; - } - final FloatingRateData rhs = (FloatingRateData) obj; - return new EqualsBuilder() // - .append(this.id, rhs.id) // - .append(this.name, rhs.name) // - .append(this.isBaseLendingRate, rhs.isBaseLendingRate) // - .append(this.isActive, rhs.isActive) // - .isEquals(); - } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (obj == this) { + return true; + } + if (obj.getClass() != getClass()) { + return false; + } + final FloatingRateData rhs = (FloatingRateData) obj; + return new EqualsBuilder() // + .append(this.id, rhs.id) // + .append(this.name, rhs.name) // + .append(this.isBaseLendingRate, rhs.isBaseLendingRate) // + .append(this.isActive, rhs.isActive) // + .isEquals(); + } - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) // - .append(this.id) // - .append(this.name) // - .append(this.isBaseLendingRate) // - .append(this.isActive) // - .toHashCode(); - } + @Override + public int hashCode() { + return new HashCodeBuilder(17, 37) // + .append(this.id) // + .append(this.name) // + .append(this.isBaseLendingRate) // + .append(this.isActive) // + .toHashCode(); + } - public static FloatingRateData toTemplate( - List interestRateFrequencyTypeOptions) { - // TODO Auto-generated method stub - return new FloatingRateData(null, null, false, true, null, null, null, - null, null, 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); + } } 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 a9edce031..4a9164d0c 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 @@ -27,110 +27,110 @@ import java.io.Serializable; import java.math.BigDecimal; public class FloatingRatePeriodData implements - Comparable, Serializable { + Comparable, Serializable { - private Long id; - private LocalDate fromDate; - private BigDecimal interestRate; - private boolean isDifferentialToBaseLendingRate; - private boolean isActive; - private String createdBy; - private LocalDate createdOn; - private String modifiedBy; - private LocalDate modifiedOn; + private Long id; + private LocalDate fromDate; + private BigDecimal interestRate; + private boolean isDifferentialToBaseLendingRate; + private boolean isActive; + private String createdBy; + private LocalDate createdOn; + 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) { - this.id = id; - this.fromDate = fromDate; - this.interestRate = interestRate; - this.isDifferentialToBaseLendingRate = isDifferentialToBaseLendingRate; - this.isActive = isActive; - this.createdBy = createdBy; - this.createdOn = createdOn; - this.modifiedBy = modifiedBy; - this.modifiedOn = 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; + this.isDifferentialToBaseLendingRate = isDifferentialToBaseLendingRate; + this.isActive = isActive; + this.createdBy = createdBy; + this.createdOn = createdOn; + this.modifiedBy = modifiedBy; + this.modifiedOn = modifiedOn; + } - public Long getId() { - return this.id; - } + public Long getId() { + return this.id; + } - public LocalDate getFromDate() { - return this.fromDate; - } + public LocalDate getFromDate() { + return this.fromDate; + } - public LocalDate getFromDateAsLocalDate() { - return new LocalDate(this.fromDate); - } + public LocalDate getFromDateAsLocalDate() { + return new LocalDate(this.fromDate); + } - public BigDecimal getInterestRate() { - return this.interestRate; - } + public BigDecimal getInterestRate() { + return this.interestRate; + } - public boolean isDifferentialToBaseLendingRate() { - return this.isDifferentialToBaseLendingRate; - } + public boolean isDifferentialToBaseLendingRate() { + return this.isDifferentialToBaseLendingRate; + } - public boolean isActive() { - return this.isActive; - } + public boolean isActive() { + return this.isActive; + } - public String getCreatedBy() { - return this.createdBy; - } + public String getCreatedBy() { + return this.createdBy; + } - public LocalDate getCreatedOn() { - return this.createdOn; - } + public LocalDate getCreatedOn() { + return this.createdOn; + } - public String getModifiedBy() { - return this.modifiedBy; - } + public String getModifiedBy() { + return this.modifiedBy; + } - public LocalDate getModifiedOn() { - return this.modifiedOn; - } + public LocalDate getModifiedOn() { + return this.modifiedOn; + } - @Override - public int compareTo(final FloatingRatePeriodData obj) { - if (obj == null) { - return -1; - } - return new CompareToBuilder() // - .append(this.id, obj.id) // - .append(this.fromDate, obj.fromDate) // - .append(this.isActive, obj.isActive) // - .toComparison(); - } + @Override + public int compareTo(final FloatingRatePeriodData obj) { + if (obj == null) { + return -1; + } + return new CompareToBuilder() // + .append(this.id, obj.id) // + .append(this.fromDate, obj.fromDate) // + .append(this.isActive, obj.isActive) // + .toComparison(); + } - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj.getClass() != getClass()) { - return false; - } - final FloatingRatePeriodData rhs = (FloatingRatePeriodData) obj; - return new EqualsBuilder() // - .append(this.id, rhs.id) // - .append(this.fromDate, rhs.fromDate) // - .append(this.isActive, rhs.isActive) // - .isEquals(); - } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (obj == this) { + return true; + } + if (obj.getClass() != getClass()) { + return false; + } + final FloatingRatePeriodData rhs = (FloatingRatePeriodData) obj; + return new EqualsBuilder() // + .append(this.id, rhs.id) // + .append(this.fromDate, rhs.fromDate) // + .append(this.isActive, rhs.isActive) // + .isEquals(); + } - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) // - .append(this.id) // - .append(this.fromDate) // - .append(this.isActive) // - .toHashCode(); - } + @Override + public int hashCode() { + return new HashCodeBuilder(17, 37) // + .append(this.id) // + .append(this.fromDate) // + .append(this.isActive) // + .toHashCode(); + } } 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 e3f01857c..ebc9b022f 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 @@ -23,72 +23,72 @@ import java.util.Date; public class InterestRatePeriodData { - private Date fromDate; - private final BigDecimal interestRate; - private final boolean isDifferentialToBLR; - private final Date blrFromDate; - private final BigDecimal blrInterestRate; - private BigDecimal loanDifferentialInterestRate; - private BigDecimal loanProductDifferentialInterestRate; - private BigDecimal effectiveInterestRate; + private Date fromDate; + private final BigDecimal interestRate; + private final boolean isDifferentialToBLR; + private final Date blrFromDate; + private final BigDecimal blrInterestRate; + private BigDecimal loanDifferentialInterestRate; + private BigDecimal loanProductDifferentialInterestRate; + private BigDecimal effectiveInterestRate; - public InterestRatePeriodData(Date fromDate, BigDecimal interestRate, - boolean isDifferentialToBLR, Date blrFromDate, - BigDecimal blrInterestRate) { - this.fromDate = fromDate; - this.interestRate = interestRate; - this.isDifferentialToBLR = isDifferentialToBLR; - this.blrFromDate = blrFromDate; - this.blrInterestRate = blrInterestRate; - } + public InterestRatePeriodData(Date fromDate, BigDecimal interestRate, + boolean isDifferentialToBLR, Date blrFromDate, + BigDecimal blrInterestRate) { + this.fromDate = fromDate; + this.interestRate = interestRate; + this.isDifferentialToBLR = isDifferentialToBLR; + this.blrFromDate = blrFromDate; + this.blrInterestRate = blrInterestRate; + } - public Date getFromDate() { - return this.fromDate; - } + public Date getFromDate() { + return this.fromDate; + } - public void setFromDate(Date fromDate) { - this.fromDate = fromDate; - } + public void setFromDate(Date fromDate) { + this.fromDate = fromDate; + } - public BigDecimal getInterestRate() { - return this.interestRate; - } + public BigDecimal getInterestRate() { + return this.interestRate; + } - public boolean isDifferentialToBLR() { - return this.isDifferentialToBLR; - } + public boolean isDifferentialToBLR() { + return this.isDifferentialToBLR; + } - public Date getBlrFromDate() { - return this.blrFromDate; - } + public Date getBlrFromDate() { + return this.blrFromDate; + } - public BigDecimal getBlrInterestRate() { - return this.blrInterestRate; - } + public BigDecimal getBlrInterestRate() { + return this.blrInterestRate; + } - public BigDecimal getLoanDifferentialInterestRate() { - return this.loanDifferentialInterestRate; - } + public BigDecimal getLoanDifferentialInterestRate() { + return this.loanDifferentialInterestRate; + } - public void setLoanDifferentialInterestRate( - BigDecimal loanDifferentialInterestRate) { - this.loanDifferentialInterestRate = loanDifferentialInterestRate; - } + public void setLoanDifferentialInterestRate( + BigDecimal loanDifferentialInterestRate) { + this.loanDifferentialInterestRate = loanDifferentialInterestRate; + } - public BigDecimal getLoanProductDifferentialInterestRate() { - return this.loanProductDifferentialInterestRate; - } + public BigDecimal getLoanProductDifferentialInterestRate() { + return this.loanProductDifferentialInterestRate; + } - public void setLoanProductDifferentialInterestRate( - BigDecimal loanProductDifferentialInterestRate) { - this.loanProductDifferentialInterestRate = loanProductDifferentialInterestRate; - } + public void setLoanProductDifferentialInterestRate( + BigDecimal loanProductDifferentialInterestRate) { + this.loanProductDifferentialInterestRate = loanProductDifferentialInterestRate; + } - public BigDecimal getEffectiveInterestRate() { - return this.effectiveInterestRate; - } + public BigDecimal getEffectiveInterestRate() { + return this.effectiveInterestRate; + } - public void setEffectiveInterestRate(BigDecimal effectiveInterestRate) { - this.effectiveInterestRate = effectiveInterestRate; - } + public void setEffectiveInterestRate(BigDecimal effectiveInterestRate) { + this.effectiveInterestRate = effectiveInterestRate; + } } 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 191347957..0289361e6 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 @@ -40,226 +40,226 @@ import com.google.gson.JsonObject; @Table(name = "m_floating_rates", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "unq_name") }) public class FloatingRate extends AbstractPersistableCustom { - @Column(name = "name", length = 200, unique = true, nullable = false) - private String name; + @Column(name = "name", length = 200, unique = true, nullable = false) + private String name; - @Column(name = "is_base_lending_rate", nullable = false) - private boolean isBaseLendingRate; + @Column(name = "is_base_lending_rate", nullable = false) + private boolean isBaseLendingRate; - @Column(name = "is_active", nullable = false) - private boolean isActive; + @Column(name = "is_active", nullable = false) + private boolean isActive; - @OrderBy(value = "fromDate,id") - @OneToMany(cascade = CascadeType.ALL, mappedBy = "floatingRate", orphanRemoval = true, fetch=FetchType.EAGER) - private List floatingRatePeriods; + @OrderBy(value = "fromDate,id") + @OneToMany(cascade = CascadeType.ALL, mappedBy = "floatingRate", orphanRemoval = true, fetch=FetchType.EAGER) + private List floatingRatePeriods; - @ManyToOne(optional = true, fetch=FetchType.LAZY) - @JoinColumn(name = "createdby_id", nullable = false) - private AppUser createdBy; + @ManyToOne(optional = true, fetch=FetchType.LAZY) + @JoinColumn(name = "createdby_id", nullable = false) + private AppUser createdBy; - @ManyToOne(optional = true, fetch=FetchType.LAZY) - @JoinColumn(name = "lastmodifiedby_id", nullable = false) - private AppUser modifiedBy; + @ManyToOne(optional = true, fetch=FetchType.LAZY) + @JoinColumn(name = "lastmodifiedby_id", nullable = false) + private AppUser modifiedBy; - @Column(name = "created_date", nullable = false) - private Date createdOn; + @Column(name = "created_date", nullable = false) + private Date createdOn; - @Column(name = "lastmodified_date", nullable = false) - private Date modifiedOn; + @Column(name = "lastmodified_date", nullable = false) + private Date modifiedOn; - public FloatingRate() { + public FloatingRate() { - } + } - 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; - this.floatingRatePeriods = floatingRatePeriods; - this.createdBy = createdBy; - this.createdOn = createdOn; - this.modifiedBy = modifiedBy; - this.modifiedOn = modifiedOn; - if (floatingRatePeriods != null) { - for (FloatingRatePeriod ratePeriod : floatingRatePeriods) { - ratePeriod.updateFloatingRate(this); - } - } - } + 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; + this.floatingRatePeriods = floatingRatePeriods; + this.createdBy = createdBy; + this.createdOn = createdOn; + this.modifiedBy = modifiedBy; + this.modifiedOn = modifiedOn; + if (floatingRatePeriods != null) { + for (FloatingRatePeriod ratePeriod : floatingRatePeriods) { + ratePeriod.updateFloatingRate(this); + } + } + } - 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") - : false; - final boolean isActive = command.parameterExists("isActive") ? command - .booleanPrimitiveValueOfParameterNamed("isActive") : true; - final List floatingRatePeriods = getRatePeriods( - currentUser, command); - final LocalDate currentDate = DateUtils.getLocalDateOfTenant(); + final String name = command.stringValueOfParameterNamed("name"); + 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 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; - } - List ratePeriods = new ArrayList<>(); - 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 boolean isActive = true; - final Date currentDate = DateUtils.getDateOfTenant(); - ratePeriods.add(new FloatingRatePeriod(fromDate, interestRate, - isDifferentialToBaseLendingRate, isActive, currentUser, - currentUser, currentDate, currentDate)); - } + 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"); + 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 boolean isActive = true; + final Date currentDate = DateUtils.getDateOfTenant(); + ratePeriods.add(new FloatingRatePeriod(fromDate, interestRate, + isDifferentialToBaseLendingRate, isActive, currentUser, + currentUser, currentDate, currentDate)); + } - return ratePeriods; - } + return ratePeriods; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public boolean isBaseLendingRate() { - return this.isBaseLendingRate; - } + public boolean isBaseLendingRate() { + return this.isBaseLendingRate; + } - public boolean isActive() { - return this.isActive; - } + public boolean isActive() { + return this.isActive; + } - public List getFloatingRatePeriods() { - return this.floatingRatePeriods; - } + public List getFloatingRatePeriods() { + return this.floatingRatePeriods; + } - public AppUser getCreatedBy() { - return this.createdBy; - } + public AppUser getCreatedBy() { + return this.createdBy; + } - public AppUser getModifiedBy() { - return this.modifiedBy; - } + public AppUser getModifiedBy() { + return this.modifiedBy; + } - public Date getCreatedOn() { - return this.createdOn; - } + public Date getCreatedOn() { + return this.createdOn; + } - public Date getModifiedOn() { - return this.modifiedOn; - } + public Date getModifiedOn() { + 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); + final Map actualChanges = new LinkedHashMap<>(9); - if (command.isChangeInStringParameterNamed("name", this.name)) { - final String newValue = command.stringValueOfParameterNamed("name"); - actualChanges.put("name", newValue); - this.name = newValue; - } + if (command.isChangeInStringParameterNamed("name", this.name)) { + final String newValue = command.stringValueOfParameterNamed("name"); + actualChanges.put("name", newValue); + this.name = newValue; + } - if (command.isChangeInBooleanParameterNamed("isBaseLendingRate", - this.isBaseLendingRate)) { - final boolean newValue = command - .booleanPrimitiveValueOfParameterNamed("isBaseLendingRate"); - actualChanges.put("isBaseLendingRate", newValue); - this.isBaseLendingRate = newValue; - } + 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"); - actualChanges.put("isActive", newValue); - this.isActive = newValue; - } + if (command.isChangeInBooleanParameterNamed("isActive", this.isActive)) { + final boolean newValue = command + .booleanPrimitiveValueOfParameterNamed("isActive"); + actualChanges.put("isActive", newValue); + this.isActive = newValue; + } - final List newRatePeriods = getRatePeriods(appUser, - command); - if (newRatePeriods != null && !newRatePeriods.isEmpty()) { - updateRatePeriods(newRatePeriods, appUser); - actualChanges.put("ratePeriods", - command.jsonFragment("ratePeriods")); - } + final List newRatePeriods = getRatePeriods(appUser, + command); + if (newRatePeriods != null && !newRatePeriods.isEmpty()) { + updateRatePeriods(newRatePeriods, appUser); + actualChanges.put("ratePeriods", + command.jsonFragment("ratePeriods")); + } - return actualChanges; - } + return actualChanges; + } - 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()); - if (fromDate.isAfter(today)) { - ratePeriod.setActive(false); - ratePeriod.setModifiedBy(appUser); - ratePeriod.setModifiedOn(today.toDate()); - } - } - } - for (FloatingRatePeriod newRatePeriod : newRatePeriods) { - newRatePeriod.updateFloatingRate(this); - this.floatingRatePeriods.add(newRatePeriod); - } - } + 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()); + if (fromDate.isAfter(today)) { + ratePeriod.setActive(false); + ratePeriod.setModifiedBy(appUser); + ratePeriod.setModifiedOn(today.toDate()); + } + } + } + for (FloatingRatePeriod newRatePeriod : newRatePeriods) { + newRatePeriod.updateFloatingRate(this); + this.floatingRatePeriods.add(newRatePeriod); + } + } - 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 (floatingRateDTO.isFloatingInterestRate()) { - addPeriodData = true; - } - if (previousPeriod != null) { - applicableRates.add(previousPeriod - .toData(floatingRateDTO)); - } else if (!addPeriodData) { - applicableRates.add(floatingRatePeriod - .toData(floatingRateDTO)); - } - } - if (addPeriodData) { - applicableRates.add(floatingRatePeriod - .toData(floatingRateDTO)); - } - previousPeriod = floatingRatePeriod; - } - } - if (applicableRates.isEmpty() && previousPeriod != null) { - applicableRates.add(previousPeriod.toData(floatingRateDTO)); - } - return applicableRates; - } + 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 (floatingRateDTO.isFloatingInterestRate()) { + addPeriodData = true; + } + if (previousPeriod != null) { + applicableRates.add(previousPeriod + .toData(floatingRateDTO)); + } else if (!addPeriodData) { + applicableRates.add(floatingRatePeriod + .toData(floatingRateDTO)); + } + } + if (addPeriodData) { + applicableRates.add(floatingRatePeriod + .toData(floatingRateDTO)); + } + previousPeriod = floatingRatePeriod; + } + } + if (applicableRates.isEmpty() && previousPeriod != null) { + applicableRates.add(previousPeriod.toData(floatingRateDTO)); + } + return applicableRates; + } } 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 f9e0b4590..5aa76e83d 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 @@ -39,127 +39,127 @@ import org.joda.time.LocalDateTime; @Table(name = "m_floating_rates_periods") public class FloatingRatePeriod extends AbstractPersistableCustom { - @ManyToOne - @JoinColumn(name = "floating_rates_id", nullable = false) - private FloatingRate floatingRate; + @ManyToOne + @JoinColumn(name = "floating_rates_id", nullable = false) + private FloatingRate floatingRate; - @Column(name = "from_date", nullable = false) - private Date fromDate; + @Column(name = "from_date", nullable = false) + private Date fromDate; - @Column(name = "interest_rate", scale = 6, precision = 19, nullable = false) - private BigDecimal interestRate; + @Column(name = "interest_rate", scale = 6, precision = 19, nullable = false) + private BigDecimal interestRate; - @Column(name = "is_differential_to_base_lending_rate", nullable = false) - private boolean isDifferentialToBaseLendingRate; + @Column(name = "is_differential_to_base_lending_rate", nullable = false) + private boolean isDifferentialToBaseLendingRate; - @Column(name = "is_active", nullable = false) - private boolean isActive; + @Column(name = "is_active", nullable = false) + private boolean isActive; - @ManyToOne(optional = true, fetch=FetchType.LAZY) - @JoinColumn(name = "createdby_id", nullable = false) - private AppUser createdBy; + @ManyToOne(optional = true, fetch=FetchType.LAZY) + @JoinColumn(name = "createdby_id", nullable = false) + private AppUser createdBy; - @ManyToOne(optional = true, fetch=FetchType.LAZY) - @JoinColumn(name = "lastmodifiedby_id", nullable = false) - private AppUser modifiedBy; + @ManyToOne(optional = true, fetch=FetchType.LAZY) + @JoinColumn(name = "lastmodifiedby_id", nullable = false) + private AppUser modifiedBy; - @Column(name = "created_date", nullable = false) - private Date createdOn; + @Column(name = "created_date", nullable = false) + private Date createdOn; - @Column(name = "lastmodified_date", nullable = false) - private Date modifiedOn; + @Column(name = "lastmodified_date", nullable = false) + private Date modifiedOn; - public FloatingRatePeriod() { + public FloatingRatePeriod() { - } + } - 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; - this.isActive = isActive; - this.createdBy = createdBy; - this.modifiedBy = modifiedBy; - this.createdOn = createdOn; - this.modifiedOn = 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; + this.isActive = isActive; + this.createdBy = createdBy; + this.modifiedBy = modifiedBy; + this.createdOn = createdOn; + this.modifiedOn = modifiedOn; + } - public void updateFloatingRate(FloatingRate floatingRate) { - this.floatingRate = floatingRate; - } + public void updateFloatingRate(FloatingRate floatingRate) { + this.floatingRate = floatingRate; + } - public FloatingRate getFloatingRatesId() { - return this.floatingRate; - } + public FloatingRate getFloatingRatesId() { + return this.floatingRate; + } - public Date getFromDate() { - return this.fromDate; - } + public Date getFromDate() { + return this.fromDate; + } - public BigDecimal getInterestRate() { - return this.interestRate; - } + public BigDecimal getInterestRate() { + return this.interestRate; + } - public boolean isDifferentialToBaseLendingRate() { - return this.isDifferentialToBaseLendingRate; - } + public boolean isDifferentialToBaseLendingRate() { + return this.isDifferentialToBaseLendingRate; + } - public boolean isActive() { - return this.isActive; - } + public boolean isActive() { + return this.isActive; + } - public AppUser getCreatedBy() { - return this.createdBy; - } + public AppUser getCreatedBy() { + return this.createdBy; + } - public AppUser getModifiedBy() { - return this.modifiedBy; - } + public AppUser getModifiedBy() { + return this.modifiedBy; + } - public Date getCreatedOn() { - return this.createdOn; - } + public Date getCreatedOn() { + return this.createdOn; + } - public Date getModifiedOn() { - return this.modifiedOn; - } + public Date getModifiedOn() { + return this.modifiedOn; + } - public void setModifiedBy(AppUser modifiedBy) { - this.modifiedBy = modifiedBy; - } + public void setModifiedBy(AppUser modifiedBy) { + this.modifiedBy = modifiedBy; + } - public void setModifiedOn(Date modifiedOn) { - this.modifiedOn = modifiedOn; - } + public void setModifiedOn(Date modifiedOn) { + this.modifiedOn = modifiedOn; + } - public void setActive(boolean b) { - this.isActive = b; - } + public void setActive(boolean b) { + this.isActive = b; + } - public LocalDate fetchFromDate() { - return new LocalDate(this.fromDate); - } + public LocalDate fetchFromDate() { + return new LocalDate(this.fromDate); + } - public FloatingRatePeriodData toData(final FloatingRateDTO floatingRateDTO) { + public FloatingRatePeriodData toData(final FloatingRateDTO floatingRateDTO) { - BigDecimal interest = getInterestRate().add( - floatingRateDTO.getInterestRateDiff()); - if (isDifferentialToBaseLendingRate()) { - 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); - } + BigDecimal interest = getInterestRate().add( + floatingRateDTO.getInterestRateDiff()); + if (isDifferentialToBaseLendingRate()) { + 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); + } } 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 8f4b93f95..b3290ced1 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 @@ -25,17 +25,17 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; public interface FloatingRateRepository extends - JpaRepository, - JpaSpecificationExecutor { + 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") - Collection retrieveFloatingRatesLinkedToBLR(); + @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") + 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 4a97e5e03..cddedb25e 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 @@ -25,28 +25,28 @@ import org.springframework.stereotype.Service; @Service public class FloatingRateRepositoryWrapper { - private final FloatingRateRepository floatingRateRepository; + private final FloatingRateRepository floatingRateRepository; - @Autowired - public FloatingRateRepositoryWrapper( - final FloatingRateRepository floatingRateRepository) { - this.floatingRateRepository = floatingRateRepository; - } + @Autowired + public FloatingRateRepositoryWrapper( + final FloatingRateRepository floatingRateRepository) { + this.floatingRateRepository = floatingRateRepository; + } - public FloatingRate retrieveBaseLendingRate() { - return this.floatingRateRepository.retrieveBaseLendingRate(); - } + public FloatingRate retrieveBaseLendingRate() { + return this.floatingRateRepository.retrieveBaseLendingRate(); + } - public FloatingRate findOneWithNotFoundDetection(final Long id) { - return this.floatingRateRepository - .findById(id).orElseThrow(() -> new FloatingRateNotFoundException(id)); - } + public FloatingRate findOneWithNotFoundDetection(final Long id) { + return this.floatingRateRepository + .findById(id).orElseThrow(() -> new FloatingRateNotFoundException(id)); + } - public void save(FloatingRate newFloatingRate) { - this.floatingRateRepository.save(newFloatingRate); - } + public void save(FloatingRate newFloatingRate) { + this.floatingRateRepository.save(newFloatingRate); + } - public void saveAndFlush(FloatingRate floatingRateForUpdate) { - this.floatingRateRepository.saveAndFlush(floatingRateForUpdate); - } + public void saveAndFlush(FloatingRate floatingRateForUpdate) { + this.floatingRateRepository.saveAndFlush(floatingRateForUpdate); + } } 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 938ef506c..3c8b37b18 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 @@ -21,14 +21,14 @@ package org.apache.fineract.portfolio.floatingrates.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; public class FloatingRateNotFoundException extends - AbstractPlatformResourceNotFoundException { + AbstractPlatformResourceNotFoundException { - public FloatingRateNotFoundException(final Long id) { - super("error.msg.floatingrate.id.invalid", - "Floating Rate with identifier " + id + " does not exist", id); - } + public FloatingRateNotFoundException(final Long id) { + super("error.msg.floatingrate.id.invalid", + "Floating Rate with identifier " + id + " does not exist", id); + } - public FloatingRateNotFoundException(final String globalisationMessageCode) { - super(globalisationMessageCode, "Floating Rate does not exist"); - } + public FloatingRateNotFoundException(final String globalisationMessageCode) { + super(globalisationMessageCode, "Floating Rate does not exist"); + } } 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 e6605fd48..2be0e8d4f 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 @@ -30,19 +30,19 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "FLOATINGRATE", action = "CREATE") public class CreateFloatingRateCommandHandler implements - NewCommandSourceHandler { + NewCommandSourceHandler { - private final FloatingRateWritePlatformService writePlatformService; + private final FloatingRateWritePlatformService writePlatformService; - @Autowired - public CreateFloatingRateCommandHandler( - final FloatingRateWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public CreateFloatingRateCommandHandler( + final FloatingRateWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.createFloatingRate(command); - } + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.writePlatformService.createFloatingRate(command); + } } 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 ccc230ef8..f38c2b6e0 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 @@ -30,19 +30,19 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "FLOATINGRATE", action = "UPDATE") public class UpdateFloatingRateCommandHandler implements - NewCommandSourceHandler { + NewCommandSourceHandler { - private final FloatingRateWritePlatformService writePlatformService; + private final FloatingRateWritePlatformService writePlatformService; - @Autowired - public UpdateFloatingRateCommandHandler( - final FloatingRateWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public UpdateFloatingRateCommandHandler( + final FloatingRateWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.updateFloatingRate(command); - } + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.writePlatformService.updateFloatingRate(command); + } } 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 32faa0115..fe9cddbd0 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 @@ -39,278 +39,278 @@ import java.util.*; @Component public class FloatingRateDataValidator { - private final Set supportedParametersForFloatingRates = new HashSet<>( - Arrays.asList("name", "isBaseLendingRate", "isActive", - "ratePeriods")); - private final Set supportedParametersForFloatingRatePeriods = new HashSet<>( - Arrays.asList("fromDate", "interestRate", - "isDifferentialToBaseLendingRate", "locale", "dateFormat")); + private final Set supportedParametersForFloatingRates = new HashSet<>( + Arrays.asList("name", "isBaseLendingRate", "isActive", + "ratePeriods")); + private final Set supportedParametersForFloatingRatePeriods = new HashSet<>( + Arrays.asList("fromDate", "interestRate", + "isDifferentialToBaseLendingRate", "locale", "dateFormat")); - private final FromJsonHelper fromApiJsonHelper; - private final FloatingRateRepository floatingRateRepository; + private final FromJsonHelper fromApiJsonHelper; + private final FloatingRateRepository floatingRateRepository; - @Autowired - public FloatingRateDataValidator(final FromJsonHelper fromApiJsonHelper, - final FloatingRateRepository floatingRateRepository) { - this.fromApiJsonHelper = fromApiJsonHelper; - this.floatingRateRepository = floatingRateRepository; - } + @Autowired + 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); + public void validateForCreate(String json) { + 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 List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( + dataValidationErrors).resource("floatingrate"); - final JsonElement element = this.fromApiJsonHelper.parse(json); + 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); + Boolean isBaseLendingRate = null; + if (this.fromApiJsonHelper + .parameterExists("isBaseLendingRate", element)) { + isBaseLendingRate = this.fromApiJsonHelper + .extractBooleanNamed("isBaseLendingRate", element); - baseDataValidator.reset().parameter("isBaseLendingRate") - .value(isBaseLendingRate).notNull(); - if (isBaseLendingRate == null) { - baseDataValidator.reset().parameter("isBaseLendingRate") - .trueOrFalseRequired(false); - } else if (isBaseLendingRate) { - 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).notNull(); + if (isBaseLendingRate == null) { + baseDataValidator.reset().parameter("isBaseLendingRate") + .trueOrFalseRequired(false); + } else if (isBaseLendingRate) { + FloatingRate baseLendingRate = this.floatingRateRepository + .retrieveBaseLendingRate(); + if (baseLendingRate != null) { + 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); - if (isActive == null) { - baseDataValidator.reset().parameter("isActive") - .trueOrFalseRequired(false); - } - } + if (this.fromApiJsonHelper.parameterExists("isActive", element)) { + final Boolean isActive = this.fromApiJsonHelper + .extractBooleanNamed("isActive", element); + if (isActive == null) { + baseDataValidator.reset().parameter("isActive") + .trueOrFalseRequired(false); + } + } - if(isBaseLendingRate == null){ - isBaseLendingRate = false; - } - validateRatePeriods(baseDataValidator, element, isBaseLendingRate, false); + if(isBaseLendingRate == null){ + isBaseLendingRate = false; + } + validateRatePeriods(baseDataValidator, element, isBaseLendingRate, false); - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } + throwExceptionIfValidationWarningsExist(dataValidationErrors); + } - 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(); + 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(); - if (ratePeriods != null) { - List fromDates = new ArrayList<>(); - for (int i = 0; i < ratePeriods.size(); i++) { - final JsonElement ratePeriod = ratePeriods.get(i); + 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.supportedParametersForFloatingRatePeriods); + 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)); - if (fromDate != null) { - fromDates.add(fromDate); - } + 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)) { - final Boolean isDifferentialToBaseLendingRate = this.fromApiJsonHelper - .extractBooleanNamed( - "isDifferentialToBaseLendingRate", - ratePeriod); - if (isDifferentialToBaseLendingRate == null) { - baseDataValidator - .reset() - .parameter( - "isDifferentialToBaseLendingRate") - .parameterAtIndexArray( - "isDifferentialToBaseLendingRate", - i + 1).trueOrFalseRequired(false); - } else if (isDifferentialToBaseLendingRate) { - FloatingRate baseLendingRate = this.floatingRateRepository - .retrieveBaseLendingRate(); - if (baseLendingRate == null || isBLRModifiedAsNonBLR) { - baseDataValidator - .reset() - .parameter( - "isDifferentialToBaseLendingRate") - .parameterAtIndexArray( - "isDifferentialToBaseLendingRate", - i + 1) - .value(isDifferentialToBaseLendingRate) - .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 (this.fromApiJsonHelper.parameterExists( + "isDifferentialToBaseLendingRate", ratePeriod)) { + final Boolean isDifferentialToBaseLendingRate = this.fromApiJsonHelper + .extractBooleanNamed( + "isDifferentialToBaseLendingRate", + ratePeriod); + if (isDifferentialToBaseLendingRate == null) { + baseDataValidator + .reset() + .parameter( + "isDifferentialToBaseLendingRate") + .parameterAtIndexArray( + "isDifferentialToBaseLendingRate", + i + 1).trueOrFalseRequired(false); + } else if (isDifferentialToBaseLendingRate) { + FloatingRate baseLendingRate = this.floatingRateRepository + .retrieveBaseLendingRate(); + if (baseLendingRate == null || isBLRModifiedAsNonBLR) { + baseDataValidator + .reset() + .parameter( + "isDifferentialToBaseLendingRate") + .parameterAtIndexArray( + "isDifferentialToBaseLendingRate", + i + 1) + .value(isDifferentialToBaseLendingRate) + .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."); + } - } - } - } - 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."); - } + } + } + } + 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."); + } - } - } - } + } + } + } - 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 List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( + dataValidationErrors).resource("floatingrate"); - final JsonElement element = this.fromApiJsonHelper.parse(json); + 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); - } + if (this.fromApiJsonHelper.parameterExists("name", element)) { + 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); + Boolean isBaseLendingRate = null; + Boolean isBLRModifiedAsNonBLR = false; + FloatingRate baseLendingRate = this.floatingRateRepository + .retrieveBaseLendingRate(); + if (this.fromApiJsonHelper + .parameterExists("isBaseLendingRate", element)) { + isBaseLendingRate = this.fromApiJsonHelper + .extractBooleanNamed("isBaseLendingRate", element); - baseDataValidator.reset().parameter("isBaseLendingRate") - .value(isBaseLendingRate).notNull(); - if (isBaseLendingRate == null) { - 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).notNull(); + if (isBaseLendingRate == null) { + 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"); + } + } + } - Boolean isActive = null; - if (this.fromApiJsonHelper.parameterExists("isActive", element)) { - isActive = this.fromApiJsonHelper - .extractBooleanNamed("isActive", element); - if (isActive == null) { - baseDataValidator.reset().parameter("isActive") - .trueOrFalseRequired(false); - } - } + Boolean isActive = null; + if (this.fromApiJsonHelper.parameterExists("isActive", element)) { + isActive = this.fromApiJsonHelper + .extractBooleanNamed("isActive", element); + if (isActive == null) { + baseDataValidator.reset().parameter("isActive") + .trueOrFalseRequired(false); + } + } - if(isBaseLendingRate == null){ - isBaseLendingRate = floatingRateForUpdate.isBaseLendingRate(); - } - - if(isActive == null){ - isActive = floatingRateForUpdate.isActive(); - } - - if(baseLendingRate != null && baseLendingRate.getId().equals(floatingRateForUpdate.getId())){ - if(!isBaseLendingRate || !isActive){ - isBLRModifiedAsNonBLR = true; - } - } - - 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", - "There are floating rates linked to this Base Lending Rate, cannot be marked as non-Base Lending Rate."); - } - } + if(isBaseLendingRate == null){ + isBaseLendingRate = floatingRateForUpdate.isBaseLendingRate(); + } + + if(isActive == null){ + isActive = floatingRateForUpdate.isActive(); + } + + if(baseLendingRate != null && baseLendingRate.getId().equals(floatingRateForUpdate.getId())){ + if(!isBaseLendingRate || !isActive){ + isBLRModifiedAsNonBLR = true; + } + } + + 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", + "There are floating rates linked to this Base Lending Rate, cannot be marked as non-Base Lending Rate."); + } + } - validateRatePeriods(baseDataValidator, element, isBaseLendingRate, isBLRModifiedAsNonBLR); + validateRatePeriods(baseDataValidator, element, isBaseLendingRate, isBLRModifiedAsNonBLR); - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } + throwExceptionIfValidationWarningsExist(dataValidationErrors); + } - private void throwExceptionIfValidationWarningsExist( - final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - } + private void throwExceptionIfValidationWarningsExist( + final List 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/floatingrates/service/FloatingRateWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRateWritePlatformService.java index cbcc5293f..b46fb9b0f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRateWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRateWritePlatformService.java @@ -23,7 +23,7 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface FloatingRateWritePlatformService { - public CommandProcessingResult createFloatingRate(JsonCommand command); + public CommandProcessingResult createFloatingRate(JsonCommand command); - public CommandProcessingResult updateFloatingRate(JsonCommand command); + public CommandProcessingResult updateFloatingRate(JsonCommand command); } 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 78e70cc83..a3caef68a 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 @@ -41,107 +41,107 @@ import org.springframework.transaction.annotation.Transactional; @Service public class FloatingRateWritePlatformServiceImpl implements - FloatingRateWritePlatformService { + FloatingRateWritePlatformService { - private final static Logger logger = LoggerFactory - .getLogger(FloatingRateWritePlatformServiceImpl.class); - private final PlatformSecurityContext context; - private final FloatingRateDataValidator fromApiJsonDeserializer; - private final FloatingRateRepositoryWrapper floatingRateRepository; + private final static Logger logger = 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) { - this.context = context; - this.fromApiJsonDeserializer = fromApiJsonDeserializer; - this.floatingRateRepository = floatingRateRepository; - } + @Autowired + public FloatingRateWritePlatformServiceImpl( + final PlatformSecurityContext context, + final FloatingRateDataValidator fromApiJsonDeserializer, + final FloatingRateRepositoryWrapper floatingRateRepository) { + this.context = context; + this.fromApiJsonDeserializer = fromApiJsonDeserializer; + this.floatingRateRepository = floatingRateRepository; + } - @Transactional - @Override - public CommandProcessingResult createFloatingRate(final JsonCommand command) { - try { - this.fromApiJsonDeserializer.validateForCreate(command.json()); - final AppUser currentUser = this.context.authenticatedUser(); - final FloatingRate newFloatingRate = FloatingRate.createNew( - currentUser, command); - this.floatingRateRepository.save(newFloatingRate); - return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(newFloatingRate.getId()) // - .build(); - } catch (final DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); - return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + @Transactional + @Override + public CommandProcessingResult createFloatingRate(final JsonCommand command) { + try { + this.fromApiJsonDeserializer.validateForCreate(command.json()); + final AppUser currentUser = this.context.authenticatedUser(); + final FloatingRate newFloatingRate = FloatingRate.createNew( + currentUser, command); + this.floatingRateRepository.save(newFloatingRate); + return new CommandProcessingResultBuilder() // + .withCommandId(command.commandId()) // + .withEntityId(newFloatingRate.getId()) // + .build(); + } catch (final DataIntegrityViolationException dve) { + handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); + return CommandProcessingResult.empty(); + }catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); - } - } + return CommandProcessingResult.empty(); + } + } - @Transactional - @Override - public CommandProcessingResult updateFloatingRate(final JsonCommand command) { - try { - 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); + @Transactional + @Override + public CommandProcessingResult updateFloatingRate(final JsonCommand command) { + try { + 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); - if (!changes.isEmpty()) { - this.floatingRateRepository.save(floatingRateForUpdate); - } + if (!changes.isEmpty()) { + this.floatingRateRepository.save(floatingRateForUpdate); + } - return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(command.entityId()) // - .with(changes) // - .build(); - } catch (final DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); - return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + return new CommandProcessingResultBuilder() // + .withCommandId(command.commandId()) // + .withEntityId(command.entityId()) // + .with(changes) // + .build(); + } catch (final DataIntegrityViolationException dve) { + handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); + return CommandProcessingResult.empty(); + }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")) { + 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); - } + final String name = command.stringValueOfParameterNamed("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", ""); - } + 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", ""); + } - logAsErrorUnexpectedDataIntegrityException(dve); - throw new PlatformDataIntegrityException( - "error.msg.floatingrates.unknown.data.integrity.issue", - "Unknown data integrity issue with resource."); - } + logAsErrorUnexpectedDataIntegrityException(dve); + throw new PlatformDataIntegrityException( + "error.msg.floatingrates.unknown.data.integrity.issue", + "Unknown data integrity issue with resource."); + } - private void logAsErrorUnexpectedDataIntegrityException( - Exception dve) { - logger.error(dve.getMessage(), dve); + private void logAsErrorUnexpectedDataIntegrityException( + Exception dve) { + logger.error(dve.getMessage(), dve); - } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRatesReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRatesReadPlatformService.java index 4c4853e47..a89590002 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRatesReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRatesReadPlatformService.java @@ -25,16 +25,16 @@ import org.apache.fineract.portfolio.floatingrates.data.InterestRatePeriodData; public interface FloatingRatesReadPlatformService { - List retrieveAll(); + List retrieveAll(); - List retrieveLookupActive(); + List retrieveLookupActive(); - FloatingRateData retrieveOne(Long floatingRateId); + FloatingRateData retrieveOne(Long floatingRateId); - List retrieveAllActive(); + List retrieveAllActive(); - FloatingRateData retrieveBaseLendingRate(); + FloatingRateData retrieveBaseLendingRate(); - List retrieveInterestRatePeriods(Long productId); + List retrieveInterestRatePeriods(Long productId); } 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 9593715a1..936b2c66c 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 @@ -39,258 +39,258 @@ import org.springframework.stereotype.Service; @Service public class FloatingRatesReadPlatformServiceImpl implements - FloatingRatesReadPlatformService { + FloatingRatesReadPlatformService { - private final JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; - @Autowired - public FloatingRatesReadPlatformServiceImpl( - final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + public FloatingRatesReadPlatformServiceImpl( + final RoutingDataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } - @Override - public List retrieveAll() { - FloatingRateRowMapper rateMapper = new FloatingRateRowMapper(false); - final String sql = "select " + rateMapper.schema(); - return this.jdbcTemplate.query(sql, rateMapper); - } + @Override + public List retrieveAll() { + FloatingRateRowMapper rateMapper = new FloatingRateRowMapper(false); + final String sql = "select " + rateMapper.schema(); + return this.jdbcTemplate.query(sql, rateMapper); + } - @Override - public List retrieveAllActive() { - FloatingRateRowMapper rateMapper = new FloatingRateRowMapper(false); - final String sql = "select " + rateMapper.schema() - + " where rate.is_active = 1 "; - return this.jdbcTemplate.query(sql, rateMapper); - } + @Override + public List retrieveAllActive() { + FloatingRateRowMapper rateMapper = new FloatingRateRowMapper(false); + 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 "; - 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 "; + return this.jdbcTemplate.query(sql, rateMapper); + } - @Override - 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 }); - } catch (final EmptyResultDataAccessException e) { - throw new FloatingRateNotFoundException(floatingRateId); - } - } + @Override + 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 }); + } catch (final EmptyResultDataAccessException e) { + throw new FloatingRateNotFoundException(floatingRateId); + } + } - @Override - public List retrieveInterestRatePeriods( - final Long productId) { - try { - FloatingInterestRatePeriodRowMapper mapper = new FloatingInterestRatePeriodRowMapper(); - return this.jdbcTemplate.query(mapper.schema(), mapper, - new Object[] { productId }); - } catch (final EmptyResultDataAccessException e) { - throw new FloatingRateNotFoundException("error.msg.floatingrate.not.found.for.product"); - } - } + @Override + public List retrieveInterestRatePeriods( + final Long productId) { + try { + FloatingInterestRatePeriodRowMapper mapper = new FloatingInterestRatePeriodRowMapper(); + return this.jdbcTemplate.query(mapper.schema(), mapper, + new Object[] { productId }); + } catch (final EmptyResultDataAccessException e) { + throw new FloatingRateNotFoundException("error.msg.floatingrate.not.found.for.product"); + } + } - @Override - 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"; - return this.jdbcTemplate.queryForObject(sql, rateMapper); - } catch (final EmptyResultDataAccessException e) { - throw new FloatingRateNotFoundException( - "error.msg.floatingrate.base.lending.rate.not.found"); - } - } + @Override + 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"; + return this.jdbcTemplate.queryForObject(sql, rateMapper); + } catch (final EmptyResultDataAccessException e) { + 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 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 ") - .append("LEFT JOIN m_appuser as moappu on rate.lastmodifiedby_id = moappu.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) { - this.addRatePeriods = addRatePeriods; - } + public FloatingRateRowMapper(final boolean addRatePeriods) { + this.addRatePeriods = addRatePeriods; + } - @Override - 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 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"); - 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 = ? " - + " order by period.from_date desc "; - ratePeriods = jdbcTemplate.query(sql, ratePeriodMapper, - new Object[] { id }); - } - return new FloatingRateData(id, name, isBaseLendingRate, isActive, - createdBy, createdOn, modifiedBy, modifiedOn, ratePeriods, - null); - } + @Override + 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 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"); + 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 = ? " + + " order by period.from_date desc "; + ratePeriods = jdbcTemplate.query(sql, ratePeriodMapper, + new Object[] { id }); + } + return new FloatingRateData(id, name, isBaseLendingRate, isActive, + createdBy, createdOn, modifiedBy, modifiedOn, ratePeriods, + null); + } - public String schema() { - return sqlQuery.toString(); - } - } + public String schema() { + return sqlQuery.toString(); + } + } - 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, ") - .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("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 "); + 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("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 { - 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 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); - } + @Override + 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 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); + } - public String schema() { - return sqlQuery.toString(); - } - } + public String schema() { + return sqlQuery.toString(); + } + } - 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 { - 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); - } + @Override + 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); + } - public String schema() { - return sqlQuery.toString(); - } - } + public String schema() { + return sqlQuery.toString(); + } + } - private final class FloatingInterestRatePeriodRowMapper implements - RowMapper { + private final class FloatingInterestRatePeriodRowMapper implements + RowMapper { - 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(" from m_product_loan as lp ") + 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(" 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("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(" 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(" 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("order by linkedratePeriods_from_date desc "); + .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(" 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(" 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("order by linkedratePeriods_from_date desc "); - @Override - 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 Date blrFromDate = rs.getDate("baserate_from_date"); - final BigDecimal blrInterestRate = rs - .getBigDecimal("baserate_interest_rate"); + @Override + 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 Date blrFromDate = rs.getDate("baserate_from_date"); + 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() { - return sqlQuery.toString(); - } - } + public String schema() { + return sqlQuery.toString(); + } + } } 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 a385469e9..81b1cbe1b 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 @@ -76,9 +76,9 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf handleFundDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleFundDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleFundDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -105,9 +105,9 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf handleFundDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleFundDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleFundDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } 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 c57dd9691..05084c32d 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 @@ -245,7 +245,7 @@ public class CenterData implements Serializable { } public String getAccountNo(){ - return this.accountNo; + return this.accountNo; } public String getName() { 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 6d5c4e3d3..c09b7163e 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 @@ -294,7 +294,7 @@ public class GroupGeneralData implements Serializable { } public String getAccountNo(){ - return this.accountNo; + return this.accountNo; } public String getName() { 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 1ef191105..c3f150a78 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 @@ -334,9 +334,9 @@ public final class Group extends AbstractPersistableCustom { actualChanges.put(GroupingTypesApiConstants.localeParamName, localeAsInput); final LocalDate newValue = command.localDateValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName); - if (newValue != null) { - this.activationDate = newValue.toDate(); - } + if (newValue != null) { + this.activationDate = newValue.toDate(); + } } if (command.isChangeInStringParameterNamed(GroupingTypesApiConstants.accountNoParamName, this.accountNumber)) { @@ -401,24 +401,24 @@ public final class Group extends AbstractPersistableCustom { return this.clientMembers.contains(client); } - public void generateHierarchy() { - if (this.parent != null) { - this.hierarchy = this.parent.hierarchyOf(getId()); - } else { - this.hierarchy = "." + getId() + "."; - for (Group group : this.groupMembers) { - group.setParent(this); - group.generateHierarchy(); - } - } - } + public void generateHierarchy() { + if (this.parent != null) { + this.hierarchy = this.parent.hierarchyOf(getId()); + } else { + this.hierarchy = "." + getId() + "."; + for (Group group : this.groupMembers) { + group.setParent(this); + group.generateHierarchy(); + } + } + } - public void resetHierarchy() { - this.hierarchy = "." + this.getId(); - } + public void resetHierarchy() { + this.hierarchy = "." + this.getId(); + } private String hierarchyOf(final Long id) { - return this.hierarchy + id.toString() + "."; + return this.hierarchy + id.toString() + "."; } public boolean isOfficeIdentifiedBy(final Long officeId) { @@ -584,7 +584,7 @@ public final class Group extends AbstractPersistableCustom { this.groupMembers.add(group); differences.add(group.getId().toString()); group.setParent(this); - group.generateHierarchy(); + group.generateHierarchy(); } return differences; @@ -597,7 +597,7 @@ public final class Group extends AbstractPersistableCustom { if (hasGroupAsMember(group)) { this.groupMembers.remove(group); differences.add(group.getId().toString()); - group.resetHierarchy(); + group.resetHierarchy(); } else { throw new GroupNotExistsInCenterException(group.getId(), getId()); } @@ -759,9 +759,9 @@ public final class Group extends AbstractPersistableCustom { this.accountNumberRequiresAutoGeneration = false; } - public void setGroupMembers(List groupMembers) { - this.groupMembers = groupMembers; - } + public void setGroupMembers(List groupMembers) { + this.groupMembers = groupMembers; + } } \ No newline at end of file diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRepository.java index 6095a807f..a95923a86 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRepository.java @@ -30,9 +30,9 @@ public interface GroupRepository extends JpaRepository, JpaSpecific Collection findByParentId(Long parentId); - public static final String RETRIEVE_SUBMITTED_ON_DATE = "select g.submittedOnDate from Group g where g.id = :groupId"; + public static final String RETRIEVE_SUBMITTED_ON_DATE = "select g.submittedOnDate from Group g where g.id = :groupId"; - @Query(RETRIEVE_SUBMITTED_ON_DATE) - Date retrieveGroupTypeSubmitteOndDate(@Param("groupId") Long groupId); + @Query(RETRIEVE_SUBMITTED_ON_DATE) + Date retrieveGroupTypeSubmitteOndDate(@Param("groupId") Long groupId); } 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 d25989174..41b468fc3 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 @@ -69,11 +69,11 @@ public class GroupRepositoryWrapper { this.repository.flush(); } - public LocalDate retrieveSubmittedOndate(final Long groupId) { - Date submittedOnDate = this.repository.retrieveGroupTypeSubmitteOndDate(groupId); - if (submittedOnDate != null) { - return new LocalDate(submittedOnDate); - } - return null; - } + public LocalDate retrieveSubmittedOndate(final Long groupId) { + Date submittedOnDate = this.repository.retrieveGroupTypeSubmitteOndDate(groupId); + if (submittedOnDate != null) { + return new LocalDate(submittedOnDate); + } + return null; + } } 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 index fe7b9f2e0..8237ccdd6 100755 --- 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 @@ -51,37 +51,37 @@ public final class GroupingTypesDataValidator { 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)); + 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, - GroupingTypesApiConstants.externalIdParamName, GroupingTypesApiConstants.centerIdParamName, - GroupingTypesApiConstants.officeIdParamName, GroupingTypesApiConstants.staffIdParamName, - GroupingTypesApiConstants.activeParamName, GroupingTypesApiConstants.activationDateParamName, - GroupingTypesApiConstants.clientMembersParamName, GroupingTypesApiConstants.collectionMeetingCalendar, - GroupingTypesApiConstants.submittedOnDateParamName, GroupingTypesApiConstants.datatables)); + 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)); + 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)); + GroupingTypesApiConstants.localeParamName, GroupingTypesApiConstants.dateFormatParamName, + GroupingTypesApiConstants.closureDateParamName, GroupingTypesApiConstants.closureReasonIdParamName)); @Autowired - public GroupingTypesDataValidator(final FromJsonHelper fromApiJsonHelper, - final GroupRepositoryWrapper groupRepositoryWrapper) { - this.fromApiJsonHelper = fromApiJsonHelper; - this.groupRepositoryWrapper = groupRepositoryWrapper; - } + public GroupingTypesDataValidator(final FromJsonHelper fromApiJsonHelper, + final GroupRepositoryWrapper groupRepositoryWrapper) { + this.fromApiJsonHelper = fromApiJsonHelper; + this.groupRepositoryWrapper = groupRepositoryWrapper; + } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { @@ -325,15 +325,15 @@ public final class GroupingTypesDataValidator { LocalDate submittedOnDate = this.groupRepositoryWrapper.retrieveSubmittedOndate(centerId); - 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); } @@ -380,15 +380,15 @@ public final class GroupingTypesDataValidator { 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); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/CenterReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/CenterReadPlatformServiceImpl.java index 5b42c4e66..3292e1351 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/CenterReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/CenterReadPlatformServiceImpl.java @@ -394,7 +394,7 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService if (searchParameters.isOrderByRequested()) { sqlBuilder.append(" order by ").append(searchParameters.getOrderBy()).append(' ').append(searchParameters.getSortOrder()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy(), - searchParameters.getSortOrder()); + searchParameters.getSortOrder()); } @@ -407,7 +407,7 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService final String sqlCountRows = "SELECT FOUND_ROWS()"; return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), - paramList.toArray(), this.centerMapper); + paramList.toArray(), this.centerMapper); } @Override @@ -435,7 +435,7 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService if (searchParameters.isOrderByRequested()) { sqlBuilder.append(" order by ").append(searchParameters.getOrderBy()).append(' ').append(searchParameters.getSortOrder()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy(), - searchParameters.getSortOrder()); + searchParameters.getSortOrder()); } if (searchParameters.isLimited()) { 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 889ba8f49..ea9aa03e9 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 @@ -163,7 +163,7 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { if (parameters.isOrderByRequested()) { sqlBuilder.append(" order by ").append(searchParameters.getOrderBy()).append(' ').append(searchParameters.getSortOrder()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy(), - searchParameters.getSortOrder()); + searchParameters.getSortOrder()); } if (parameters.isLimited()) { @@ -175,7 +175,7 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { final String sqlCountRows = "SELECT FOUND_ROWS()"; return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), - paramList.toArray(), this.allGroupTypesDataMapper); + paramList.toArray(), this.allGroupTypesDataMapper); } @Override @@ -241,7 +241,7 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { final String name = searchCriteria.getName(); if (name != null) { - paramList.add("%" + name + "%"); + paramList.add("%" + name + "%"); extraCriteria.append(" and g.display_name like ? "); } 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 a2564cdb8..1d5f60a1d 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 @@ -239,27 +239,27 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group handleGroupDataIntegrityIssues(command, dve.getMostSpecificCause(), dve, groupingType); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleGroupDataIntegrityIssues(command, throwable, dve, groupingType); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } private void generateAccountNumberIfRequired(Group newGroup){ - if (newGroup.isAccountNumberRequiresAutoGeneration()) { - EntityAccountType entityAccountType = null; - AccountNumberFormat accountNumberFormat = null; - if(newGroup.isCenter()){ - entityAccountType = EntityAccountType.CENTER; - accountNumberFormat = this.accountNumberFormatRepository + if (newGroup.isAccountNumberRequiresAutoGeneration()) { + EntityAccountType entityAccountType = null; + AccountNumberFormat accountNumberFormat = null; + if(newGroup.isCenter()){ + entityAccountType = EntityAccountType.CENTER; + accountNumberFormat = this.accountNumberFormatRepository .findByAccountType(entityAccountType); newGroup.updateAccountNo(this.accountNumberGenerator.generateCenterAccountNumber(newGroup, accountNumberFormat)); - }else { - entityAccountType = EntityAccountType.GROUP; - accountNumberFormat = this.accountNumberFormatRepository + }else { + entityAccountType = EntityAccountType.GROUP; + accountNumberFormat = this.accountNumberFormatRepository .findByAccountType(entityAccountType); newGroup.updateAccountNo(this.accountNumberGenerator.generateGroupAccountNumber(newGroup, accountNumberFormat)); - } + } } } @@ -332,7 +332,7 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group }catch (final PersistenceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleGroupDataIntegrityIssues(command, throwable, dve, GroupTypes.GROUP); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -470,9 +470,9 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group handleGroupDataIntegrityIssues(command, dve.getMostSpecificCause(), dve, groupingType); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleGroupDataIntegrityIssues(command, throwable, dve, groupingType); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } 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 index ab5c3ec43..e2dbf1cf1 100755 --- 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 @@ -60,13 +60,13 @@ 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)); + private static final Set INTERESTRATE_INCENTIVE_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + 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)); + private static final Set INTERESTRATE_INCENTIVE_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(InterestIncentiveApiConstants.idParamName, entityTypeParamName, attributeNameParamName, + conditionTypeParamName, attributeValueParamName, incentiveTypeparamName, amountParamName)); @Autowired public InterestIncentiveDataValidator(final FromJsonHelper fromApiJsonHelper) { 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 55bc4b3c5..9279572e9 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 @@ -58,15 +58,15 @@ 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)); + 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)); - 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, 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 7c7ac38de..df06e4e55 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 @@ -61,17 +61,17 @@ 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)); + 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)); - 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)); + 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)); @Autowired public InterestRateChartSlabDataValidator(final FromJsonHelper fromApiJsonHelper, 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 fe81e38c0..b004e6b7b 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 @@ -79,8 +79,8 @@ public class LoanDisbursementDetailApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String updateDisbursementDate(@PathParam("loanId") final Long loanId, @PathParam("disbursementId") final Long disbursementId, final String apiRequestBodyAsJson) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateDisbusementDate(loanId, disbursementId) + + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateDisbusementDate(loanId, disbursementId) .withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -94,7 +94,7 @@ public class LoanDisbursementDetailApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String addAndDeleteDisbursementDetail(@PathParam("loanId") final Long loanId, final String apiRequestBodyAsJson) { - CommandWrapper commandRequest = new CommandWrapperBuilder().addAndDeleteDisbursementDetails(loanId) + CommandWrapper commandRequest = new CommandWrapperBuilder().addAndDeleteDisbursementDetails(loanId) .withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); 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 3b8580bb6..cf936f77f 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 @@ -431,7 +431,7 @@ public class LoansApiResource { Collection members = loanAccountGroupData.groupData().clientMembers(); accountLinkingOptions = new ArrayList<>(); if(members != null){ - for (ClientData clientData : members) { + for (ClientData clientData : members) { Integer loanCounter = this.loanReadPlatformService.retriveLoanCounter(clientData.id(), productId); memberLoanCycle.put(clientData.id(), loanCounter); accountLinkingOptions.addAll(getaccountLinkingOptions(newLoanAccount, clientData.id(), groupId)); @@ -514,7 +514,7 @@ public class LoansApiResource { compoundingCalendarData); } if (loanBasicDetails.isMonthlyRepaymentFrequencyType()) { - Collection loanCalendarDatas = this.calendarReadPlatformService + Collection loanCalendarDatas = this.calendarReadPlatformService .retrieveCalendarsByEntity(loanId, CalendarEntityType.LOANS.getValue(), null); CalendarData calendarData = null; @@ -522,7 +522,7 @@ public class LoansApiResource { calendarData = loanCalendarDatas.iterator().next(); } if(calendarData != null) - loanBasicDetails = LoanAccountData.withLoanCalendarData(loanBasicDetails, calendarData); + loanBasicDetails = LoanAccountData.withLoanCalendarData(loanBasicDetails, calendarData); } Collection interestRatesPeriods = this.loanReadPlatformService.retrieveLoanInterestRatePeriodData(loanBasicDetails); Collection loanRepayments = null; 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 d3c68adc6..d675b3d37 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 @@ -58,12 +58,12 @@ public class LoanTransactionData { private final BigDecimal outstandingLoanBalance; private final LocalDate submittedOnDate; private final boolean manuallyReversed; - private final LocalDate possibleNextRepaymentDate; + private final LocalDate possibleNextRepaymentDate; // templates final Collection paymentTypeOptions; - private Collection writeOffReasonOptions = null; + private Collection writeOffReasonOptions = null; //import fields private transient Integer rowIndex; @@ -259,36 +259,36 @@ public class LoanTransactionData { } 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); - - } + 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; + 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; @@ -310,16 +310,16 @@ public class LoanTransactionData { this.submittedOnDate = submittedOnDate; this.manuallyReversed = manuallyReversed; this.possibleNextRepaymentDate = possibleNextRepaymentDate; - } + } - + - public LocalDate dateOf() { + public LocalDate dateOf() { return this.date; } public boolean isNotDisbursement() { - return type.id() == 1; + return type.id() == 1; } @@ -338,6 +338,6 @@ public class LoanTransactionData { } public void setWriteOffReasonOptions(Collection writeOffReasonOptions){ - this.writeOffReasonOptions =writeOffReasonOptions; + this.writeOffReasonOptions =writeOffReasonOptions; } } \ 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 index b437af711..f873ebe14 100755 --- 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 @@ -52,7 +52,7 @@ public class ScheduleGeneratorDTO { final Calendar calendar, final CalendarHistoryDataWrapper calendarHistoryDataWrapper, final Boolean isInterestChargedFromDateAsDisbursementDateEnabled, final Integer numberOfdays, final boolean isSkipRepaymentOnFirstDayofMonth, final Boolean isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled) { - + this.loanScheduleFactory = loanScheduleFactory; this.applicationCurrency = applicationCurrency; this.calculatedRepaymentsStartingFromDate = calculatedRepaymentsStartingFromDate; @@ -119,7 +119,7 @@ public class ScheduleGeneratorDTO { } public Calendar getCalendar(){ - return this.calendar; + return this.calendar; } public CalendarHistoryDataWrapper getCalendarHistoryDataWrapper(){ 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 index 678885d2e..6704e8204 100755 --- 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 @@ -762,12 +762,12 @@ 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) { @@ -1262,7 +1262,7 @@ public class Loan extends AbstractPersistableCustom { final Map actualChanges = this.loanRepaymentScheduleDetail.updateLoanApplicationAttributes(command, aprCalculator); final MonetaryCurrency currency = new MonetaryCurrency(loanProduct.getCurrency().getCode(), loanProduct.getCurrency().getDigitsAfterDecimal(), - loanProduct.getCurrency().getCurrencyInMultiplesOf()); + loanProduct.getCurrency().getCurrencyInMultiplesOf()); this.loanRepaymentScheduleDetail.updateCurrency(currency); if (!actualChanges.isEmpty()) { @@ -3847,11 +3847,11 @@ public class Loan extends AbstractPersistableCustom { return disbursementDate; } - public void setActualDisbursementDate(Date actualDisbursementDate) { - this.actualDisbursementDate = actualDisbursementDate; - } + public void setActualDisbursementDate(Date actualDisbursementDate) { + this.actualDisbursementDate = actualDisbursementDate; + } - public LocalDate getWrittenOffDate() { + public LocalDate getWrittenOffDate() { LocalDate writtenOffDate = null; if (this.writtenOffOnDate != null) { writtenOffDate = new LocalDate(this.writtenOffOnDate); @@ -4717,9 +4717,9 @@ public class Loan extends AbstractPersistableCustom { if (loanCharge.isInstalmentFee()) { List installments = getRepaymentScheduleInstallments() ; for (final LoanRepaymentScheduleInstallment installment : installments) { - if(installment.isRecalculatedInterestComponent()){ - continue; - } + if(installment.isRecalculatedInterestComponent()){ + continue; + } BigDecimal amount = BigDecimal.ZERO; if (loanCharge.getChargeCalculation().isFlat()) { amount = loanCharge.amountOrPercentage(); @@ -6149,33 +6149,33 @@ public class Loan extends AbstractPersistableCustom { 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()))); - } else { - feeForCurrentPeriod = feeForCurrentPeriod.plus(loanCharge.getAmount(currency)); - feeAccountedForCurrentPeriod = feeAccountedForCurrentPeriod - .plus(loanCharge.getAmountWaived(getCurrency()).plus( + 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()))); + } else { + feeForCurrentPeriod = feeForCurrentPeriod.plus(loanCharge.getAmount(currency)); + feeAccountedForCurrentPeriod = feeAccountedForCurrentPeriod + .plus(loanCharge.getAmountWaived(getCurrency()).plus( - loanCharge.getAmountPaid(getCurrency()))); - } - } else if (loanCharge.isInstalmentFee()) { - LoanInstallmentCharge loanInstallmentCharge = loanCharge - .getInstallmentLoanCharge(installment.getInstallmentNumber()); - if (loanCharge.isPenaltyCharge()) { - penaltyAccoutedForCurrentPeriod = penaltyAccoutedForCurrentPeriod - .plus(loanInstallmentCharge.getAmountPaid(currency)); - } else { - feeAccountedForCurrentPeriod = feeAccountedForCurrentPeriod - .plus(loanInstallmentCharge.getAmountPaid(currency)); - } - } - } - } + loanCharge.getAmountPaid(getCurrency()))); + } + } else if (loanCharge.isInstalmentFee()) { + LoanInstallmentCharge loanInstallmentCharge = loanCharge + .getInstallmentLoanCharge(installment.getInstallmentNumber()); + if (loanCharge.isPenaltyCharge()) { + penaltyAccoutedForCurrentPeriod = penaltyAccoutedForCurrentPeriod + .plus(loanInstallmentCharge.getAmountPaid(currency)); + } else { + feeAccountedForCurrentPeriod = feeAccountedForCurrentPeriod + .plus(loanInstallmentCharge.getAmountPaid(currency)); + } + } + } + } Money[] balances = new Money[6]; balances[0] = interestForCurrentPeriod; @@ -6327,9 +6327,9 @@ public class Loan extends AbstractPersistableCustom { if (!installment.getDueDate().isBefore(transactionDate)) { totalPrincipal = totalPrincipal.plus(installment.getPrincipal(currency)); newInstallments.remove(installment); - if (installment.getDueDate().isEqual(transactionDate)) { - isInterestComponent = false; - } + if (installment.getDueDate().isEqual(transactionDate)) { + isInterestComponent = false; + } } } @@ -6346,14 +6346,14 @@ public class Loan extends AbstractPersistableCustom { installmentStartDate = newInstallments.get((newInstallments.size() - 1)).getDueDate(); } - int installmentNumber = newInstallments.size(); + int installmentNumber = newInstallments.size(); - if (!isInterestComponent) { - installmentNumber++; - } + if (!isInterestComponent) { + installmentNumber++; + } - LoanRepaymentScheduleInstallment newInstallment = new LoanRepaymentScheduleInstallment(null, newInstallments.size() + 1, + LoanRepaymentScheduleInstallment newInstallment = new LoanRepaymentScheduleInstallment(null, newInstallments.size() + 1, installmentStartDate, transactionDate, totalPrincipal.getAmount(), balances[0].getAmount(), balances[1].getAmount(), balances[2].getAmount(), isInterestComponent, null); newInstallment.updateInstallmentNumber(newInstallments.size() + 1); @@ -6372,22 +6372,22 @@ 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))) { - loanTransaction.reverse(); - } - } + 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))) { + loanTransaction.reverse(); + } + } - } - } + } + } } public void updateLoanScheduleOnForeclosure(final Collection installments) { @@ -6410,17 +6410,17 @@ public class Loan extends AbstractPersistableCustom { return isForeClosure; } - public Set getActiveLoanTermVariations() { - Set retData = new HashSet<>(); - if(this.loanTermVariations != null && this.loanTermVariations.size() > 0){ - for (LoanTermVariations loanTermVariations : this.loanTermVariations) { - if(loanTermVariations.isActive()){ - retData.add(loanTermVariations); - } - } - } + public Set getActiveLoanTermVariations() { + Set retData = new HashSet<>(); + if(this.loanTermVariations != null && this.loanTermVariations.size() > 0){ + for (LoanTermVariations loanTermVariations : this.loanTermVariations) { + if(loanTermVariations.isActive()){ + retData.add(loanTermVariations); + } + } + } return retData.size()>0?retData:null; - } + } public void setIsTopup(final boolean isTopup) { this.isTopup = isTopup; 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 index 53168eff5..47614b9e2 100755 --- 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 @@ -293,12 +293,12 @@ public class LoanInstallmentCharge extends AbstractPersistableCustom imple return amountToDeductOnThisCharge; } - public LoanCharge getLoancharge() { - return this.loancharge; - } - public LoanRepaymentScheduleInstallment getInstallment() { - return this.installment; - } + public LoanCharge getLoancharge() { + return this.loancharge; + } + public LoanRepaymentScheduleInstallment getInstallment() { + return this.installment; + } } \ No newline at end of file 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 d8985613d..ee5bcc426 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 @@ -128,8 +128,8 @@ public enum LoanTransactionType { loanTransactionType = LoanTransactionType.REFUND_FOR_ACTIVE_LOAN; break; case 19: - loanTransactionType = LoanTransactionType.INCOME_POSTING; - break; + loanTransactionType = LoanTransactionType.INCOME_POSTING; + break; default: loanTransactionType = LoanTransactionType.INVALID; break; 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 b0e09c426..a07bf730a 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 @@ -30,10 +30,10 @@ import org.joda.time.LocalDate; public class DateMismatchException extends AbstractPlatformDomainRuleException { public DateMismatchException(final LocalDate actualDisbursementDate, - final LocalDate expectedDisbursedOnLocalDate) { + 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); + + "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/UndoLastTrancheDisbursementException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/UndoLastTrancheDisbursementException.java index e66c2729a..c8a672115 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 @@ -22,10 +22,10 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR 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); - - } + 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); + + } } 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 1be3d268e..e8181c0ba 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 @@ -82,9 +82,9 @@ public class GuarantorsApiResource { "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, - AccountTransfersApiConstants.currencyParamName)); + private static final Set ACCOUNT_TRANSFER_API_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(AccountDetailConstants.idParamName, AccountTransfersApiConstants.transferDescriptionParamName, + AccountTransfersApiConstants.currencyParamName)); private final String resourceNameForPermission = "GUARANTOR"; 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 30f253b26..79f5560b1 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 @@ -24,33 +24,33 @@ import java.math.BigDecimal; @SuppressWarnings("unused") public class ObligeeData { - private final String firstName; - private final String lastName; - private final String displayName; - private final String accountNumber; - private final BigDecimal loanAmount; - private final BigDecimal guaranteeAmount; - private final BigDecimal amountReleased; - private final BigDecimal amountTransferred; + private final String firstName; + private final String lastName; + private final String displayName; + private final String accountNumber; + private final BigDecimal loanAmount; + private final BigDecimal guaranteeAmount; + 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) { - this.firstName = firstname; - this.lastName = lastname; - this.displayName = displayName; - this.accountNumber = accountNumber; - this.loanAmount = loanAmount; - this.guaranteeAmount = guaranteeAmount; - this.amountReleased = amountReleased; - this.amountTransferred = 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; + this.accountNumber = accountNumber; + this.loanAmount = loanAmount; + this.guaranteeAmount = guaranteeAmount; + this.amountReleased = amountReleased; + 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/service/GuarantorReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformService.java index 7beb348e2..7e521a4eb 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 @@ -42,8 +42,8 @@ public interface GuarantorReadPlatformService { */ List retrieveGuarantorsForLoan(Long loanId); - GuarantorData retrieveGuarantor(Long loanId, Long guarantorId); + GuarantorData retrieveGuarantor(Long loanId, Long guarantorId); - List retrieveObligeeDetails(Long clientId); + 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 6489153b9..2317b37e7 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 @@ -290,56 +290,56 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe return guarantorData; } - @Override - public List retrieveObligeeDetails(final Long clientId) { - final ObligeeMapper rm = new ObligeeMapper(); - String sql = rm.schema(); - try { - return this.jdbcTemplate.query(sql, rm, new Object[] { clientId }); - } catch (final EmptyResultDataAccessException e) { - return null; - } + @Override + public List retrieveObligeeDetails(final Long clientId) { + final ObligeeMapper rm = new ObligeeMapper(); + String sql = rm.schema(); + try { + return this.jdbcTemplate.query(sql, rm, new Object[] { clientId }); + } catch (final EmptyResultDataAccessException e) { + return null; + } - } + } - private static final class ObligeeMapper implements RowMapper { + private static final class ObligeeMapper implements RowMapper { - private final String sql; + private final String sql; - public ObligeeMapper() { - StringBuilder sb = new StringBuilder( - "SELECT cl.firstname, cl.lastname,cl.display_name as displayName, loan.account_no as loanAccountNumber, loan.principal_amount as loanAmount, gfd.amount as guaranteedAmount, "); - 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 cl ON loan.client_id = cl.id "); - sql = sb.toString(); - } + public ObligeeMapper() { + StringBuilder sb = new StringBuilder( + "SELECT cl.firstname, cl.lastname,cl.display_name as displayName, loan.account_no as loanAccountNumber, loan.principal_amount as loanAmount, gfd.amount as guaranteedAmount, "); + 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 cl ON loan.client_id = cl.id "); + sql = sb.toString(); + } - public String schema() { - return this.sql; - } + public String schema() { + return this.sql; + } - @Override - 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"); - final String loanAccountNumber = rs.getString("loanAccountNumber"); + @Override + 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"); + final String loanAccountNumber = rs.getString("loanAccountNumber"); - final BigDecimal loanAmount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "loanAmount"); - final BigDecimal guaranteeAmount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "guaranteedAmount"); - final BigDecimal amountReleased = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountReleased"); - final BigDecimal amountTransferred = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountTransferred"); + final BigDecimal loanAmount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "loanAmount"); + final BigDecimal guaranteeAmount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "guaranteedAmount"); + 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/handler/UpdateLoanDisbuseDateCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanDisbuseDateCommandHandler.java index 215f606dc..79ff52525 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 @@ -39,7 +39,7 @@ public class UpdateLoanDisbuseDateCommandHandler implements NewCommandSourceHand @Transactional @Override public CommandProcessingResult processCommand(final JsonCommand command) { - + 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/loanschedule/domain/AbstractLoanScheduleGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/AbstractLoanScheduleGenerator.java index fb5c12ab0..c641cda1e 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 @@ -541,7 +541,7 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener LocalDate periodStartDateApplicableForInterest, final double interestCalculationGraceOnRepaymentPeriodFraction, final ScheduleCurrentPeriodParams currentPeriodParams, final Money lastTotalOutstandingInterestPaymentDueToGrace, final LocalDate transactionDate, final LoanScheduleModelPeriod installment, Set loanCharges) { - LoanScheduleModelPeriod modifiedInstallment = installment; + LoanScheduleModelPeriod modifiedInstallment = installment; Money oustanding = scheduleParams.getOutstandingBalance(); PrincipalInterest tempPrincipalInterest = new PrincipalInterest(currentPeriodParams.getPrincipalForThisPeriod(), currentPeriodParams.getInterestForThisPeriod(), null); @@ -1396,29 +1396,29 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener totalInterest = totalInterest.plus(interest); if(loanApplicationTerms.getInterestRecalculationCompoundingMethod().isCompoundingEnabled()) { - Money uncompounded = params.getUnCompoundedAmount(); - Money compounded = uncompounded.zero(); - for (Map.Entry mapEntry : params.getCompoundingMap().entrySet()) { - if (mapEntry.getKey().isAfter(params.getPeriodStartDate())) { - compounded = compounded.plus(mapEntry.getValue()); - } - } - if (compounded.isGreaterThanZero() && startDate.isEqual(additionalPeriodsStartDate)) { - params.setCompoundedInLastInstallment(uncompoundedFromLastInstallment);// uncompounded in last installment - additionalPeriodsStartDate = additionalPeriodsStartDate.plusDays(1); - } - Money compoundedForThisPeriod = compounded.minus(uncompounded); - Money uncompoundedForThisPeriod = interest.minus(compoundedForThisPeriod); - params.setUnCompoundedAmount(uncompoundedForThisPeriod); - LocalDate compoundingDate = params.getPeriodStartDate(); - if (loanApplicationTerms.allowCompoundingOnEod()) { - compoundingDate = compoundingDate.minusDays(1); - } - compoundingDate = getNextCompoundScheduleDate(compoundingDate, loanApplicationTerms, holidayDetailDTO); - if(compoundingDate.isEqual(params.getActualRepaymentDate())){ - params.getCompoundingMap().put(compoundingDate, uncompoundedForThisPeriod); - params.setUnCompoundedAmount(uncompoundedForThisPeriod.zero()); - } + Money uncompounded = params.getUnCompoundedAmount(); + Money compounded = uncompounded.zero(); + for (Map.Entry mapEntry : params.getCompoundingMap().entrySet()) { + if (mapEntry.getKey().isAfter(params.getPeriodStartDate())) { + compounded = compounded.plus(mapEntry.getValue()); + } + } + if (compounded.isGreaterThanZero() && startDate.isEqual(additionalPeriodsStartDate)) { + params.setCompoundedInLastInstallment(uncompoundedFromLastInstallment);// uncompounded in last installment + additionalPeriodsStartDate = additionalPeriodsStartDate.plusDays(1); + } + Money compoundedForThisPeriod = compounded.minus(uncompounded); + Money uncompoundedForThisPeriod = interest.minus(compoundedForThisPeriod); + params.setUnCompoundedAmount(uncompoundedForThisPeriod); + LocalDate compoundingDate = params.getPeriodStartDate(); + if (loanApplicationTerms.allowCompoundingOnEod()) { + compoundingDate = compoundingDate.minusDays(1); + } + compoundingDate = getNextCompoundScheduleDate(compoundingDate, loanApplicationTerms, holidayDetailDTO); + if(compoundingDate.isEqual(params.getActualRepaymentDate())){ + params.getCompoundingMap().put(compoundingDate, uncompoundedForThisPeriod); + params.setUnCompoundedAmount(uncompoundedForThisPeriod.zero()); + } } } params.setPeriodStartDate(params.getActualRepaymentDate()); 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 24b166ea5..3ba4d4f88 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 @@ -899,9 +899,9 @@ public final class LoanApplicationTerms { final int totalRepaymentsWithCapitalPayment = calculateNumberOfRepaymentsWithPrincipalPayment(); Money principalPerPeriod = null; if (getFixedEmiAmount() == null) { - principalPerPeriod = this.principal.minus(totalPrincipalAccounted).dividedBy(totalRepaymentsWithCapitalPayment, mc.getRoundingMode()).plus( + principalPerPeriod = this.principal.minus(totalPrincipalAccounted).dividedBy(totalRepaymentsWithCapitalPayment, mc.getRoundingMode()).plus( this.adjustPrincipalForFlatLoans); - if (isPrincipalGraceApplicableForThisPeriod(periodNumber)) { + if (isPrincipalGraceApplicableForThisPeriod(periodNumber)) { principalPerPeriod = principalPerPeriod.zero(); } if (!isPrincipalGraceApplicableForThisPeriod(periodNumber) && currentPeriodFixedPrincipalAmount != null) { @@ -911,8 +911,8 @@ public final class LoanApplicationTerms { } }else{ - principalPerPeriod = Money.of(this.getCurrency(), getFixedEmiAmount()).minus(interestForThisInstallment); - return principalPerPeriod; + principalPerPeriod = Money.of(this.getCurrency(), getFixedEmiAmount()).minus(interestForThisInstallment); + return principalPerPeriod; } return principalPerPeriod; @@ -1133,7 +1133,7 @@ public final class LoanApplicationTerms { * if grace period available then need to be subtracted */ if(this.interestChargingGrace != null){ - periodsRemaining = periodsRemaining - this.interestChargingGrace; + periodsRemaining = periodsRemaining - this.interestChargingGrace; } return periodsRemaining; } 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 8b6edd1d4..2daff5bdc 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 @@ -532,7 +532,7 @@ public class LoanScheduleAssembler { } private void validateRepaymentsStartDateWithMeetingDates(final LocalDate repaymentsStartingFromDate, final Calendar calendar, - boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays) { + boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays) { if (repaymentsStartingFromDate != null && !CalendarUtils.isValidRedurringDate(calendar.getRecurrence(), calendar.getStartDateLocalDate(), repaymentsStartingFromDate, isSkipRepaymentOnFirstDayOfMonth, numberOfDays)) { 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 4c30ba805..194f4a8d5 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 @@ -50,26 +50,26 @@ import com.google.gson.reflect.TypeToken; 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, - RescheduleLoansApiConstants.rejectedOnDateParam)); + private static final Set REJECT_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(RescheduleLoansApiConstants.localeParamName, RescheduleLoansApiConstants.dateFormatParamName, + RescheduleLoansApiConstants.rejectedOnDateParam)); - private static final Set APPROVE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(RescheduleLoansApiConstants.localeParamName, RescheduleLoansApiConstants.dateFormatParamName, - RescheduleLoansApiConstants.approvedOnDateParam)); + private static final Set APPROVE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(RescheduleLoansApiConstants.localeParamName, RescheduleLoansApiConstants.dateFormatParamName, + RescheduleLoansApiConstants.approvedOnDateParam)); @Autowired public LoanRescheduleRequestDataValidator(FromJsonHelper fromJsonHelper) { 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 8e58e8c5d..53ea0c4c5 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 @@ -22,47 +22,47 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; import org.apache.fineract.portfolio.loanaccount.domain.LoanStatus; public class LoanRescheduleRequestEnumerations { - - public static EnumOptionData status(final LoanRescheduleRequestStatusEnumData status) { - Long id = status.id(); + + public static EnumOptionData status(final LoanRescheduleRequestStatusEnumData status) { + Long id = status.id(); String code = status.code(); String value = status.value(); return new EnumOptionData(id, code, value); - } + } - public static LoanRescheduleRequestStatusEnumData status(final Integer statusId) { - return status(LoanStatus.fromInt(statusId)); - } - - 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"); - - switch(status) { - case SUBMITTED_AND_PENDING_APPROVAL: - enumData = new LoanRescheduleRequestStatusEnumData( - LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue().longValue(), - LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getCode(), "Submitted and pending approval"); - break; - - case APPROVED: - enumData = new LoanRescheduleRequestStatusEnumData( - LoanStatus.APPROVED.getValue().longValue(), - LoanStatus.APPROVED.getCode(), "Approved"); - break; - - case REJECTED: - enumData = new LoanRescheduleRequestStatusEnumData( - LoanStatus.REJECTED.getValue().longValue(), - LoanStatus.REJECTED.getCode(), "Rejected"); - break; - - default: - break; - } - - return enumData; - } + public static LoanRescheduleRequestStatusEnumData status(final Integer statusId) { + return status(LoanStatus.fromInt(statusId)); + } + + 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"); + + switch(status) { + case SUBMITTED_AND_PENDING_APPROVAL: + enumData = new LoanRescheduleRequestStatusEnumData( + LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue().longValue(), + LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getCode(), "Submitted and pending approval"); + break; + + case APPROVED: + enumData = new LoanRescheduleRequestStatusEnumData( + LoanStatus.APPROVED.getValue().longValue(), + LoanStatus.APPROVED.getCode(), "Approved"); + break; + + case REJECTED: + enumData = new LoanRescheduleRequestStatusEnumData( + LoanStatus.REJECTED.getValue().longValue(), + LoanStatus.REJECTED.getCode(), "Rejected"); + break; + + default: + 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 9fe8bcd49..eed7cee34 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 @@ -25,7 +25,7 @@ import org.joda.time.LocalDate; **/ @SuppressWarnings("unused") public class LoanRescheduleRequestTimelineData { - private final LocalDate submittedOnDate; + private final LocalDate submittedOnDate; private final String submittedByUsername; private final String submittedByFirstname; private final String submittedByLastname; @@ -44,8 +44,8 @@ public class LoanRescheduleRequestTimelineData { 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; + + this.submittedOnDate = submittedOnDate; this.submittedByUsername = submittedByUsername; this.submittedByFirstname = submittedByFirstname; this.submittedByLastname = submittedByLastname; @@ -59,6 +59,6 @@ public class LoanRescheduleRequestTimelineData { this.rejectedByUsername = rejectedByUsername; this.rejectedByFirstname = rejectedByFirstname; this.rejectedByLastname = rejectedByLastname; - + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleModalPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleModalPeriod.java index 0ae239bc5..f979b879e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleModalPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleModalPeriod.java @@ -24,12 +24,12 @@ import org.apache.fineract.portfolio.loanaccount.loanschedule.data.LoanScheduleP import org.joda.time.LocalDate; public interface LoanRescheduleModalPeriod { - - LoanSchedulePeriodData toData(); - - Integer periodNumber(); - - Integer oldPeriodNumber(); + + LoanSchedulePeriodData toData(); + + Integer periodNumber(); + + Integer oldPeriodNumber(); LocalDate periodFromDate(); 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 bf06f7712..5f2e9b75d 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 @@ -46,11 +46,11 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity @Table(name = "m_loan_reschedule_request") public class LoanRescheduleRequest extends AbstractPersistableCustom { - + @ManyToOne @JoinColumn(name = "loan_id", nullable = false) private Loan loan; - + @Column(name = "status_enum", nullable = false) private Integer statusEnum; @@ -82,15 +82,15 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { @Temporal(TemporalType.DATE) @Column(name = "approved_on_date") private Date approvedOnDate; - + @ManyToOne @JoinColumn(name = "approved_by_user_id") private AppUser approvedByUser; - + @Temporal(TemporalType.DATE) @Column(name = "rejected_on_date") private Date rejectedOnDate; - + @ManyToOne @JoinColumn(name = "rejected_by_user_id") private AppUser rejectedByUser; @@ -98,7 +98,7 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) @JoinColumn(name = "loan_reschedule_request_id", nullable = false) private Set loanRescheduleRequestToTermVariationMappings = new HashSet<>(); - + /** * LoanRescheduleRequest constructor **/ @@ -125,7 +125,7 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { this.rejectedByUser = rejectedByUser; this.recalculateInterest = recalculateInterest; } - + /** * @return a new instance of the LoanRescheduleRequest class **/ @@ -138,163 +138,163 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { rescheduleReasonCodeValue, rescheduleReasonComment, submittedOnDate, submittedByUser, approvedOnDate, approvedByUser, rejectedOnDate, rejectedByUser); } - - /** - * @return the reschedule request loan object - **/ - public Loan getLoan() { - return this.loan; - } - - /** - * @return the status enum - **/ - public Integer getStatusEnum() { - return this.statusEnum; - } - - /** - * @return installment number of the rescheduling start point - **/ - public Integer getRescheduleFromInstallment() { - return this.rescheduleFromInstallment; - } - - /** - * @return due date of the rescheduling start point - **/ - public LocalDate getRescheduleFromDate() { - - LocalDate localDate = null; - - if(this.rescheduleFromDate != null) { - localDate = new LocalDate(this.rescheduleFromDate); - } - - return localDate; - } - - /** - * @return the reschedule reason code value object - **/ - public CodeValue getRescheduleReasonCodeValue() { - return this.rescheduleReasonCodeValue; - } - - /** - * @return the reschedule reason comment added by the "submittedByUser" - **/ - public String getRescheduleReasonComment() { - return this.rescheduleReasonComment; - } - - /** - * @return the date the request was submitted - **/ - public LocalDate getSubmittedOnDate() { - LocalDate localDate = null; - - if(this.submittedOnDate != null) { - localDate = new LocalDate(this.submittedOnDate); - } - - return localDate; - } - - /** - * @return the user that submitted the request - **/ - public AppUser getSubmittedByUser() { - return this.submittedByUser; - } - - /** - * @return the date the request was approved - **/ - public LocalDate getApprovedOnDate() { - LocalDate localDate = null; - - if(this.approvedOnDate != null) { - localDate = new LocalDate(this.approvedOnDate); - } - - return localDate; - } - - /** - * @return the user that approved the request - **/ - public AppUser getApprovedByUser() { - return this.approvedByUser; - } - - /** - * @return the date the request was rejected - **/ - public LocalDate getRejectedOnDate() { - LocalDate localDate = null; - - if(this.rejectedOnDate != null) { - localDate = new LocalDate(this.rejectedOnDate); - } - - return localDate; - } - - /** - * @return the recalculate interest option (true/false) - **/ - public Boolean getRecalculateInterest() { - boolean recalculateInterest = false; - - if(this.recalculateInterest != null) { - recalculateInterest = this.recalculateInterest; - } - - return recalculateInterest; - } - - /** - * @return the user that rejected the request - **/ - public AppUser getRejectedByUser() { - return this.rejectedByUser; - } - - /** - * 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 - * - **/ - public void approve(final AppUser approvedByUser, final LocalDate approvedOnDate) { - - if(approvedOnDate != null) { - this.approvedByUser = approvedByUser; - this.approvedOnDate = approvedOnDate.toDate(); - this.statusEnum = LoanStatus.APPROVED.getValue(); - } - } - - /** - * 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 - * - **/ - public void reject(final AppUser approvedByUser, final LocalDate approvedOnDate) { - - if(approvedOnDate != null) { - this.rejectedByUser = approvedByUser; - this.rejectedOnDate = approvedOnDate.toDate(); - this.statusEnum = LoanStatus.REJECTED.getValue(); - } - } - + + /** + * @return the reschedule request loan object + **/ + public Loan getLoan() { + return this.loan; + } + + /** + * @return the status enum + **/ + public Integer getStatusEnum() { + return this.statusEnum; + } + + /** + * @return installment number of the rescheduling start point + **/ + public Integer getRescheduleFromInstallment() { + return this.rescheduleFromInstallment; + } + + /** + * @return due date of the rescheduling start point + **/ + public LocalDate getRescheduleFromDate() { + + LocalDate localDate = null; + + if(this.rescheduleFromDate != null) { + localDate = new LocalDate(this.rescheduleFromDate); + } + + return localDate; + } + + /** + * @return the reschedule reason code value object + **/ + public CodeValue getRescheduleReasonCodeValue() { + return this.rescheduleReasonCodeValue; + } + + /** + * @return the reschedule reason comment added by the "submittedByUser" + **/ + public String getRescheduleReasonComment() { + return this.rescheduleReasonComment; + } + + /** + * @return the date the request was submitted + **/ + public LocalDate getSubmittedOnDate() { + LocalDate localDate = null; + + if(this.submittedOnDate != null) { + localDate = new LocalDate(this.submittedOnDate); + } + + return localDate; + } + + /** + * @return the user that submitted the request + **/ + public AppUser getSubmittedByUser() { + return this.submittedByUser; + } + + /** + * @return the date the request was approved + **/ + public LocalDate getApprovedOnDate() { + LocalDate localDate = null; + + if(this.approvedOnDate != null) { + localDate = new LocalDate(this.approvedOnDate); + } + + return localDate; + } + + /** + * @return the user that approved the request + **/ + public AppUser getApprovedByUser() { + return this.approvedByUser; + } + + /** + * @return the date the request was rejected + **/ + public LocalDate getRejectedOnDate() { + LocalDate localDate = null; + + if(this.rejectedOnDate != null) { + localDate = new LocalDate(this.rejectedOnDate); + } + + return localDate; + } + + /** + * @return the recalculate interest option (true/false) + **/ + public Boolean getRecalculateInterest() { + boolean recalculateInterest = false; + + if(this.recalculateInterest != null) { + recalculateInterest = this.recalculateInterest; + } + + return recalculateInterest; + } + + /** + * @return the user that rejected the request + **/ + public AppUser getRejectedByUser() { + return this.rejectedByUser; + } + + /** + * 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 + * + **/ + public void approve(final AppUser approvedByUser, final LocalDate approvedOnDate) { + + if(approvedOnDate != null) { + this.approvedByUser = approvedByUser; + this.approvedOnDate = approvedOnDate.toDate(); + this.statusEnum = LoanStatus.APPROVED.getValue(); + } + } + + /** + * 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 + * + **/ + public void reject(final AppUser approvedByUser, final LocalDate approvedOnDate) { + + if(approvedOnDate != null) { + this.rejectedByUser = approvedByUser; + this.rejectedOnDate = approvedOnDate.toDate(); + this.statusEnum = LoanStatus.REJECTED.getValue(); + } + } + public void updateLoanRescheduleRequestToTermVariationMappings(final List mapping) { this.loanRescheduleRequestToTermVariationMappings.addAll(mapping); } @@ -303,15 +303,15 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { return this.loanRescheduleRequestToTermVariationMappings; } - public LoanTermVariations getDueDateTermVariationIfExists() { - if(this.loanRescheduleRequestToTermVariationMappings != null - && this.loanRescheduleRequestToTermVariationMappings.size() > 0){ - for (LoanRescheduleRequestToTermVariationMapping mapping : this.loanRescheduleRequestToTermVariationMappings) { - if(mapping.getLoanTermVariations().getTermType().isDueDateVariation()){ - return mapping.getLoanTermVariations(); - } - } - } - return null; - } + public LoanTermVariations getDueDateTermVariationIfExists() { + if(this.loanRescheduleRequestToTermVariationMappings != null + && this.loanRescheduleRequestToTermVariationMappings.size() > 0){ + for (LoanRescheduleRequestToTermVariationMapping mapping : this.loanRescheduleRequestToTermVariationMappings) { + if(mapping.getLoanTermVariations().getTermType().isDueDateVariation()){ + return mapping.getLoanTermVariations(); + } + } + } + return null; + } } 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 9775290a3..c837c5193 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 @@ -25,15 +25,15 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc **/ public class LoanRescheduleRequestNotFoundException extends AbstractPlatformResourceNotFoundException { - /** - * LoanRescheduleRequestNotFoundException constructor - * - * @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); - } + /** + * LoanRescheduleRequestNotFoundException constructor + * + * @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); + } } 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 974a81185..d13e8fd93 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,17 +30,17 @@ 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) { - this.loanRescheduleRequestWritePlatformService = loanRescheduleRequestWritePlatformService; - } - - @Transactional - @Override - public CommandProcessingResult processCommand(JsonCommand jsonCommand) { - return this.loanRescheduleRequestWritePlatformService.approve(jsonCommand); - } + private final LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService; + + @Autowired + public ApproveLoanRescheduleRequestCommandHandler( + LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { + this.loanRescheduleRequestWritePlatformService = loanRescheduleRequestWritePlatformService; + } + + @Transactional + @Override + public CommandProcessingResult processCommand(JsonCommand jsonCommand) { + return this.loanRescheduleRequestWritePlatformService.approve(jsonCommand); + } } 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 b76e316e6..012770887 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 @@ -30,19 +30,19 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "RESCHEDULELOAN", action = "CREATE") public class CreateLoanRescheduleRequestCommandHandler implements NewCommandSourceHandler { - - private final LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService; - - @Autowired - public CreateLoanRescheduleRequestCommandHandler( - LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { - this.loanRescheduleRequestWritePlatformService = loanRescheduleRequestWritePlatformService; - } + + private final LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService; + + @Autowired + public CreateLoanRescheduleRequestCommandHandler( + LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { + this.loanRescheduleRequestWritePlatformService = loanRescheduleRequestWritePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(JsonCommand jsonCommand) { - return this.loanRescheduleRequestWritePlatformService.create(jsonCommand); - } + @Transactional + @Override + public CommandProcessingResult processCommand(JsonCommand jsonCommand) { + return this.loanRescheduleRequestWritePlatformService.create(jsonCommand); + } } 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 4e97a072d..8d742c4cd 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,17 +30,17 @@ 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) { - this.loanRescheduleRequestWritePlatformService = loanRescheduleRequestWritePlatformService; - } - - @Transactional - @Override - public CommandProcessingResult processCommand(JsonCommand jsonCommand) { - return this.loanRescheduleRequestWritePlatformService.reject(jsonCommand); - } + private final LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService; + + @Autowired + public RejectLoanRescheduleRequestCommandHandler( + LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { + this.loanRescheduleRequestWritePlatformService = loanRescheduleRequestWritePlatformService; + } + + @Transactional + @Override + public CommandProcessingResult processCommand(JsonCommand jsonCommand) { + return this.loanRescheduleRequestWritePlatformService.reject(jsonCommand); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanReschedulePreviewPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanReschedulePreviewPlatformService.java index f91649eeb..79a089bae 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanReschedulePreviewPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanReschedulePreviewPlatformService.java @@ -21,6 +21,6 @@ package org.apache.fineract.portfolio.loanaccount.rescheduleloan.service; import org.apache.fineract.portfolio.loanaccount.loanschedule.domain.LoanScheduleModel; public interface LoanReschedulePreviewPlatformService { - - public LoanScheduleModel previewLoanReschedule(Long requestId); + + public LoanScheduleModel previewLoanReschedule(Long requestId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestWritePlatformService.java index b2dccf9c3..da8706bec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestWritePlatformService.java @@ -22,10 +22,10 @@ import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface LoanRescheduleRequestWritePlatformService { - - CommandProcessingResult create(JsonCommand jsonCommand); + + CommandProcessingResult create(JsonCommand jsonCommand); - CommandProcessingResult approve(JsonCommand jsonCommand); - - CommandProcessingResult reject(JsonCommand jsonCommand); + CommandProcessingResult approve(JsonCommand jsonCommand); + + CommandProcessingResult reject(JsonCommand jsonCommand); } 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 3366ddeb4..401ad7b51 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 @@ -1100,7 +1100,7 @@ public final class LoanApplicationCommandFromApiJsonHelper { final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.disbursementDataParameterName, element) && expectedDisbursement != null && totalPrincipal != null) { - + BigDecimal tatalDisbursement = BigDecimal.ZERO; final JsonArray variationArray = this.fromApiJsonHelper.extractJsonArrayNamed(LoanApiConstants.disbursementDataParameterName, element); @@ -1121,10 +1121,10 @@ public final class LoanApplicationCommandFromApiJsonHelper { .parameterAtIndexArray(LoanApiConstants.disbursementDateParameterName, i).value(expectedDisbursementDate) .notNull(); if(i == 0 && expectedDisbursementDate != null && !expectedDisbursement.equals(expectedDisbursementDate)) { - baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName) + 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) + baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName) .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_BEFORE_ERROR); } 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 3f70aec4a..a1ac49eac 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 @@ -56,7 +56,7 @@ public final class LoanEventApiJsonValidator { @Autowired public LoanEventApiJsonValidator(final FromJsonHelper fromApiJsonHelper, - final LoanApplicationCommandFromApiJsonHelper fromApiJsonDeserializer) { + final LoanApplicationCommandFromApiJsonHelper fromApiJsonDeserializer) { this.fromApiJsonHelper = fromApiJsonHelper; this.fromApiJsonDeserializer = fromApiJsonDeserializer; } @@ -248,7 +248,7 @@ public final class LoanEventApiJsonValidator { baseDataValidator.reset().parameter("amount").value(amount).notNull().positiveAmount(); if (this.fromApiJsonHelper.parameterExists("dueDate", element)) { - final LocalDate dueDate = this.fromApiJsonHelper.extractLocalDateNamed("dueDate", element); + final LocalDate dueDate = this.fromApiJsonHelper.extractLocalDateNamed("dueDate", element); baseDataValidator.reset().parameter("dueDate").value(dueDate).notBlank(); } @@ -404,11 +404,11 @@ public final class LoanEventApiJsonValidator { final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject()); final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalNamed(LoanApiConstants.updatedDisbursementPrincipalParameterName, - element,locale); + 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); 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 index 96f400828..9742bb3e7 100755 --- 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 @@ -235,7 +235,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa } final Long groupId = this.fromJsonHelper.extractLongNamed("groupId", command.parsedJson()); if(groupId != null){ - Group group= this.groupRepository.findOneWithNotFoundDetection(groupId); + Group group= this.groupRepository.findOneWithNotFoundDetection(groupId); officeSpecificLoanProductValidation( productId,group.getOffice().getId()); } @@ -262,7 +262,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa final Loan newLoanApplication = this.loanAssembler.assembleFrom(command, currentUser); - checkForProductMixRestrictions(newLoanApplication); + checkForProductMixRestrictions(newLoanApplication); validateSubmittedOnDate(newLoanApplication); @@ -417,9 +417,9 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -988,16 +988,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 @@ -1026,7 +1026,7 @@ public void checkForProductMixRestrictions(final Loan loan) { }catch (final PersistenceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -1035,7 +1035,7 @@ public void checkForProductMixRestrictions(final Loan loan) { * is. */ 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"))) { final String accountNo = command.stringValueOfParameterNamed("accountNo"); @@ -1068,11 +1068,11 @@ public void checkForProductMixRestrictions(final Loan loan) { 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); return new CommandProcessingResultBuilder() // @@ -1402,19 +1402,19 @@ 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 index 6a39299d0..0564003fe 100755 --- 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 @@ -334,8 +334,8 @@ public class LoanArrearsAgingServiceImpl implements LoanArrearsAgingService, Bus 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"); 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 84e7d66f9..cb078c3c0 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 @@ -135,11 +135,11 @@ public interface LoanReadPlatformService { LoanTransactionData retrieveLoanForeclosureTemplate(final Long loanId, final LocalDate transactionDate); - LoanAccountData retrieveLoanByLoanAccount(String loanAccountNumber); - - Long retrieveLoanIdByAccountNumber(String loanAccountNumber); - - String retrieveAccountNumberByAccountId(Long accountId); + LoanAccountData retrieveLoanByLoanAccount(String loanAccountNumber); + + Long retrieveLoanIdByAccountNumber(String loanAccountNumber); + + String retrieveAccountNumberByAccountId(Long accountId); Integer retrieveNumberOfActiveLoans(); 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 c64227488..be9c9b60f 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 @@ -462,19 +462,19 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { 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; } @@ -2258,14 +2258,14 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { } - public String retrieveAccountNumberByAccountId(Long accountId) { - try { - final String sql = "select loan.account_no from m_loan loan where loan.id = ?"; - return this.jdbcTemplate.queryForObject(sql, new Object[] { accountId }, String.class); - } catch (final EmptyResultDataAccessException e) { - throw new LoanNotFoundException(accountId); - } - } + public String retrieveAccountNumberByAccountId(Long accountId) { + try { + final String sql = "select loan.account_no from m_loan loan where loan.id = ?"; + return this.jdbcTemplate.queryForObject(sql, new Object[] { accountId }, String.class); + } catch (final EmptyResultDataAccessException e) { + throw new LoanNotFoundException(accountId); + } + } @Override 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 cdd1d21fe..014efe68e 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 @@ -45,279 +45,279 @@ import java.util.concurrent.*; @Service public class LoanSchedularServiceImpl implements LoanSchedularService { - private final static Logger logger = LoggerFactory.getLogger(LoanSchedularServiceImpl.class); - private final ConfigurationDomainService configurationDomainService; - private final LoanReadPlatformService loanReadPlatformService; - private final LoanWritePlatformService loanWritePlatformService; - private final OfficeReadPlatformService officeReadPlatformService; - private final ApplicationContext applicationContext; + private final static Logger logger = LoggerFactory.getLogger(LoanSchedularServiceImpl.class); + private final ConfigurationDomainService configurationDomainService; + private final LoanReadPlatformService loanReadPlatformService; + private final LoanWritePlatformService loanWritePlatformService; + private final OfficeReadPlatformService officeReadPlatformService; + private final ApplicationContext applicationContext; - @Autowired - public LoanSchedularServiceImpl(final ConfigurationDomainService configurationDomainService, - final LoanReadPlatformService loanReadPlatformService, final LoanWritePlatformService loanWritePlatformService, - final OfficeReadPlatformService officeReadPlatformService, - final ApplicationContext applicationContext) { - this.configurationDomainService = configurationDomainService; - this.loanReadPlatformService = loanReadPlatformService; - this.loanWritePlatformService = loanWritePlatformService; - this.officeReadPlatformService = officeReadPlatformService; - this.applicationContext=applicationContext; - } + @Autowired + public LoanSchedularServiceImpl(final ConfigurationDomainService configurationDomainService, + final LoanReadPlatformService loanReadPlatformService, final LoanWritePlatformService loanWritePlatformService, + final OfficeReadPlatformService officeReadPlatformService, + final ApplicationContext applicationContext) { + this.configurationDomainService = configurationDomainService; + this.loanReadPlatformService = loanReadPlatformService; + this.loanWritePlatformService = loanWritePlatformService; + this.officeReadPlatformService = officeReadPlatformService; + this.applicationContext=applicationContext; + } - @Override - @CronTarget(jobName = JobName.APPLY_CHARGE_TO_OVERDUE_LOAN_INSTALLMENT) - public void applyChargeForOverdueLoans() throws JobExecutionException { + @Override + @CronTarget(jobName = JobName.APPLY_CHARGE_TO_OVERDUE_LOAN_INSTALLMENT) + public void applyChargeForOverdueLoans() throws JobExecutionException { - final Long penaltyWaitPeriodValue = this.configurationDomainService.retrievePenaltyWaitPeriod(); - final Boolean backdatePenalties = this.configurationDomainService.isBackdatePenaltiesEnabled(); - final Collection overdueLoanScheduledInstallments = this.loanReadPlatformService - .retrieveAllLoansWithOverdueInstallments(penaltyWaitPeriodValue,backdatePenalties); + final Long penaltyWaitPeriodValue = this.configurationDomainService.retrievePenaltyWaitPeriod(); + final Boolean backdatePenalties = this.configurationDomainService.isBackdatePenaltiesEnabled(); + final Collection overdueLoanScheduledInstallments = this.loanReadPlatformService + .retrieveAllLoansWithOverdueInstallments(penaltyWaitPeriodValue,backdatePenalties); - if (!overdueLoanScheduledInstallments.isEmpty()) { - final StringBuilder sb = new StringBuilder(); - final Map> overdueScheduleData = new HashMap<>(); - for (final OverdueLoanScheduleData overdueInstallment : overdueLoanScheduledInstallments) { - if (overdueScheduleData.containsKey(overdueInstallment.getLoanId())) { - overdueScheduleData.get(overdueInstallment.getLoanId()).add(overdueInstallment); - } else { - Collection loanData = new ArrayList<>(); - loanData.add(overdueInstallment); - overdueScheduleData.put(overdueInstallment.getLoanId(), loanData); - } - } + if (!overdueLoanScheduledInstallments.isEmpty()) { + final StringBuilder sb = new StringBuilder(); + final Map> overdueScheduleData = new HashMap<>(); + for (final OverdueLoanScheduleData overdueInstallment : overdueLoanScheduledInstallments) { + if (overdueScheduleData.containsKey(overdueInstallment.getLoanId())) { + overdueScheduleData.get(overdueInstallment.getLoanId()).add(overdueInstallment); + } else { + Collection loanData = new ArrayList<>(); + loanData.add(overdueInstallment); + overdueScheduleData.put(overdueInstallment.getLoanId(), loanData); + } + } - for (final Long loanId : overdueScheduleData.keySet()) { - try { - this.loanWritePlatformService.applyOverdueChargesForLoan(loanId, overdueScheduleData.get(loanId)); + for (final Long loanId : overdueScheduleData.keySet()) { + try { + this.loanWritePlatformService.applyOverdueChargesForLoan(loanId, overdueScheduleData.get(loanId)); - } catch (final PlatformApiDataValidationException e) { - final List errors = e.getErrors(); - for (final ApiParameterError error : errors) { - logger.error("Apply Charges due for overdue loans failed for account:" + loanId + " with message " - + error.getDeveloperMessage()); - sb.append("Apply Charges due for overdue loans failed for account:").append(loanId).append(" with message ") - .append(error.getDeveloperMessage()); - } - } catch (final AbstractPlatformDomainRuleException ex) { - logger.error("Apply Charges due for overdue loans failed for account:" + loanId + " with message " - + ex.getDefaultUserMessage()); - sb.append("Apply Charges due for overdue loans failed for account:").append(loanId).append(" with message ") - .append(ex.getDefaultUserMessage()); - } catch (Exception e) { - Throwable realCause = e; - if (e.getCause() != null) { - realCause = e.getCause(); - } - logger.error("Apply Charges due for overdue loans failed for account:" + loanId + " with message " - + realCause.getMessage()); - sb.append("Apply Charges due for overdue loans failed for account:").append(loanId).append(" with message ") - .append(realCause.getMessage()); - } - } - if (sb.length() > 0) { throw new JobExecutionException(sb.toString()); } - } - } + } catch (final PlatformApiDataValidationException e) { + final List errors = e.getErrors(); + for (final ApiParameterError error : errors) { + logger.error("Apply Charges due for overdue loans failed for account:" + loanId + " with message " + + error.getDeveloperMessage()); + sb.append("Apply Charges due for overdue loans failed for account:").append(loanId).append(" with message ") + .append(error.getDeveloperMessage()); + } + } catch (final AbstractPlatformDomainRuleException ex) { + logger.error("Apply Charges due for overdue loans failed for account:" + loanId + " with message " + + ex.getDefaultUserMessage()); + sb.append("Apply Charges due for overdue loans failed for account:").append(loanId).append(" with message ") + .append(ex.getDefaultUserMessage()); + } catch (Exception e) { + Throwable realCause = e; + if (e.getCause() != null) { + realCause = e.getCause(); + } + logger.error("Apply Charges due for overdue loans failed for account:" + loanId + " with message " + + realCause.getMessage()); + sb.append("Apply Charges due for overdue loans failed for account:").append(loanId).append(" with message ") + .append(realCause.getMessage()); + } + } + if (sb.length() > 0) { throw new JobExecutionException(sb.toString()); } + } + } - @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(); - int i = 0; - if (!loanIds.isEmpty()) { - final StringBuilder sb = new StringBuilder(); - for (Long loanId : loanIds) { - logger.info("Loan ID " + loanId); - Integer numberOfRetries = 0; - while (numberOfRetries <= maxNumberOfRetries) { - try { - this.loanWritePlatformService - .recalculateInterest(loanId); - numberOfRetries = maxNumberOfRetries + 1; - } catch (CannotAcquireLockException - | ObjectOptimisticLockingFailureException exception) { - logger.info("Recalulate interest job has been retried " - + numberOfRetries + " time(s)"); - /*** - * Fail if the transaction has been retired for - * maxNumberOfRetries - **/ - if (numberOfRetries >= maxNumberOfRetries) { - logger.warn("Recalulate interest job has been retried for the max allowed attempts of " - + numberOfRetries - + " and will be rolled back"); - sb.append("Recalulate interest job has been retried for the max allowed attempts of " - + numberOfRetries - + " and will be rolled back"); - break; - } - /*** - * 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) { - sb.append("Interest recalculation for loans failed " + exception.getMessage()) ; - break; - } - } catch (Exception e) { - Throwable realCause = e; - if (e.getCause() != null) { - realCause = e.getCause(); - } - logger.error("Interest recalculation for loans failed for account:" + loanId + " with message " - + realCause.getMessage()); - sb.append("Interest recalculation for loans failed for account:").append(loanId).append(" with message ") - .append(realCause.getMessage()); - numberOfRetries = maxNumberOfRetries + 1; - } - i++; - } - logger.info("Loans count " + i); - } - if (sb.length() > 0) { - throw new JobExecutionException(sb.toString()); - } - } + @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(); + int i = 0; + if (!loanIds.isEmpty()) { + final StringBuilder sb = new StringBuilder(); + for (Long loanId : loanIds) { + logger.info("Loan ID " + loanId); + Integer numberOfRetries = 0; + while (numberOfRetries <= maxNumberOfRetries) { + try { + this.loanWritePlatformService + .recalculateInterest(loanId); + numberOfRetries = maxNumberOfRetries + 1; + } catch (CannotAcquireLockException + | ObjectOptimisticLockingFailureException exception) { + logger.info("Recalulate interest job has been retried " + + numberOfRetries + " time(s)"); + /*** + * Fail if the transaction has been retired for + * maxNumberOfRetries + **/ + if (numberOfRetries >= maxNumberOfRetries) { + logger.warn("Recalulate interest job has been retried for the max allowed attempts of " + + numberOfRetries + + " and will be rolled back"); + sb.append("Recalulate interest job has been retried for the max allowed attempts of " + + numberOfRetries + + " and will be rolled back"); + break; + } + /*** + * 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) { + sb.append("Interest recalculation for loans failed " + exception.getMessage()) ; + break; + } + } catch (Exception e) { + Throwable realCause = e; + if (e.getCause() != null) { + realCause = e.getCause(); + } + logger.error("Interest recalculation for loans failed for account:" + loanId + " with message " + + realCause.getMessage()); + sb.append("Interest recalculation for loans failed for account:").append(loanId).append(" with message ") + .append(realCause.getMessage()); + numberOfRetries = maxNumberOfRetries + 1; + } + i++; + } + logger.info("Loans count " + i); + } + if (sb.length() > 0) { + throw new JobExecutionException(sb.toString()); + } + } - } + } - @Override - @CronTarget(jobName = JobName.RECALCULATE_INTEREST_FOR_LOAN) - public void recalculateInterest(Map jobParameters) { - //gets the officeId - final String officeId = jobParameters.get("officeId"); - logger.info(officeId); - Long officeIdLong=Long.valueOf(officeId); - //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")); + @Override + @CronTarget(jobName = JobName.RECALCULATE_INTEREST_FOR_LOAN) + public void recalculateInterest(Map jobParameters) { + //gets the officeId + final String officeId = jobParameters.get("officeId"); + logger.info(officeId); + Long officeIdLong=Long.valueOf(officeId); + //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")); - recalculateInterest(office,threadPoolSize,batchSize); - } + recalculateInterest(office,threadPoolSize,batchSize); + } - @Override - public void recalculateInterest(OfficeData office, int threadPoolSize, int batchSize) { - final int pageSize = batchSize * threadPoolSize; + @Override + public void recalculateInterest(OfficeData office, int threadPoolSize, int batchSize) { + final int pageSize = batchSize * threadPoolSize; - //initialise the executor service with fetched configurations - final ExecutorService executorService = Executors.newFixedThreadPool(threadPoolSize); + //initialise the executor service with fetched configurations + final ExecutorService executorService = Executors.newFixedThreadPool(threadPoolSize); - Long maxLoanIdInList = 0L; - final String officeHierarchy = office.getHierarchy() + "%"; + Long maxLoanIdInList = 0L; + final String officeHierarchy = office.getHierarchy() + "%"; - //Get the loanIds from service - List loanIds = Collections.synchronizedList(this.loanReadPlatformService - .fetchLoansForInterestRecalculation(pageSize, maxLoanIdInList, officeHierarchy)); + //Get the loanIds from service + List loanIds = Collections.synchronizedList(this.loanReadPlatformService + .fetchLoansForInterestRecalculation(pageSize, maxLoanIdInList, officeHierarchy)); - // gets the loanIds data set iteratively and call addAccuruals for that paginated dataset - do { - int totalFilteredRecords = loanIds.size(); - logger.info("Starting accrual - total filtered records - " + totalFilteredRecords); - recalculateInterest(loanIds, threadPoolSize, batchSize, - executorService); - maxLoanIdInList+= pageSize+1; - loanIds = Collections.synchronizedList(this.loanReadPlatformService - .fetchLoansForInterestRecalculation(pageSize, maxLoanIdInList, officeHierarchy)); - } while (!CollectionUtils.isEmpty(loanIds)); + // gets the loanIds data set iteratively and call addAccuruals for that paginated dataset + do { + int totalFilteredRecords = loanIds.size(); + logger.info("Starting accrual - total filtered records - " + totalFilteredRecords); + recalculateInterest(loanIds, threadPoolSize, batchSize, + executorService); + maxLoanIdInList+= pageSize+1; + loanIds = Collections.synchronizedList(this.loanReadPlatformService + .fetchLoansForInterestRecalculation(pageSize, maxLoanIdInList, officeHierarchy)); + } while (!CollectionUtils.isEmpty(loanIds)); - //shutdown the executor when done - executorService.shutdownNow(); - } + //shutdown the executor when done + executorService.shutdownNow(); + } - private void recalculateInterest(List loanIds, - int threadPoolSize, int batchSize, final ExecutorService executorService) { - //StringBuilder sb = new StringBuilder(); + private void recalculateInterest(List loanIds, + int threadPoolSize, int batchSize, final ExecutorService executorService) { + //StringBuilder sb = new StringBuilder(); - List> posters = new ArrayList>(); - int fromIndex = 0; - // get the size of current paginated dataset - int size = loanIds.size(); - //calculate the batch size - double toGetCeilValue = (double) (size / threadPoolSize); - batchSize = (int) Math.ceil(toGetCeilValue); + List> posters = new ArrayList>(); + int fromIndex = 0; + // get the size of current paginated dataset + int size = loanIds.size(); + //calculate the batch size + double toGetCeilValue = (double) (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 ++; - } - boolean lastBatch = false; - int loopCount = size/batchSize+1; + 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; - 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(Executors.callable(poster)); - if(lastBatch) - break; - 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 ++; - } - } + 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(Executors.callable(poster)); + if(lastBatch) + break; + 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 ++; + } + } - try { - List> responses = executorService.invokeAll(posters); - checkCompletion(responses); - } catch (InterruptedException e1) { - logger.error("Interrupted while recalculateInterest", e1); - } - } - //break the lists into sub lists - public List safeSubList(List list, int fromIndex, int toIndex) { - int size = list.size(); - if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) { - return Collections.emptyList(); - } + try { + List> responses = executorService.invokeAll(posters); + checkCompletion(responses); + } catch (InterruptedException e1) { + logger.error("Interrupted while recalculateInterest", e1); + } + } + //break the lists into sub lists + public List safeSubList(List list, int fromIndex, int toIndex) { + int size = list.size(); + if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) { + return Collections.emptyList(); + } - fromIndex = Math.max(0, fromIndex); - toIndex = Math.min(size, toIndex); + fromIndex = Math.max(0, fromIndex); + toIndex = Math.min(size, toIndex); - return list.subList(fromIndex, toIndex); - } - //checks the execution of task by each thread in the executor service - private void checkCompletion(List> responses) { - try { - for(Future f : responses) { - f.get(); - } - boolean allThreadsExecuted = false; - int noOfThreadsExecuted = 0; - for (Future future : responses) { - if (future.isDone()) { - noOfThreadsExecuted++; - } - } - allThreadsExecuted = noOfThreadsExecuted == responses.size(); - if(!allThreadsExecuted) - logger.error("All threads could not execute."); - } catch (InterruptedException e1) { - logger.error("Interrupted while posting IR entries", e1); - } catch (ExecutionException e2) { - logger.error("Execution exception while posting IR entries", e2); - } - } + return list.subList(fromIndex, toIndex); + } + //checks the execution of task by each thread in the executor service + private void checkCompletion(List> responses) { + try { + for(Future f : responses) { + f.get(); + } + boolean allThreadsExecuted = false; + int noOfThreadsExecuted = 0; + for (Future future : responses) { + if (future.isDone()) { + noOfThreadsExecuted++; + } + } + allThreadsExecuted = noOfThreadsExecuted == responses.size(); + if(!allThreadsExecuted) + logger.error("All threads could not execute."); + } catch (InterruptedException e1) { + logger.error("Interrupted while posting IR entries", e1); + } catch (ExecutionException e2) { + logger.error("Execution exception while posting IR entries", e2); + } + } 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 ec85b8315..0b579f956 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 @@ -147,28 +147,28 @@ public class LoanUtilService { return scheduleGeneratorDTO; } - public Boolean isLoanRepaymentsSyncWithMeeting(final Group group, final Calendar calendar) { - Boolean isSkipRepaymentOnFirstMonth = false; - Long entityId = null; - Long entityTypeId = null; + public Boolean isLoanRepaymentsSyncWithMeeting(final Group group, final Calendar calendar) { + Boolean isSkipRepaymentOnFirstMonth = false; + Long entityId = null; + Long entityTypeId = null; - if (group != null) { - if (group.getParent() != null) { - entityId = group.getParent().getId(); - entityTypeId = CalendarEntityType.CENTERS.getValue().longValue(); - } else { - entityId = group.getId(); - entityTypeId = CalendarEntityType.GROUPS.getValue().longValue(); - } - } + if (group != null) { + if (group.getParent() != null) { + entityId = group.getParent().getId(); + entityTypeId = CalendarEntityType.CENTERS.getValue().longValue(); + } else { + entityId = group.getId(); + entityTypeId = CalendarEntityType.GROUPS.getValue().longValue(); + } + } - if (entityId == null || calendar == null) { - return isSkipRepaymentOnFirstMonth; - } - isSkipRepaymentOnFirstMonth = this.calendarReadPlatformService - .isCalendarAssociatedWithEntity(entityId, calendar.getId(), entityTypeId); - return isSkipRepaymentOnFirstMonth; - } + if (entityId == null || calendar == null) { + return isSkipRepaymentOnFirstMonth; + } + isSkipRepaymentOnFirstMonth = this.calendarReadPlatformService + .isCalendarAssociatedWithEntity(entityId, calendar.getId(), entityTypeId); + return isSkipRepaymentOnFirstMonth; + } public LocalDate getCalculatedRepaymentsStartingFromDate(final Loan loan) { 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 index 69bc84ed8..ba682c4b1 100755 --- 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 @@ -329,7 +329,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf // validate ActualDisbursement Date Against Expected Disbursement Date LoanProduct loanProduct = loan.loanProduct(); if(loanProduct.syncExpectedWithDisbursementDate()){ - syncExpectedDateWithActualDisbursementDate(loan, actualDisbursementDate); + syncExpectedDateWithActualDisbursementDate(loan, actualDisbursementDate); } checkClientOrGroupActive(loan); @@ -342,7 +342,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf LocalDate recalculateFrom = null; if(!loan.isMultiDisburmentLoan()){ - loan.setActualDisbursementDate(actualDisbursementDate.toDate()); + loan.setActualDisbursementDate(actualDisbursementDate.toDate()); } ScheduleGeneratorDTO scheduleGeneratorDTO = this.loanUtilService.buildScheduleGeneratorDTO(loan, recalculateFrom); @@ -363,13 +363,13 @@ 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(); @@ -428,7 +428,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf regenerateScheduleOnDisbursement(command, loan, recalculateSchedule, scheduleGeneratorDTO, nextPossibleRepaymentDate, rescheduledRepaymentDate); if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) { - createAndSaveLoanScheduleArchive(loan, scheduleGeneratorDTO); + createAndSaveLoanScheduleArchive(loan, scheduleGeneratorDTO); } if (isPaymnetypeApplicableforDisbursementCharge) { changedTransactionDetail = loan.disburse(currentUser, command, changes, scheduleGeneratorDTO, paymentDetail); @@ -498,13 +498,13 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf .build(); } - private void createAndSaveLoanScheduleArchive(final Loan loan, ScheduleGeneratorDTO scheduleGeneratorDTO) { - LoanRescheduleRequest loanRescheduleRequest = null; - LoanScheduleModel loanScheduleModel = loan.regenerateScheduleModel(scheduleGeneratorDTO); - List installments = retrieveRepaymentScheduleFromModel(loanScheduleModel); - this.loanScheduleHistoryWritePlatformService.createAndSaveLoanScheduleArchive(installments, - loan, loanRescheduleRequest); - } + private void createAndSaveLoanScheduleArchive(final Loan loan, ScheduleGeneratorDTO scheduleGeneratorDTO) { + LoanRescheduleRequest loanRescheduleRequest = null; + LoanScheduleModel loanScheduleModel = loan.regenerateScheduleModel(scheduleGeneratorDTO); + List installments = retrieveRepaymentScheduleFromModel(loanScheduleModel); + this.loanScheduleHistoryWritePlatformService.createAndSaveLoanScheduleArchive(installments, + loan, loanRescheduleRequest); + } /** * create standing instruction for disbursed loan @@ -634,7 +634,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf // validate ActualDisbursement Date Against Expected Disbursement Date LoanProduct loanProduct = loan.loanProduct(); if(loanProduct.syncExpectedWithDisbursementDate()){ - syncExpectedDateWithActualDisbursementDate(loan, actualDisbursementDate); + syncExpectedDateWithActualDisbursementDate(loan, actualDisbursementDate); } checkClientOrGroupActive(loan); this.businessEventNotifierService.notifyBusinessEventToBeExecuted(BUSINESS_EVENTS.LOAN_DISBURSAL, @@ -678,7 +678,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf regenerateScheduleOnDisbursement(command, loan, recalculateSchedule, scheduleGeneratorDTO, nextPossibleRepaymentDate, rescheduledRepaymentDate); if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) { - createAndSaveLoanScheduleArchive(loan, scheduleGeneratorDTO); + createAndSaveLoanScheduleArchive(loan, scheduleGeneratorDTO); } if (configurationDomainService.isPaymnetypeApplicableforDisbursementCharge()) { changedTransactionDetail = loan.disburse(currentUser, command, changes, scheduleGeneratorDTO, paymentDetail); @@ -1123,10 +1123,10 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf changes.put("dateFormat", command.dateFormat()); final Loan loan = this.loanAssembler.assembleFrom(loanId); if(command.hasParameter("writeoffReasonId")){ - Long writeoffReasonId = command.longValueOfParameterNamed("writeoffReasonId"); - CodeValue writeoffReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(LoanApiConstants.WRITEOFFREASONS, writeoffReasonId); - changes.put("writeoffReasonId", writeoffReasonId); - loan.updateWriteOffReason(writeoffReason); + Long writeoffReasonId = command.longValueOfParameterNamed("writeoffReasonId"); + CodeValue writeoffReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(LoanApiConstants.WRITEOFFREASONS, writeoffReasonId); + changes.put("writeoffReasonId", writeoffReasonId); + loan.updateWriteOffReason(writeoffReason); } checkClientOrGroupActive(loan); @@ -3009,25 +3009,25 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } private void syncExpectedDateWithActualDisbursementDate(final Loan loan, LocalDate actualDisbursementDate){ - if(!loan.getExpectedDisbursedOnLocalDate().equals(actualDisbursementDate)){ - throw new DateMismatchException(actualDisbursementDate, - loan.getExpectedDisbursedOnLocalDate()); - } - - } + if(!loan.getExpectedDisbursedOnLocalDate().equals(actualDisbursementDate)){ + throw new DateMismatchException(actualDisbursementDate, + loan.getExpectedDisbursedOnLocalDate()); + } + + } - private void validateTransactionsForTransfer(final Loan loan, final LocalDate transferDate) { + private void validateTransactionsForTransfer(final Loan loan, final LocalDate transferDate) { - for (LoanTransaction transaction : loan.getLoanTransactions()) { - if ((transaction.getTransactionDate().isEqual(transferDate) - && transaction.getCreatedDateTime().isEqual(transferDate.toDateTimeAtStartOfDay().toLocalDateTime())) - || transaction.getTransactionDate().isAfter(transferDate)) { - throw new GeneralPlatformDomainRuleException(TransferApiConstants.transferClientLoanException, - TransferApiConstants.transferClientLoanExceptionMessage, transaction.getCreatedDateTime().toLocalDate(), - transferDate); - } + for (LoanTransaction transaction : loan.getLoanTransactions()) { + if ((transaction.getTransactionDate().isEqual(transferDate) + && transaction.getCreatedDateTime().isEqual(transferDate.toDateTimeAtStartOfDay().toLocalDateTime())) + || transaction.getTransactionDate().isAfter(transferDate)) { + throw new GeneralPlatformDomainRuleException(TransferApiConstants.transferClientLoanException, + TransferApiConstants.transferClientLoanExceptionMessage, transaction.getCreatedDateTime().toLocalDate(), + transferDate); + } - } + } - } + } } 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 4a08f9955..e97a634f2 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 @@ -125,7 +125,7 @@ public class RecalculateInterestPoster implements Runnable { if (e.getCause() != null) { realCause = e.getCause(); } - logger.error("Interest recalculation for loans failed for account:" + loanId + " with message " + realCause.getMessage(), e); + logger.error("Interest recalculation for loans failed for account:" + loanId + " with message " + realCause.getMessage(), e); sb.append("Interest recalculation for loans failed for account:").append(loanId).append(" with message ") .append(realCause.getMessage()); numberOfRetries = maxNumberOfRetries + 1; 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 cd28c6b72..0ffe7b2e8 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 @@ -942,7 +942,7 @@ public class LoanProductData implements Serializable { } public Integer getRecurringMoratoriumOnPrincipalPeriods() { - return this.recurringMoratoriumOnPrincipalPeriods; + return this.recurringMoratoriumOnPrincipalPeriods; } public Integer getGraceOnInterestPayment() { @@ -1196,9 +1196,9 @@ public class LoanProductData implements Serializable { return this.allowPartialPeriodInterestCalcualtion; } - public boolean syncExpectedWithDisbursementDate() { - return syncExpectedWithDisbursementDate; - } + public boolean syncExpectedWithDisbursementDate() { + return syncExpectedWithDisbursementDate; + } public boolean canUseForTopup() { return this.canUseForTopup; 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 b7336846f..eba4eac30 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 @@ -309,10 +309,10 @@ public class LoanProduct extends AbstractPersistableCustom { final boolean syncExpectedWithDisbursementDate = command.booleanPrimitiveValueOfParameterNamed("syncExpectedWithDisbursementDate"); - final boolean canUseForTopup = command.parameterExists(LoanProductConstants.canUseForTopup) - ? command.booleanPrimitiveValueOfParameterNamed(LoanProductConstants.canUseForTopup) - : false; - + final boolean canUseForTopup = command.parameterExists(LoanProductConstants.canUseForTopup) + ? command.booleanPrimitiveValueOfParameterNamed(LoanProductConstants.canUseForTopup) + : false; + final boolean isEqualAmortization = command.parameterExists(LoanProductConstants.isEqualAmortizationParam) ? command .booleanPrimitiveValueOfParameterNamed(LoanProductConstants.isEqualAmortizationParam) : false; @@ -634,7 +634,7 @@ public class LoanProduct extends AbstractPersistableCustom { this.canDefineInstallmentAmount = canDefineEmiAmount; this.installmentAmountInMultiplesOf = installmentAmountInMultiplesOf; this.syncExpectedWithDisbursementDate = - syncExpectedWithDisbursementDate; + syncExpectedWithDisbursementDate; this.canUseForTopup = canUseForTopup; this.isEqualAmortization = isEqualAmortization; } @@ -861,10 +861,10 @@ public class LoanProduct extends AbstractPersistableCustom { } if(command.isChangeInBooleanParameterNamed("syncExpectedWithDisbursementDate" - , this.syncExpectedWithDisbursementDate)){ - final boolean newValue = command.booleanPrimitiveValueOfParameterNamed("syncExpectedWithDisbursementDate"); - actualChanges.put("syncExpectedWithDisbursementDate", newValue); - this.syncExpectedWithDisbursementDate = newValue; + , this.syncExpectedWithDisbursementDate)){ + final boolean newValue = command.booleanPrimitiveValueOfParameterNamed("syncExpectedWithDisbursementDate"); + actualChanges.put("syncExpectedWithDisbursementDate", newValue); + this.syncExpectedWithDisbursementDate = newValue; } /** @@ -1170,14 +1170,14 @@ public class LoanProduct extends AbstractPersistableCustom { } public boolean syncExpectedWithDisbursementDate() { - return syncExpectedWithDisbursementDate; - } + return syncExpectedWithDisbursementDate; + } - public void setSyncExpectedWithDisbursementDate(boolean syncExpectedWithDisbursementDate) { - this.syncExpectedWithDisbursementDate = syncExpectedWithDisbursementDate; - } + public void setSyncExpectedWithDisbursementDate(boolean syncExpectedWithDisbursementDate) { + this.syncExpectedWithDisbursementDate = syncExpectedWithDisbursementDate; + } - public Map fetchBorrowerCycleVariationsForCycleNumber(final Integer cycleNumber) { + public Map fetchBorrowerCycleVariationsForCycleNumber(final Integer cycleNumber) { Map borrowerCycleVariations = new HashMap<>(); borrowerCycleVariations.put(LoanProductConstants.principal, this.loanProductRelatedDetail.getPrincipal().getAmount()); borrowerCycleVariations.put(LoanProductConstants.interestRatePerPeriod, 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 85f319be4..7a8e5613f 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 @@ -58,12 +58,12 @@ public class LoanProductConfigurableAttributes extends AbstractPersistableCustom @Column(name = "grace_on_arrears_ageing", nullable = true) private Boolean graceOnArrearsAgeing; - private static final String[] supportedloanConfigurableAttributes = {LoanProductConstants.amortizationTypeParamName, - LoanProductConstants.interestTypeParamName, LoanProductConstants.transactionProcessingStrategyIdParamName, - LoanProductConstants.interestCalculationPeriodTypeParamName, - LoanProductConstants.inArrearsToleranceParamName, LoanProductConstants.repaymentEveryParamName, - LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName, - LoanProductConstants.graceOnArrearsAgeingParameterName}; + private static final String[] supportedloanConfigurableAttributes = {LoanProductConstants.amortizationTypeParamName, + LoanProductConstants.interestTypeParamName, LoanProductConstants.transactionProcessingStrategyIdParamName, + LoanProductConstants.interestCalculationPeriodTypeParamName, + LoanProductConstants.inArrearsToleranceParamName, LoanProductConstants.repaymentEveryParamName, + LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName, + LoanProductConstants.graceOnArrearsAgeingParameterName}; public static LoanProductConfigurableAttributes createFrom(JsonCommand command) { @@ -216,14 +216,14 @@ public class LoanProductConfigurableAttributes extends AbstractPersistableCustom 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); + 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 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 42adbc1e1..bc0f4923e 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,22 +61,22 @@ public class LoanProductFloatingRates extends AbstractPersistableCustom { private BigDecimal maxDifferentialLendingRate; @Column(name = "is_floating_interest_rate_calculation_allowed", nullable = false) - private boolean isFloatingInterestRateCalculationAllowed; + private boolean isFloatingInterestRateCalculationAllowed; - public LoanProductFloatingRates(){ - - } - public LoanProductFloatingRates(FloatingRate floatingRate, LoanProduct loanProduct, BigDecimal interestRateDifferential, + public LoanProductFloatingRates(){ + + } + public LoanProductFloatingRates(FloatingRate floatingRate, LoanProduct loanProduct, BigDecimal interestRateDifferential, BigDecimal minDifferentialLendingRate, BigDecimal maxDifferentialLendingRate, BigDecimal defaultDifferentialLendingRate, boolean isFloatingInterestRateCalculationAllowed){ - this.floatingRate = floatingRate; - this.loanProduct = loanProduct; - this.interestRateDifferential = interestRateDifferential; - this.minDifferentialLendingRate = minDifferentialLendingRate; - this.maxDifferentialLendingRate = maxDifferentialLendingRate; - this.defaultDifferentialLendingRate = defaultDifferentialLendingRate; - this.isFloatingInterestRateCalculationAllowed = isFloatingInterestRateCalculationAllowed; - } + this.floatingRate = floatingRate; + this.loanProduct = loanProduct; + this.interestRateDifferential = interestRateDifferential; + this.minDifferentialLendingRate = minDifferentialLendingRate; + this.maxDifferentialLendingRate = maxDifferentialLendingRate; + this.defaultDifferentialLendingRate = defaultDifferentialLendingRate; + this.isFloatingInterestRateCalculationAllowed = isFloatingInterestRateCalculationAllowed; + } public LoanProduct getLoanProduct() { return this.loanProduct; 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 e70a14f60..dec0b629f 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 @@ -275,19 +275,19 @@ public class LoanProductInterestRecalculationDetails extends AbstractPersistable } if (frequencyType.isWeekly()) { - this.restFrequencyNthDay = null; - this.restFrequencyOnDay = null; + this.restFrequencyNthDay = null; + this.restFrequencyOnDay = null; } else if (frequencyType.isMonthly()) { - if(command.integerValueOfParameterNamed(LoanProductConstants.recalculationRestFrequencyOnDayParamName) != null) { - this.restFrequencyNthDay = null; - this.restFrequencyWeekday = null; - } else { - this.restFrequencyOnDay = null; - } + if(command.integerValueOfParameterNamed(LoanProductConstants.recalculationRestFrequencyOnDayParamName) != null) { + this.restFrequencyNthDay = null; + this.restFrequencyWeekday = null; + } else { + this.restFrequencyOnDay = null; + } } else if (frequencyType.isDaily()) { - this.restFrequencyNthDay = null; - this.restFrequencyWeekday = null; - this.restFrequencyOnDay = null; + this.restFrequencyNthDay = null; + this.restFrequencyWeekday = null; + this.restFrequencyOnDay = null; } } @@ -347,19 +347,19 @@ public class LoanProductInterestRecalculationDetails extends AbstractPersistable } if (compoundingfrequencyType.isWeekly()) { - this.compoundingFrequencyNthDay = null; - this.compoundingFrequencyOnDay = null; + this.compoundingFrequencyNthDay = null; + this.compoundingFrequencyOnDay = null; } else if (compoundingfrequencyType.isMonthly()) { - if(command.integerValueOfParameterNamed(LoanProductConstants.recalculationCompoundingFrequencyOnDayParamName) != null) { - this.compoundingFrequencyNthDay = null; - this.compoundingFrequencyWeekday = null; - } else { - this.compoundingFrequencyOnDay = null; - } + if(command.integerValueOfParameterNamed(LoanProductConstants.recalculationCompoundingFrequencyOnDayParamName) != null) { + this.compoundingFrequencyNthDay = null; + this.compoundingFrequencyWeekday = null; + } else { + this.compoundingFrequencyOnDay = null; + } } else if (compoundingfrequencyType.isDaily()) { - this.compoundingFrequencyNthDay = null; - this.compoundingFrequencyWeekday = null; - this.compoundingFrequencyOnDay = null; + this.compoundingFrequencyNthDay = null; + this.compoundingFrequencyWeekday = null; + this.compoundingFrequencyOnDay = null; } } if (!compoundingfrequencyType.isDaily()) { @@ -375,8 +375,8 @@ public class LoanProductInterestRecalculationDetails extends AbstractPersistable this.compoundingFrequencyType = null; this.compoundingInterval = null; this.compoundingFrequencyNthDay = null; - this.compoundingFrequencyWeekday = null; - this.compoundingFrequencyOnDay = null; + this.compoundingFrequencyWeekday = null; + this.compoundingFrequencyOnDay = null; } if (command.isChangeInBooleanParameterNamed(LoanProductConstants.isArrearsBasedOnOriginalScheduleParamName, 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 bc8dbe239..61b073491 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 @@ -160,9 +160,9 @@ public class LoanProductMinMaxConstraints { return this.maxNumberOfRepayments; } - public void updateForFloatingInterestRates() { - this.minNominalInterestRatePerPeriod = null; - this.maxNominalInterestRatePerPeriod = null; - } + public void updateForFloatingInterestRates() { + this.minNominalInterestRatePerPeriod = null; + this.maxNominalInterestRatePerPeriod = null; + } } \ No newline at end of file diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductMinimumRepaymentScheduleRelatedDetail.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductMinimumRepaymentScheduleRelatedDetail.java index 218d8394e..6cfbb427b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductMinimumRepaymentScheduleRelatedDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductMinimumRepaymentScheduleRelatedDetail.java @@ -30,30 +30,30 @@ import org.apache.fineract.portfolio.common.domain.PeriodFrequencyType; */ public interface LoanProductMinimumRepaymentScheduleRelatedDetail { - MonetaryCurrency getCurrency(); - - Money getPrincipal(); - - Integer graceOnInterestCharged(); - - Integer graceOnInterestPayment(); - - Integer graceOnPrincipalPayment(); - - Integer recurringMoratoriumOnPrincipalPeriods(); - - Money getInArrearsTolerance(); - - BigDecimal getNominalInterestRatePerPeriod(); - - PeriodFrequencyType getInterestPeriodFrequencyType(); - - BigDecimal getAnnualNominalInterestRate(); - - InterestMethod getInterestMethod(); - - InterestCalculationPeriodMethod getInterestCalculationPeriodMethod(); - + MonetaryCurrency getCurrency(); + + Money getPrincipal(); + + Integer graceOnInterestCharged(); + + Integer graceOnInterestPayment(); + + Integer graceOnPrincipalPayment(); + + Integer recurringMoratoriumOnPrincipalPeriods(); + + Money getInArrearsTolerance(); + + BigDecimal getNominalInterestRatePerPeriod(); + + PeriodFrequencyType getInterestPeriodFrequencyType(); + + BigDecimal getAnnualNominalInterestRate(); + + InterestMethod getInterestMethod(); + + InterestCalculationPeriodMethod getInterestCalculationPeriodMethod(); + Integer getRepayEvery(); PeriodFrequencyType getRepaymentPeriodFrequencyType(); 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 76b57fb59..75937dca0 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 @@ -352,7 +352,7 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche this.repaymentPeriodFrequencyType = PeriodFrequencyType.fromInt(newValue); } if (this.repaymentPeriodFrequencyType == PeriodFrequencyType.MONTHS) { - Integer newValue = null; + Integer newValue = null; final String repaymentFrequencyNthDayTypeParamName = "repaymentFrequencyNthDayType"; newValue = command.integerValueOfParameterNamed(repaymentFrequencyNthDayTypeParamName); actualChanges.put(repaymentFrequencyNthDayTypeParamName, newValue); @@ -510,7 +510,7 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche } public void updateCurrency(final MonetaryCurrency currency) { - this.currency = currency ; + this.currency = currency ; } public void validateRepaymentPeriodWithGraceSettings() { @@ -534,19 +534,19 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche int graceOnPrincipal = 0; if (this.getGraceOnPrincipalPayment() != null) { - graceOnPrincipal = this.getGraceOnPrincipalPayment().intValue(); + graceOnPrincipal = this.getGraceOnPrincipalPayment().intValue(); } int recurMoratoriumOnPrincipal = 0; if (this.recurringMoratoriumOnPrincipalPeriods() != null) { - recurMoratoriumOnPrincipal = this.recurringMoratoriumOnPrincipalPeriods().intValue(); + recurMoratoriumOnPrincipal = this.recurringMoratoriumOnPrincipalPeriods().intValue(); } if ( ( recurMoratoriumOnPrincipal > 0 ) - && ( (this.numberOfRepayments - graceOnPrincipal) % ( recurMoratoriumOnPrincipal + 1) != 1) ) { + && ( (this.numberOfRepayments - graceOnPrincipal) % ( recurMoratoriumOnPrincipal + 1) != 1) ) { baseDataValidator.reset().parameter("graceOnPrincipalPayments.and.recurringMoratoriumOnPrincipalPeriods") - .value(graceOnPrincipal) - .value(recurMoratoriumOnPrincipal) - .failWithCode("causes.principal.moratorium.for.last.installment"); + .value(graceOnPrincipal) + .value(recurMoratoriumOnPrincipal) + .failWithCode("causes.principal.moratorium.for.last.installment"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } 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 5b68a4ffd..c51b3783b 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 @@ -23,6 +23,6 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR 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); + "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/serialization/LoanProductDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/serialization/LoanProductDataValidator.java index d2b836925..1d2bd9c35 100755 --- 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 @@ -331,8 +331,8 @@ public final class LoanProductDataValidator { if (this.fromApiJsonHelper.parameterExists("isLinkedToFloatingInterestRates", element) && this.fromApiJsonHelper.extractBooleanNamed("isLinkedToFloatingInterestRates", element) == true) { if (isEqualAmortization) { throw new EqualAmortizationUnsupportedFeatureException("floating.interest.rate", - "floating interest rate"); } - if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) { + "floating interest rate"); } + if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) { baseDataValidator .reset() .parameter("interestRatePerPeriod") @@ -652,7 +652,7 @@ public final class LoanProductDataValidator { private void validateVariableInstallmentSettings(final DataValidatorBuilder baseDataValidator, final JsonElement element) { if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.allowVariableInstallmentsParamName, element) && this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.allowVariableInstallmentsParamName, element)) { - + boolean isEqualAmortization = false; if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.isEqualAmortizationParam, element)) { isEqualAmortization = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.isEqualAmortizationParam, element); @@ -1170,8 +1170,8 @@ public final class LoanProductDataValidator { isLinkedToFloatingInterestRates = this.fromApiJsonHelper.extractBooleanNamed("isLinkedToFloatingInterestRates", element); } if (isLinkedToFloatingInterestRates) { - 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 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 638e011bd..9a3f984c4 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 @@ -610,7 +610,7 @@ public class LoanEnumerations { return interestRecalculationCompoundingNthDayType(NthDayType.fromInt(id)); } public static EnumOptionData interestRecalculationCompoundingNthDayType(final NthDayType type) { - final String codePrefix = "interestRecalculationCompounding."; + final String codePrefix = "interestRecalculationCompounding."; long nthDayValue = type.getValue().longValue(); EnumOptionData optionData = null; switch (type) { 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 8635de836..c0e07428b 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 @@ -133,8 +133,8 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro FloatingRate floatingRate = null; if(command.parameterExists("floatingRatesId")){ - floatingRate = this.floatingRateRepository - .findOneWithNotFoundDetection(command.longValueOfParameterNamed("floatingRatesId")); + floatingRate = this.floatingRateRepository + .findOneWithNotFoundDetection(command.longValueOfParameterNamed("floatingRatesId")); } final LoanProduct loanproduct = LoanProduct.assembleFromJson(fund, loanTransactionProcessingStrategy, charges, command, this.aprCalculator, floatingRate); @@ -147,14 +147,14 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro // 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(BUSINESS_EVENTS.LOAN_PRODUCT_CREATE, constructEntityMap(BUSINESS_ENTITY.LOAN_PRODUCT, loanproduct)); this.businessEventNotifierService.notifyBusinessEventWasExecuted(BUSINESS_EVENTS.LOAN_PRODUCT_CREATE, - constructEntityMap(BUSINESS_ENTITY.LOAN_PRODUCT, loanproduct)); + constructEntityMap(BUSINESS_ENTITY.LOAN_PRODUCT, loanproduct)); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -165,9 +165,9 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -204,14 +204,14 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro validateInputDates(command); if(anyChangeInCriticalFloatingRateLinkedParams(command, product) - && this.loanRepositoryWrapper.doNonClosedLoanAccountsExistForProduct(product.getId())){ - throw new LoanProductCannotBeModifiedDueToNonClosedLoansException(product.getId()); + && this.loanRepositoryWrapper.doNonClosedLoanAccountsExistForProduct(product.getId())){ + throw new LoanProductCannotBeModifiedDueToNonClosedLoansException(product.getId()); } FloatingRate floatingRate = null; if(command.parameterExists("floatingRatesId")){ - floatingRate = this.floatingRateRepository - .findOneWithNotFoundDetection(command.longValueOfParameterNamed("floatingRatesId")); + floatingRate = this.floatingRateRepository + .findOneWithNotFoundDetection(command.longValueOfParameterNamed("floatingRatesId")); } final Map changes = product.update(command, this.aprCalculator, floatingRate); @@ -256,22 +256,22 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return new CommandProcessingResult(Long.valueOf(-1)); }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + 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 isChangeInCriticalFloatingRateParams = product.getFloatingRates() != null - && (command.isChangeInLongParameterNamed("floatingRatesId", product.getFloatingRates().getFloatingRate().getId()) - || command.isChangeInBigDecimalParameterNamed("interestRateDifferential", product.getFloatingRates().getInterestRateDifferential())); - return isChangeFromFloatingToFlatOrViceVersa || isChangeInCriticalFloatingRateParams; - } + final boolean isChangeInCriticalFloatingRateParams = product.getFloatingRates() != null + && (command.isChangeInLongParameterNamed("floatingRatesId", product.getFloatingRates().getFloatingRate().getId()) + || command.isChangeInBigDecimalParameterNamed("interestRateDifferential", product.getFloatingRates().getInterestRateDifferential())); + return isChangeFromFloatingToFlatOrViceVersa || isChangeInCriticalFloatingRateParams; + } - private List assembleListOfProductCharges(final JsonCommand command, final String currencyCode) { + private List assembleListOfProductCharges(final JsonCommand command, final String currencyCode) { final List charges = new ArrayList<>(); 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 4614dbae2..7f3cda187 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 @@ -81,10 +81,10 @@ public class MeetingsApiResource { private final DefaultToApiJsonSerializer toApiJsonSerializer; 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)); + private static final Set MEETING_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(MeetingApiConstants.idParamName, MeetingApiConstants.meetingDateParamName, + MeetingApiConstants.clientsAttendance, MeetingApiConstants.clients, + MeetingApiConstants.calendarData, MeetingApiConstants.attendanceTypeOptions)); @Autowired public MeetingsApiResource(final PlatformSecurityContext context, final MeetingReadPlatformService readPlatformService, 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 63b04e9a2..cbf4c802c 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 @@ -53,11 +53,11 @@ import com.google.gson.reflect.TypeToken; @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 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)); @Autowired public MeetingDataValidator(final FromJsonHelper fromApiJsonHelper) { 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 b61f867f4..577590147 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 @@ -78,10 +78,10 @@ public class Meeting extends AbstractPersistableCustom { } 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 '" + 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); } return new Meeting(calendarInstance, meetingDate); } @@ -180,7 +180,7 @@ public class Meeting extends AbstractPersistableCustom { } private static boolean isValidMeetingDate(final CalendarInstance calendarInstance, final Date meetingDate, - final boolean isSkipRepaymentOnFirstMonth, final int numberOfDays) { + final boolean isSkipRepaymentOnFirstMonth, final int numberOfDays) { final Calendar calendar = calendarInstance.getCalendar(); LocalDate meetingDateLocalDate = null; if (meetingDate != null) { 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 14a576a37..83b90c828 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 @@ -115,7 +115,7 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit Integer numberOfDays = 0; boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); if(isSkipRepaymentOnFirstMonthEnabled){ - if(calendarInstance != null){isSkipRepaymentOnFirstMonth = true;} + if(calendarInstance != null){isSkipRepaymentOnFirstMonth = true;} if(isSkipRepaymentOnFirstMonth) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } } final Meeting newMeeting = Meeting.createNew(calendarInstance, meetingDate, isTransactionDateOnNonMeetingDate, isSkipRepaymentOnFirstMonth, numberOfDays); @@ -233,20 +233,20 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit public CommandProcessingResult updateMeeting(final JsonCommand command) { this.meetingDataValidator.validateForUpdate(command); - final CalendarInstance calendarInstance = getCalendarInstance(command); - - // create new meeting - Boolean isSkipRepaymentOnFirstMonth = false; - - Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService - .isSkippingMeetingOnFirstDayOfMonthEnabled(); - if (isSkipRepaymentOnFirstMonthEnabled) { - if (calendarInstance != null) { - isSkipRepaymentOnFirstMonth = true; - numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); - } - } + final CalendarInstance calendarInstance = getCalendarInstance(command); + + // create new meeting + Boolean isSkipRepaymentOnFirstMonth = false; + + Integer numberOfDays = 0; + boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService + .isSkippingMeetingOnFirstDayOfMonthEnabled(); + if (isSkipRepaymentOnFirstMonthEnabled) { + if (calendarInstance != null) { + isSkipRepaymentOnFirstMonth = true; + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); + } + } final Meeting meetingForUpdate = this.meetingRepositoryWrapper.findOneWithNotFoundDetection(command.entityId()); final Map changes = meetingForUpdate.update(command, isSkipRepaymentOnFirstMonth, numberOfDays); @@ -313,22 +313,22 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit try { final CalendarInstance calendarInstance = getCalendarInstance(command); - final Meeting meeting = this.meetingRepository - .findByCalendarInstanceIdAndMeetingDate(calendarInstance.getId(), meetingDate); - Boolean isSkipRepaymentOnFirstMonth = false; - Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService - .isSkippingMeetingOnFirstDayOfMonthEnabled(); - if (isSkipRepaymentOnFirstMonthEnabled) { - isSkipRepaymentOnFirstMonth = true; - if (isSkipRepaymentOnFirstMonth) { - numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate() - .intValue(); - } - } + final Meeting meeting = this.meetingRepository + .findByCalendarInstanceIdAndMeetingDate(calendarInstance.getId(), meetingDate); + Boolean isSkipRepaymentOnFirstMonth = false; + Integer numberOfDays = 0; + boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService + .isSkippingMeetingOnFirstDayOfMonthEnabled(); + if (isSkipRepaymentOnFirstMonthEnabled) { + isSkipRepaymentOnFirstMonth = true; + if (isSkipRepaymentOnFirstMonth) { + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate() + .intValue(); + } + } // create new meeting final Meeting newMeeting = (meeting != null) ? meeting : Meeting.createNew(calendarInstance, meetingDate, isTransactionDateOnNonMeetingDate, - isSkipRepaymentOnFirstMonth, numberOfDays); + 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/service/NoteReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteReadPlatformServiceImpl.java index 61f1b8b21..1cb0797ae 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 @@ -121,12 +121,12 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { String conditionSql = ""; switch (noteType) { case CLIENT: - paramList.add(NoteType.CLIENT.getValue()); + paramList.add(NoteType.CLIENT.getValue()); conditionSql = " n.client_id = ? and note_type_enum = ?"; break; case LOAN: - paramList.add(NoteType.LOAN.getValue()); - paramList.add(NoteType.LOAN_TRANSACTION.getValue()); + paramList.add(NoteType.LOAN.getValue()); + paramList.add(NoteType.LOAN_TRANSACTION.getValue()); conditionSql = " n.loan_id = ? and ( n.note_type_enum = ? or n.note_type_enum = ? )"; break; case LOAN_TRANSACTION: 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 b7d0f1458..6cc92964e 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 @@ -74,14 +74,14 @@ public class PaymentTypeData implements Serializable { 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); + Objects.equals(name, that.name) && + Objects.equals(description, that.description) && + Objects.equals(isCashPayment, that.isCashPayment) && + Objects.equals(position, that.position); } @Override public int hashCode() { - return Objects.hash(id, name, description, isCashPayment, position); + return Objects.hash(id, name, description, isCashPayment, position); } } 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 dd79f9d54..d65f0b114 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 @@ -43,13 +43,13 @@ import com.google.gson.reflect.TypeToken; public class PaymentTypeDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set CREATE_PAYMENT_TYPE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(PaymentTypeApiResourceConstants.NAME, PaymentTypeApiResourceConstants.DESCRIPTION, - PaymentTypeApiResourceConstants.ISCASHPAYMENT, PaymentTypeApiResourceConstants.POSITION)); + private static final Set CREATE_PAYMENT_TYPE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(PaymentTypeApiResourceConstants.NAME, PaymentTypeApiResourceConstants.DESCRIPTION, + PaymentTypeApiResourceConstants.ISCASHPAYMENT, PaymentTypeApiResourceConstants.POSITION)); - private static final Set UPDATE_PAYMENT_TYPE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(PaymentTypeApiResourceConstants.NAME, PaymentTypeApiResourceConstants.DESCRIPTION, - PaymentTypeApiResourceConstants.ISCASHPAYMENT, PaymentTypeApiResourceConstants.POSITION)); + private static final Set UPDATE_PAYMENT_TYPE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(PaymentTypeApiResourceConstants.NAME, PaymentTypeApiResourceConstants.DESCRIPTION, + PaymentTypeApiResourceConstants.ISCASHPAYMENT, PaymentTypeApiResourceConstants.POSITION)); @Autowired public PaymentTypeDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -105,8 +105,8 @@ 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); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/domain/PaymentType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/domain/PaymentType.java index 1e910aaaf..311476f19 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/domain/PaymentType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/domain/PaymentType.java @@ -95,8 +95,8 @@ public class PaymentType extends AbstractPersistableCustom { return PaymentTypeData.instance(getId(), this.name, this.description, this.isCashPayment, this.position); } - public Boolean isCashPayment() { - return isCashPayment; - } - + public Boolean isCashPayment() { + return isCashPayment; + } + } 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 a84a2b338..37bab8fe3 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 @@ -291,15 +291,15 @@ public class DepositsApiConstants { * Depost Account parameters */ - 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)); + 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)); public static final Set FIXED_DEPOSIT_ACCOUNT_REQUEST_DATA_PARAMETERS = fixedDepositAccountRequestData(); public static final Set FIXED_DEPOSIT_ACCOUNT_RESPONSE_DATA_PARAMETERS = fixedDepositAccountResponseData(); @@ -345,9 +345,9 @@ public class DepositsApiConstants { return recurringDepositResponseData; } - private static final Set RECURRING_DEPOSIT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(idParamName, "accountId", accountNoParamName, "currency", "amount", dateParamName, - paymentDetailDataParamName, runningBalanceParamName, reversedParamName)); + private static final Set RECURRING_DEPOSIT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( + 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, 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 093a12e15..d80d1183a 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 @@ -113,7 +113,7 @@ public enum SavingsAccountTransactionType { savingsAccountTransactionType = SavingsAccountTransactionType.WITHHOLD_TAX; break; case 19: - savingsAccountTransactionType = SavingsAccountTransactionType.ESCHEAT; + savingsAccountTransactionType = SavingsAccountTransactionType.ESCHEAT; break; case 20: savingsAccountTransactionType = SavingsAccountTransactionType.AMOUNT_HOLD; @@ -137,10 +137,10 @@ public enum SavingsAccountTransactionType { return this.value.equals(SavingsAccountTransactionType.INTEREST_POSTING.getValue()); } - public boolean isOverDraftInterestPosting() { - return this.value.equals(SavingsAccountTransactionType.OVERDRAFT_INTEREST.getValue()); - } - + public boolean isOverDraftInterestPosting() { + return this.value.equals(SavingsAccountTransactionType.OVERDRAFT_INTEREST.getValue()); + } + public boolean isWithHoldTax() { return this.value.equals(SavingsAccountTransactionType.WITHHOLD_TAX.getValue()); } 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 index f84eb19d9..abf1ff349 100755 --- 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 @@ -78,8 +78,8 @@ public class DepositAccountOnHoldFundTransactionsApiResource { 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); + 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 d0785f9f5..c793f423f 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,13 +65,13 @@ public class FixedDepositAccountTransactionsApiResource { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final ApiRequestParameterHelper apiRequestParameterHelper; private final SavingsAccountReadPlatformService savingsAccountReadPlatformService; - 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)); + 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)); @Autowired public FixedDepositAccountTransactionsApiResource(final PlatformSecurityContext context, @@ -129,8 +129,8 @@ public class FixedDepositAccountTransactionsApiResource { 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 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 8c34bff7e..4fdb29d4b 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 @@ -151,8 +151,8 @@ public class RecurringDepositAccountTransactionsApiResource { 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 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 5e206c6be..5e4e05c7d 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 @@ -123,8 +123,8 @@ public class SavingsAccountsApiResource { staffInSelectedOfficeOnly); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, savingsAccount, - SavingsApiSetConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, savingsAccount, + SavingsApiSetConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); } @GET @@ -145,8 +145,8 @@ 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 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 4b61fdb09..e6c99661d 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 @@ -28,57 +28,57 @@ import java.util.Set; public class SavingsApiSetConstants extends SavingsApiConstants { - /** - * These parameters will match the class level parameters of - * {@link SavingsProductData}. Where possible, we try to get response - * parameters to match those of request parameters. - */ - 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 + * {@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)); - /** - * These parameters will match the class level parameters of - * {@link SavingsAccountData}. Where possible, we try to get response - * parameters to match those of request parameters. - */ + /** + * These parameters will match the class level parameters of + * {@link SavingsAccountData}. Where possible, we try to get response + * parameters to match those of request parameters. + */ - 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)); + 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)); - protected static final Set SAVINGS_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(idParamName, "accountId", accountNoParamName, "currency", "amount", dateParamName, - paymentDetailDataParamName, runningBalanceParamName, reversedParamName, noteParamName)); + protected static final Set SAVINGS_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( + 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)); + 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)); - 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 27ecdca42..06472c768 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 @@ -154,8 +154,8 @@ 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 @@ -193,8 +193,8 @@ public class SavingsProductsApiResource { savingProductData = handleTemplateRelatedData(savingProductData); } - return this.toApiJsonSerializer.serialize(settings, savingProductData, - SavingsApiSetConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, savingProductData, + SavingsApiSetConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); } @GET @@ -210,8 +210,8 @@ 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) { 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 e20641a57..d6a82c16d 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 @@ -63,25 +63,25 @@ 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)); + 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)); - 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)); + private static final Set DEPOSIT_ACCOUNT_PRE_MATURE_CALCULATION_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(DepositsApiConstants.localeParamName, DepositsApiConstants.dateFormatParamName, + closedOnDateParamName)); @Autowired @@ -96,8 +96,8 @@ 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 @@ -131,8 +131,8 @@ public class DepositAccountTransactionDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - DEPOSIT_ACCOUNT_RECOMMENDED_DEPOSIT_AMOUNT_UPDATE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + DEPOSIT_ACCOUNT_RECOMMENDED_DEPOSIT_AMOUNT_UPDATE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -177,8 +177,8 @@ public class DepositAccountTransactionDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - DEPOSIT_ACCOUNT_PRE_MATURE_CALCULATION_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + DEPOSIT_ACCOUNT_PRE_MATURE_CALCULATION_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(depositAccountType @@ -198,8 +198,8 @@ 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 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 80a4fbb2b..dfac0e6cc 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 @@ -26,51 +26,51 @@ import java.util.Set; public class SavingsAccountConstant extends SavingsApiConstants { - /** - * These parameters will match the class level parameters of - * {@link SavingsProductData}. Where possible, we try to get response - * parameters to match those of request parameters. - */ - protected static final Set SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - localeParamName, dateFormatParamName, monthDayFormatParamName, staffIdParamName, 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)); + /** + * These parameters will match the class level parameters of + * {@link SavingsProductData}. Where possible, we try to get response + * parameters to match those of request parameters. + */ + protected static final Set SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( + localeParamName, dateFormatParamName, monthDayFormatParamName, staffIdParamName, 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)); - /** - * These parameters will match the class level parameters of - * {@link SavingsAccountData}. Where possible, we try to get response - * parameters to match those of request parameters. - */ + /** + * These parameters will match the class level parameters of + * {@link SavingsAccountData}. Where possible, we try to get response + * parameters to match those of request parameters. + */ - protected static final Set SAVINGS_ACCOUNT_TRANSACTION_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(localeParamName, dateFormatParamName, transactionDateParamName, transactionAmountParamName, - paymentTypeIdParamName, transactionAccountNumberParamName, checkNumberParamName, - routingCodeParamName, receiptNumberParamName, bankNumberParamName, noteParamName)); + protected static final Set SAVINGS_ACCOUNT_TRANSACTION_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(localeParamName, dateFormatParamName, transactionDateParamName, transactionAmountParamName, + paymentTypeIdParamName, transactionAccountNumberParamName, checkNumberParamName, + routingCodeParamName, receiptNumberParamName, bankNumberParamName, noteParamName)); - protected static final Set SAVINGS_ACCOUNT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(idParamName, accountNoParamName)); + protected static final Set SAVINGS_ACCOUNT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(idParamName, accountNoParamName)); - protected static final Set SAVINGS_ACCOUNT_ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(localeParamName, dateFormatParamName, activatedOnDateParamName)); + 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)); + protected static final Set SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS = new HashSet<>( + 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)); + 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 4396e3ed9..4d9acde15 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 @@ -491,7 +491,7 @@ public class SavingsAccountData implements Serializable { final Integer daysToInactive = null; final Integer daysToDormancy = null; final Integer daysToEscheat = null; - final BigDecimal savingsAmountOnHold = null; + final BigDecimal savingsAmountOnHold = null; return new SavingsAccountData(accountId, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualInterestRate, @@ -625,7 +625,7 @@ public class SavingsAccountData implements Serializable { final Integer daysToInactive = null; final Integer daysToDormancy = null; final Integer daysToEscheat = null; - final BigDecimal savingsAmountOnHold = null; + final BigDecimal savingsAmountOnHold = null; return new SavingsAccountData(id, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualInterestRate, 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 a84cb292f..88ddb229e 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 @@ -92,8 +92,8 @@ public class SavingsAccountDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - SavingsAccountConstant.SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + SavingsAccountConstant.SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -465,7 +465,7 @@ public class SavingsAccountDataValidator { } public void validateForUnAssignSavingsOfficer(final String json) { - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Set supportedParameters = new HashSet<>(Arrays.asList("unassignedDate","locale","dateFormat")); 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 index 4cfaa304a..4b3da56f8 100755 --- 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 @@ -99,9 +99,9 @@ public class SavingsAccountTransactionDTO { return this.appUser; } - public Integer getAccountType() { - return this.depositAccountType; - } + public Integer getAccountType() { + return this.depositAccountType; + } } 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 b3868582e..7e660c4f5 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 @@ -66,9 +66,9 @@ import com.google.gson.reflect.TypeToken; 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)); + private static final Set SAVINGS_ACCOUNT_HOLD_AMOUNT_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(transactionDateParamName, SavingsApiConstants.dateFormatParamName, + SavingsApiConstants.localeParamName, transactionAmountParamName)); @Autowired public SavingsAccountTransactionDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -146,10 +146,10 @@ public class SavingsAccountTransactionDataValidator { baseDataValidator.reset().parameter(withdrawBalanceParamName).value(withdrawBalance).isOneOfTheseValues(true, false); } - if (account.getSavingsHoldAmount().compareTo(BigDecimal.ZERO) == 1) { - baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( - "amount.is.on.hold.release.the.amount.to.continue", account.getId()); - } + if (account.getSavingsHoldAmount().compareTo(BigDecimal.ZERO) == 1) { + baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( + "amount.is.on.hold.release.the.amount.to.continue", account.getId()); + } validatePaymentTypeDetails(baseDataValidator, element); @@ -224,21 +224,21 @@ public class SavingsAccountTransactionDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME); - if (holdTransaction == null) { - baseDataValidator.failWithCode("validation.msg.validation.errors.exist", "Transaction not found"); - } else if (holdTransaction.getReleaseIdOfHoldAmountTransaction() != null) { - baseDataValidator.parameter(SavingsApiConstants.amountParamName).value(holdTransaction.getAmount()) - .failWithCode("validation.msg.amount.is.not.on.hold", "Transaction amount is not on hold"); - } + if (holdTransaction == null) { + baseDataValidator.failWithCode("validation.msg.validation.errors.exist", "Transaction not found"); + } else if (holdTransaction.getReleaseIdOfHoldAmountTransaction() != null) { + baseDataValidator.parameter(SavingsApiConstants.amountParamName).value(holdTransaction.getAmount()) + .failWithCode("validation.msg.amount.is.not.on.hold", "Transaction amount is not on hold"); + } - if (holdTransaction != null) { - boolean isActive = holdTransaction.getSavingsAccount().isActive(); - if (!isActive) { - baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) - .failWithCodeNoParameterAddedToErrorCode( - SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); - } - } + if (holdTransaction != null) { + boolean isActive = holdTransaction.getSavingsAccount().isActive(); + if (!isActive) { + baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) + .failWithCodeNoParameterAddedToErrorCode( + SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); + } + } throwExceptionIfValidationWarningsExist(dataValidationErrors); Date createdDate = new Date(); 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 525c29e11..da46a244f 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 @@ -143,7 +143,7 @@ public class SavingsAccountTransactionEnumData implements Serializable { } public boolean isEscheat() { - return this.escheat; + return this.escheat; } public boolean isAmountOnHold() { 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 f4c830870..6ed3d5bd4 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 @@ -88,10 +88,10 @@ public class SavingsProductData implements Serializable { private final Collection chargeOptions; private final Collection penaltyOptions; private final Collection taxGroupOptions; - private final Boolean isDormancyTrackingActive; - private final Long daysToInactive; - private final Long daysToDormancy; - private final Long daysToEscheat; + private final Boolean isDormancyTrackingActive; + private final Long daysToInactive; + private final Long daysToDormancy; + private final Long daysToEscheat; public static SavingsProductData template(final CurrencyData currency, final EnumOptionData interestCompoundingPeriodType, final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, @@ -439,13 +439,13 @@ public class SavingsProductData implements Serializable { return this.name; } - public String getDepositAccountType() { - return depositAccountType; - } + public String getDepositAccountType() { + return depositAccountType; + } - public void setDepositAccountType(String depositAccountType) { - this.depositAccountType = depositAccountType; - } + public void setDepositAccountType(String depositAccountType) { + this.depositAccountType = depositAccountType; + } public BigDecimal getNominalAnnualInterestRate() { return nominalAnnualInterestRate; 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 b2baac673..182d231a0 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 @@ -85,34 +85,34 @@ import com.google.gson.reflect.TypeToken; 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, SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_INTEREST.getValue(), - SAVINGS_PRODUCT_ACCOUNTING_PARAMS.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, SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_INTEREST.getValue(), + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.ESCHEAT_LIABILITY.getValue(), isDormancyTrackingActiveParamName, + daysToDormancyParamName, daysToInactiveParamName, daysToEscheatParamName, allowOverdraftParamName, + overdraftLimitParamName, nominalAnnualInterestRateOverdraftParamName, + minOverdraftForInterestCalculationParamName, SavingsApiConstants.minRequiredBalanceParamName, + SavingsApiConstants.enforceMinRequiredBalanceParamName, minBalanceForInterestCalculationParamName, + withHoldTaxParamName, taxGroupIdParamName)); @Autowired public SavingsProductDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -275,21 +275,21 @@ public class SavingsProductDataValidator { final Boolean isDormancyActive = this.fromApiJsonHelper.extractBooleanNamed(isDormancyTrackingActiveParamName, element); if(null != isDormancyActive && isDormancyActive){ - final Long daysToInact = this.fromApiJsonHelper.extractLongNamed(daysToInactiveParamName, element); - baseDataValidator.reset().parameter(daysToInactiveParamName).value(daysToInact).notNull().longGreaterThanZero(); + final Long daysToInact = this.fromApiJsonHelper.extractLongNamed(daysToInactiveParamName, element); + baseDataValidator.reset().parameter(daysToInactiveParamName).value(daysToInact).notNull().longGreaterThanZero(); - final Long daysToDor = this.fromApiJsonHelper.extractLongNamed(daysToDormancyParamName, element); - baseDataValidator.reset().parameter(daysToDormancyParamName).value(daysToDor).notNull().longGreaterThanZero(); + final Long daysToDor = this.fromApiJsonHelper.extractLongNamed(daysToDormancyParamName, element); + baseDataValidator.reset().parameter(daysToDormancyParamName).value(daysToDor).notNull().longGreaterThanZero(); - final Long daysToEsc = this.fromApiJsonHelper.extractLongNamed(daysToEscheatParamName, element); - baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).notNull().longGreaterThanZero(); + final Long daysToEsc = this.fromApiJsonHelper.extractLongNamed(daysToEscheatParamName, element); + baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).notNull().longGreaterThanZero(); - if(null != daysToInact - && null != daysToDor - && null != daysToEsc){ - baseDataValidator.reset().parameter(daysToDormancyParamName).value(daysToDor).longGreaterThanNumber(daysToInact); - baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).longGreaterThanNumber(daysToDor); - } + if(null != daysToInact + && null != daysToDor + && null != daysToEsc){ + baseDataValidator.reset().parameter(daysToDormancyParamName).value(daysToDor).longGreaterThanNumber(daysToInact); + baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).longGreaterThanNumber(daysToDor); + } } // accounting related data validation @@ -344,7 +344,7 @@ public class SavingsProductDataValidator { .notNull().integerGreaterThanZero(); if(null != isDormancyActive && isDormancyActive){ - final Long escheatLiabilityAccountId = this.fromApiJsonHelper.extractLongNamed( + final Long escheatLiabilityAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.ESCHEAT_LIABILITY.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.ESCHEAT_LIABILITY.getValue()) .value(escheatLiabilityAccountId).notNull().integerGreaterThanZero(); @@ -521,38 +521,38 @@ public class SavingsProductDataValidator { //dormancy final Boolean isDormancyActive = this.fromApiJsonHelper.parameterExists(isDormancyTrackingActiveParamName, element)? - this.fromApiJsonHelper.extractBooleanNamed(isDormancyTrackingActiveParamName, element): - product.isDormancyTrackingActive(); + 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(); - baseDataValidator.reset().parameter(daysToInactiveParamName).value(daysToInact).notNull().longGreaterThanZero(); + 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(); - baseDataValidator.reset().parameter(daysToDormancyParamName).value(daysToDor).notNull().longGreaterThanZero(); + 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(); - baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).notNull().longGreaterThanZero(); + 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){ - baseDataValidator.reset().parameter(daysToDormancyParamName).value(daysToDor).longGreaterThanNumber(daysToInact); - baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).longGreaterThanNumber(daysToDor); - } + 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(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.ESCHEAT_LIABILITY.getValue(), element)){ - final Long escheatLiabilityAccountId = this.fromApiJsonHelper.extractLongNamed( + if(this.fromApiJsonHelper.parameterExists(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.ESCHEAT_LIABILITY.getValue(), element)){ + final Long escheatLiabilityAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.ESCHEAT_LIABILITY.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.ESCHEAT_LIABILITY.getValue()) .value(escheatLiabilityAccountId).notNull().integerGreaterThanZero(); - } + } } validatePaymentChannelFundSourceMappings(baseDataValidator, element); 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 5f09e6835..ec5bb5d93 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 @@ -829,7 +829,7 @@ public class FixedDepositAccount extends SavingsAccount { @Override public void loadLazyCollections() { - super.loadLazyCollections(); - this.chart.getId() ; + super.loadLazyCollections(); + this.chart.getId() ; } } \ 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 index d4f3842dc..a870eecef 100755 --- 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 @@ -952,8 +952,8 @@ public class SavingsAccount extends AbstractPersistableCustom { this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); if(this.sub_status.equals(SavingsAccountSubStatusEnum.INACTIVE.getValue()) - || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())){ - this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); + || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())){ + this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); } return transaction; @@ -1045,8 +1045,8 @@ public class SavingsAccount extends AbstractPersistableCustom { payWithdrawalFee(transactionDTO.getTransactionAmount(), transactionDTO.getTransactionDate(), transactionDTO.getAppUser()); } if(this.sub_status.equals(SavingsAccountSubStatusEnum.INACTIVE.getValue()) - || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())){ - this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); + || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())){ + this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); } return transaction; } @@ -1136,16 +1136,16 @@ public class SavingsAccount extends AbstractPersistableCustom { //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 (runningBalance.minus(minRequiredBalance).isLessThanZero()) { throw new InsufficientAccountBalanceException( + "transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } } - if (this.getSavingsHoldAmount().compareTo(BigDecimal.ZERO) == 1) { - if (runningBalance.minus(this.getSavingsHoldAmount()).isLessThanZero()) { - throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, - transactionAmount); - } - } + if (this.getSavingsHoldAmount().compareTo(BigDecimal.ZERO) == 1) { + if (runningBalance.minus(this.getSavingsHoldAmount()).isLessThanZero()) { + throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, + transactionAmount); + } + } } public void validateAccountBalanceDoesNotBecomeNegative(final String transactionAction, @@ -1202,8 +1202,8 @@ 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 (runningBalance.minus(minRequiredBalance).isLessThanZero()) { throw new InsufficientAccountBalanceException( + "transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } } } @@ -2876,9 +2876,9 @@ public class SavingsAccount extends AbstractPersistableCustom { return recalucateDailyBalance; } - public void setSubStatusInactive(AppUser appUser) { - this.sub_status = SavingsAccountSubStatusEnum.INACTIVE.getValue(); - LocalDate transactionDate = DateUtils.getLocalDateOfTenant(); + public void setSubStatusInactive(AppUser appUser) { + this.sub_status = SavingsAccountSubStatusEnum.INACTIVE.getValue(); + LocalDate transactionDate = DateUtils.getLocalDateOfTenant(); for (SavingsAccountCharge charge : this.charges()) { if (charge.isSavingsNoActivity() && charge.isActive()) { charge.updateWithdralFeeAmount(this.getAccountBalance()); @@ -2887,28 +2887,28 @@ public class SavingsAccount extends AbstractPersistableCustom { } recalculateDailyBalances(Money.zero(this.currency), transactionDate); this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); - } - + } + - public void setSubStatusDormant() { - this.sub_status = SavingsAccountSubStatusEnum.DORMANT.getValue(); - } + public void setSubStatusDormant() { + this.sub_status = SavingsAccountSubStatusEnum.DORMANT.getValue(); + } - public void escheat(AppUser appUser) { - this.status = SavingsAccountStatusType.CLOSED.getValue(); - this.sub_status = SavingsAccountSubStatusEnum.ESCHEAT.getValue(); - this.closedOnDate = DateUtils.getDateOfTenant(); - this.closedBy = appUser; + public void escheat(AppUser appUser) { + this.status = SavingsAccountStatusType.CLOSED.getValue(); + this.sub_status = SavingsAccountSubStatusEnum.ESCHEAT.getValue(); + this.closedOnDate = DateUtils.getDateOfTenant(); + this.closedBy = appUser; boolean postInterestAsOnDate = false; - LocalDate transactionDate = DateUtils.getLocalDateOfTenant(); - if(this.getSummary().getAccountBalance(this.getCurrency()).isGreaterThanZero()){ + LocalDate transactionDate = DateUtils.getLocalDateOfTenant(); + if(this.getSummary().getAccountBalance(this.getCurrency()).isGreaterThanZero()){ SavingsAccountTransaction transaction = SavingsAccountTransaction.escheat(this, transactionDate, appUser, postInterestAsOnDate); - this.transactions.add(transaction); - } + this.transactions.add(transaction); + } recalculateDailyBalances(Money.zero(this.currency), transactionDate); - this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); - } - + this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); + } + public void loadLazyCollections() { transactions.size(); charges.size(); @@ -2989,11 +2989,11 @@ public class SavingsAccount extends AbstractPersistableCustom { .failWithCodeNoParameterAddedToErrorCode("currently.set"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - if (SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { - this.sub_status = SavingsAccountSubStatusEnum.BLOCK.getValue(); - } else { - this.sub_status = SavingsAccountSubStatusEnum.BLOCK_CREDIT.getValue(); - } + if (SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { + this.sub_status = SavingsAccountSubStatusEnum.BLOCK.getValue(); + } else { + this.sub_status = SavingsAccountSubStatusEnum.BLOCK_CREDIT.getValue(); + } actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; @@ -3013,17 +3013,17 @@ public class SavingsAccount extends AbstractPersistableCustom { } final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.sub_status); - if (!(SavingsAccountSubStatusEnum.BLOCK_CREDIT.hasStateOf(currentSubStatus) - || SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus))) { - baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) - .failWithCodeNoParameterAddedToErrorCode("credits.are.not.blocked"); - } + if (!(SavingsAccountSubStatusEnum.BLOCK_CREDIT.hasStateOf(currentSubStatus) + || SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus))) { + baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) + .failWithCodeNoParameterAddedToErrorCode("credits.are.not.blocked"); + } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus)) { - this.sub_status = SavingsAccountSubStatusEnum.BLOCK_DEBIT.getValue(); - } else { - this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); - } + if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus)) { + this.sub_status = SavingsAccountSubStatusEnum.BLOCK_DEBIT.getValue(); + } else { + this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); + } actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; } @@ -3048,11 +3048,11 @@ public class SavingsAccount extends AbstractPersistableCustom { .failWithCodeNoParameterAddedToErrorCode("currently.set"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - if (SavingsAccountSubStatusEnum.BLOCK_CREDIT.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { - this.sub_status = SavingsAccountSubStatusEnum.BLOCK.getValue(); - } else { - this.sub_status = SavingsAccountSubStatusEnum.BLOCK_DEBIT.getValue(); - } + if (SavingsAccountSubStatusEnum.BLOCK_CREDIT.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { + this.sub_status = SavingsAccountSubStatusEnum.BLOCK.getValue(); + } else { + this.sub_status = SavingsAccountSubStatusEnum.BLOCK_DEBIT.getValue(); + } actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; @@ -3075,17 +3075,17 @@ public class SavingsAccount extends AbstractPersistableCustom { } final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.sub_status); - if (!(SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(currentSubStatus) - || SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus))) { - baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName) - .failWithCodeNoParameterAddedToErrorCode("debits.are.not.blocked"); - } + if (!(SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(currentSubStatus) + || SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus))) { + baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName) + .failWithCodeNoParameterAddedToErrorCode("debits.are.not.blocked"); + } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus)) { - this.sub_status = SavingsAccountSubStatusEnum.BLOCK_CREDIT.getValue(); - } else { - this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); - } + if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus)) { + this.sub_status = SavingsAccountSubStatusEnum.BLOCK_CREDIT.getValue(); + } else { + this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); + } actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; } @@ -3141,7 +3141,7 @@ public class SavingsAccount extends AbstractPersistableCustom { } private boolean isOverdraft() { - return allowOverdraft; + return allowOverdraft; } } \ No newline at end of file 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 fd578f20c..7a1649669 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 @@ -213,7 +213,7 @@ public class SavingsAccountCharge extends AbstractPersistableCustom { populateDerivedFields(transactionAmount, chargeAmount); if (this.isWithdrawalFee() - || this.isSavingsNoActivity()) { + || this.isSavingsNoActivity()) { this.amountOutstanding = BigDecimal.ZERO; } @@ -646,7 +646,7 @@ public class SavingsAccountCharge extends AbstractPersistableCustom { } public boolean isSavingsNoActivity(){ - return ChargeTimeType.fromInt(this.chargeTime).isSavingsNoActivityFee(); + return ChargeTimeType.fromInt(this.chargeTime).isSavingsNoActivityFee(); } public boolean isSavingsClosure() { @@ -684,25 +684,25 @@ public class SavingsAccountCharge extends AbstractPersistableCustom { 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); + 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 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 index b3ea4db0e..b7d3df2a7 100755 --- 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 @@ -171,7 +171,7 @@ public class SavingsAccountDomainServiceJpa implements SavingsAccountDomainServi if (account.isBeforeLastPostingPeriod(transactionDate)) { final LocalDate today = DateUtils.getLocalDateOfTenant(); account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, - postInterestOnDate); + postInterestOnDate); } else { final LocalDate today = DateUtils.getLocalDateOfTenant(); account.calculateInterestUsing(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, 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 2b5222125..f4c8dbde6 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 @@ -83,13 +83,13 @@ public class SavingsAccountRepositoryWrapper { } @Transactional(readOnly=true) - public Page findByStatus(Integer status, Pageable pageable) { - Page accounts = this.repository.findByStatus(status, pageable); - loadLazyCollections(accounts); - return accounts; - } + 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) ; } @@ -129,8 +129,8 @@ public class SavingsAccountRepositoryWrapper { } private void loadLazyCollections(Page accounts) { - for (SavingsAccount account : accounts) { - account.loadLazyCollections(); - } - } + for (SavingsAccount account : accounts) { + account.loadLazyCollections(); + } + } } 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 889a69a0e..2cc3e17eb 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 @@ -36,29 +36,29 @@ public enum SavingsAccountSubStatusEnum { public static SavingsAccountSubStatusEnum fromInt(final Integer type) { - SavingsAccountSubStatusEnum enumeration = SavingsAccountSubStatusEnum.NONE; - if(null != type){ + SavingsAccountSubStatusEnum enumeration = SavingsAccountSubStatusEnum.NONE; + if(null != type){ switch (type) { - case 100: - enumeration = SavingsAccountSubStatusEnum.INACTIVE; - break; - case 200: - enumeration = SavingsAccountSubStatusEnum.DORMANT; - break; - case 300: - enumeration = SavingsAccountSubStatusEnum.ESCHEAT; - break; - case 400: - enumeration = SavingsAccountSubStatusEnum.BLOCK; - break; - case 500: + case 100: + enumeration = SavingsAccountSubStatusEnum.INACTIVE; + break; + case 200: + enumeration = SavingsAccountSubStatusEnum.DORMANT; + break; + case 300: + enumeration = SavingsAccountSubStatusEnum.ESCHEAT; + break; + case 400: + enumeration = SavingsAccountSubStatusEnum.BLOCK; + break; + case 500: enumeration = SavingsAccountSubStatusEnum.BLOCK_CREDIT; break; - case 600: + case 600: enumeration = SavingsAccountSubStatusEnum.BLOCK_DEBIT; break; - } - } + } + } return enumeration; } 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 dc6192ead..d6f538b30 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 @@ -112,7 +112,7 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { @JoinColumn(name = "tax_group_id") private TaxGroup taxGroup; - @Column(name = "is_dormancy_tracking_active") - private Boolean isDormancyTrackingActive; + @Column(name = "is_dormancy_tracking_active") + private Boolean isDormancyTrackingActive; @Column(name = "days_to_inactive") - private Long daysToInactive; + private Long daysToInactive; @Column(name = "days_to_dormancy") - private Long daysToDormancy; + private Long daysToDormancy; @Column(name = "days_to_escheat") - private Long daysToEscheat; + private Long daysToEscheat; public static SavingsProduct createNew(final String name, final String shortName, final String description, final MonetaryCurrency currency, final BigDecimal interestRate, @@ -596,9 +596,9 @@ public class SavingsProduct extends AbstractPersistableCustom { } if(this.isDormancyTrackingActive == null || !this.isDormancyTrackingActive){ - this.daysToInactive = null; - this.daysToDormancy = null; - this.daysToEscheat = null; + this.daysToInactive = null; + this.daysToDormancy = null; + this.daysToEscheat = null; } validateLockinDetails(); @@ -740,19 +740,19 @@ public class SavingsProduct extends AbstractPersistableCustom { } public boolean isDormancyTrackingActive() { - return null == this.isDormancyTrackingActive? false: this.isDormancyTrackingActive; - } + return null == this.isDormancyTrackingActive? false: this.isDormancyTrackingActive; + } - public Long getDaysToInactive() { - return this.daysToInactive; - } + public Long getDaysToInactive() { + return this.daysToInactive; + } - public Long getDaysToDormancy() { - return this.daysToDormancy; - } + public Long getDaysToDormancy() { + return this.daysToDormancy; + } - public Long getDaysToEscheat() { - return this.daysToEscheat; - } + public Long getDaysToEscheat() { + return this.daysToEscheat; + } } \ 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 682e7d8f6..32ad959c7 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 @@ -179,8 +179,8 @@ public class AnnualCompoundingPeriod implements CompoundingPeriod { this.endOfDayBalances = endOfDayBalances; } - @Override - public LocalDateInterval getPeriodInterval() { - return this.periodInterval; - } + @Override + 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 f07fb0f24..f995e0d0b 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 @@ -179,8 +179,8 @@ public class BiAnnualCompoundingPeriod implements CompoundingPeriod { this.endOfDayBalances = endOfDayBalances; } - @Override - public LocalDateInterval getPeriodInterval() { - return this.periodInterval; - } + @Override + 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 55cd5a627..0a20e226b 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 @@ -46,10 +46,10 @@ public class CompoundInterestHelper { Money interestEarned = Money.zero(currency); // 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); + BigDecimal compoundedInterest = BigDecimal.ZERO; + BigDecimal unCompoundedInterest = BigDecimal.ZERO; + final CompoundInterestValues compoundInterestValues = new CompoundInterestValues(compoundedInterest, + unCompoundedInterest); for (final PostingPeriod postingPeriod : allPeriods) { final BigDecimal interestEarnedThisPeriod = postingPeriod.calculateInterest(compoundInterestValues); @@ -63,7 +63,7 @@ public class CompoundInterestHelper { // calculation. if (!(postingPeriod.isInterestTransfered() || !interestTransferEnabled || (lockUntil != null && !postingPeriod.dateOfPostingTransaction().isAfter(lockUntil)))) { - compoundInterestValues.setcompoundedInterest(BigDecimal.ZERO); + compoundInterestValues.setcompoundedInterest(BigDecimal.ZERO); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundInterestValues.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundInterestValues.java index 98e91f134..09a871e8d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundInterestValues.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundInterestValues.java @@ -22,32 +22,32 @@ import java.math.BigDecimal; public class CompoundInterestValues { - private BigDecimal compoundedInterest; - private BigDecimal uncompoundedInterest; + private BigDecimal compoundedInterest; + private BigDecimal uncompoundedInterest; - public CompoundInterestValues(final BigDecimal compoundedInterest, final BigDecimal uncompoundedInterest) { - this.compoundedInterest = compoundedInterest; - this.uncompoundedInterest = uncompoundedInterest; - } + public CompoundInterestValues(final BigDecimal compoundedInterest, final BigDecimal uncompoundedInterest) { + this.compoundedInterest = compoundedInterest; + this.uncompoundedInterest = uncompoundedInterest; + } - public BigDecimal getcompoundedInterest() { - return this.compoundedInterest; - } + public BigDecimal getcompoundedInterest() { + return this.compoundedInterest; + } - public BigDecimal getuncompoundedInterest() { - return this.uncompoundedInterest; - } + public BigDecimal getuncompoundedInterest() { + return this.uncompoundedInterest; + } - public void setcompoundedInterest(BigDecimal interestToBeCompounded) { - this.compoundedInterest = interestToBeCompounded; - } + public void setcompoundedInterest(BigDecimal interestToBeCompounded) { + this.compoundedInterest = interestToBeCompounded; + } - public void setuncompoundedInterest(BigDecimal interestToBeUncompounded) { - this.uncompoundedInterest = interestToBeUncompounded; - } + public void setuncompoundedInterest(BigDecimal interestToBeUncompounded) { + this.uncompoundedInterest = interestToBeUncompounded; + } - public void setZeroForInterestToBeUncompounded() { - this.uncompoundedInterest = BigDecimal.ZERO; - } + public void setZeroForInterestToBeUncompounded() { + this.uncompoundedInterest = BigDecimal.ZERO; + } } 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 743344013..872fce061 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 @@ -97,8 +97,8 @@ public class DailyCompoundingPeriod implements CompoundingPeriod { return interestEarned; } - @Override - public LocalDateInterval getPeriodInterval() { - return this.periodInterval; - } + @Override + 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 f21368111..e7ad79480 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 @@ -68,17 +68,17 @@ public class EndOfDayBalance { final BigDecimal realBalanceForInterestCalculation = this.endOfDayBalance.getAmount().add(interestToCompound); 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 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); interest = realBalanceForInterestCalculation.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } } else { 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 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); interest = realBalanceForInterestCalculation.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } 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 ca39033ef..ef3dac989 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 @@ -175,8 +175,8 @@ public class MonthlyCompoundingPeriod implements CompoundingPeriod { this.endOfDayBalances = endOfDayBalances; } - @Override - public LocalDateInterval getPeriodInterval() { - return this.periodInterval; - } + @Override + 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 6e4070c23..d71a4f319 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 @@ -59,8 +59,8 @@ public class PostingPeriod { // minimum balance for interest calculation private final Money minBalanceForInterestCalculation; - private BigDecimal overdraftInterestRateAsFraction; - private Money minOverdraftForInterestCalculation; + private BigDecimal overdraftInterestRateAsFraction; + private Money minOverdraftForInterestCalculation; private Integer financialYearBeginningMonth; @@ -71,14 +71,14 @@ public class PostingPeriod { final LocalDate upToInterestCalculationDate, Collection interestPostTransactions, boolean isInterestTransfer, 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, - overdraftInterestRateAsFraction, minOverdraftForInterestCalculation, isUserPosting, 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, + overdraftInterestRateAsFraction, minOverdraftForInterestCalculation, isUserPosting, financialYearBeginningMonth); } // isInterestTransfer boolean is to identify newly created transaction is @@ -207,23 +207,23 @@ public class PostingPeriod { final BigDecimal interestUnrounded = compoundingPeriod.calculateInterest(this.interestCompoundingType, this.interestCalculationType, compoundInterestValues.getcompoundedInterest(), this.interestRateAsFraction, this.daysInYear, - this.minBalanceForInterestCalculation.getAmount(), this.overdraftInterestRateAsFraction, + 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()); - } + 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()); + } - if (compoundingPeriodEndDate.equals(compoundingPeriod.getPeriodInterval().endDate())) { - BigDecimal interestCompounded = compoundInterestValues.getcompoundedInterest() - .add(unCompoundedInterest); - compoundInterestValues.setcompoundedInterest(interestCompounded); - compoundInterestValues.setZeroForInterestToBeUncompounded(); - } + if (compoundingPeriodEndDate.equals(compoundingPeriod.getPeriodInterval().endDate())) { + BigDecimal interestCompounded = compoundInterestValues.getcompoundedInterest() + .add(unCompoundedInterest); + compoundInterestValues.setcompoundedInterest(interestCompounded); + compoundInterestValues.setZeroForInterestToBeUncompounded(); + } interestEarned = interestEarned.add(interestUnrounded); } 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 8ffdbc159..148f0e05b 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 @@ -178,8 +178,8 @@ public class QuarterlyCompoundingPeriod implements CompoundingPeriod { this.endOfDayBalances = endOfDayBalances; } - @Override - public LocalDateInterval getPeriodInterval() { - return this.periodInterval; - } + @Override + 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/service/DepositAccountOnHoldTransactionReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountOnHoldTransactionReadPlatformServiceImpl.java index 2677bd2c3..50c28c76f 100755 --- 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 @@ -48,7 +48,7 @@ public class DepositAccountOnHoldTransactionReadPlatformServiceImpl implements D @Autowired public DepositAccountOnHoldTransactionReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); mapper = new DepositAccountOnHoldTransactionsMapper(); this.columnValidator = columnValidator; 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 index 65e4dee26..b540cfa52 100755 --- 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 @@ -563,7 +563,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo boolean isInterestTransfer = false; LocalDate postInterestOnDate = null; account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, - postInterestOnDate); + postInterestOnDate); this.savingAccountRepositoryWrapper.saveAndFlush(account); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds); @@ -632,7 +632,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo if (savingsAccountTransaction.isPostInterestCalculationRequired() && account.isBeforeLastPostingPeriod(savingsAccountTransaction.transactionLocalDate())) { account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, - postInterestOnDate); + postInterestOnDate); } else { account.calculateInterestUsing(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postInterestOnDate); @@ -735,7 +735,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo if (account.isBeforeLastPostingPeriod(transactionDate) || account.isBeforeLastPostingPeriod(savingsAccountTransaction.transactionLocalDate())) { account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, - postInterestOnDate); + postInterestOnDate); } else { account.calculateInterestUsing(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postInterestOnDate); @@ -1180,7 +1180,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo if (account.isBeforeLastPostingPeriod(savingsAccountCharge.getDueLocalDate())) { final LocalDate today = DateUtils.getLocalDateOfTenant(); account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, - postInterestOnDate); + postInterestOnDate); } else { final LocalDate today = DateUtils.getLocalDateOfTenant(); account.calculateInterestUsing(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, @@ -1315,7 +1315,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo if (account.isBeforeLastPostingPeriod(transactionDate)) { final LocalDate today = DateUtils.getLocalDateOfTenant(); account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, - postInterestOnDate); + postInterestOnDate); } else { final LocalDate today = DateUtils.getLocalDateOfTenant(); account.calculateInterestUsing(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, @@ -1398,7 +1398,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo account = this.depositAccountAssembler.assembleFrom(accountTransactionDTO.getSavingsAccountId(), DepositAccountType.CURRENT_DEPOSIT); } - return this.depositAccountDomainService.handleSavingDeposit(account, accountTransactionDTO.getFormatter(), + return this.depositAccountDomainService.handleSavingDeposit(account, accountTransactionDTO.getFormatter(), accountTransactionDTO.getTransactionDate(), accountTransactionDTO.getTransactionAmount(), paymentDetail, isRegularTransaction); 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 709a4681d..1bdc72279 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 @@ -212,7 +212,7 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl final Long savingsId = account.getId(); this.businessEventNotifierService.notifyBusinessEventWasExecuted( BUSINESS_EVENTS.FIXED_DEPOSIT_ACCOUNT_CREATE, - constructEntityMap(BUSINESS_ENTITY.DEPOSIT_ACCOUNT, account)); + constructEntityMap(BUSINESS_ENTITY.DEPOSIT_ACCOUNT, account)); this.businessEventNotifierService.notifyBusinessEventWasExecuted( BUSINESS_EVENTS.FIXED_DEPOSIT_ACCOUNT_CREATE, constructEntityMap(BUSINESS_ENTITY.DEPOSIT_ACCOUNT, account)); @@ -229,8 +229,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } } @@ -275,7 +275,7 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl account.validateApplicableInterestRate(); this.savingAccountRepository.save(account); this.businessEventNotifierService.notifyBusinessEventWasExecuted( BUSINESS_EVENTS.RECURRING_DEPOSIT_ACCOUNT_CREATE, - constructEntityMap(BUSINESS_ENTITY.DEPOSIT_ACCOUNT, account)); + constructEntityMap(BUSINESS_ENTITY.DEPOSIT_ACCOUNT, account)); this.businessEventNotifierService.notifyBusinessEventWasExecuted( BUSINESS_EVENTS.RECURRING_DEPOSIT_ACCOUNT_CREATE, constructEntityMap(BUSINESS_ENTITY.DEPOSIT_ACCOUNT, account)); @@ -292,8 +292,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } } @@ -328,7 +328,7 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl 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."; + 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()); @@ -442,9 +442,9 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return new CommandProcessingResult((long) -1); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return new CommandProcessingResult((long) -1); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return new CommandProcessingResult((long) -1); } } @@ -513,9 +513,9 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return new CommandProcessingResult(Long.valueOf(-1)); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return new CommandProcessingResult(Long.valueOf(-1)); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return new CommandProcessingResult(Long.valueOf(-1)); } } 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 423d0732a..af55b0743 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 @@ -104,9 +104,9 @@ public class FixedDepositProductWritePlatformServiceJpaRepositoryImpl implements handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -164,9 +164,9 @@ public class FixedDepositProductWritePlatformServiceJpaRepositoryImpl implements handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + 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/RecurringDepositProductWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/RecurringDepositProductWritePlatformServiceJpaRepositoryImpl.java index 159be86e3..749c684f9 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 @@ -105,8 +105,8 @@ public class RecurringDepositProductWritePlatformServiceJpaRepositoryImpl implem return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -164,9 +164,9 @@ public class RecurringDepositProductWritePlatformServiceJpaRepositoryImpl implem handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + 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/SavingsAccountReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformService.java index 2593297b5..c6bceba6b 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 @@ -60,6 +60,6 @@ public interface SavingsAccountReadPlatformService { List retrieveSavingsIdsPendingEscheat(LocalDate tenantLocalDate); boolean isAccountBelongsToClient(final Long clientId, final Long accountId, final DepositAccountType depositAccountType, final String currencyCode) ; - String retrieveAccountNumberByAccountId(Long accountId); + 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 b0ba652c7..b786888b7 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 @@ -95,7 +95,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead private final StaffReadPlatformService staffReadPlatformService; private final SavingsDropdownReadPlatformService dropdownReadPlatformService; private final ChargeReadPlatformService chargeReadPlatformService; - private final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); + private final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); // mappers private final SavingsAccountTransactionTemplateMapper transactionTemplateMapper; @@ -377,17 +377,17 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead Integer daysToDormancy = null; Integer daysToEscheat = null; - LocalDate localTenantDate = DateUtils.getLocalDateOfTenant(); + LocalDate localTenantDate = DateUtils.getLocalDateOfTenant(); if(isDormancyTrackingActive && statusEnum.equals(SavingsAccountStatusType.ACTIVE.getValue())){ - if(subStatusEnum < SavingsAccountSubStatusEnum.ESCHEAT.getValue()){ + if(subStatusEnum < SavingsAccountSubStatusEnum.ESCHEAT.getValue()){ daysToEscheat = Days.daysBetween(localTenantDate,lastActiveTransactionDate.plusDays(numDaysToEscheat)).getDays(); - } - if(subStatusEnum < SavingsAccountSubStatusEnum.DORMANT.getValue()){ + } + if(subStatusEnum < SavingsAccountSubStatusEnum.DORMANT.getValue()){ daysToDormancy = Days.daysBetween(localTenantDate,lastActiveTransactionDate.plusDays(numDaysToDormancy)).getDays(); - } - if(subStatusEnum < SavingsAccountSubStatusEnum.INACTIVE.getValue()){ + } + if(subStatusEnum < SavingsAccountSubStatusEnum.INACTIVE.getValue()){ daysToInactive = Days.daysBetween(localTenantDate,lastActiveTransactionDate.plusDays(numDaysToInactive)).getDays(); - } + } } final LocalDate submittedOnDate = JdbcSupport.getLocalDate(rs, "submittedOnDate"); @@ -534,8 +534,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead BigDecimal interestNotPosted = BigDecimal.ZERO; LocalDate lastInterestCalculationDate = null; if(totalInterestEarned != null){ - interestNotPosted = totalInterestEarned.subtract(totalInterestPosted).add(totalOverdraftInterestDerived); - lastInterestCalculationDate = JdbcSupport.getLocalDate(rs, "lastInterestCalculationDate"); + interestNotPosted = totalInterestEarned.subtract(totalInterestPosted).add(totalOverdraftInterestDerived); + lastInterestCalculationDate = JdbcSupport.getLocalDate(rs, "lastInterestCalculationDate"); } final SavingsAccountSummaryData summary = new SavingsAccountSummaryData(currency, totalDeposits, totalWithdrawals, @@ -1130,83 +1130,83 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead } - @Override - public List retrieveSavingsIdsPendingInactive( - LocalDate tenantLocalDate) { - List ret = null; - StringBuilder sql = new StringBuilder("select sa.id "); - sql.append(" from m_savings_account as sa "); - sql.append(" inner join m_savings_product as sp on (sa.product_id = sp.id and sp.is_dormancy_tracking_active = 1) "); - sql.append(" where sa.status_enum = 300 "); - sql.append(" and sa.sub_status_enum = 0 "); - sql.append(" and DATEDIFF(?,(select IFNULL(max(sat.transaction_date),sa.activatedon_date) "); - sql.append(" from m_savings_account_transaction as sat "); - sql.append(" where sat.is_reversed = 0 "); - sql.append(" and sat.transaction_type_enum in (1,2) "); - 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)}); - } catch (EmptyResultDataAccessException e) { - // ignore empty result scenario - } catch (DataAccessException e) { - throw e; - } - - return ret; - } + @Override + public List retrieveSavingsIdsPendingInactive( + LocalDate tenantLocalDate) { + List ret = null; + StringBuilder sql = new StringBuilder("select sa.id "); + sql.append(" from m_savings_account as sa "); + sql.append(" inner join m_savings_product as sp on (sa.product_id = sp.id and sp.is_dormancy_tracking_active = 1) "); + sql.append(" where sa.status_enum = 300 "); + sql.append(" and sa.sub_status_enum = 0 "); + sql.append(" and DATEDIFF(?,(select IFNULL(max(sat.transaction_date),sa.activatedon_date) "); + sql.append(" from m_savings_account_transaction as sat "); + sql.append(" where sat.is_reversed = 0 "); + sql.append(" and sat.transaction_type_enum in (1,2) "); + 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)}); + } catch (EmptyResultDataAccessException e) { + // ignore empty result scenario + } catch (DataAccessException e) { + throw e; + } + + return ret; + } - @Override - public List retrieveSavingsIdsPendingDormant( - LocalDate tenantLocalDate) { - List ret = null; - StringBuilder sql = new StringBuilder("select sa.id "); - sql.append(" from m_savings_account as sa "); - sql.append(" inner join m_savings_product as sp on (sa.product_id = sp.id and sp.is_dormancy_tracking_active = 1) "); - sql.append(" where sa.status_enum = 300 "); - sql.append(" and sa.sub_status_enum = 100 "); - sql.append(" and DATEDIFF(?,(select IFNULL(max(sat.transaction_date),sa.activatedon_date) "); - sql.append(" from m_savings_account_transaction as sat "); - sql.append(" where sat.is_reversed = 0 "); - sql.append(" and sat.transaction_type_enum in (1,2) "); - 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)}); - } catch (EmptyResultDataAccessException e) { - // ignore empty result scenario - } catch (DataAccessException e) { - throw e; - } - - return ret; - } + @Override + public List retrieveSavingsIdsPendingDormant( + LocalDate tenantLocalDate) { + List ret = null; + StringBuilder sql = new StringBuilder("select sa.id "); + sql.append(" from m_savings_account as sa "); + sql.append(" inner join m_savings_product as sp on (sa.product_id = sp.id and sp.is_dormancy_tracking_active = 1) "); + sql.append(" where sa.status_enum = 300 "); + sql.append(" and sa.sub_status_enum = 100 "); + sql.append(" and DATEDIFF(?,(select IFNULL(max(sat.transaction_date),sa.activatedon_date) "); + sql.append(" from m_savings_account_transaction as sat "); + sql.append(" where sat.is_reversed = 0 "); + sql.append(" and sat.transaction_type_enum in (1,2) "); + 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)}); + } catch (EmptyResultDataAccessException e) { + // ignore empty result scenario + } catch (DataAccessException e) { + throw e; + } + + return ret; + } - @Override - public List retrieveSavingsIdsPendingEscheat( - LocalDate tenantLocalDate) { - List ret = null; - StringBuilder sql = new StringBuilder("select sa.id "); - sql.append(" from m_savings_account as sa "); - sql.append(" inner join m_savings_product as sp on (sa.product_id = sp.id and sp.is_dormancy_tracking_active = 1) "); - sql.append(" where sa.status_enum = 300 "); - sql.append(" and sa.sub_status_enum = 200 "); - sql.append(" and DATEDIFF(?,(select IFNULL(max(sat.transaction_date),sa.activatedon_date) "); - sql.append(" from m_savings_account_transaction as sat "); - sql.append(" where sat.is_reversed = 0 "); - sql.append(" and sat.transaction_type_enum in (1,2) "); - 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)}); - } catch (EmptyResultDataAccessException e) { - // ignore empty result scenario - } catch (DataAccessException e) { - throw e; - } - - return ret; - } + @Override + public List retrieveSavingsIdsPendingEscheat( + LocalDate tenantLocalDate) { + List ret = null; + StringBuilder sql = new StringBuilder("select sa.id "); + sql.append(" from m_savings_account as sa "); + sql.append(" inner join m_savings_product as sp on (sa.product_id = sp.id and sp.is_dormancy_tracking_active = 1) "); + sql.append(" where sa.status_enum = 300 "); + sql.append(" and sa.sub_status_enum = 200 "); + sql.append(" and DATEDIFF(?,(select IFNULL(max(sat.transaction_date),sa.activatedon_date) "); + sql.append(" from m_savings_account_transaction as sat "); + sql.append(" where sat.is_reversed = 0 "); + sql.append(" and sat.transaction_type_enum in (1,2) "); + 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)}); + } catch (EmptyResultDataAccessException e) { + // ignore empty result scenario + } catch (DataAccessException e) { + throw e; + } + + return ret; + } @Override public boolean isAccountBelongsToClient(final Long clientId, final Long accountId, final DepositAccountType depositAccountType, @@ -1249,13 +1249,13 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead * annualFeeNextDueDate); } } */ - @Override - public String retrieveAccountNumberByAccountId(Long accountId) { - try { - final String sql = "select s.account_no from m_savings_account s where s.id = ?"; - return this.jdbcTemplate.queryForObject(sql, new Object[] { accountId }, String.class); - } catch (final EmptyResultDataAccessException e) { - throw new SavingsAccountNotFoundException(accountId); - } - } + @Override + public String retrieveAccountNumberByAccountId(Long accountId) { + try { + final String sql = "select s.account_no from m_savings_account s where s.id = ?"; + return this.jdbcTemplate.queryForObject(sql, new Object[] { accountId }, String.class); + } catch (final EmptyResultDataAccessException e) { + throw new SavingsAccountNotFoundException(accountId); + } + } } \ No newline at end of file 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 d23e09d14..251e04fb5 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 @@ -79,11 +79,11 @@ public interface SavingsAccountWritePlatformService { CommandProcessingResult modifyWithHoldTax(Long savingsAccountId, JsonCommand command); - void setSubStatusInactive(Long savingsId); + void setSubStatusInactive(Long savingsId); - void setSubStatusDormant(Long savingsId); + void setSubStatusDormant(Long savingsId); - void escheat(Long savingsId); + void escheat(Long savingsId); CommandProcessingResult postInterest(JsonCommand command); 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 index bac81236a..32bce4c7b 100755 --- 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 @@ -367,10 +367,10 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi final DateTimeFormatter fmt = DateTimeFormat.forPattern("dd MM yyyy"); fmt.withZone(DateUtils.getDateTimeZoneOfTenant()); - while (todaysDate.isAfter(savingsAccountCharge.getDueLocalDate())) { - this.payCharge(savingsAccountCharge, savingsAccountCharge.getDueLocalDate(), savingsAccountCharge.amount(), - fmt, user); - } + while (todaysDate.isAfter(savingsAccountCharge.getDueLocalDate())) { + this.payCharge(savingsAccountCharge, savingsAccountCharge.getDueLocalDate(), savingsAccountCharge.amount(), + fmt, user); + } return new CommandProcessingResultBuilder() // .withEntityId(savingsAccountCharge.getId()) // @@ -1543,18 +1543,18 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi .withClientId(account.clientId()).withGroupId(account.groupId()).withSavingsId(savingsId).with(changes).build(); } - private void validateTransactionsForTransfer(final SavingsAccount savingsAccount, final LocalDate transferDate) { + private void validateTransactionsForTransfer(final SavingsAccount savingsAccount, final LocalDate transferDate) { - for (SavingsAccountTransaction transaction : savingsAccount.getTransactions()) { - if ((transaction.getTransactionLocalDate().isEqual(transferDate) - && transaction.getTransactionLocalDate().isAfter(new LocalDate(transferDate))) - || transaction.getTransactionLocalDate().isAfter(transferDate)) { - throw new GeneralPlatformDomainRuleException(TransferApiConstants.transferClientSavingsException, - TransferApiConstants.transferClientSavingsException, new LocalDate(transaction.createdDate()), - transferDate); - } + for (SavingsAccountTransaction transaction : savingsAccount.getTransactions()) { + if ((transaction.getTransactionLocalDate().isEqual(transferDate) + && transaction.getTransactionLocalDate().isAfter(new LocalDate(transferDate))) + || transaction.getTransactionLocalDate().isAfter(transferDate)) { + throw new GeneralPlatformDomainRuleException(TransferApiConstants.transferClientSavingsException, + TransferApiConstants.transferClientSavingsException, new LocalDate(transaction.createdDate()), + transferDate); + } - } + } - } + } } 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 509b87206..23def1fdc 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 @@ -97,7 +97,7 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl private final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository; private final BusinessEventNotifierService businessEventNotifierService; private final EntityDatatableChecksWritePlatformService entityDatatableChecksWritePlatformService; - + @Autowired public SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final SavingsAccountRepositoryWrapper savingAccountRepository, final SavingsAccountAssembler savingAccountAssembler, @@ -196,9 +196,9 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -298,9 +298,9 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return new CommandProcessingResult(Long.valueOf(-1)); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + 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/SavingsEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsEnumerations.java index d74e4a8ef..8f026f7d4 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 @@ -307,20 +307,20 @@ public class SavingsEnumerations { final boolean blockDebit = type.isSubStatusDebitBlocked(); SavingsAccountSubStatusEnumData optionData = new SavingsAccountSubStatusEnumData(SavingsAccountSubStatusEnum.NONE.getValue().longValue(), - SavingsAccountSubStatusEnum.NONE.getCode(), "None", true, inactive, dormant, escheat, block, blockCredit, blockDebit); + 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(), 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 fec8a217e..121c8acaa 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 @@ -270,9 +270,9 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead } if(inClauseAdded) { - sql += " and sp.deposit_type_enum = ?"; + sql += " and sp.deposit_type_enum = ?"; }else { - sql += " where sp.deposit_type_enum = ?"; + sql += " where sp.deposit_type_enum = ?"; } return this.jdbcTemplate.query(sql, this.savingsProductLookupsRowMapper, new Object[] { DepositAccountType.SAVINGS_DEPOSIT.getValue() }); 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 abcf213e7..5218862b7 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 @@ -138,9 +138,9 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -197,9 +197,9 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + 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/SavingsSchedularServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularServiceImpl.java index bd41c22b7..dad4f18ba 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 @@ -67,10 +67,10 @@ public class SavingsSchedularServiceImpl implements SavingsSchedularService { for (SavingsAccount savingsAccount : savingsAccounts.getContent()) { try { this.savingAccountAssembler.assignSavingAccountHelpers(savingsAccount); - boolean postInterestAsOn = false; - LocalDate transactionDate = null; - this.savingsAccountWritePlatformService.postInterest(savingsAccount, postInterestAsOn, - transactionDate); + boolean postInterestAsOn = false; + LocalDate transactionDate = null; + this.savingsAccountWritePlatformService.postInterest(savingsAccount, postInterestAsOn, + transactionDate); } catch (Exception e) { Throwable realCause = e; if (e.getCause() != null) { @@ -90,30 +90,30 @@ public class SavingsSchedularServiceImpl implements SavingsSchedularService { @CronTarget(jobName = JobName.UPDATE_SAVINGS_DORMANT_ACCOUNTS) @Override public void updateSavingsDormancyStatus() throws JobExecutionException { - final LocalDate tenantLocalDate = DateUtils.getLocalDateOfTenant(); + final LocalDate tenantLocalDate = DateUtils.getLocalDateOfTenant(); - final List savingsPendingInactive = this.savingAccountReadPlatformService - .retrieveSavingsIdsPendingInactive(tenantLocalDate); - if(null != savingsPendingInactive && savingsPendingInactive.size() > 0){ - for(Long savingsId : savingsPendingInactive){ - this.savingsAccountWritePlatformService.setSubStatusInactive(savingsId); - } - } + final List savingsPendingInactive = this.savingAccountReadPlatformService + .retrieveSavingsIdsPendingInactive(tenantLocalDate); + if(null != savingsPendingInactive && savingsPendingInactive.size() > 0){ + for(Long savingsId : savingsPendingInactive){ + this.savingsAccountWritePlatformService.setSubStatusInactive(savingsId); + } + } - final List savingsPendingDormant = this.savingAccountReadPlatformService - .retrieveSavingsIdsPendingDormant(tenantLocalDate); - if(null != savingsPendingDormant && savingsPendingDormant.size() > 0){ - for(Long savingsId : savingsPendingDormant){ - this.savingsAccountWritePlatformService.setSubStatusDormant(savingsId); - } - } + final List savingsPendingDormant = this.savingAccountReadPlatformService + .retrieveSavingsIdsPendingDormant(tenantLocalDate); + if(null != savingsPendingDormant && savingsPendingDormant.size() > 0){ + for(Long savingsId : savingsPendingDormant){ + this.savingsAccountWritePlatformService.setSubStatusDormant(savingsId); + } + } - final List savingsPendingEscheat = this.savingAccountReadPlatformService - .retrieveSavingsIdsPendingEscheat(tenantLocalDate); - if(null != savingsPendingEscheat && savingsPendingEscheat.size() > 0){ - for(Long savingsId : savingsPendingEscheat){ - this.savingsAccountWritePlatformService.escheat(savingsId); - } - } + final List savingsPendingEscheat = this.savingAccountReadPlatformService + .retrieveSavingsIdsPendingEscheat(tenantLocalDate); + 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/api/SearchApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/api/SearchApiResource.java index cb1d86ca5..6f74f8e43 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 @@ -97,7 +97,7 @@ public class SearchApiResource { @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 Collection searchResults = this.searchReadPlatformService.retriveMatchingData(searchConditions); 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 dfdef1dae..76be2c9ca 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 @@ -45,22 +45,22 @@ import com.google.gson.reflect.TypeToken; 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", "<=", ">=", "<", ">", "=")); @@ -69,10 +69,10 @@ public class AdHocQueryDataValidator { AdHocQuerySearchConstants.createDateOption, AdHocQuerySearchConstants.disbursalDateOption }; - private static final Object[] loanStatusOptions = {AdHocQuerySearchConstants.allLoanStatusOption, - AdHocQuerySearchConstants.activeLoanStatusOption, AdHocQuerySearchConstants.overpaidLoanStatusOption, - AdHocQuerySearchConstants.arrearsLoanStatusOption, AdHocQuerySearchConstants.closedLoanStatusOption, - AdHocQuerySearchConstants.writeoffLoanStatusOption}; + private static final Object[] loanStatusOptions = {AdHocQuerySearchConstants.allLoanStatusOption, + AdHocQuerySearchConstants.activeLoanStatusOption, AdHocQuerySearchConstants.overpaidLoanStatusOption, + AdHocQuerySearchConstants.arrearsLoanStatusOption, AdHocQuerySearchConstants.closedLoanStatusOption, + AdHocQuerySearchConstants.writeoffLoanStatusOption}; @Autowired public AdHocQueryDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -215,10 +215,10 @@ public class AdHocQueryDataValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); List loanStatus = null; - if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.loanStatusParamName, element)) { - loanStatus = Arrays.asList( - this.fromApiJsonHelper.extractArrayNamed(AdHocQuerySearchConstants.loanStatusParamName, element)); - } + if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.loanStatusParamName, element)) { + loanStatus = Arrays.asList( + this.fromApiJsonHelper.extractArrayNamed(AdHocQuerySearchConstants.loanStatusParamName, element)); + } List loanProducts = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.loanProductsParamName, element)) { @@ -289,7 +289,7 @@ public class AdHocQueryDataValidator { if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.outstandingAmountConditionParamName, element)) { outstandingAmountCondition = this.fromApiJsonHelper.extractStringNamed( AdHocQuerySearchConstants.outstandingAmountConditionParamName, element); - SQLInjectionValidator.validateSQLInput(outstandingAmountCondition); + SQLInjectionValidator.validateSQLInput(outstandingAmountCondition); } BigDecimal minOutstandingAmount = null; 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 a0be77784..0ed3f843c 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 @@ -27,8 +27,8 @@ public class SearchConditions { private final Boolean clientSearch; private final Boolean groupSearch; private final Boolean loanSeach; - private final Boolean savingSeach; - private final Boolean shareSeach; + private final Boolean savingSeach; + private final Boolean shareSeach; private final Boolean clientIdentifierSearch; private Boolean exactMatch; @@ -44,9 +44,9 @@ public class SearchConditions { SEARCH_SUPPORTED_RESOURCES.LOANS.name().toLowerCase())) ? true : false; this.savingSeach = (null == searchResource || searchResource.toLowerCase().contains( SEARCH_SUPPORTED_RESOURCES.SAVINGS.name().toLowerCase())) ? true : false; - this.shareSeach = (null == searchResource || searchResource.toLowerCase().contains( + this.shareSeach = (null == searchResource || searchResource.toLowerCase().contains( SEARCH_SUPPORTED_RESOURCES.SHARES.name().toLowerCase())) ? true : false; - this.clientIdentifierSearch = (null == searchResource || searchResource.toLowerCase().contains( + this.clientIdentifierSearch = (null == searchResource || searchResource.toLowerCase().contains( SEARCH_SUPPORTED_RESOURCES.CLIENTIDENTIFIERS.name().toLowerCase())) ? true : false; } @@ -57,8 +57,8 @@ public class SearchConditions { this.clientSearch = clientSearch; this.groupSearch = groupSearch; this.loanSeach = loanSeach; - this.savingSeach = savingSeach; - this.shareSeach = shareSeach; + this.savingSeach = savingSeach; + this.shareSeach = shareSeach; this.clientIdentifierSearch = clientIdentifierSearch; this.exactMatch=exactMatch; } @@ -71,7 +71,7 @@ public class SearchConditions { return this.searchResource; } public Boolean getExactMatch() { - return this.exactMatch; + return this.exactMatch; } public Boolean isClientSearch() { return this.clientSearch; @@ -88,12 +88,12 @@ public class SearchConditions { public Boolean isSavingSeach() { return this.savingSeach; } - - public Boolean isShareSeach() { + + public Boolean isShareSeach() { return this.shareSeach; } - public Boolean isClientIdentifierSearch() { + public Boolean isClientIdentifierSearch() { return this.clientIdentifierSearch; } 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 cfe58d785..6479ba0ec 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 @@ -81,10 +81,10 @@ public class SearchData { } public String getEntityMobileNo() { - return this.entityMobileNo; - } + return this.entityMobileNo; + } - public EnumOptionData getEntityStatus() { + public EnumOptionData getEntityStatus() { return this.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 33959ea1f..62ca5e53a 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 @@ -76,10 +76,10 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService final MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("hierarchy", hierarchy + "%"); if(searchConditions.getExactMatch()){ - params.addValue("search", searchConditions.getSearchQuery()); - }else{ - params.addValue("search", "%" + searchConditions.getSearchQuery() + "%"); - } + params.addValue("search", searchConditions.getSearchQuery()); + }else{ + params.addValue("search", "%" + searchConditions.getSearchQuery() + "%"); + } return this.namedParameterjdbcTemplate.query(rm.searchSchema(searchConditions), params, rm); } @@ -101,8 +101,8 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService + " , 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 " + " where (o.hierarchy IS NULL OR o.hierarchy like :hierarchy) and (s.account_no like :search or s.external_id like :search)) "; - - final String shareMatchSql = " (select 'SHARE' as entityType, s.id as entityId, sp.name as entityName, s.external_id as entityExternalId, s.account_no as entityAccountNo " + + final String shareMatchSql = " (select 'SHARE' as entityType, s.id as entityId, sp.name as entityName, s.external_id as entityExternalId, s.account_no as entityAccountNo " + " , c.id as parentId, c.display_name as parentName, null as entityMobileNo, s.status_enum as entityStatusEnum, 'client' as parentType " + " from m_share_account s left join m_client c on s.client_id = c.id left join m_office o on o.id = c.office_id left join m_share_product sp on sp.id=s.product_id " + " where (o.hierarchy IS NULL OR o.hierarchy like :hierarchy) and (s.account_no like :search or s.external_id like :search)) "; @@ -127,8 +127,8 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService if (searchConditions.isSavingSeach()) { sql.append(savingMatchSql).append(union); } - - if (searchConditions.isShareSeach()) { + + if (searchConditions.isShareSeach()) { sql.append(shareMatchSql).append(union); } 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 47819a886..00b84ca2f 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 @@ -59,128 +59,128 @@ import io.swagger.annotations.*; @Scope("singleton") @Api(tags = {"Self Account Transfer"}) @SwaggerDefinition(tags = { - @Tag(name = "Self Account transfer", description = "") + @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/SelfBeneficiariesTPTApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiConstants.java index cb1971a79..ad9e59f9c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiConstants.java @@ -24,16 +24,16 @@ import java.util.Set; public interface SelfBeneficiariesTPTApiConstants { - public static final String BENEFICIARY_ENTITY_NAME = "SSBENEFICIARYTPT"; - public static final String RESOURCE_NAME = "beneficiary"; - public static final String LOCALE = "locale"; - public static final String NAME_PARAM_NAME = "name"; - public static final String OFFICE_NAME_PARAM_NAME = "officeName"; - public static final String ACCOUNT_TYPE_PARAM_NAME = "accountType"; - public static final String ACCOUNT_NUMBER_PARAM_NAME = "accountNumber"; - public static final String TRANSFER_LIMIT_PARAM_NAME = "transferLimit"; + public static final String BENEFICIARY_ENTITY_NAME = "SSBENEFICIARYTPT"; + public static final String RESOURCE_NAME = "beneficiary"; + public static final String LOCALE = "locale"; + public static final String NAME_PARAM_NAME = "name"; + public static final String OFFICE_NAME_PARAM_NAME = "officeName"; + public static final String ACCOUNT_TYPE_PARAM_NAME = "accountType"; + public static final String ACCOUNT_NUMBER_PARAM_NAME = "accountNumber"; + public static final String TRANSFER_LIMIT_PARAM_NAME = "transferLimit"; - public static final String ID_PARAM_NAME = "id"; - public static final String CLIENT_NAME_PARAM_NAME = "clientName"; - public static final String ACCOUNT_TYPE_OPTIONS_PARAM_NAME = "accountTypeOptions"; + public static final String ID_PARAM_NAME = "id"; + public static final String CLIENT_NAME_PARAM_NAME = "clientName"; + public static final String ACCOUNT_TYPE_OPTIONS_PARAM_NAME = "accountTypeOptions"; } 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 e43fdf43c..8db644c33 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 @@ -50,128 +50,128 @@ import java.util.Set; @Scope("singleton") @Api(tags = {"Self Third Party Transfer"}) @SwaggerDefinition(tags = { - @Tag(name = "Self Third Party Transfer", description = "") + @Tag(name = "Self Third Party Transfer", description = "") }) public class SelfBeneficiariesTPTApiResource { - private final PlatformSecurityContext context; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - private final ApiRequestParameterHelper apiRequestParameterHelper; - 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.TRANSFER_LIMIT_PARAM_NAME, SelfBeneficiariesTPTApiConstants.ID_PARAM_NAME, - SelfBeneficiariesTPTApiConstants.CLIENT_NAME_PARAM_NAME, - SelfBeneficiariesTPTApiConstants.ACCOUNT_TYPE_OPTIONS_PARAM_NAME)); + private final PlatformSecurityContext context; + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final ApiRequestParameterHelper apiRequestParameterHelper; + 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.TRANSFER_LIMIT_PARAM_NAME, SelfBeneficiariesTPTApiConstants.ID_PARAM_NAME, + SelfBeneficiariesTPTApiConstants.CLIENT_NAME_PARAM_NAME, + SelfBeneficiariesTPTApiConstants.ACCOUNT_TYPE_OPTIONS_PARAM_NAME)); - @Autowired - public SelfBeneficiariesTPTApiResource( - final PlatformSecurityContext context, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final ApiRequestParameterHelper apiRequestParameterHelper, - final SelfBeneficiariesTPTReadPlatformService readPlatformService) { - this.context = context; - this.toApiJsonSerializer = toApiJsonSerializer; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.readPlatformService = readPlatformService; - } + @Autowired + public SelfBeneficiariesTPTApiResource( + final PlatformSecurityContext context, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final ApiRequestParameterHelper apiRequestParameterHelper, + final SelfBeneficiariesTPTReadPlatformService readPlatformService) { + this.context = context; + this.toApiJsonSerializer = toApiJsonSerializer; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.readPlatformService = readPlatformService; + } - @GET - @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)}) - public String template(@Context final UriInfo uriInfo) { + @GET + @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)}) + 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()); - return this.toApiJsonSerializer.serialize(settings, templateData, RESPONSE_DATA_PARAMETERS); - } + 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)}) - public String add(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @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)}) + public String add(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .addSelfServiceBeneficiaryTPT().withJson(apiRequestBodyAsJson) - .build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } + final CommandWrapper commandRequest = new CommandWrapperBuilder() + .addSelfServiceBeneficiaryTPT().withJson(apiRequestBodyAsJson) + .build(); + final CommandProcessingResult result = this.commandsSourceWritePlatformService + .logCommandSource(commandRequest); + return this.toApiJsonSerializer.serialize(result); + } - @PUT - @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)}) - public String update(@PathParam("beneficiaryId") @ApiParam(value = "beneficiaryId") final Long beneficiaryId, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @PUT + @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)}) + public String update(@PathParam("beneficiaryId") @ApiParam(value = "beneficiaryId") final Long beneficiaryId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .updateSelfServiceBeneficiaryTPT(beneficiaryId) - .withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } + final CommandWrapper commandRequest = new CommandWrapperBuilder() + .updateSelfServiceBeneficiaryTPT(beneficiaryId) + .withJson(apiRequestBodyAsJson).build(); + final CommandProcessingResult result = this.commandsSourceWritePlatformService + .logCommandSource(commandRequest); + return this.toApiJsonSerializer.serialize(result); + } - @DELETE - @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) { + @DELETE + @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) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .deleteSelfServiceBeneficiaryTPT(beneficiaryId) - .withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } + final CommandWrapper commandRequest = new CommandWrapperBuilder() + .deleteSelfServiceBeneficiaryTPT(beneficiaryId) + .withJson(apiRequestBodyAsJson).build(); + 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")}) - public String retrieveAll(@Context final UriInfo uriInfo) { + @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")}) + 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()); - return this.toApiJsonSerializer.serialize(settings, beneficiaries, RESPONSE_DATA_PARAMETERS); - } + 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/data/SelfAccountTemplateData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTemplateData.java index 17b2ebe3c..3ff5d4d0a 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 @@ -26,90 +26,90 @@ import org.apache.fineract.portfolio.account.service.AccountTransferEnumerations @SuppressWarnings("unused") public class SelfAccountTemplateData implements - Comparable { + Comparable { - private final Long accountId; - private final String accountNo; - private final EnumOptionData accountType; - private final Long clientId; - private final String clientName; - private final Long officeId; - private final String officeName; + private final Long accountId; + private final String accountNo; + private final EnumOptionData accountType; + private final Long clientId; + private final String clientName; + 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) { - this.accountId = accountId; - this.accountNo = accountNo; - this.accountType = AccountTransferEnumerations.accountType(accountType); - this.clientId = clientId; - this.clientName = clientName; - this.officeId = officeId; - this.officeName = 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); + this.clientId = clientId; + this.clientName = clientName; + this.officeId = officeId; + this.officeName = officeName; + } - 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); - this.clientId = clientId; - this.clientName = null; - this.officeId = officeId; - this.officeName = null; - } + 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); + this.clientId = clientId; + this.clientName = null; + this.officeId = officeId; + this.officeName = null; + } - @Override - public int compareTo(final SelfAccountTemplateData obj) { - if (obj == null) { - return -1; - } - return new CompareToBuilder() // - .append(this.accountId, obj.accountId) // - .append(this.accountType.getValue(), obj.accountType.getValue()) // - .append(this.clientId, obj.clientId) // - .append(this.officeId, obj.officeId) // - .toComparison(); - } + @Override + public int compareTo(final SelfAccountTemplateData obj) { + if (obj == null) { + return -1; + } + return new CompareToBuilder() // + .append(this.accountId, obj.accountId) // + .append(this.accountType.getValue(), obj.accountType.getValue()) // + .append(this.clientId, obj.clientId) // + .append(this.officeId, obj.officeId) // + .toComparison(); + } - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj.getClass() != getClass()) { - return false; - } - final SelfAccountTemplateData rhs = (SelfAccountTemplateData) obj; - return new EqualsBuilder() // - .append(this.accountId, rhs.accountId) // - .append(this.accountType.getValue(), rhs.accountType.getValue()) // - .append(this.clientId, rhs.clientId) // - .append(this.officeId, rhs.officeId) // - .isEquals(); - } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (obj == this) { + return true; + } + if (obj.getClass() != getClass()) { + return false; + } + final SelfAccountTemplateData rhs = (SelfAccountTemplateData) obj; + return new EqualsBuilder() // + .append(this.accountId, rhs.accountId) // + .append(this.accountType.getValue(), rhs.accountType.getValue()) // + .append(this.clientId, rhs.clientId) // + .append(this.officeId, rhs.officeId) // + .isEquals(); + } - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) // - .append(this.accountId) // - .append(this.accountType.getValue()) // - .append(this.clientId) // - .append(this.officeId) // - .toHashCode(); - } + @Override + public int hashCode() { + return new HashCodeBuilder(17, 37) // + .append(this.accountId) // + .append(this.accountType.getValue()) // + .append(this.clientId) // + .append(this.officeId) // + .toHashCode(); + } - public Long getAccountId() { - return this.accountId; - } + public Long getAccountId() { + return this.accountId; + } - public Integer getAccountType() { - return this.accountType.getId().intValue(); - } + public Integer getAccountType() { + 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 5ca23c29f..2ab56e0b6 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 @@ -23,14 +23,14 @@ import java.util.Collection; @SuppressWarnings("unused") public class SelfAccountTransferData { - private final Collection fromAccountOptions; - private final Collection toAccountOptions; + private final Collection fromAccountOptions; + private final Collection toAccountOptions; - public SelfAccountTransferData( - final Collection fromAccountOptions, - Collection toAccountOptions) { - this.fromAccountOptions = fromAccountOptions; - this.toAccountOptions = toAccountOptions; - } + 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 f986a678e..8b63b6906 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 @@ -57,85 +57,85 @@ import com.google.gson.JsonElement; @Component public class SelfAccountTransferDataValidator { - private final PlatformSecurityContext context; - private final SelfAccountTransferReadService selfAccountTransferReadService; - private final SelfBeneficiariesTPTReadPlatformService tptBeneficiaryReadPlatformService; - private final FromJsonHelper fromApiJsonHelper; + private final PlatformSecurityContext context; + private final SelfAccountTransferReadService selfAccountTransferReadService; + private final SelfBeneficiariesTPTReadPlatformService tptBeneficiaryReadPlatformService; + private final FromJsonHelper fromApiJsonHelper; - @Autowired - public SelfAccountTransferDataValidator( - final PlatformSecurityContext context, - final SelfAccountTransferReadService selfAccountTransferReadService, - final SelfBeneficiariesTPTReadPlatformService tptBeneficiaryReadPlatformService, - final FromJsonHelper fromApiJsonHelper) { - this.context = context; - this.selfAccountTransferReadService = selfAccountTransferReadService; - this.tptBeneficiaryReadPlatformService = tptBeneficiaryReadPlatformService; - this.fromApiJsonHelper = fromApiJsonHelper; - } + @Autowired + public SelfAccountTransferDataValidator( + final PlatformSecurityContext context, + final SelfAccountTransferReadService selfAccountTransferReadService, + 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 List dataValidationErrors = new ArrayList<>(); + 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() - .isOneOfTheseValues(Integer.valueOf(1), Integer.valueOf(2)); + 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); baseDataValidator.reset().parameter(transferDateParamName).value(transactionDate).notNull(); @@ -147,82 +147,82 @@ public class SelfAccountTransferDataValidator { baseDataValidator.reset().parameter(transferDescriptionParamName).value(transactionDescription).notBlank() .notExceedingLengthOf(200); - throwExceptionIfValidationWarningsExist(dataValidationErrors); + 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); - - Map ret = new HashMap<>(); - ret.put("fromAccount", fromAccount); - ret.put("toAccount", toAccount); - ret.put("transactionDate", transactionDate); - ret.put("transactionAmount", transactionAmount); - - return ret; + validateUserAccounts(fromAccount, toAccount, baseDataValidator, type); + throwExceptionIfValidationWarningsExist(dataValidationErrors); + + Map ret = new HashMap<>(); + ret.put("fromAccount", fromAccount); + ret.put("toAccount", toAccount); + ret.put("transactionDate", transactionDate); + ret.put("transactionAmount", transactionAmount); + + return ret; - } + } - 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); + 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 validToAccounts = validFromAccounts; - if (type.equals("tpt")) { - validToAccounts = this.tptBeneficiaryReadPlatformService - .retrieveTPTSelfAccountTemplateData(user); - } + Collection validToAccounts = validFromAccounts; + if (type.equals("tpt")) { + validToAccounts = this.tptBeneficiaryReadPlatformService + .retrieveTPTSelfAccountTemplateData(user); + } - boolean validFromAccount = false; - for (SelfAccountTemplateData validAccount : validFromAccounts) { - if (validAccount.equals(fromAccount)) { - validFromAccount = true; - break; - } - } + boolean validFromAccount = false; + for (SelfAccountTemplateData validAccount : validFromAccounts) { + if (validAccount.equals(fromAccount)) { + validFromAccount = true; + break; + } + } - boolean validToAccount = false; - for (SelfAccountTemplateData validAccount : validToAccounts) { - if (validAccount.equals(toAccount)) { - validToAccount = true; - break; - } - } + boolean validToAccount = false; + for (SelfAccountTemplateData validAccount : validToAccounts) { + if (validAccount.equals(toAccount)) { + validToAccount = true; + break; + } + } - if (!validFromAccount) { - baseDataValidator - .reset() - .failWithCode("invalid.from.account.details", - "Source account details doesn't match with valid user account details."); - } + if (!validFromAccount) { + 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."); - } + if (!validToAccount) { + 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."); - } + if (fromAccount.equals(toAccount)) { + 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 ff56606c1..761f6f5c0 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 @@ -23,47 +23,47 @@ import java.util.Collection; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class SelfBeneficiariesTPTData { - @SuppressWarnings("unused") - private final Long id; - @SuppressWarnings("unused") - private final String name; - @SuppressWarnings("unused") - private final String officeName; - @SuppressWarnings("unused") - private final String clientName; - @SuppressWarnings("unused") - private final EnumOptionData accountType; - @SuppressWarnings("unused") - private final String accountNumber; - @SuppressWarnings("unused") - private final Long transferLimit; - @SuppressWarnings("unused") - private final Collection accountTypeOptions; + @SuppressWarnings("unused") + private final Long id; + @SuppressWarnings("unused") + private final String name; + @SuppressWarnings("unused") + private final String officeName; + @SuppressWarnings("unused") + private final String clientName; + @SuppressWarnings("unused") + private final EnumOptionData accountType; + @SuppressWarnings("unused") + private final String accountNumber; + @SuppressWarnings("unused") + private final Long transferLimit; + @SuppressWarnings("unused") + private final Collection accountTypeOptions; - public SelfBeneficiariesTPTData( - final Collection accountTypeOptions) { - this.accountTypeOptions = accountTypeOptions; - this.id = null; - this.name = null; - this.officeName = null; - this.clientName = null; - this.accountType = null; - this.accountNumber = null; - this.transferLimit = null; - } + public SelfBeneficiariesTPTData( + final Collection accountTypeOptions) { + this.accountTypeOptions = accountTypeOptions; + this.id = null; + this.name = null; + this.officeName = null; + this.clientName = null; + this.accountType = null; + this.accountNumber = null; + 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) { - this.accountTypeOptions = null; - this.id = id; - this.name = name; - this.officeName = officeName; - this.clientName = clientName; - this.accountType = accountType; - this.accountNumber = accountNumber; - this.transferLimit = 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; + this.officeName = officeName; + this.clientName = clientName; + this.accountType = accountType; + this.accountNumber = accountNumber; + this.transferLimit = transferLimit; + } } 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 2c8592340..5756e505c 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 @@ -51,124 +51,124 @@ import com.google.gson.reflect.TypeToken; @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 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 UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(NAME_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) { - this.fromApiJsonHelper = fromApiJsonHelper; - } + @Autowired + public SelfBeneficiariesTPTDataValidator( + final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } - public HashMap validateForCreate(String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public HashMap validateForCreate(String json) { + 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 JsonElement element = this.fromApiJsonHelper.parse(json); + final List dataValidationErrors = new ArrayList<>(); + 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); + throwExceptionIfValidationWarningsExist(dataValidationErrors); - HashMap ret = new HashMap<>(); - ret.put(NAME_PARAM_NAME, name); - ret.put(OFFICE_NAME_PARAM_NAME, officeName); - ret.put(ACCOUNT_NUMBER_PARAM_NAME, accountNo); - ret.put(ACCOUNT_TYPE_PARAM_NAME, accountType); - ret.put(TRANSFER_LIMIT_PARAM_NAME, transferLimit); + HashMap ret = new HashMap<>(); + ret.put(NAME_PARAM_NAME, name); + ret.put(OFFICE_NAME_PARAM_NAME, officeName); + ret.put(ACCOUNT_NUMBER_PARAM_NAME, accountNo); + ret.put(ACCOUNT_TYPE_PARAM_NAME, accountType); + ret.put(TRANSFER_LIMIT_PARAM_NAME, transferLimit); - return ret; - } + return ret; + } - public HashMap validateForUpdate(String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public HashMap validateForUpdate(String json) { + 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 JsonElement element = this.fromApiJsonHelper.parse(json); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( + dataValidationErrors).resource(RESOURCE_NAME); + final JsonElement element = this.fromApiJsonHelper.parse(json); - HashMap ret = new HashMap<>(); + 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); - ret.put(NAME_PARAM_NAME, name); - } + 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); + 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(); - ret.put(TRANSFER_LIMIT_PARAM_NAME, transferLimit); - } + 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); + } - throwExceptionIfValidationWarningsExist(dataValidationErrors); + throwExceptionIfValidationWarningsExist(dataValidationErrors); - return ret; - } + 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 30e0e2041..71d675b40 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 @@ -32,105 +32,105 @@ 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") }) + "name", "app_user_id", "is_active" }, name = "name") }) public class SelfBeneficiariesTPT extends AbstractPersistableCustom { - @Column(name = "app_user_id", nullable = false) - private Long appUserId; + @Column(name = "app_user_id", nullable = false) + private Long appUserId; - @Column(name = "name", length = 50, nullable = false) - private String name; + @Column(name = "name", length = 50, nullable = false) + private String name; - @Column(name = "office_id", nullable = false) - private Long officeId; + @Column(name = "office_id", nullable = false) + private Long officeId; - @Column(name = "client_id", nullable = false) - private Long clientId; + @Column(name = "client_id", nullable = false) + private Long clientId; - @Column(name = "account_id", nullable = false) - private Long accountId; + @Column(name = "account_id", nullable = false) + private Long accountId; - @Column(name = "account_type", nullable = false) - private Integer accountType; + @Column(name = "account_type", nullable = false) + private Integer accountType; - @Column(name = "transfer_limit", nullable = true) - private Long transferLimit; + @Column(name = "transfer_limit", nullable = true) + private Long transferLimit; - @Column(name = "is_active", nullable = false) - private boolean isActive = true; + @Column(name = "is_active", nullable = false) + private boolean isActive = true; - protected SelfBeneficiariesTPT() { - // - } + protected SelfBeneficiariesTPT() { + // + } - public SelfBeneficiariesTPT(Long appUserId, String name, Long officeId, - Long clientId, Long accountId, Integer accountType, - Long transferLimit) { - this.appUserId = appUserId; - this.name = name; - this.officeId = officeId; - this.clientId = clientId; - this.accountId = accountId; - this.accountType = accountType; - this.transferLimit = transferLimit; - } + public SelfBeneficiariesTPT(Long appUserId, String name, Long officeId, + Long clientId, Long accountId, Integer accountType, + Long transferLimit) { + this.appUserId = appUserId; + this.name = name; + this.officeId = officeId; + this.clientId = clientId; + this.accountId = accountId; + this.accountType = accountType; + this.transferLimit = transferLimit; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Long getTransferLimit() { - return this.transferLimit; - } + public Long getTransferLimit() { + return this.transferLimit; + } - public void setTransferLimit(Long transferLimit) { - this.transferLimit = transferLimit; - } + public void setTransferLimit(Long transferLimit) { + this.transferLimit = transferLimit; + } - public boolean isActive() { - return this.isActive; - } + public boolean isActive() { + return this.isActive; + } - public void setActive(boolean isActive) { - this.isActive = isActive; - } + public void setActive(boolean isActive) { + this.isActive = isActive; + } - public Long getAppUserId() { - return this.appUserId; - } + public Long getAppUserId() { + return this.appUserId; + } - public Long getOfficeId() { - return this.officeId; - } + public Long getOfficeId() { + return this.officeId; + } - public Long getClientId() { - return this.clientId; - } + public Long getClientId() { + return this.clientId; + } - public Long getAccountId() { - return this.accountId; - } + public Long getAccountId() { + return this.accountId; + } - public Integer getAccountType() { - return this.accountType; - } + public Integer getAccountType() { + return this.accountType; + } - public Map update(String newName, Long newTransferLimit) { - Map changes = new HashMap<>(); - if (!this.name.equals(newName)) { - this.name = newName; - changes.put(NAME_PARAM_NAME, newName); - } - if ((this.transferLimit !=null && !this.transferLimit.equals(newTransferLimit)) - || (this.transferLimit == null && newTransferLimit != null)) { - this.transferLimit = newTransferLimit; - changes.put(TRANSFER_LIMIT_PARAM_NAME, newTransferLimit); - } - return changes; - } + public Map update(String newName, Long newTransferLimit) { + Map changes = new HashMap<>(); + if (!this.name.equals(newName)) { + this.name = newName; + changes.put(NAME_PARAM_NAME, newName); + } + if ((this.transferLimit !=null && !this.transferLimit.equals(newTransferLimit)) + || (this.transferLimit == null && newTransferLimit != null)) { + this.transferLimit = newTransferLimit; + changes.put(TRANSFER_LIMIT_PARAM_NAME, newTransferLimit); + } + return changes; + } } 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 a74ebeaba..35b7d144a 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 @@ -22,7 +22,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface SelfBeneficiariesTPTRepository extends - JpaRepository, - JpaSpecificationExecutor { + 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 3623d3344..5fd0db1c4 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 @@ -22,9 +22,9 @@ 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"); - } + public BeneficiaryTransferLimitExceededException() { + 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 fb365f8fc..a2ece00a1 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,10 @@ 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 7362077be..3f3274d40 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 @@ -21,12 +21,12 @@ 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"); - } + 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 daac892e1..00900ddce 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 @@ -21,9 +21,9 @@ package org.apache.fineract.portfolio.self.account.exception; import org.apache.fineract.infrastructure.core.exception.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"); - } + AbstractPlatformDomainRuleException { + public InvalidBeneficiaryException(final Long beneficiaryId) { + 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 cd88fa1ae..6bb2c0ec0 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 @@ -29,18 +29,18 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "SSBENEFICIARYTPT", action = "CREATE") public class AddSelfBeneficiariesTPTCommandHandler implements - NewCommandSourceHandler { - private final SelfBeneficiariesTPTWritePlatformService writePlatformService; + NewCommandSourceHandler { + private final SelfBeneficiariesTPTWritePlatformService writePlatformService; - @Autowired - public AddSelfBeneficiariesTPTCommandHandler( - final SelfBeneficiariesTPTWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public AddSelfBeneficiariesTPTCommandHandler( + final SelfBeneficiariesTPTWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.add(command); - } + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.writePlatformService.add(command); + } } 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 46f378030..187bf2f53 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 @@ -29,18 +29,18 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "SSBENEFICIARYTPT", action = "DELETE") public class DeleteSelfBeneficiariesTPTCommandHandler implements - NewCommandSourceHandler { - private final SelfBeneficiariesTPTWritePlatformService writePlatformService; + NewCommandSourceHandler { + private final SelfBeneficiariesTPTWritePlatformService writePlatformService; - @Autowired - public DeleteSelfBeneficiariesTPTCommandHandler( - final SelfBeneficiariesTPTWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public DeleteSelfBeneficiariesTPTCommandHandler( + final SelfBeneficiariesTPTWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.delete(command); - } + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.writePlatformService.delete(command); + } } 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 e92123ea6..4ed9feda5 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 @@ -29,18 +29,18 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "SSBENEFICIARYTPT", action = "UPDATE") public class UpdateSelfBeneficiariesTPTCommandHandler implements - NewCommandSourceHandler { - private final SelfBeneficiariesTPTWritePlatformService writePlatformService; + NewCommandSourceHandler { + private final SelfBeneficiariesTPTWritePlatformService writePlatformService; - @Autowired - public UpdateSelfBeneficiariesTPTCommandHandler( - final SelfBeneficiariesTPTWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public UpdateSelfBeneficiariesTPTCommandHandler( + final SelfBeneficiariesTPTWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.update(command); - } + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.writePlatformService.update(command); + } } 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 9bac993fb..ee5e8f479 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 @@ -25,7 +25,7 @@ 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 4c4af1b3b..f85540692 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 @@ -32,71 +32,71 @@ import org.springframework.stereotype.Service; @Service public class SelfAccountTransferReadServiceImpl implements - SelfAccountTransferReadService { + SelfAccountTransferReadService { - private final JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; - @Autowired - public SelfAccountTransferReadServiceImpl(final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + public SelfAccountTransferReadServiceImpl(final RoutingDataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } - @Override - public Collection retrieveSelfAccountTemplateData( - AppUser user) { - SelfAccountTemplateMapper mapper = new SelfAccountTemplateMapper(); - StringBuffer sql = new StringBuffer() - .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() }); - } + @Override + public Collection retrieveSelfAccountTemplateData( + AppUser user) { + SelfAccountTemplateMapper mapper = new SelfAccountTemplateMapper(); + StringBuffer sql = new StringBuffer() + .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() }); + } - 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 { - final Long accountId = rs.getLong("accountId"); - final String accountNo = rs.getString("accountNo"); - final Integer accountType = rs.getInt("accountType"); - final Long clientId = rs.getLong("clientId"); - final String clientName = rs.getString("clientName"); - final Long officeId = rs.getLong("officeId"); - final String officeName = rs.getString("officeName"); + @Override + 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"); + final Long clientId = rs.getLong("clientId"); + final String clientName = rs.getString("clientName"); + 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 d60b47f99..8cb249c4b 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 @@ -26,11 +26,11 @@ import org.apache.fineract.useradministration.domain.AppUser; public interface SelfBeneficiariesTPTReadPlatformService { - Collection retrieveAll(); + Collection retrieveAll(); - Collection retrieveTPTSelfAccountTemplateData( - AppUser user); + Collection retrieveTPTSelfAccountTemplateData( + AppUser user); - Long getTransferLimit(Long id, Long accountId, Integer accountType); + 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 c209a4d1b..1f366c6db 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 @@ -37,186 +37,186 @@ import org.springframework.stereotype.Service; @Service public class SelfBeneficiariesTPTReadPlatformServiceImpl implements - SelfBeneficiariesTPTReadPlatformService { + SelfBeneficiariesTPTReadPlatformService { - private final PlatformSecurityContext context; - private final JdbcTemplate jdbcTemplate; - private final BeneficiaryMapper mapper; - private final AccountTemplateMapper accountTemplateMapper; + private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final BeneficiaryMapper mapper; + private final AccountTemplateMapper accountTemplateMapper; - @Autowired - public SelfBeneficiariesTPTReadPlatformServiceImpl( - final PlatformSecurityContext context, - final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.mapper = new BeneficiaryMapper(); - this.accountTemplateMapper = new AccountTemplateMapper(); - } + @Autowired + public SelfBeneficiariesTPTReadPlatformServiceImpl( + final PlatformSecurityContext context, + final RoutingDataSource dataSource) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.mapper = new BeneficiaryMapper(); + this.accountTemplateMapper = new AccountTemplateMapper(); + } - @Override - public Collection retrieveAll() { - AppUser user = this.context.authenticatedUser(); - return this.jdbcTemplate.query(this.mapper.schema(), this.mapper, - new Object[] { user.getId(), user.getId() }); - } + @Override + public Collection retrieveAll() { + AppUser user = this.context.authenticatedUser(); + 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, - new Object[] { user.getId(), user.getId() }); - } + @Override + 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; + private final String schemaSql; - public BeneficiaryMapper() { - 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, "); - sqlBuilder.append(" b.account_type as accountType, "); - 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(" where b.is_active = 1 "); - sqlBuilder.append(" and b.account_type = 2 "); - sqlBuilder.append(" and b.app_user_id = ?) "); - sqlBuilder.append(" union all "); - sqlBuilder.append(" (select b.id as id, "); - sqlBuilder.append(" b.name as name, "); - sqlBuilder.append(" o.name as officeName, "); - sqlBuilder.append(" c.display_name as clientName, "); - sqlBuilder.append(" b.account_type as accountType, "); - 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(" where b.is_active = 1 "); - sqlBuilder.append(" and b.account_type = 1 "); - sqlBuilder.append(" and b.app_user_id = ?) "); + public BeneficiaryMapper() { + 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, "); + sqlBuilder.append(" b.account_type as accountType, "); + 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(" where b.is_active = 1 "); + sqlBuilder.append(" and b.account_type = 2 "); + sqlBuilder.append(" and b.app_user_id = ?) "); + sqlBuilder.append(" union all "); + sqlBuilder.append(" (select b.id as id, "); + sqlBuilder.append(" b.name as name, "); + sqlBuilder.append(" o.name as officeName, "); + sqlBuilder.append(" c.display_name as clientName, "); + sqlBuilder.append(" b.account_type as accountType, "); + 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(" where b.is_active = 1 "); + sqlBuilder.append(" and b.account_type = 1 "); + sqlBuilder.append(" and b.app_user_id = ?) "); - this.schemaSql = sqlBuilder.toString(); - } + this.schemaSql = sqlBuilder.toString(); + } - public String schema() { - return this.schemaSql; - } + public String schema() { + return this.schemaSql; + } - @Override - public SelfBeneficiariesTPTData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + @Override + 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 String accountNumber = rs.getString("accountNumber"); - final Long transferLimit = rs.getLong("transferLimit"); + 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 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; + private final String schemaSql; - public AccountTemplateMapper() { - 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, "); - sqlBuilder.append(" b.account_type as accountType, "); - 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(" where b.is_active = 1 "); - sqlBuilder.append(" and b.account_type = 2 "); - sqlBuilder.append(" and b.app_user_id = ?) "); - sqlBuilder.append(" union all "); - sqlBuilder.append(" (select o.name as officeName, "); - sqlBuilder.append(" o.id as officeId, "); - sqlBuilder.append(" c.display_name as clientName, "); - sqlBuilder.append(" c.id as clientId, "); - sqlBuilder.append(" b.account_type as accountType, "); - 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(" where b.is_active = 1 "); - sqlBuilder.append(" and b.account_type = 1 "); - sqlBuilder.append(" and b.app_user_id = ?) "); + public AccountTemplateMapper() { + 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, "); + sqlBuilder.append(" b.account_type as accountType, "); + 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(" where b.is_active = 1 "); + sqlBuilder.append(" and b.account_type = 2 "); + sqlBuilder.append(" and b.app_user_id = ?) "); + sqlBuilder.append(" union all "); + sqlBuilder.append(" (select o.name as officeName, "); + sqlBuilder.append(" o.id as officeId, "); + sqlBuilder.append(" c.display_name as clientName, "); + sqlBuilder.append(" c.id as clientId, "); + sqlBuilder.append(" b.account_type as accountType, "); + 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(" where b.is_active = 1 "); + sqlBuilder.append(" and b.account_type = 1 "); + sqlBuilder.append(" and b.app_user_id = ?) "); - this.schemaSql = sqlBuilder.toString(); - } + this.schemaSql = sqlBuilder.toString(); + } - public String schema() { - return this.schemaSql; - } + public String schema() { + return this.schemaSql; + } - @Override - public SelfAccountTemplateData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + @Override + 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"); - final String clientName = rs.getString("clientName"); - final Long clientId = rs.getLong("clientId"); - final Integer accountTypeId = rs.getInt("accountType"); - final String accountNumber = rs.getString("accountNumber"); - final Long accountId = rs.getLong("accountId"); + final String officeName = rs.getString("officeName"); + final Long officeId = rs.getLong("officeId"); + final String clientName = rs.getString("clientName"); + final Long clientId = rs.getLong("clientId"); + final Integer accountTypeId = rs.getInt("accountType"); + 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); + } + } - @Override - public Long getTransferLimit(Long appUserId, Long accountId, Integer accountType) { - final StringBuilder sqlBuilder = new StringBuilder("select b.transfer_limit "); - sqlBuilder.append(" from m_selfservice_beneficiaries_tpt as b "); - sqlBuilder.append(" where b.app_user_id = ? "); - sqlBuilder.append(" and b.account_id = ? "); - 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); - } + @Override + public Long getTransferLimit(Long appUserId, Long accountId, Integer accountType) { + final StringBuilder sqlBuilder = new StringBuilder("select b.transfer_limit "); + sqlBuilder.append(" from m_selfservice_beneficiaries_tpt as b "); + sqlBuilder.append(" where b.app_user_id = ? "); + sqlBuilder.append(" and b.account_id = ? "); + 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); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTWritePlatformService.java index 5d4519b87..2ce5a9578 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTWritePlatformService.java @@ -23,10 +23,10 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface SelfBeneficiariesTPTWritePlatformService { - CommandProcessingResult add(JsonCommand command); + CommandProcessingResult add(JsonCommand command); - CommandProcessingResult update(JsonCommand command); + CommandProcessingResult update(JsonCommand command); - CommandProcessingResult delete(JsonCommand command); + CommandProcessingResult delete(JsonCommand command); } 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 93bc379b9..cfa06f3be 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 @@ -52,158 +52,158 @@ import org.springframework.transaction.annotation.Transactional; @Service public class SelfBeneficiariesTPTWritePlatformServiceImpl implements - SelfBeneficiariesTPTWritePlatformService { + SelfBeneficiariesTPTWritePlatformService { - private final Logger logger; - private final PlatformSecurityContext context; - private final SelfBeneficiariesTPTRepository repository; - private final SelfBeneficiariesTPTDataValidator validator; - private final LoanRepositoryWrapper loanRepositoryWrapper; - private final SavingsAccountRepositoryWrapper savingRepositoryWrapper; + private final Logger logger; + private final PlatformSecurityContext context; + private final SelfBeneficiariesTPTRepository repository; + private final SelfBeneficiariesTPTDataValidator validator; + private final LoanRepositoryWrapper loanRepositoryWrapper; + private final SavingsAccountRepositoryWrapper savingRepositoryWrapper; - @Autowired - 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.logger = LoggerFactory - .getLogger(SelfBeneficiariesTPTWritePlatformServiceImpl.class); - } + @Autowired + 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.logger = LoggerFactory + .getLogger(SelfBeneficiariesTPTWritePlatformServiceImpl.class); + } - @Transactional - @Override - public CommandProcessingResult add(JsonCommand command) { - HashMap params = this.validator - .validateForCreate(command.json()); + @Transactional + @Override + public CommandProcessingResult add(JsonCommand command) { + HashMap params = this.validator + .validateForCreate(command.json()); - String name = (String) params.get(NAME_PARAM_NAME); - Integer accountType = (Integer) params.get(ACCOUNT_TYPE_PARAM_NAME); - String accountNumber = (String) params.get(ACCOUNT_NUMBER_PARAM_NAME); - String officeName = (String) params.get(OFFICE_NAME_PARAM_NAME); - Long transferLimit = (Long) params.get(TRANSFER_LIMIT_PARAM_NAME); + String name = (String) params.get(NAME_PARAM_NAME); + Integer accountType = (Integer) params.get(ACCOUNT_TYPE_PARAM_NAME); + String accountNumber = (String) params.get(ACCOUNT_NUMBER_PARAM_NAME); + String officeName = (String) params.get(OFFICE_NAME_PARAM_NAME); + Long transferLimit = (Long) params.get(TRANSFER_LIMIT_PARAM_NAME); - Long accountId = null; - Long clientId = null; - Long officeId = null; + Long accountId = null; + Long clientId = null; + Long officeId = null; - 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)) { - accountId = loan.getId(); - officeId = loan.getOfficeId(); - clientId = loan.getClientId(); - } else { - validAccountDetails = false; - } - } else { - 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(); - } else { - validAccountDetails = false; - } - } + 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)) { + accountId = loan.getId(); + officeId = loan.getOfficeId(); + clientId = loan.getClientId(); + } else { + validAccountDetails = false; + } + } else { + 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(); + } else { + validAccountDetails = false; + } + } - if (validAccountDetails) { - try { - AppUser user = this.context.authenticatedUser(); - SelfBeneficiariesTPT beneficiary = new SelfBeneficiariesTPT( - user.getId(), name, officeId, clientId, accountId, - accountType, transferLimit); - this.repository.save(beneficiary); - return new CommandProcessingResultBuilder().withEntityId( - beneficiary.getId()).build(); - } catch (DataAccessException dae) { - handleDataIntegrityIssues(command, dae); - } - } - throw new InvalidAccountInformationException(officeName, accountNumber, - PortfolioAccountType.fromInt(accountType).getCode()); + if (validAccountDetails) { + try { + AppUser user = this.context.authenticatedUser(); + SelfBeneficiariesTPT beneficiary = new SelfBeneficiariesTPT( + user.getId(), name, officeId, clientId, accountId, + accountType, transferLimit); + this.repository.save(beneficiary); + return new CommandProcessingResultBuilder().withEntityId( + beneficiary.getId()).build(); + } catch (DataAccessException dae) { + handleDataIntegrityIssues(command, dae); + } + } + throw new InvalidAccountInformationException(officeName, accountNumber, + PortfolioAccountType.fromInt(accountType).getCode()); - } + } - @Transactional - @Override - public CommandProcessingResult update(JsonCommand command) { - 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())) { - String name = (String) params.get(NAME_PARAM_NAME); - Long transferLimit = (Long) params.get(TRANSFER_LIMIT_PARAM_NAME); + @Transactional + @Override + public CommandProcessingResult update(JsonCommand command) { + 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())) { + String name = (String) params.get(NAME_PARAM_NAME); + Long transferLimit = (Long) params.get(TRANSFER_LIMIT_PARAM_NAME); - Map changes = beneficiary.update(name, - transferLimit); - if (!changes.isEmpty()) { - try { - this.repository.save(beneficiary); + Map changes = beneficiary.update(name, + transferLimit); + if (!changes.isEmpty()) { + try { + this.repository.save(beneficiary); - return new CommandProcessingResultBuilder() // - .withEntityId(beneficiary.getId()) // - .with(changes).build(); - } catch (DataAccessException dae) { - handleDataIntegrityIssues(command, dae); - } + return new CommandProcessingResultBuilder() // + .withEntityId(beneficiary.getId()) // + .with(changes).build(); + } catch (DataAccessException dae) { + handleDataIntegrityIssues(command, dae); + } - } - } - throw new InvalidBeneficiaryException(beneficiaryId); - } + } + } + throw new InvalidBeneficiaryException(beneficiaryId); + } - @Transactional - @Override - public CommandProcessingResult delete(JsonCommand command) { - 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())) { + @Transactional + @Override + public CommandProcessingResult delete(JsonCommand command) { + 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())) { - beneficiary.setActive(false); - this.repository.save(beneficiary); + beneficiary.setActive(false); + this.repository.save(beneficiary); - return new CommandProcessingResultBuilder() // - .withEntityId(beneficiary.getId()) // - .build(); - } - throw new InvalidBeneficiaryException(beneficiaryId); - } + return new CommandProcessingResultBuilder() // + .withEntityId(beneficiary.getId()) // + .build(); + } + 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 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.logger.error(dae.getMessage(), dae); - throw new PlatformDataIntegrityException( - "error.msg.beneficiary.unknown.data.integrity.issue", - "Unknown data integrity issue with resource."); - } + this.logger.error(dae.getMessage(), dae); + 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 86e728620..3fc238c98 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 @@ -59,241 +59,241 @@ import com.sun.jersey.multipart.FormDataParam; @Scope("singleton") @Api(tags = {"Self Client"}) @SwaggerDefinition(tags = { - @Tag(name = "Self Client", description = "") + @Tag(name = "Self Client", description = "") }) public class SelfClientsApiResource { - private final PlatformSecurityContext context; - private final ClientsApiResource clientApiResource; - private final ImagesApiResource imagesApiResource; - private final ClientChargesApiResource clientChargesApiResource; - private final ClientTransactionsApiResource clientTransactionsApiResource; - private final AppuserClientMapperReadService appUserClientMapperReadService; - private final SelfClientDataValidator dataValidator; + private final PlatformSecurityContext context; + private final ClientsApiResource clientApiResource; + private final ImagesApiResource imagesApiResource; + private final ClientChargesApiResource clientChargesApiResource; + private final ClientTransactionsApiResource clientTransactionsApiResource; + private final AppuserClientMapperReadService appUserClientMapperReadService; + private final SelfClientDataValidator dataValidator; - @Autowired - public SelfClientsApiResource( - final PlatformSecurityContext context, - final ClientsApiResource clientApiResource, - final ImagesApiResource imagesApiResource, - final ClientChargesApiResource clientChargesApiResource, - final ClientTransactionsApiResource clientTransactionsApiResource, - final AppuserClientMapperReadService appUserClientMapperReadService, - final SelfClientDataValidator dataValidator) { - this.context = context; - this.clientApiResource = clientApiResource; - this.imagesApiResource = imagesApiResource; - this.clientChargesApiResource = clientChargesApiResource; - this.clientTransactionsApiResource = clientTransactionsApiResource; - this.appUserClientMapperReadService = appUserClientMapperReadService; - this.dataValidator = dataValidator; - } + @Autowired + public SelfClientsApiResource( + final PlatformSecurityContext context, + final ClientsApiResource clientApiResource, + final ImagesApiResource imagesApiResource, + final ClientChargesApiResource clientChargesApiResource, + final ClientTransactionsApiResource clientTransactionsApiResource, + final AppuserClientMapperReadService appUserClientMapperReadService, + final SelfClientDataValidator dataValidator) { + this.context = context; + this.clientApiResource = clientApiResource; + this.imagesApiResource = imagesApiResource; + this.clientChargesApiResource = clientChargesApiResource; + this.clientTransactionsApiResource = clientTransactionsApiResource; + this.appUserClientMapperReadService = appUserClientMapperReadService; + this.dataValidator = dataValidator; + } - @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)}) - public String retrieveAll(@Context final UriInfo uriInfo, - @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("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) { + @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)}) + public String retrieveAll(@Context final UriInfo uriInfo, + @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("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 String sqlSearch = null; - final Long officeId = null; - final String externalId = null; - final String hierarchy = null; - final Boolean orphansOnly = null; - return this.clientApiResource.retrieveAll(uriInfo, sqlSearch, officeId, - externalId, displayName, firstname, lastname, hierarchy, - offset, limit, orderBy, sortOrder, orphansOnly, true); - } + final String sqlSearch = null; + final Long officeId = null; + final String externalId = null; + final String hierarchy = null; + final Boolean orphansOnly = null; + return this.clientApiResource.retrieveAll(uriInfo, sqlSearch, officeId, + externalId, displayName, firstname, lastname, hierarchy, + offset, limit, orderBy, sortOrder, orphansOnly, true); + } - @GET - @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) { + @GET + @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) { - this.dataValidator.validateRetrieveOne(uriInfo); + this.dataValidator.validateRetrieveOne(uriInfo); - validateAppuserClientsMapping(clientId); + validateAppuserClientsMapping(clientId); - final boolean staffInSelectedOfficeOnly = false; - return this.clientApiResource.retrieveOne(clientId, uriInfo, - staffInSelectedOfficeOnly); - } + final boolean staffInSelectedOfficeOnly = false; + 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, - @Context final UriInfo uriInfo) { + @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, + @Context final UriInfo uriInfo) { - validateAppuserClientsMapping(clientId); + 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 }) - @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")}) - 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, - @QueryParam("output") @ApiParam(example = "output") final String output) { + @GET + @Path("{clientId}/images") + @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")}) + 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, + @QueryParam("output") @ApiParam(example = "output") final String output) { - validateAppuserClientsMapping(clientId); + 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, - @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) { + @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, + @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) { - validateAppuserClientsMapping(clientId); + 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) { + @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) { - this.dataValidator.validateClientCharges(uriInfo); + this.dataValidator.validateClientCharges(uriInfo); - validateAppuserClientsMapping(clientId); + 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, - @QueryParam("limit") @ApiParam(value = "limit") final Integer limit) { + @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, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit) { - validateAppuserClientsMapping(clientId); + 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) { + @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) { - validateAppuserClientsMapping(clientId); + 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); - } - } - - @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, - @FormDataParam("file") final FormDataBodyPart bodyPart) { + 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); + } + } + + @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, + @FormDataParam("file") final FormDataBodyPart bodyPart) { - validateAppuserClientsMapping(clientId); - return this.imagesApiResource.addNewClientImage(ClientApiConstants.clientEntityName, clientId, fileSize, - inputStream, fileDetails, bodyPart); + validateAppuserClientsMapping(clientId); + return this.imagesApiResource.addNewClientImage(ClientApiConstants.clientEntityName, clientId, fileSize, + inputStream, fileDetails, bodyPart); - } - - @POST - @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) { - validateAppuserClientsMapping(clientId); - return this.imagesApiResource.addNewClientImage(ClientApiConstants.clientEntityName, clientId, jsonRequestBody); + } + + @POST + @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) { + validateAppuserClientsMapping(clientId); + return this.imagesApiResource.addNewClientImage(ClientApiConstants.clientEntityName, clientId, jsonRequestBody); - } + } - @DELETE - @Path("{clientId}/images") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String deleteClientImage(@PathParam("clientId") final Long clientId) { - - validateAppuserClientsMapping(clientId); - return this.imagesApiResource.deleteClientImage(ClientApiConstants.clientEntityName, clientId); + @DELETE + @Path("{clientId}/images") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String deleteClientImage(@PathParam("clientId") final Long clientId) { + + validateAppuserClientsMapping(clientId); + return this.imagesApiResource.deleteClientImage(ClientApiConstants.clientEntityName, clientId); - } + } - @GET - @Path("{clientId}/obligeedetails") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveObligeeDetails(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { + @GET + @Path("{clientId}/obligeedetails") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveObligeeDetails(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { - validateAppuserClientsMapping(clientId); + validateAppuserClientsMapping(clientId); - return this.clientApiResource.retrieveObligeeDetails(clientId, uriInfo); - } + 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/data/SelfClientDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/data/SelfClientDataValidator.java index 730da19e1..02f842920 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 @@ -33,45 +33,45 @@ 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<>(); + public void validateClientCharges(final UriInfo uriInfo) { + List unsupportedParams = new ArrayList<>(); - Set associationParameters = ApiParameterHelper - .extractAssociationsForResponseIfProvided(uriInfo - .getQueryParameters()); - if (!associationParameters.isEmpty()) { - associationParameters - .removeAll(allowedChargesAssociationParameters); - if (!associationParameters.isEmpty()) { - unsupportedParams.addAll(associationParameters); - } - } + Set associationParameters = ApiParameterHelper + .extractAssociationsForResponseIfProvided(uriInfo + .getQueryParameters()); + if (!associationParameters.isEmpty()) { + associationParameters + .removeAll(allowedChargesAssociationParameters); + if (!associationParameters.isEmpty()) { + unsupportedParams.addAll(associationParameters); + } + } - if (uriInfo.getQueryParameters().getFirst("exclude") != null) { - unsupportedParams.add("exclude"); - } + if (uriInfo.getQueryParameters().getFirst("exclude") != null) { + 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<>(); + public void validateRetrieveOne(final UriInfo uriInfo) { + List unsupportedParams = new ArrayList<>(); - final boolean templateRequest = ApiParameterHelper.template(uriInfo - .getQueryParameters()); - if (templateRequest) { - unsupportedParams.add("template"); - } + 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/AppuserClientMapperReadService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/service/AppuserClientMapperReadService.java index 2090756ad..5d8694aca 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/service/AppuserClientMapperReadService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/service/AppuserClientMapperReadService.java @@ -20,8 +20,8 @@ package org.apache.fineract.portfolio.self.client.service; public interface AppuserClientMapperReadService { - public Boolean isClientMappedToUser(Long clientId, Long appUserId); - - public void validateAppuserClientsMapping(final Long clientId); + public Boolean isClientMappedToUser(Long clientId, Long appUserId); + + public void validateAppuserClientsMapping(final Long clientId); } 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 408166e34..d51aa76ee 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 @@ -28,37 +28,37 @@ import org.springframework.stereotype.Service; @Service public class AppuserClientMapperReadServiceImpl implements - AppuserClientMapperReadService { + AppuserClientMapperReadService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public AppuserClientMapperReadServiceImpl(final RoutingDataSource dataSource, final PlatformSecurityContext context) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.context = context; - } + @Autowired + public AppuserClientMapperReadServiceImpl(final RoutingDataSource dataSource, final PlatformSecurityContext context) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.context = context; + } - @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); - } - - @Override - public void validateAppuserClientsMapping(final Long clientId) { - AppUser user = this.context.authenticatedUser(); - if (clientId != null) { - final boolean mappedClientId = isClientMappedToUser(clientId, user.getId()); - if (!mappedClientId) { - throw new ClientNotFoundException(clientId); - } - } else - throw new ClientNotFoundException(clientId); + @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); + } + + @Override + public void validateAppuserClientsMapping(final Long clientId) { + AppUser user = this.context.authenticatedUser(); + if (clientId != null) { + final boolean mappedClientId = isClientMappedToUser(clientId, user.getId()); + 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 936a2e99c..702877d89 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 @@ -49,103 +49,103 @@ import java.util.HashMap; @Scope("singleton") @Api(tags = {"Self Loans"}) @SwaggerDefinition(tags = { - @Tag(name = "Self Loans", description = "") + @Tag(name = "Self Loans", description = "") }) public class SelfLoansApiResource { - private final PlatformSecurityContext context; - private final LoansApiResource loansApiResource; - private final LoanTransactionsApiResource loanTransactionsApiResource; - private final LoanChargesApiResource loanChargesApiResource; - private final AppuserLoansMapperReadService appuserLoansMapperReadService; - private final AppuserClientMapperReadService appUserClientMapperReadService; - private final SelfLoansDataValidator dataValidator; - private final GuarantorsApiResource guarantorsApiResource; + private final PlatformSecurityContext context; + private final LoansApiResource loansApiResource; + private final LoanTransactionsApiResource loanTransactionsApiResource; + private final LoanChargesApiResource loanChargesApiResource; + private final AppuserLoansMapperReadService appuserLoansMapperReadService; + private final AppuserClientMapperReadService appUserClientMapperReadService; + private final SelfLoansDataValidator dataValidator; + private final GuarantorsApiResource guarantorsApiResource; - @Autowired - 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) { - this.context = context; - this.loansApiResource = loansApiResource; - this.loanTransactionsApiResource = loanTransactionsApiResource; - this.loanChargesApiResource = loanChargesApiResource; - this.appuserLoansMapperReadService = appuserLoansMapperReadService; - this.appUserClientMapperReadService = appUserClientMapperReadService; - this.dataValidator = dataValidator; - this.guarantorsApiResource = guarantorsApiResource; - } + @Autowired + 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) { + this.context = context; + this.loansApiResource = loansApiResource; + this.loanTransactionsApiResource = loanTransactionsApiResource; + this.loanChargesApiResource = loanChargesApiResource; + this.appuserLoansMapperReadService = appuserLoansMapperReadService; + this.appUserClientMapperReadService = appUserClientMapperReadService; + this.dataValidator = dataValidator; + this.guarantorsApiResource = guarantorsApiResource; + } - @GET - @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) { + @GET + @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) { - this.dataValidator.validateRetrieveLoan(uriInfo); + this.dataValidator.validateRetrieveLoan(uriInfo); - validateAppuserLoanMapping(loanId); + validateAppuserLoanMapping(loanId); - final boolean staffInSelectedOfficeOnly = false; - return this.loansApiResource.retrieveLoan(loanId, - staffInSelectedOfficeOnly, uriInfo); - } + final boolean staffInSelectedOfficeOnly = false; + 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)}) - public String retrieveTransaction(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, - @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, - @Context final UriInfo 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)}) + public String retrieveTransaction(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, + @Context final UriInfo uriInfo) { - this.dataValidator.validateRetrieveTransaction(uriInfo); + this.dataValidator.validateRetrieveTransaction(uriInfo); - validateAppuserLoanMapping(loanId); + 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, - @Context final UriInfo 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, + @Context final UriInfo uriInfo) { - validateAppuserLoanMapping(loanId); + 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)}) - public String retrieveLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, - @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, - @Context final UriInfo 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)}) + public String retrieveLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, + @Context final UriInfo uriInfo) { - validateAppuserLoanMapping(loanId); + validateAppuserLoanMapping(loanId); - return this.loanChargesApiResource.retrieveLoanCharge(loanId, loanChargeId, uriInfo); - } + return this.loanChargesApiResource.retrieveLoanCharge(loanId, loanChargeId, uriInfo); + } @GET @Path("template") @@ -154,27 +154,27 @@ public class SelfLoansApiResource { @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) { - - if(clientId != null){ - validateAppuserClientsMapping(clientId); - } - + @QueryParam("productId") @ApiParam(value = "productId") final Long productId, + @QueryParam("templateType") @ApiParam(value = "templateType") final String templateType, + @Context final UriInfo uriInfo) { + + 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"))){ + || 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); + final Long groupId = null; + final boolean staffInSelectedOfficeOnly = false; + final boolean onlyActive = true; + return this.loansApiResource.template(clientId, groupId, productId, + templateType, staffInSelectedOfficeOnly, onlyActive, uriInfo); } @@ -186,80 +186,80 @@ public class SelfLoansApiResource { @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); + + 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 @Path("{loanId}") @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)}) + @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) { - HashMap attr = this.dataValidator.validateModifyLoanApplication(apiRequestBodyAsJson); + HashMap attr = this.dataValidator.validateModifyLoanApplication(apiRequestBodyAsJson); validateAppuserLoanMapping(loanId); final Long clientId = (Long) attr.get("clientId"); if(clientId != null){ validateAppuserClientsMapping(clientId); } - return this.loansApiResource.modifyLoanApplication(loanId, apiRequestBodyAsJson); + return this.loansApiResource.modifyLoanApplication(loanId, apiRequestBodyAsJson); } @POST @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)}) + @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); - } - validateAppuserLoanMapping(loanId); - return this.loansApiResource.stateTransitions(loanId, commandParam, apiRequestBodyAsJson); + 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); - } - } + AppUser user = this.context.authenticatedUser(); + 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); - } - } + 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 boolean is(final String commandParam, final String commandValue) { return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); } - @GET - @Path("{loanId}/guarantors") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveGuarantorDetails(@PathParam("loanId") final Long loanId, @Context final UriInfo uriInfo) { + @GET + @Path("{loanId}/guarantors") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveGuarantorDetails(@PathParam("loanId") final Long loanId, @Context final UriInfo uriInfo) { - validateAppuserLoanMapping(loanId); - return this.guarantorsApiResource.retrieveGuarantorDetails(uriInfo, loanId); - } + validateAppuserLoanMapping(loanId); + return this.guarantorsApiResource.retrieveGuarantorDetails(uriInfo, loanId); + } } 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 2e3e6dba0..ed4ff7cfc 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 @@ -42,48 +42,48 @@ import com.google.gson.JsonElement; @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; - } - - public void validateRetrieveLoan(final UriInfo uriInfo) { - List unsupportedParams = new ArrayList<>(); + private static final Set allowedAssociationParameters = new HashSet<>( + Arrays.asList("repaymentSchedule", "futureSchedule", + "originalSchedule", "transactions", "charges", + "guarantors", "collateral", "linkedAccount", + "multiDisburseDetails")); + private final FromJsonHelper fromApiJsonHelper; - Set associationParameters = ApiParameterHelper - .extractAssociationsForResponseIfProvided(uriInfo - .getQueryParameters()); - if (!associationParameters.isEmpty()) { - associationParameters.removeAll(allowedAssociationParameters); - if (!associationParameters.isEmpty()) { - unsupportedParams.addAll(associationParameters); - } - } + @Autowired + public SelfLoansDataValidator(final FromJsonHelper fromApiJsonHelper){ + this.fromApiJsonHelper = fromApiJsonHelper; + } - if (uriInfo.getQueryParameters().getFirst("exclude") != null) { - unsupportedParams.add("exclude"); - } + public void validateRetrieveLoan(final UriInfo uriInfo) { + List unsupportedParams = new ArrayList<>(); - throwExceptionIfReqd(unsupportedParams); - } + Set associationParameters = ApiParameterHelper + .extractAssociationsForResponseIfProvided(uriInfo + .getQueryParameters()); + if (!associationParameters.isEmpty()) { + associationParameters.removeAll(allowedAssociationParameters); + if (!associationParameters.isEmpty()) { + unsupportedParams.addAll(associationParameters); + } + } - public void validateRetrieveTransaction(UriInfo uriInfo) { - List unsupportedParams = new ArrayList<>(); + if (uriInfo.getQueryParameters().getFirst("exclude") != null) { + unsupportedParams.add("exclude"); + } - validateTemplate(uriInfo, unsupportedParams); + throwExceptionIfReqd(unsupportedParams); + } - throwExceptionIfReqd(unsupportedParams); + public void validateRetrieveTransaction(UriInfo uriInfo) { + List unsupportedParams = new ArrayList<>(); - } - - public HashMap validateLoanApplication(final String json){ + validateTemplate(uriInfo, unsupportedParams); + + throwExceptionIfReqd(unsupportedParams); + + } + + public HashMap validateLoanApplication(final String json){ if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final List dataValidationErrors = new ArrayList<>(); @@ -100,14 +100,14 @@ public class SelfLoansDataValidator { baseDataValidator.reset().parameter(clientIdParameterName).value(clientId).notNull().longGreaterThanZero(); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - + HashMap retAttr = new HashMap<>(); retAttr.put("clientId", Long.parseLong(clientId)); - - return retAttr; - } - public HashMap validateModifyLoanApplication(final String json) { + return retAttr; + } + + public HashMap validateModifyLoanApplication(final String json) { final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan"); @@ -127,27 +127,27 @@ public class SelfLoansDataValidator { } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - + HashMap retAttr = new HashMap<>(); 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/AppuserLoansMapperReadService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/service/AppuserLoansMapperReadService.java index eb94f734c..0b28723fb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/service/AppuserLoansMapperReadService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/service/AppuserLoansMapperReadService.java @@ -20,5 +20,5 @@ package org.apache.fineract.portfolio.self.loanaccount.service; public interface AppuserLoansMapperReadService { - public Boolean isLoanMappedToUser(Long loanId, Long appUserId); + public Boolean isLoanMappedToUser(Long loanId, Long appUserId); } 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 ec3ec6304..60cb4a591 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 @@ -25,24 +25,24 @@ import org.springframework.stereotype.Service; @Service public class AppuserLoansMapperReadServiceImpl implements - AppuserLoansMapperReadService { + AppuserLoansMapperReadService { - private final JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; - @Autowired - public AppuserLoansMapperReadServiceImpl(final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + public AppuserLoansMapperReadServiceImpl(final RoutingDataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } - @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); - } + @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); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiConstants.java index 11df8cc21..58ab2dff4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiConstants.java @@ -21,29 +21,29 @@ package org.apache.fineract.portfolio.self.pockets.api; public interface PocketApiConstants { - String pocketsResourceName = "pockets"; - String linkAccountsToPocketCommandParam = "linkAccounts"; - String delinkAccountsFromPocketCommandParam = "delinkAccounts"; + String pocketsResourceName = "pockets"; + String linkAccountsToPocketCommandParam = "linkAccounts"; + String delinkAccountsFromPocketCommandParam = "delinkAccounts"; - String linkAccountsActionName = "LINK_ACCOUNT_TO"; - String pocketEntityName = "POCKET"; - String delinkAccountsActionName = "DELINK_ACCOUNT_FROM"; + String linkAccountsActionName = "LINK_ACCOUNT_TO"; + String pocketEntityName = "POCKET"; + String delinkAccountsActionName = "DELINK_ACCOUNT_FROM"; - String accountIdParamName = "accountId"; - String accountTypeParamName = "accountType"; - String accountsDetail = "accountsDetail"; - String pocketAccountMappingList = "pocketAccountMappingIds"; - String pocketAccountMappingId = "pocketAccountMappingId"; + String accountIdParamName = "accountId"; + String accountTypeParamName = "accountType"; + String accountsDetail = "accountsDetail"; + String pocketAccountMappingList = "pocketAccountMappingIds"; + String pocketAccountMappingId = "pocketAccountMappingId"; - String dataValidationMessage = "validation.msg.validation.errors.exist"; - String validationErrorMessage = "Validation errors exist."; - String pocketNotFoundException = "error.msg.pocket.not.found"; - String pocketNotFoundErrorMessage = "Pocket not found."; - String mappingIdNotLinkedToPocketException = "mapping.id.not.linked.to.pocket.exception"; - String mappingIdNotLinkedToPocketErrorMessage = "Mapping Id is not linked to Pocket."; - String uniqueConstraintName = "m_pocket_account_unique_mapping"; - String duplicateMappingException = "error.msg.one.or.more.accounts.are.already.mapped.to.pocket."; - String duplicateMappingExceptionMessage = "One or more accounts are already mapped to pocket."; - String unknownDataIntegrityException = "error.msg.unknown.data.integrity.issue"; - String unknownDataIntegrityExceptionMessage = "Unknown data integrity issue with resource."; + String dataValidationMessage = "validation.msg.validation.errors.exist"; + String validationErrorMessage = "Validation errors exist."; + String pocketNotFoundException = "error.msg.pocket.not.found"; + String pocketNotFoundErrorMessage = "Pocket not found."; + String mappingIdNotLinkedToPocketException = "mapping.id.not.linked.to.pocket.exception"; + String mappingIdNotLinkedToPocketErrorMessage = "Mapping Id is not linked to Pocket."; + String uniqueConstraintName = "m_pocket_account_unique_mapping"; + String duplicateMappingException = "error.msg.one.or.more.accounts.are.already.mapped.to.pocket."; + String duplicateMappingExceptionMessage = "One or more accounts are already mapped to pocket."; + String unknownDataIntegrityException = "error.msg.unknown.data.integrity.issue"; + String unknownDataIntegrityExceptionMessage = "Unknown data integrity issue with resource."; } 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 2952e182a..37c1f03dd 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 @@ -47,62 +47,62 @@ import io.swagger.annotations.*; @Scope("singleton") @Api(tags = {"Pocket"}) @SwaggerDefinition(tags = { - @Tag(name = "Pocket", description = "") + @Tag(name = "Pocket", description = "") }) public class PocketApiResource { - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - @SuppressWarnings("rawtypes") - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService; + 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; - } + @SuppressWarnings("rawtypes") + @Autowired + public PocketApiResource(PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService) { + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.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) { + @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) { - final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); + final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); - CommandProcessingResult result = null; + CommandProcessingResult result = null; - 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); - } + 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); + } - if (result == null) { - throw new UnrecognizedQueryParamException("command", commandParam); - } + if (result == null) { + throw new UnrecognizedQueryParamException("command", commandParam); + } - return this.toApiJsonSerializer.serialize(result); - } + return this.toApiJsonSerializer.serialize(result); + } - @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()); - } + @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); - } + 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/data/PocketAccountMappingData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/data/PocketAccountMappingData.java index 34b984f63..8607f76ab 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 @@ -26,20 +26,20 @@ import org.apache.fineract.portfolio.self.pockets.domain.PocketAccountMapping; @SuppressWarnings("unused") public class PocketAccountMappingData { - private final Collection loanAccounts; - private final Collection savingsAccounts; - private final Collection shareAccounts; + private final Collection loanAccounts; + private final Collection savingsAccounts; + private final Collection shareAccounts; - private PocketAccountMappingData(final Collection loanAccounts, Collection savingsAccounts, final Collection shareAccounts ) { - this.loanAccounts = loanAccounts; - this.savingsAccounts = savingsAccounts; - this.shareAccounts = 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); + 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 29d762420..9b68e3604 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 @@ -44,97 +44,97 @@ import com.google.gson.reflect.TypeToken; @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)); + private final Set delinkingAccountsSupportedParameters = new HashSet<>( + Arrays.asList(PocketApiConstants.pocketAccountMappingList)); - private final FromJsonHelper fromApiJsonHelper; + private final FromJsonHelper fromApiJsonHelper; - @Autowired - public PocketDataValidator(FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } + @Autowired + public PocketDataValidator(FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } - public void validateForLinkingAccounts(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public void validateForLinkingAccounts(final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } - final Type typeOfMap = new TypeToken>() { - }.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.linkingAccountsSupportedParameters); + final Type typeOfMap = new TypeToken>() { + }.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.linkingAccountsSupportedParameters); - final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(PocketApiConstants.pocketsResourceName); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(PocketApiConstants.pocketsResourceName); - final JsonElement element = this.fromApiJsonHelper.parse(json); + 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()); + final List valueList = Arrays.asList(EntityAccountType.LOAN.name().toLowerCase(), + EntityAccountType.SAVINGS.name().toLowerCase(), EntityAccountType.SHARES.name().toLowerCase()); - for (JsonElement accountDetails : accountsDetail) { + for (JsonElement accountDetails : accountsDetail) { - final Long accountId = this.fromApiJsonHelper.extractLongNamed(PocketApiConstants.accountIdParamName, - accountDetails); - baseDataValidator.reset().parameter(PocketApiConstants.accountIdParamName).value(accountId).notBlank(); + 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); - baseDataValidator.reset().parameter(PocketApiConstants.accountTypeParamName).value(accountType).notBlank() - .isOneOfTheseStringValues(valueList); + final String accountType = this.fromApiJsonHelper + .extractStringNamed(PocketApiConstants.accountTypeParamName, accountDetails); + baseDataValidator.reset().parameter(PocketApiConstants.accountTypeParamName).value(accountType).notBlank() + .isOneOfTheseStringValues(valueList); - } + } - throwExceptionIfValidationWarningsExist(dataValidationErrors); + throwExceptionIfValidationWarningsExist(dataValidationErrors); - } + } - public void validateForDeLinkingAccounts(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public void validateForDeLinkingAccounts(final String json) { + 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) - .resource(PocketApiConstants.pocketsResourceName); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(PocketApiConstants.pocketsResourceName); - final JsonElement element = this.fromApiJsonHelper.parse(json); + 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) { + for (JsonElement pocketAccountMapping : pocketAccountMappingList) { - final Long mappingId = pocketAccountMapping.getAsLong(); - baseDataValidator.reset().parameter(PocketApiConstants.pocketAccountMappingId).value(mappingId).notBlank(); + final Long mappingId = pocketAccountMapping.getAsLong(); + baseDataValidator.reset().parameter(PocketApiConstants.pocketAccountMappingId).value(mappingId).notBlank(); - } + } - throwExceptionIfValidationWarningsExist(dataValidationErrors); + throwExceptionIfValidationWarningsExist(dataValidationErrors); - } + } - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(PocketApiConstants.dataValidationMessage, - PocketApiConstants.validationErrorMessage, dataValidationErrors); - } - } + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException(PocketApiConstants.dataValidationMessage, + PocketApiConstants.validationErrorMessage, dataValidationErrors); + } + } } 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 fe52535d9..45daa2c27 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 @@ -29,31 +29,31 @@ 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") }) + @UniqueConstraint(columnNames = { "app_user_id" }, name = "unique_app_user") }) public class Pocket extends AbstractPersistableCustom { - @Column(name = "app_user_id", length = 20, nullable = false) - private Long appUserId; + @Column(name = "app_user_id", length = 20, nullable = false) + private Long appUserId; - public Long getAppUserId() { - return appUserId; - } + public Long getAppUserId() { + return appUserId; + } - public void setAppUserId(Long appUserId) { - this.appUserId = appUserId; - } + public void setAppUserId(Long appUserId) { + this.appUserId = appUserId; + } - protected Pocket() { - } + protected Pocket() { + } - private Pocket(final Long appUserId) { - this.appUserId = appUserId; + private Pocket(final Long appUserId) { + this.appUserId = appUserId; - } + } - public static Pocket instance(final Long appUserId) { - return new Pocket(appUserId); + public static Pocket instance(final Long appUserId) { + return new Pocket(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 4ee65b9eb..502e5f162 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 @@ -30,57 +30,57 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_pocket_accounts_mapping") public class PocketAccountMapping extends AbstractPersistableCustom { - @Column(name = "pocket_id", length = 20, nullable = false) - private Long pocketId; + @Column(name = "pocket_id", length = 20, nullable = false) + private Long pocketId; - @Column(name = "account_id", length = 20, nullable = false) - private Long accountId; + @Column(name = "account_id", length = 20, nullable = false) + private Long accountId; - @Column(name = "account_type", nullable = false) - private Integer accountType; + @Column(name = "account_type", nullable = false) + private Integer accountType; - @Column(name = "account_number", nullable = false) - private String accountNumber; + @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) { - this.pocketId = pocketId; - this.accountId = accountId; - this.accountType = accountType; - this.accountNumber = accountNumber; - } + private PocketAccountMapping(final Long pocketId, final Long accountId, final Integer accountType, + final String accountNumber) { + this.pocketId = pocketId; + this.accountId = accountId; + this.accountType = accountType; + this.accountNumber = accountNumber; + } - public static PocketAccountMapping instance(final Long pocketId, final Long accountId, final Integer accountType, - final String accountNumber) { - return new PocketAccountMapping(pocketId, accountId, accountType, accountNumber); + public static PocketAccountMapping instance(final Long pocketId, final Long accountId, final Integer accountType, + final String accountNumber) { + return new PocketAccountMapping(pocketId, accountId, accountType, accountNumber); - } + } - public Long getPocketId() { - return pocketId; - } + public Long getPocketId() { + return pocketId; + } - public void setPocketId(Long pocketId) { - this.pocketId = pocketId; - } + public void setPocketId(Long pocketId) { + this.pocketId = pocketId; + } - public Long getAccountId() { - return accountId; - } + public Long getAccountId() { + return accountId; + } - public void setAccountId(Long accountId) { - this.accountId = accountId; - } + public void setAccountId(Long accountId) { + this.accountId = accountId; + } - public Integer getAccountType() { - return accountType; - } + public Integer getAccountType() { + return accountType; + } - public void setAccountType(Integer accountType) { - this.accountType = accountType; - } + public void setAccountType(Integer accountType) { + this.accountType = accountType; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMappingRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMappingRepository.java index bf58742c0..5c8c1a62a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMappingRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMappingRepository.java @@ -27,12 +27,12 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface PocketAccountMappingRepository - extends JpaRepository, JpaSpecificationExecutor { + extends JpaRepository, JpaSpecificationExecutor { - @Query("select pam from PocketAccountMapping pam where pam.id = :id and pam.pocketId =:pocketId") - PocketAccountMapping findByIdAndPocketId(@Param("id") Long id, @Param("pocketId") Long pocketId); + @Query("select pam from PocketAccountMapping pam where pam.id = :id and pam.pocketId =:pocketId") + PocketAccountMapping findByIdAndPocketId(@Param("id") Long id, @Param("pocketId") Long pocketId); - @Query("select pam from PocketAccountMapping pam where pam.pocketId =:pocketId") - Collection findByPocketId(@Param("pocketId") Long pocketId); + @Query("select pam from PocketAccountMapping pam where pam.pocketId =:pocketId") + Collection findByPocketId(@Param("pocketId") Long pocketId); } 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 3fcf8bca0..25318e0db 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 @@ -29,38 +29,38 @@ import org.springframework.stereotype.Service; @Service public class PocketAccountMappingRepositoryWrapper { - private final PocketAccountMappingRepository pocketAccountMappingRepository; + private final PocketAccountMappingRepository pocketAccountMappingRepository; - @Autowired - public PocketAccountMappingRepositoryWrapper(final PocketAccountMappingRepository pocketAccountMappingRepository) { - this.pocketAccountMappingRepository = pocketAccountMappingRepository; - } + @Autowired + public PocketAccountMappingRepositoryWrapper(final PocketAccountMappingRepository pocketAccountMappingRepository) { + this.pocketAccountMappingRepository = pocketAccountMappingRepository; + } - public void save(final PocketAccountMapping pocketAccountMapping) { - this.pocketAccountMappingRepository.save(pocketAccountMapping); - } + public void save(final PocketAccountMapping pocketAccountMapping) { + this.pocketAccountMappingRepository.save(pocketAccountMapping); + } - public List save(final List pocketAccountsList) { - return this.pocketAccountMappingRepository.saveAll(pocketAccountsList); - } + public List save(final List pocketAccountsList) { + return this.pocketAccountMappingRepository.saveAll(pocketAccountsList); + } - public void delete(final List pocketAccountsList) { - this.pocketAccountMappingRepository.deleteAll(pocketAccountsList); - } + public void delete(final List pocketAccountsList) { + this.pocketAccountMappingRepository.deleteAll(pocketAccountsList); + } - public PocketAccountMapping findByIdAndPocketIdWithNotFoundException(final Long id, final Long pocketId) { - PocketAccountMapping pocketAccountMapping = this.pocketAccountMappingRepository.findByIdAndPocketId(id, - pocketId); - if (pocketAccountMapping == null) { - throw new MappingIdNotLinkedToPocketException(id); - } - return pocketAccountMapping; + public PocketAccountMapping findByIdAndPocketIdWithNotFoundException(final Long id, final Long pocketId) { + PocketAccountMapping pocketAccountMapping = this.pocketAccountMappingRepository.findByIdAndPocketId(id, + pocketId); + if (pocketAccountMapping == null) { + throw new MappingIdNotLinkedToPocketException(id); + } + return pocketAccountMapping; - } + } - public Collection findByPocketId(final Long pocketId) { - return this.pocketAccountMappingRepository.findByPocketId(pocketId); + public Collection findByPocketId(final Long pocketId) { + return this.pocketAccountMappingRepository.findByPocketId(pocketId); - } + } } 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 7987a2e75..ea031d458 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 @@ -25,8 +25,8 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface PocketRepository extends JpaRepository , JpaSpecificationExecutor{ - - @Query("select pocket.id from Pocket pocket where pocket.appUserId= :appUserId") - Long findByAppUserId(@Param("appUserId") Long appUserId); + + @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 a72b2fde1..90f0a415d 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,27 +25,27 @@ import org.springframework.stereotype.Service; @Service public class PocketRepositoryWrapper { - private final PocketRepository pocketRepository; + private final PocketRepository pocketRepository; - @Autowired - public PocketRepositoryWrapper(final PocketRepository pocketRepository) { - this.pocketRepository = pocketRepository; - } + @Autowired + public PocketRepositoryWrapper(final PocketRepository pocketRepository) { + this.pocketRepository = pocketRepository; + } - public void saveAndFlush(final Pocket pocket) { - this.pocketRepository.saveAndFlush(pocket); - } + public void saveAndFlush(final Pocket pocket) { + this.pocketRepository.saveAndFlush(pocket); + } - public Long findByAppUserId(final Long appUserId) { - return this.pocketRepository.findByAppUserId(appUserId); - } + public Long findByAppUserId(final Long appUserId) { + return this.pocketRepository.findByAppUserId(appUserId); + } - public Long findByAppUserIdWithNotFoundDetection(final Long appUserId) { - final Long pocketId = this.pocketRepository.findByAppUserId(appUserId); - if (pocketId == null) { - throw new PocketNotFoundException(); - } - return pocketId; - } + public Long findByAppUserIdWithNotFoundDetection(final Long appUserId) { + final Long pocketId = this.pocketRepository.findByAppUserId(appUserId); + 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 4a3316231..35a892658 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 @@ -24,8 +24,8 @@ import org.apache.fineract.portfolio.self.pockets.api.PocketApiConstants; @SuppressWarnings("serial") public class MappingIdNotLinkedToPocketException extends AbstractPlatformDomainRuleException { - public MappingIdNotLinkedToPocketException(final Long id) { - super(PocketApiConstants.mappingIdNotLinkedToPocketException, - PocketApiConstants.mappingIdNotLinkedToPocketErrorMessage, id); - } + public MappingIdNotLinkedToPocketException(final Long 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/exception/PocketNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/exception/PocketNotFoundException.java index 7ae00b414..34b3f9a80 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/exception/PocketNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/exception/PocketNotFoundException.java @@ -25,8 +25,8 @@ import org.apache.fineract.portfolio.self.pockets.api.PocketApiConstants; @SuppressWarnings("serial") public class PocketNotFoundException extends AbstractPlatformDomainRuleException { - public PocketNotFoundException() { - super(PocketApiConstants.pocketNotFoundException, PocketApiConstants.pocketNotFoundErrorMessage); - } + public PocketNotFoundException() { + super(PocketApiConstants.pocketNotFoundException, PocketApiConstants.pocketNotFoundErrorMessage); + } } 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 51d769021..56f510696 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,17 +32,17 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = PocketApiConstants.pocketEntityName, action = PocketApiConstants.delinkAccountsActionName) public class DelinkAccountsFromPocketCommandHandler implements NewCommandSourceHandler { - private final PocketWritePlatformService pocketWritePlatformService; + private final PocketWritePlatformService pocketWritePlatformService; - @Autowired - public DelinkAccountsFromPocketCommandHandler(final PocketWritePlatformService pocketWritePlatformService) { - this.pocketWritePlatformService = pocketWritePlatformService; - } + @Autowired + public DelinkAccountsFromPocketCommandHandler(final PocketWritePlatformService pocketWritePlatformService) { + this.pocketWritePlatformService = pocketWritePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.pocketWritePlatformService.delinkAccounts(command); - } + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.pocketWritePlatformService.delinkAccounts(command); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/handler/LinkAccountsToPocketCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/handler/LinkAccountsToPocketCommandHandler.java index 98ef91b41..81ade40c8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/handler/LinkAccountsToPocketCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/handler/LinkAccountsToPocketCommandHandler.java @@ -33,18 +33,18 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = PocketApiConstants.pocketEntityName, action = PocketApiConstants.linkAccountsActionName) public class LinkAccountsToPocketCommandHandler implements NewCommandSourceHandler { - private final PocketWritePlatformService pocketWritePlatformService; + private final PocketWritePlatformService pocketWritePlatformService; - @Autowired - public LinkAccountsToPocketCommandHandler(final PocketWritePlatformService pocketWritePlatformService) { - this.pocketWritePlatformService = pocketWritePlatformService; - } + @Autowired + public LinkAccountsToPocketCommandHandler(final PocketWritePlatformService pocketWritePlatformService) { + this.pocketWritePlatformService = pocketWritePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.pocketWritePlatformService.linkAccounts(command); - } + return this.pocketWritePlatformService.linkAccounts(command); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityService.java index 18dd1b4f1..b0684abae 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityService.java @@ -21,9 +21,9 @@ package org.apache.fineract.portfolio.self.pockets.service; public interface AccountEntityService { - String getKey(); + String getKey(); - void validateSelfUserAccountMapping(Long accountId); + void validateSelfUserAccountMapping(Long accountId); - String retrieveAccountNumberByAccountId(Long accountId); + String retrieveAccountNumberByAccountId(Long accountId); } 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 5edb17a98..674c6ba5e 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 @@ -31,18 +31,18 @@ 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); - } - } + @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); - } - - + 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 c4408167c..116c159db 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 @@ -30,38 +30,38 @@ import org.springframework.stereotype.Service; @Service public class AccountEntityServiceForLoanImpl implements AccountEntityService { - private final String KEY = EntityAccountType.LOAN.name(); + private final String KEY = EntityAccountType.LOAN.name(); - private final PlatformSecurityContext context; - private final AppuserLoansMapperReadService appuserLoansMapperReadService; - private final LoanReadPlatformService loanReadPlatformService; + private final PlatformSecurityContext context; + private final AppuserLoansMapperReadService appuserLoansMapperReadService; + private final LoanReadPlatformService loanReadPlatformService; - @Autowired - public AccountEntityServiceForLoanImpl(final PlatformSecurityContext context, - final AppuserLoansMapperReadService appuserLoansMapperReadService, - final LoanReadPlatformService loanReadPlatformService) { + @Autowired + public AccountEntityServiceForLoanImpl(final PlatformSecurityContext context, + final AppuserLoansMapperReadService appuserLoansMapperReadService, + final LoanReadPlatformService loanReadPlatformService) { - this.context = context; - this.appuserLoansMapperReadService = appuserLoansMapperReadService; - this.loanReadPlatformService = loanReadPlatformService; + this.context = context; + this.appuserLoansMapperReadService = appuserLoansMapperReadService; + this.loanReadPlatformService = loanReadPlatformService; - } + } - @Override - public String getKey() { - return KEY; - } + @Override + public String getKey() { + return KEY; + } - @Override - public void validateSelfUserAccountMapping(Long accountId) { - if (!this.appuserLoansMapperReadService.isLoanMappedToUser(accountId, - this.context.authenticatedUser().getId())) { - throw new LoanNotFoundException(accountId); - } - } + @Override + public void validateSelfUserAccountMapping(Long accountId) { + if (!this.appuserLoansMapperReadService.isLoanMappedToUser(accountId, + this.context.authenticatedUser().getId())) { + throw new LoanNotFoundException(accountId); + } + } - @Override - public String retrieveAccountNumberByAccountId(Long accountId) { - return this.loanReadPlatformService.retrieveAccountNumberByAccountId(accountId); - } + @Override + public String retrieveAccountNumberByAccountId(Long accountId) { + return this.loanReadPlatformService.retrieveAccountNumberByAccountId(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 5afbf3abe..2abefeb01 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 @@ -30,41 +30,41 @@ import org.springframework.stereotype.Service; @Service public class AccountEntityServiceForSavingsImpl implements AccountEntityService { - private final String KEY = EntityAccountType.SAVINGS.name(); + private final String KEY = EntityAccountType.SAVINGS.name(); - private final PlatformSecurityContext context; - private final AppuserSavingsMapperReadService appuserSavingsMapperReadService; - private final SavingsAccountReadPlatformService savingsAccountReadPlatformService; + private final PlatformSecurityContext context; + private final AppuserSavingsMapperReadService appuserSavingsMapperReadService; + private final SavingsAccountReadPlatformService savingsAccountReadPlatformService; - @Autowired - public AccountEntityServiceForSavingsImpl(final PlatformSecurityContext context, - final AppuserSavingsMapperReadService appuserSavingsMapperReadService, - final SavingsAccountReadPlatformService savingsAccountReadPlatformService) { + @Autowired + public AccountEntityServiceForSavingsImpl(final PlatformSecurityContext context, + final AppuserSavingsMapperReadService appuserSavingsMapperReadService, + final SavingsAccountReadPlatformService savingsAccountReadPlatformService) { - this.context = context; - this.appuserSavingsMapperReadService = appuserSavingsMapperReadService; - this.savingsAccountReadPlatformService = savingsAccountReadPlatformService; + this.context = context; + this.appuserSavingsMapperReadService = appuserSavingsMapperReadService; + this.savingsAccountReadPlatformService = savingsAccountReadPlatformService; - } + } - @Override - public String getKey() { - return KEY; - } + @Override + public String getKey() { + return KEY; + } - @Override - public void validateSelfUserAccountMapping(Long accountId) { + @Override + public void validateSelfUserAccountMapping(Long accountId) { - if (!this.appuserSavingsMapperReadService.isSavingsMappedToUser(accountId, - this.context.getAuthenticatedUserIfPresent().getId())) { - throw new SavingsAccountNotFoundException(accountId); + if (!this.appuserSavingsMapperReadService.isSavingsMappedToUser(accountId, + this.context.getAuthenticatedUserIfPresent().getId())) { + throw new SavingsAccountNotFoundException(accountId); - } - } + } + } - @Override - public String retrieveAccountNumberByAccountId(Long accountId) { - return this.savingsAccountReadPlatformService.retrieveAccountNumberByAccountId(accountId); - } + @Override + public String retrieveAccountNumberByAccountId(Long accountId) { + return this.savingsAccountReadPlatformService.retrieveAccountNumberByAccountId(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 6f0112e96..a73cb8f1b 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 @@ -31,39 +31,39 @@ import org.springframework.stereotype.Service; @Service public class AccountEntityServiceForShareAccountsImpl implements AccountEntityService { - private final String KEY = EntityAccountType.SHARES.name(); + private final String KEY = EntityAccountType.SHARES.name(); - private final PlatformSecurityContext context; - private final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService; - private final ShareAccountReadPlatformService shareAccountReadPlatformService; + private final PlatformSecurityContext context; + private final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService; + private final ShareAccountReadPlatformService shareAccountReadPlatformService; - @Autowired - public AccountEntityServiceForShareAccountsImpl(final PlatformSecurityContext context, - final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService, - final ShareAccountReadPlatformService shareAccountReadPlatformService) { - this.context = context; - this.appUserShareAccountsMapperReadPlatformService = appUserShareAccountsMapperReadPlatformService; - this.shareAccountReadPlatformService = shareAccountReadPlatformService; - } + @Autowired + public AccountEntityServiceForShareAccountsImpl(final PlatformSecurityContext context, + final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService, + final ShareAccountReadPlatformService shareAccountReadPlatformService) { + this.context = context; + this.appUserShareAccountsMapperReadPlatformService = appUserShareAccountsMapperReadPlatformService; + this.shareAccountReadPlatformService = shareAccountReadPlatformService; + } - @Override - public String getKey() { - return KEY; - } + @Override + public String getKey() { + return KEY; + } - @Override - public void validateSelfUserAccountMapping(Long accountId) { - if (!this.appUserShareAccountsMapperReadPlatformService.isShareAccountsMappedToUser(accountId, - this.context.getAuthenticatedUserIfPresent().getId())) { - throw new ShareAccountNotFoundException(accountId); + @Override + public void validateSelfUserAccountMapping(Long accountId) { + if (!this.appUserShareAccountsMapperReadPlatformService.isShareAccountsMappedToUser(accountId, + this.context.getAuthenticatedUserIfPresent().getId())) { + throw new ShareAccountNotFoundException(accountId); - } - } + } + } - @Override - public String retrieveAccountNumberByAccountId(Long accountId) { - return this.shareAccountReadPlatformService.retrieveAccountNumberByAccountId(accountId); - } + @Override + public String retrieveAccountNumberByAccountId(Long accountId) { + return this.shareAccountReadPlatformService.retrieveAccountNumberByAccountId(accountId); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketAccountMappingReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketAccountMappingReadPlatformService.java index 7b496aae7..dc3c2b949 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketAccountMappingReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketAccountMappingReadPlatformService.java @@ -22,8 +22,8 @@ import org.apache.fineract.portfolio.self.pockets.data.PocketAccountMappingData; public interface PocketAccountMappingReadPlatformService { - PocketAccountMappingData retrieveAll(); + PocketAccountMappingData retrieveAll(); - boolean validatePocketAndAccountMapping(Long pocketId, Long accountId, Integer accountType); + boolean validatePocketAndAccountMapping(Long pocketId, Long accountId, Integer accountType); } 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 b293a29b5..e51d8a253 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 @@ -36,56 +36,56 @@ import org.springframework.stereotype.Service; @Service public class PocketAccountMappingReadPlatformServiceImpl implements PocketAccountMappingReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; - private final PocketRepositoryWrapper pocketRepositoryWrapper; - private final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; + private final PocketRepositoryWrapper pocketRepositoryWrapper; + private final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper; - @Autowired - public PocketAccountMappingReadPlatformServiceImpl(final RoutingDataSource dataSource, - final PlatformSecurityContext context, final PocketRepositoryWrapper pocketRepositoryWrapper, - final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.context = context; - this.pocketRepositoryWrapper = pocketRepositoryWrapper; - this.pocketAccountMappingRepositoryWrapper = pocketAccountMappingRepositoryWrapper; - } + @Autowired + public PocketAccountMappingReadPlatformServiceImpl(final RoutingDataSource dataSource, + final PlatformSecurityContext context, final PocketRepositoryWrapper pocketRepositoryWrapper, + final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.context = context; + this.pocketRepositoryWrapper = pocketRepositoryWrapper; + this.pocketAccountMappingRepositoryWrapper = pocketAccountMappingRepositoryWrapper; + } - @Override - public PocketAccountMappingData retrieveAll() { - final Long pocketId = this.pocketRepositoryWrapper.findByAppUserId(this.context.authenticatedUser().getId()); - if (pocketId != null) { - Collection pocketAccountMappingList = this.pocketAccountMappingRepositoryWrapper - .findByPocketId(pocketId); - if (pocketAccountMappingList != null && !pocketAccountMappingList.isEmpty()) { - Collection loanAccounts = new ArrayList<>(); - Collection savingsAccounts = new ArrayList<>(); - Collection shareAccounts = new ArrayList<>(); - for (PocketAccountMapping pocketMapping : pocketAccountMappingList) { + @Override + public PocketAccountMappingData retrieveAll() { + final Long pocketId = this.pocketRepositoryWrapper.findByAppUserId(this.context.authenticatedUser().getId()); + if (pocketId != null) { + Collection pocketAccountMappingList = this.pocketAccountMappingRepositoryWrapper + .findByPocketId(pocketId); + if (pocketAccountMappingList != null && !pocketAccountMappingList.isEmpty()) { + Collection loanAccounts = new ArrayList<>(); + Collection savingsAccounts = new ArrayList<>(); + Collection shareAccounts = new ArrayList<>(); + for (PocketAccountMapping pocketMapping : pocketAccountMappingList) { - if (pocketMapping.getAccountType().equals(EntityAccountType.LOAN.getValue())) { - loanAccounts.add(pocketMapping); - } else if (pocketMapping.getAccountType().equals(EntityAccountType.SAVINGS.getValue())) { - savingsAccounts.add(pocketMapping); - } else { - shareAccounts.add(pocketMapping); - } - } - return PocketAccountMappingData.instance(loanAccounts, savingsAccounts, shareAccounts); - } - } - return null; - } + if (pocketMapping.getAccountType().equals(EntityAccountType.LOAN.getValue())) { + loanAccounts.add(pocketMapping); + } else if (pocketMapping.getAccountType().equals(EntityAccountType.SAVINGS.getValue())) { + savingsAccounts.add(pocketMapping); + } else { + shareAccounts.add(pocketMapping); + } + } + return PocketAccountMappingData.instance(loanAccounts, savingsAccounts, shareAccounts); + } + } + return null; + } - @Override - 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); - } catch (EmptyResultDataAccessException e) { - return false; - } - } + @Override + 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); + } 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 9a6649ddd..63e61ec87 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 @@ -25,8 +25,8 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface PocketWritePlatformService { - CommandProcessingResult linkAccounts(JsonCommand command); + CommandProcessingResult linkAccounts(JsonCommand command); - CommandProcessingResult delinkAccounts(JsonCommand command); + CommandProcessingResult delinkAccounts(JsonCommand command); } 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 ecb8b397a..51f4701d7 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 @@ -45,94 +45,94 @@ import com.google.gson.JsonObject; @Service public class PocketWritePlatformServiceImpl implements PocketWritePlatformService { - private final PlatformSecurityContext context; - private final PocketDataValidator pocketDataValidator; - private final AccountEntityServiceFactory accountEntityServiceFactory; - private final PocketRepositoryWrapper pocketRepositoryWrapper; - private final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper; - private final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService; + private final PlatformSecurityContext context; + private final PocketDataValidator pocketDataValidator; + private final AccountEntityServiceFactory accountEntityServiceFactory; + private final PocketRepositoryWrapper pocketRepositoryWrapper; + private final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper; + private final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService; - @Autowired - public PocketWritePlatformServiceImpl(final PlatformSecurityContext context, - PocketDataValidator pocketDataValidator, final AccountEntityServiceFactory accountEntityServiceFactory, - final PocketRepositoryWrapper pocketRepositoryWrapper, - final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper, - final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService) { - this.context = context; - this.pocketDataValidator = pocketDataValidator; - this.accountEntityServiceFactory = accountEntityServiceFactory; - this.pocketRepositoryWrapper = pocketRepositoryWrapper; - this.pocketAccountMappingRepositoryWrapper = pocketAccountMappingRepositoryWrapper; - this.pocketAccountMappingReadPlatformService = pocketAccountMappingReadPlatformService; - } + @Autowired + public PocketWritePlatformServiceImpl(final PlatformSecurityContext context, + PocketDataValidator pocketDataValidator, final AccountEntityServiceFactory accountEntityServiceFactory, + final PocketRepositoryWrapper pocketRepositoryWrapper, + final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper, + final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService) { + this.context = context; + this.pocketDataValidator = pocketDataValidator; + this.accountEntityServiceFactory = accountEntityServiceFactory; + this.pocketRepositoryWrapper = pocketRepositoryWrapper; + this.pocketAccountMappingRepositoryWrapper = pocketAccountMappingRepositoryWrapper; + this.pocketAccountMappingReadPlatformService = pocketAccountMappingReadPlatformService; + } - @Transactional - @Override - public CommandProcessingResult linkAccounts(JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult linkAccounts(JsonCommand command) { - this.pocketDataValidator.validateForLinkingAccounts(command.json()); - JsonArray accountsDetail = command.arrayOfParameterNamed(PocketApiConstants.accountsDetail); + this.pocketDataValidator.validateForLinkingAccounts(command.json()); + JsonArray accountsDetail = command.arrayOfParameterNamed(PocketApiConstants.accountsDetail); - Long pocketId = this.pocketRepositoryWrapper.findByAppUserId(this.context.authenticatedUser().getId()); + Long pocketId = this.pocketRepositoryWrapper.findByAppUserId(this.context.authenticatedUser().getId()); - if (pocketId == null) { - final Pocket pocket = Pocket.instance(this.context.authenticatedUser().getId()); - this.pocketRepositoryWrapper.saveAndFlush(pocket); - pocketId = pocket.getId(); - } + if (pocketId == null) { + final Pocket pocket = Pocket.instance(this.context.authenticatedUser().getId()); + this.pocketRepositoryWrapper.saveAndFlush(pocket); + pocketId = pocket.getId(); + } - final List pocketAccounts = new ArrayList<>(); + final List pocketAccounts = new ArrayList<>(); - for (int i = 0; i < accountsDetail.size(); i++) { - final JsonObject element = accountsDetail.get(i).getAsJsonObject(); - final Long accountId = element.get(PocketApiConstants.accountIdParamName).getAsLong(); - final String accountType = element.get(PocketApiConstants.accountTypeParamName).getAsString(); + for (int i = 0; i < accountsDetail.size(); i++) { + final JsonObject element = accountsDetail.get(i).getAsJsonObject(); + final Long accountId = element.get(PocketApiConstants.accountIdParamName).getAsLong(); + final String accountType = element.get(PocketApiConstants.accountTypeParamName).getAsString(); - final AccountEntityService accountEntityService = this.accountEntityServiceFactory - .getAccountEntityService(accountType); - accountEntityService.validateSelfUserAccountMapping(accountId); - Integer accountTypeValue = EntityAccountType.valueOf(accountType).getValue(); - if (this.pocketAccountMappingReadPlatformService.validatePocketAndAccountMapping(pocketId, accountId, - accountTypeValue)) { - throw new PlatformDataIntegrityException(PocketApiConstants.duplicateMappingException, - PocketApiConstants.duplicateMappingExceptionMessage, accountId, accountType); - } + final AccountEntityService accountEntityService = this.accountEntityServiceFactory + .getAccountEntityService(accountType); + accountEntityService.validateSelfUserAccountMapping(accountId); + Integer accountTypeValue = EntityAccountType.valueOf(accountType).getValue(); + if (this.pocketAccountMappingReadPlatformService.validatePocketAndAccountMapping(pocketId, accountId, + accountTypeValue)) { + throw new PlatformDataIntegrityException(PocketApiConstants.duplicateMappingException, + PocketApiConstants.duplicateMappingExceptionMessage, accountId, accountType); + } - final String accountNumber = accountEntityService.retrieveAccountNumberByAccountId(accountId); + final String accountNumber = accountEntityService.retrieveAccountNumberByAccountId(accountId); - pocketAccounts.add(PocketAccountMapping.instance(pocketId, accountId, accountTypeValue, accountNumber)); + pocketAccounts.add(PocketAccountMapping.instance(pocketId, accountId, accountTypeValue, accountNumber)); - } - this.pocketAccountMappingRepositoryWrapper.save(pocketAccounts); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(pocketId).build(); + } + this.pocketAccountMappingRepositoryWrapper.save(pocketAccounts); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(pocketId).build(); - } + } - @Override - public CommandProcessingResult delinkAccounts(JsonCommand command) { - this.pocketDataValidator.validateForDeLinkingAccounts(command.json()); - JsonArray pocketAccountMappingList = command.arrayOfParameterNamed(PocketApiConstants.pocketAccountMappingList); + @Override + public CommandProcessingResult delinkAccounts(JsonCommand command) { + 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<>(); + final List pocketAccounts = new ArrayList<>(); - for (JsonElement mapping : pocketAccountMappingList) { + for (JsonElement mapping : pocketAccountMappingList) { - final Long mappingId = mapping.getAsLong(); + final Long mappingId = mapping.getAsLong(); - PocketAccountMapping pocketAccountMapping = this.pocketAccountMappingRepositoryWrapper - .findByIdAndPocketIdWithNotFoundException(mappingId, pocketId); + PocketAccountMapping pocketAccountMapping = this.pocketAccountMappingRepositoryWrapper + .findByIdAndPocketIdWithNotFoundException(mappingId, pocketId); - if (pocketAccountMapping != null) { - pocketAccounts.add(pocketAccountMapping); - } - } + if (pocketAccountMapping != null) { + pocketAccounts.add(pocketAccountMapping); + } + } - this.pocketAccountMappingRepositoryWrapper.delete(pocketAccounts); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(pocketId).build(); + this.pocketAccountMappingRepositoryWrapper.delete(pocketAccounts); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(pocketId).build(); - } + } } 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 3c8a44286..b587297af 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 @@ -42,170 +42,170 @@ import io.swagger.annotations.*; @Scope("singleton") @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; - private final AppuserClientMapperReadService appUserClientMapperReadService; + private final LoanProductsApiResource loanProductsApiResource; + private final AppuserClientMapperReadService appUserClientMapperReadService; - @Autowired - public SelfLoanProductsApiResource(final LoanProductsApiResource loanProductsApiResource, - final AppuserClientMapperReadService appUserClientMapperReadService) { - this.loanProductsApiResource = loanProductsApiResource; - this.appUserClientMapperReadService = appUserClientMapperReadService; + @Autowired + public SelfLoanProductsApiResource(final LoanProductsApiResource loanProductsApiResource, + final AppuserClientMapperReadService appUserClientMapperReadService) { + this.loanProductsApiResource = loanProductsApiResource; + this.appUserClientMapperReadService = appUserClientMapperReadService; - } + } - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveAllLoanProducts(@QueryParam(LoanApiConstants.clientIdParameterName) final Long clientId, - @Context final UriInfo uriInfo) { + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveAllLoanProducts(@QueryParam(LoanApiConstants.clientIdParameterName) final Long clientId, + @Context final UriInfo uriInfo) { - this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); - return this.loanProductsApiResource.retrieveAllLoanProducts(uriInfo); + this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); + return this.loanProductsApiResource.retrieveAllLoanProducts(uriInfo); - } + } - @GET - @Path("{productId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveLoanProductDetails(@QueryParam(LoanApiConstants.clientIdParameterName) final Long clientId, - @PathParam(LoanApiConstants.productIdParameterName) final Long productId, @Context final UriInfo uriInfo) { + @GET + @Path("{productId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveLoanProductDetails(@QueryParam(LoanApiConstants.clientIdParameterName) final Long clientId, + @PathParam(LoanApiConstants.productIdParameterName) final Long productId, @Context final UriInfo uriInfo) { - this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); - return this.loanProductsApiResource.retrieveLoanProductDetails(productId, uriInfo); - } + this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); + return this.loanProductsApiResource.retrieveLoanProductDetails(productId, uriInfo); + } } 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 d3753637d..930dd7d87 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 @@ -41,38 +41,38 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class SelfSavingsProductsApiResource { - private final SavingsProductsApiResource savingsProductsApiResource; - private final AppuserClientMapperReadService appUserClientMapperReadService; + private final SavingsProductsApiResource savingsProductsApiResource; + private final AppuserClientMapperReadService appUserClientMapperReadService; - @Autowired - public SelfSavingsProductsApiResource(final SavingsProductsApiResource savingsProductsApiResource, - final AppuserClientMapperReadService appUserClientMapperReadService) { - this.savingsProductsApiResource = savingsProductsApiResource; - this.appUserClientMapperReadService = appUserClientMapperReadService; + @Autowired + public SelfSavingsProductsApiResource(final SavingsProductsApiResource savingsProductsApiResource, + final AppuserClientMapperReadService appUserClientMapperReadService) { + this.savingsProductsApiResource = savingsProductsApiResource; + this.appUserClientMapperReadService = appUserClientMapperReadService; - } + } - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveAll(@QueryParam(SavingsApiConstants.clientIdParamName) final Long clientId, - @Context final UriInfo uriInfo) { + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveAll(@QueryParam(SavingsApiConstants.clientIdParamName) final Long clientId, + @Context final UriInfo uriInfo) { - this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); - return this.savingsProductsApiResource.retrieveAll(uriInfo); + this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); + return this.savingsProductsApiResource.retrieveAll(uriInfo); - } + } - @GET - @Path("{productId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveOne(@PathParam(SavingsApiConstants.productIdParamName) final Long productId, - @QueryParam(SavingsApiConstants.clientIdParamName) final Long clientId, @Context final UriInfo uriInfo) { + @GET + @Path("{productId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveOne(@PathParam(SavingsApiConstants.productIdParamName) final Long productId, + @QueryParam(SavingsApiConstants.clientIdParamName) final Long clientId, @Context final UriInfo uriInfo) { - this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); - return this.savingsProductsApiResource.retrieveOne(productId, uriInfo); + this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); + return this.savingsProductsApiResource.retrieveOne(productId, 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 97035d486..088396f56 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 @@ -41,39 +41,39 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class SelfShareProductsApiResource { - private final ProductsApiResource productsApiResource; - private final AppuserClientMapperReadService appUserClientMapperReadService; + private final ProductsApiResource productsApiResource; + private final AppuserClientMapperReadService appUserClientMapperReadService; - @Autowired - public SelfShareProductsApiResource(final ProductsApiResource productsApiResource, - final AppuserClientMapperReadService appUserClientMapperReadService) { - this.productsApiResource = productsApiResource; - this.appUserClientMapperReadService = appUserClientMapperReadService; + @Autowired + public SelfShareProductsApiResource(final ProductsApiResource productsApiResource, + final AppuserClientMapperReadService appUserClientMapperReadService) { + this.productsApiResource = productsApiResource; + this.appUserClientMapperReadService = appUserClientMapperReadService; - } + } - @GET - @Path("{productId}") - @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) { - this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); - return this.productsApiResource.retrieveProduct(productId, ShareAccountApiConstants.shareEntityType, uriInfo); + @GET + @Path("{productId}") + @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) { + this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); + return this.productsApiResource.retrieveProduct(productId, ShareAccountApiConstants.shareEntityType, uriInfo); - } + } - @GET - @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) { - this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); - return this.productsApiResource.retrieveAllProducts(ShareAccountApiConstants.shareEntityType, offset, limit, - uriInfo); + @GET + @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) { + this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); + return this.productsApiResource.retrieveAllProducts(ShareAccountApiConstants.shareEntityType, offset, limit, + uriInfo); - } + } } 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 34d1427ef..b8937dfd4 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 @@ -54,165 +54,165 @@ import org.springframework.stereotype.Component; @Scope("singleton") @Api(tags = {"Self Savings Account"}) @SwaggerDefinition(tags = { - @Tag(name = "Self Savings Account", description = "") + @Tag(name = "Self Savings Account", description = "") }) public class SelfSavingsApiResource { - private final PlatformSecurityContext context; - private final SavingsAccountsApiResource savingsAccountsApiResource; - private final SavingsAccountChargesApiResource savingsAccountChargesApiResource; - private final SavingsAccountTransactionsApiResource savingsAccountTransactionsApiResource; - private final AppuserSavingsMapperReadService appuserSavingsMapperReadService; - private final SelfSavingsDataValidator dataValidator; - private final AppuserClientMapperReadService appUserClientMapperReadService; + private final PlatformSecurityContext context; + private final SavingsAccountsApiResource savingsAccountsApiResource; + private final SavingsAccountChargesApiResource savingsAccountChargesApiResource; + private final SavingsAccountTransactionsApiResource savingsAccountTransactionsApiResource; + private final AppuserSavingsMapperReadService appuserSavingsMapperReadService; + private final SelfSavingsDataValidator dataValidator; + private final AppuserClientMapperReadService appUserClientMapperReadService; - @Autowired - public SelfSavingsApiResource( - final PlatformSecurityContext context, - final SavingsAccountsApiResource savingsAccountsApiResource, - final SavingsAccountChargesApiResource savingsAccountChargesApiResource, - final SavingsAccountTransactionsApiResource savingsAccountTransactionsApiResource, - final AppuserSavingsMapperReadService appuserSavingsMapperReadService, - final SelfSavingsDataValidator dataValidator, - final AppuserClientMapperReadService appUserClientMapperReadService) { - this.context = context; - this.savingsAccountsApiResource = savingsAccountsApiResource; - this.savingsAccountChargesApiResource = savingsAccountChargesApiResource; - this.savingsAccountTransactionsApiResource = savingsAccountTransactionsApiResource; - this.appuserSavingsMapperReadService = appuserSavingsMapperReadService; - this.dataValidator = dataValidator; - this.appUserClientMapperReadService = appUserClientMapperReadService; - } + @Autowired + public SelfSavingsApiResource( + final PlatformSecurityContext context, + final SavingsAccountsApiResource savingsAccountsApiResource, + final SavingsAccountChargesApiResource savingsAccountChargesApiResource, + final SavingsAccountTransactionsApiResource savingsAccountTransactionsApiResource, + final AppuserSavingsMapperReadService appuserSavingsMapperReadService, + final SelfSavingsDataValidator dataValidator, + final AppuserClientMapperReadService appUserClientMapperReadService) { + this.context = context; + this.savingsAccountsApiResource = savingsAccountsApiResource; + this.savingsAccountChargesApiResource = savingsAccountChargesApiResource; + this.savingsAccountTransactionsApiResource = savingsAccountTransactionsApiResource; + this.appuserSavingsMapperReadService = appuserSavingsMapperReadService; + this.dataValidator = dataValidator; + this.appUserClientMapperReadService = appUserClientMapperReadService; + } - @GET - @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, - @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, - @Context final UriInfo uriInfo) { + @GET + @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, + @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, + @Context final UriInfo uriInfo) { - this.dataValidator.validateRetrieveSavings(uriInfo); + this.dataValidator.validateRetrieveSavings(uriInfo); - validateAppuserSavingsAccountMapping(accountId); + validateAppuserSavingsAccountMapping(accountId); - final boolean staffInSelectedOfficeOnly = false; - return this.savingsAccountsApiResource.retrieveOne(accountId, - staffInSelectedOfficeOnly, chargeStatus, uriInfo); - } + final boolean staffInSelectedOfficeOnly = false; + 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) { + @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) { - this.dataValidator.validateRetrieveSavingsTransaction(uriInfo); + this.dataValidator.validateRetrieveSavingsTransaction(uriInfo); - validateAppuserSavingsAccountMapping(accountId); + 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, - @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, - @Context final UriInfo 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, + @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, + @Context final UriInfo uriInfo) { - validateAppuserSavingsAccountMapping(accountId); + 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, - @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId") final Long savingsAccountChargeId, - @Context final UriInfo 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, + @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId") final Long savingsAccountChargeId, + @Context final UriInfo uriInfo) { - validateAppuserSavingsAccountMapping(accountId); + 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); - } - } + 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); + } + } - @GET - @Path("template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String template(@QueryParam("clientId") final Long clientId, @QueryParam("productId") final Long productId, - final String apiRequestBodyAsJson, @Context final UriInfo uriInfo) { + @GET + @Path("template") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String template(@QueryParam("clientId") final Long clientId, @QueryParam("productId") final Long productId, + final String apiRequestBodyAsJson, @Context final UriInfo uriInfo) { - validateAppuserClientsMapping(clientId); - Long groupId = null; - boolean staffInSelectedOfficeOnly = false; - return this.savingsAccountsApiResource.template(clientId, groupId, productId, staffInSelectedOfficeOnly, - uriInfo); + validateAppuserClientsMapping(clientId); + Long groupId = null; + boolean staffInSelectedOfficeOnly = false; + 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) { + @POST + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + 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); - validateAppuserClientsMapping(clientId); - return this.savingsAccountsApiResource.submitApplication(apiRequestBodyAsJson); - } + HashMap parameterMap = this.dataValidator.validateSavingsApplication(apiRequestBodyAsJson); + final Long clientId = (Long) parameterMap.get(SelfSavingsAccountConstants.clientIdParameterName); + validateAppuserClientsMapping(clientId); + return this.savingsAccountsApiResource.submitApplication(apiRequestBodyAsJson); + } - @PUT - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String modifySavingsAccountApplication(@PathParam("accountId") final Long accountId, - @QueryParam("command") final String commandParam, final String apiRequestBodyAsJson) { + @PUT + @Path("{accountId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String modifySavingsAccountApplication(@PathParam("accountId") final Long accountId, + @QueryParam("command") final String commandParam, final String apiRequestBodyAsJson) { - validateAppuserSavingsAccountMapping(accountId); - this.dataValidator.validateSavingsApplication(apiRequestBodyAsJson); - return this.savingsAccountsApiResource.update(accountId, apiRequestBodyAsJson, commandParam); - } + validateAppuserSavingsAccountMapping(accountId); + this.dataValidator.validateSavingsApplication(apiRequestBodyAsJson); + return this.savingsAccountsApiResource.update(accountId, apiRequestBodyAsJson, commandParam); + } - 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/savings/data/SelfSavingsAccountConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/data/SelfSavingsAccountConstants.java index ec37bbbcf..326c0210f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/data/SelfSavingsAccountConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/data/SelfSavingsAccountConstants.java @@ -21,8 +21,8 @@ package org.apache.fineract.portfolio.self.savings.data; public class SelfSavingsAccountConstants { - public static final String savingsAccountResource = "savings"; - public static final String clientIdParameterName = "clientId"; - public static final String productIdParameterName = "productId"; + public static final String savingsAccountResource = "savings"; + public static final String clientIdParameterName = "clientId"; + public static final String productIdParameterName = "productId"; } 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 7ed14ab87..a47c4ca00 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 @@ -43,88 +43,88 @@ import com.google.gson.JsonElement; @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"); - } - } - - public HashMap validateSavingsApplication(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + 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(); + } - 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; - } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/service/AppuserSavingsMapperReadService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/service/AppuserSavingsMapperReadService.java index 3923e8415..c8693f543 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/service/AppuserSavingsMapperReadService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/service/AppuserSavingsMapperReadService.java @@ -20,6 +20,6 @@ package org.apache.fineract.portfolio.self.savings.service; public interface AppuserSavingsMapperReadService { - public Boolean isSavingsMappedToUser(Long savingsId, Long appUserId); + public Boolean isSavingsMappedToUser(Long savingsId, Long appUserId); } 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 5d6acd741..87ab0b258 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 @@ -25,24 +25,24 @@ import org.springframework.stereotype.Service; @Service public class AppuserSavingsMapperReadServiceImpl implements - AppuserSavingsMapperReadService { + AppuserSavingsMapperReadService { - private final JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; - @Autowired - public AppuserSavingsMapperReadServiceImpl( - final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + 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); - } + @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); + } } 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 58e337890..115719bfe 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 @@ -36,24 +36,24 @@ import javax.ws.rs.core.MediaType; @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; + private final AuthenticationApiResource authenticationApiResource; - @Autowired - public SelfAuthenticationApiResource( - final AuthenticationApiResource authenticationApiResource) { - this.authenticationApiResource = authenticationApiResource; - } + @Autowired + 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.openmf.org/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); - } + @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.openmf.org/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/SelfUserDetailsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserDetailsApiResource.java index e2158d365..c1069c95e 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 @@ -37,25 +37,25 @@ import javax.ws.rs.core.MediaType; @Scope("singleton") @Api(tags = {"Self User Details"}) @SwaggerDefinition(tags = { - @Tag(name = "Self User Details", description = "") + @Tag(name = "Self User Details", description = "") }) public class SelfUserDetailsApiResource { - private final UserDetailsApiResource userDetailsApiResource; + private final UserDetailsApiResource userDetailsApiResource; - @Autowired - public SelfUserDetailsApiResource( - final UserDetailsApiResource userDetailsApiResource) { - this.userDetailsApiResource = userDetailsApiResource; - } + @Autowired + 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.openmf.org/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); - } + @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.openmf.org/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/shareaccounts/api/SelfShareAccountsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/api/SelfShareAccountsApiResource.java index db4332f6e..3923eabb2 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 @@ -64,120 +64,120 @@ import io.swagger.annotations.*; @Scope("singleton") @Api(tags = {"Self Share Accounts"}) @SwaggerDefinition(tags = { - @Tag(name = "Self Share Accounts", description = "") + @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 }) + @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) { + 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 }) + @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); - } + 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 }) + @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) + // 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()); - } + 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/data/SelfShareAccountsDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/data/SelfShareAccountsDataValidator.java index c762ecb75..28ef56176 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 @@ -38,38 +38,38 @@ import com.google.gson.JsonElement; @Component public class SelfShareAccountsDataValidator { - private final FromJsonHelper fromApiJsonHelper; + private final FromJsonHelper fromApiJsonHelper; - @Autowired - public SelfShareAccountsDataValidator(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } + @Autowired + public SelfShareAccountsDataValidator(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } - public HashMap validateShareAccountApplication(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public HashMap validateShareAccountApplication(final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } - final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(ShareAccountApiConstants.shareEntityType); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(ShareAccountApiConstants.shareEntityType); - final JsonElement element = this.fromApiJsonHelper.parse(json); + 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)); + HashMap retAttr = new HashMap<>(); + retAttr.put(ShareAccountApiConstants.clientid_paramname, Long.parseLong(clientId)); - return retAttr; + return retAttr; - } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/service/AppUserShareAccountsMapperReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/service/AppUserShareAccountsMapperReadPlatformService.java index 3e7edbdfb..c0cd875bc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/service/AppUserShareAccountsMapperReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/service/AppUserShareAccountsMapperReadPlatformService.java @@ -21,6 +21,6 @@ package org.apache.fineract.portfolio.self.shareaccounts.service; public interface AppUserShareAccountsMapperReadPlatformService { - public Boolean isShareAccountsMappedToUser(Long accountId, Long appUserId); + public Boolean isShareAccountsMappedToUser(Long accountId, Long appUserId); } 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 eb464f1a2..eed7dade6 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 @@ -26,26 +26,26 @@ import org.springframework.stereotype.Service; @Service public class AppUserShareAccountsMapperReadPlatformServiceImpl - implements AppUserShareAccountsMapperReadPlatformService { + implements AppUserShareAccountsMapperReadPlatformService { - private final JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; - @Autowired - 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); - } + @Autowired + 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); + } } 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 70ea371d1..c204d67d8 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 @@ -46,53 +46,53 @@ import org.springframework.transaction.annotation.Transactional; @Scope("singleton") @Api(tags = {"Self Score Card"}) @SwaggerDefinition(tags = { - @Tag(name = "Self Score Card", description = "") + @Tag(name = "Self Score Card", description = "") }) public class SelfScorecardApiResource { - private final PlatformSecurityContext context; - private final ScorecardApiResource scorecardApiResource; - private final AppuserClientMapperReadService appuserClientMapperReadService; + private final PlatformSecurityContext context; + private final ScorecardApiResource scorecardApiResource; + private final AppuserClientMapperReadService appuserClientMapperReadService; - @Autowired - public SelfScorecardApiResource(final PlatformSecurityContext securityContext, - final AppuserClientMapperReadService appuserClientMapperReadService, - final ScorecardApiResource scorecardApiResource) { - this.context = securityContext; - this.scorecardApiResource = scorecardApiResource; - this.appuserClientMapperReadService = appuserClientMapperReadService; - } + @Autowired + public SelfScorecardApiResource(final PlatformSecurityContext securityContext, + final AppuserClientMapperReadService appuserClientMapperReadService, + final ScorecardApiResource scorecardApiResource) { + this.context = securityContext; + this.scorecardApiResource = scorecardApiResource; + this.appuserClientMapperReadService = appuserClientMapperReadService; + } - @GET - @Path("clients/{clientId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @Transactional - public List findByClient(@PathParam("clientId") final Long clientId) { + @GET + @Path("clients/{clientId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @Transactional + public List findByClient(@PathParam("clientId") final Long clientId) { - validateAppuserClientsMapping(clientId); - return this.scorecardApiResource.findByClient(clientId); - } + validateAppuserClientsMapping(clientId); + return this.scorecardApiResource.findByClient(clientId); + } - @POST - @Path("{surveyId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @Transactional - public void createScorecard(@PathParam("surveyId") final Long surveyId, final ScorecardData scorecardData) { - if (scorecardData.getClientId() != null) { - validateAppuserClientsMapping(scorecardData.getClientId()); - this.scorecardApiResource.createScorecard(surveyId, scorecardData); - } + @POST + @Path("{surveyId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @Transactional + public void createScorecard(@PathParam("surveyId") final Long surveyId, final ScorecardData scorecardData) { + if (scorecardData.getClientId() != null) { + validateAppuserClientsMapping(scorecardData.getClientId()); + this.scorecardApiResource.createScorecard(surveyId, scorecardData); + } - } + } - 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/spm/api/SelfSpmApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/spm/api/SelfSpmApiResource.java index f576c0f98..1193aaf22 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 @@ -41,27 +41,27 @@ import org.springframework.transaction.annotation.Transactional; @Scope("singleton") @Api(tags = {"Self Spm"}) @SwaggerDefinition(tags = { - @Tag(name = "Self Spm", description = "") + @Tag(name = "Self Spm", description = "") }) public class SelfSpmApiResource { - private final PlatformSecurityContext securityContext; - private final SpmApiResource spmApiResource; + private final PlatformSecurityContext securityContext; + private final SpmApiResource spmApiResource; - @Autowired - public SelfSpmApiResource(final PlatformSecurityContext securityContext, final SpmApiResource spmApiResource) { - this.securityContext = securityContext; - this.spmApiResource = spmApiResource; - } + @Autowired + public SelfSpmApiResource(final PlatformSecurityContext securityContext, final SpmApiResource spmApiResource) { + this.securityContext = securityContext; + this.spmApiResource = spmApiResource; + } - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @Transactional - public List fetchAllSurveys() { - securityContext.authenticatedUser(); - final Boolean isActive = true; - return this.spmApiResource.fetchAllSurveys(isActive); - } + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @Transactional + public List fetchAllSurveys() { + securityContext.authenticatedUser(); + final Boolean isActive = true; + return this.spmApiResource.fetchAllSurveys(isActive); + } } 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 8c42ec135..bb4137c4c 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 @@ -25,7 +25,7 @@ import java.io.Serializable; @SuppressWarnings("unused") public class ShareAccountApplicationTimelineData implements Serializable { - private final LocalDate submittedOnDate; + private final LocalDate submittedOnDate; private final String submittedByUsername; private final String submittedByFirstname; private final String submittedByLastname; 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 d6e6f7917..73e24dcc9 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 @@ -371,7 +371,7 @@ public class ShareAccount extends AbstractPersistableCustom { } public void updateRequestedShares(ShareAccountTransaction purchased) { - for(ShareAccountTransaction transaction: this.shareAccountTransactions) { + for(ShareAccountTransaction transaction: this.shareAccountTransactions) { if(!transaction.isChargeTransaction() && transaction.getId().equals(purchased.getId())) { transaction.update(purchased.getPurchasedDate(), purchased.getTotalShares(), purchased.getPurchasePrice()); } 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 33b9cc970..6f3e392df 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 ; - } - - public ShareAccount findOneWithNotFoundDetection(final Long accountId) { - return this.shareAccountRepository.findById(accountId) - .orElseThrow(() -> new ShareAccountNotFoundException(accountId)); - } - public void save(final ShareAccount shareAccount) { - this.shareAccountRepository.save(shareAccount) ; - } - - public void saveAndFlush(final ShareAccount shareAccount) { - this.shareAccountRepository.saveAndFlush(shareAccount) ; - } + @Autowired + public ShareAccountRepositoryWrapper(final ShareAccountRepository shareAccountRepository) { + this.shareAccountRepository = shareAccountRepository ; + } + + public ShareAccount findOneWithNotFoundDetection(final Long accountId) { + return this.shareAccountRepository.findById(accountId) + .orElseThrow(() -> new ShareAccountNotFoundException(accountId)); + } + public void save(final ShareAccount shareAccount) { + this.shareAccountRepository.save(shareAccount) ; + } + + public void saveAndFlush(final ShareAccount shareAccount) { + this.shareAccountRepository.saveAndFlush(shareAccount) ; + } } 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 1f608bff4..cbda0c303 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 @@ -24,5 +24,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 195e6d858..6011fd88a 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 @@ -35,55 +35,55 @@ import org.springframework.stereotype.Service; @Service public class PurchasedSharesReadPlatformServiceImpl implements - PurchasedSharesReadPlatformService { + PurchasedSharesReadPlatformService { - private final JdbcTemplate jdbcTemplate; - - @Autowired - public PurchasedSharesReadPlatformServiceImpl(final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource) ; - } - @Override - 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}); - } + private final JdbcTemplate jdbcTemplate; + + @Autowired + public PurchasedSharesReadPlatformServiceImpl(final RoutingDataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource) ; + } + @Override + 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}); + } - private final static class PurchasedSharesDataRowMapper implements RowMapper { + private final static class PurchasedSharesDataRowMapper implements RowMapper { - private final String schema ; - - public PurchasedSharesDataRowMapper() { - StringBuffer buff = new StringBuffer() - .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); - } - - public String schema() { - return this.schema ; - } - } + private final String schema ; + + public PurchasedSharesDataRowMapper() { + StringBuffer buff = new StringBuffer() + .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); + } + + public String 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 af23abea2..c0adaae38 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 @@ -24,5 +24,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 66fb61eab..04f688c9d 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 @@ -37,114 +37,114 @@ import org.springframework.stereotype.Service; @Service public class ShareAccountChargeReadPlatformServiceImpl implements - ShareAccountChargeReadPlatformService { + ShareAccountChargeReadPlatformService { - private final JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; - @Autowired - public ShareAccountChargeReadPlatformServiceImpl( - final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + @Autowired + public ShareAccountChargeReadPlatformServiceImpl( + final RoutingDataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } - @Override - 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=? "); - if (status.equalsIgnoreCase("active")) { - sqlBuilder.append(" and sc.is_active = 1 "); - } else if (status.equalsIgnoreCase("inactive")) { - sqlBuilder.append(" and sc.is_active = 0 "); - } - sqlBuilder.append(" order by sc.charge_time_enum ASC"); + @Override + 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=? "); + if (status.equalsIgnoreCase("active")) { + sqlBuilder.append(" and sc.is_active = 1 "); + } else if (status.equalsIgnoreCase("inactive")) { + sqlBuilder.append(" and sc.is_active = 0 "); + } + 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; + private final String schema; - public ShareAccountChargeMapper() { - StringBuffer buff = new StringBuffer() - .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, ") - .append("sc.calculation_on_amount as amountPercentageAppliedTo, sc.charge_time_enum as chargeTime, ") - .append("sc.charge_calculation_enum as chargeCalculation, c.is_active as isActive, ") - .append("c.currency_code as currencyCode, oc.name as currencyName, ") - .append("oc.decimal_places as currencyDecimalPlaces, oc.currency_multiplesof as inMultiplesOf, oc.display_symbol as currencyDisplaySymbol, ") - .append("sc.charge_amount_or_percentage, ") - .append("oc.internationalized_name_code as currencyNameCode from m_charge c ") - .append("join m_organisation_currency oc on c.currency_code = oc.code ") - .append("join m_share_account_charge sc on sc.charge_id = c.id "); + public ShareAccountChargeMapper() { + StringBuffer buff = new StringBuffer() + .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, ") + .append("sc.calculation_on_amount as amountPercentageAppliedTo, sc.charge_time_enum as chargeTime, ") + .append("sc.charge_calculation_enum as chargeCalculation, c.is_active as isActive, ") + .append("c.currency_code as currencyCode, oc.name as currencyName, ") + .append("oc.decimal_places as currencyDecimalPlaces, oc.currency_multiplesof as inMultiplesOf, oc.display_symbol as currencyDisplaySymbol, ") + .append("sc.charge_amount_or_percentage, ") + .append("oc.internationalized_name_code as currencyNameCode from m_charge c ") + .append("join m_organisation_currency oc on c.currency_code = oc.code ") + .append("join m_share_account_charge sc on sc.charge_id = c.id "); - schema = buff.toString(); - } + schema = buff.toString(); + } - @Override - 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"); + @Override + 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 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 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 CurrencyData currency = new CurrencyData(currencyCode, - currencyName, currencyDecimalPlaces, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, + currencyName, currencyDecimalPlaces, inMultiplesOf, + currencyDisplaySymbol, currencyNameCode); - final int chargeTime = rs.getInt("chargeTime"); - final EnumOptionData chargeTimeType = ChargeEnumerations - .chargeTimeType(chargeTime); + final int chargeTime = rs.getInt("chargeTime"); + final EnumOptionData chargeTimeType = ChargeEnumerations + .chargeTimeType(chargeTime); - final int chargeCalculation = rs.getInt("chargeCalculation"); - final EnumOptionData chargeCalculationType = ChargeEnumerations - .chargeCalculationType(chargeCalculation); - final Boolean isActive = rs.getBoolean("isActive"); - 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); - } + final int chargeCalculation = rs.getInt("chargeCalculation"); + final EnumOptionData chargeCalculationType = ChargeEnumerations + .chargeCalculationType(chargeCalculation); + final Boolean isActive = rs.getBoolean("isActive"); + 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); + } - public String schema() { - return this.schema; - } - } + public String schema() { + return this.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 926aa0dca..2b5c7e300 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 @@ -64,7 +64,7 @@ public class ShareAccountCommandsServiceImpl implements AccountsCommandsService } public Object approveShareAccount(Long accountId, JsonCommand jsonCommand) { - return null ; + return null ; } public Object rejectShareAccount(Long accountId, JsonCommand jsonCommand) { 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 440d2f0e7..a1797c1f7 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 @@ -50,7 +50,7 @@ public class ShareAccountDividendReadPlatformServiceImpl implements ShareAccount @Autowired public ShareAccountDividendReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + 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 a6fa93f6b..42a1bf67e 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 @@ -38,5 +38,5 @@ public interface ShareAccountReadPlatformService extends AccountReadPlatformServ Collection retrieveAllShareAccountDataForDividends(Long productId, boolean fetchInActiveAccounts, LocalDate startDate); - String retrieveAccountNumberByAccountId(Long accountId); + 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 1df67559a..4b95d9af0 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 @@ -505,13 +505,13 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat } } - @Override - public String retrieveAccountNumberByAccountId(Long accountId) { - try { - final String sql = "select s.account_no from m_share_account s where s.id = ?"; - return this.jdbcTemplate.queryForObject(sql, new Object[] { accountId }, String.class); - } catch (final EmptyResultDataAccessException e) { - throw new ShareAccountNotFoundException(accountId); - } - } + @Override + public String retrieveAccountNumberByAccountId(Long accountId) { + try { + final String sql = "select s.account_no from m_share_account s where s.id = ?"; + return this.jdbcTemplate.queryForObject(sql, new Object[] { accountId }, String.class); + } catch (final EmptyResultDataAccessException e) { + throw new ShareAccountNotFoundException(accountId); + } + } } 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 90259ce73..192449b22 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 @@ -121,9 +121,9 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(jsonCommand, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(jsonCommand, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -219,9 +219,9 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(jsonCommand, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(jsonCommand, throwable, dve); + return CommandProcessingResult.empty(); } } 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 d04b5f060..545ed052f 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 @@ -48,7 +48,7 @@ public enum SharePeriodFrequencyType { } public static SharePeriodFrequencyType fromInt(final Integer type) { - SharePeriodFrequencyType repaymentFrequencyType = SharePeriodFrequencyType.INVALID; + SharePeriodFrequencyType repaymentFrequencyType = SharePeriodFrequencyType.INVALID; if (type != null) { switch (type) { case 0: 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 97b3e1af4..fcaf1c4a0 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.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 031bc06fd..fefd1d4d0 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 @@ -286,26 +286,26 @@ public class ShareProduct extends AbstractAuditableCustom { } public boolean setMarketPrice(Set marketPrice) { - boolean update = true; - Set marketPriceTemp = new HashSet(); - if (marketPrice != null && marketPrice.size() > 0) { - for (ShareProductMarketPriceData data : marketPrice) { + 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); - } else { - for (ShareProductMarketPrice priceData : this.marketPrice) { - if (priceData.getId().equals(data.getId())) { - priceData.setStartDate(data.getStartDate()); - priceData.setShareValue(data.getShareValue()); - marketPriceTemp.add(priceData); - } - } - } - } - } - this.marketPrice = marketPriceTemp; + } else { + for (ShareProductMarketPrice priceData : this.marketPrice) { + if (priceData.getId().equals(data.getId())) { + priceData.setStartDate(data.getStartDate()); + priceData.setShareValue(data.getShareValue()); + marketPriceTemp.add(priceData); + } + } + } + } + } + this.marketPrice = marketPriceTemp; return update; } 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 2ca7e661b..9bcc16532 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 @@ -47,7 +47,7 @@ public class ShareProductMarketPrice extends AbstractPersistableCustom { private BigDecimal shareValue ; public ShareProductMarketPrice() { - + } public ShareProductMarketPrice(final Date fromDate, final BigDecimal shareValue) { @@ -68,10 +68,10 @@ public class ShareProductMarketPrice extends AbstractPersistableCustom { } 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/ShareProductRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductRepositoryWrapper.java index e284ae5ac..038cecf3e 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,23 @@ import org.springframework.stereotype.Service; @Service public class ShareProductRepositoryWrapper { - private final ShareProductRepository shareProductRepository ; - - @Autowired - public ShareProductRepositoryWrapper(final ShareProductRepository shareProductRepository) { - this.shareProductRepository = shareProductRepository ; - } - - public ShareProduct findOneWithNotFoundDetection(final Long productId) { - return this.shareProductRepository.findById(productId) - .orElseThrow(() -> new ProductNotFoundException(productId, "share")); - } - - public void save(ShareProduct product) { - this.shareProductRepository.save(product) ; - } - - public void saveAndFlush(ShareProduct product) { - this.shareProductRepository.saveAndFlush(product) ; - } + private final ShareProductRepository shareProductRepository ; + + @Autowired + public ShareProductRepositoryWrapper(final ShareProductRepository shareProductRepository) { + this.shareProductRepository = shareProductRepository ; + } + + public ShareProduct findOneWithNotFoundDetection(final Long productId) { + return this.shareProductRepository.findById(productId) + .orElseThrow(() -> new ProductNotFoundException(productId, "share")); + } + + public void save(ShareProduct product) { + this.shareProductRepository.save(product) ; + } + + public void saveAndFlush(ShareProduct product) { + this.shareProductRepository.saveAndFlush(product) ; + } } 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 4b517e8eb..59fda9792 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 @@ -68,31 +68,31 @@ 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, - 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.lockperiod_paramname, ShareProductApiConstants.lockinperiodfrequencytype_paramname, - ShareProductApiConstants.minimumactiveperiodfordividends_paramname, - ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, - ShareProductApiConstants.sharecapital_paramname, ShareProductApiConstants.accountingRuleParamName, - AccountingConstants.SHARES_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), - AccountingConstants.SHARES_PRODUCT_ACCOUNTING_PARAMS.SHARES_EQUITY.getValue(), - AccountingConstants.SHARES_PRODUCT_ACCOUNTING_PARAMS.SHARES_REFERENCE.getValue(), - AccountingConstants.SHARES_PRODUCT_ACCOUNTING_PARAMS.SHARES_SUSPENSE.getValue())); + 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.lockperiod_paramname, ShareProductApiConstants.lockinperiodfrequencytype_paramname, + ShareProductApiConstants.minimumactiveperiodfordividends_paramname, + ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, + ShareProductApiConstants.sharecapital_paramname, ShareProductApiConstants.accountingRuleParamName, + AccountingConstants.SHARES_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), + AccountingConstants.SHARES_PRODUCT_ACCOUNTING_PARAMS.SHARES_EQUITY.getValue(), + AccountingConstants.SHARES_PRODUCT_ACCOUNTING_PARAMS.SHARES_REFERENCE.getValue(), + AccountingConstants.SHARES_PRODUCT_ACCOUNTING_PARAMS.SHARES_SUSPENSE.getValue())); - private static final Set supportedParametersForDivident = new HashSet<>(Arrays.asList( - ShareProductApiConstants.locale_paramname, ShareProductApiConstants.dateFormatParamName, - ShareProductApiConstants.dividendPeriodStartDateParamName, - ShareProductApiConstants.dividendPeriodEndDateParamName, ShareProductApiConstants.dividendAmountParamName)); + private static final Set supportedParametersForDivident = new HashSet<>(Arrays.asList( + ShareProductApiConstants.locale_paramname, ShareProductApiConstants.dateFormatParamName, + ShareProductApiConstants.dividendPeriodStartDateParamName, + ShareProductApiConstants.dividendPeriodEndDateParamName, ShareProductApiConstants.dividendAmountParamName)); @Autowired public ShareProductDataSerializer(final FromJsonHelper fromApiJsonHelper, final ChargeRepositoryWrapper chargeRepository, @@ -105,8 +105,8 @@ 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"); @@ -119,10 +119,10 @@ 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(); @@ -275,8 +275,8 @@ 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"); @@ -474,8 +474,8 @@ 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) 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 afb9b9b7d..a1833f1f4 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 @@ -51,7 +51,7 @@ public class ShareProductDividendReadPlatformServiceImpl implements ShareProduct @Autowired public ShareProductDividendReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + 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 ae3f98f23..ff1126e0b 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 @@ -24,7 +24,7 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; public interface ShareProductDropdownReadPlatformService { - Collection retrieveLockinPeriodFrequencyTypeOptions(); - - Collection retrieveMinimumActivePeriodFrequencyTypeOptions() ; + Collection retrieveLockinPeriodFrequencyTypeOptions(); + + Collection retrieveMinimumActivePeriodFrequencyTypeOptions() ; } 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 1a4ff23e1..278db437f 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 @@ -93,9 +93,9 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(jsonCommand, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(jsonCommand, throwable, dve); + return CommandProcessingResult.empty(); } } @@ -124,9 +124,9 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(jsonCommand, throwable, dve); - return CommandProcessingResult.empty(); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(jsonCommand, throwable, dve); + return CommandProcessingResult.empty(); } } 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 37519e92e..35e2b09ad 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 @@ -20,24 +20,24 @@ package org.apache.fineract.portfolio.transfer.api; public class TransferApiConstants { - // general - public static final String localeParamName = "locale"; - public static final String dateFormatParamName = "dateFormat"; + // general + public static final String localeParamName = "locale"; + public static final String dateFormatParamName = "dateFormat"; - // request parameters - public static final String idParamName = "id"; - public static final String destinationGroupIdParamName = "destinationGroupId"; - public static final String clients = "clients"; - public static final String inheritDestinationGroupLoanOfficer = "inheritDestinationGroupLoanOfficer"; - public static final String newStaffIdParamName = "staffId"; - public static final String transferActiveLoans = "transferActiveLoans"; - public static final String destinationOfficeIdParamName = "destinationOfficeId"; - public static final String note = "note"; - public static final String transferDate = "transferDate"; - public static final String transferClientLoanException = "error.msg.caanot.transfer.client.as.loan.transaction.present.on.or.after.transfer.date"; - public static final String transferClientLoanExceptionMessage = "error msg caanot transfer client as loan transaction present on or after transfer date"; - public static final String transferClientSavingsException = "error.msg.caanot.transfer.client.as.savings.transaction.present.on.or.after.transfer.date"; - 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"; + // request parameters + public static final String idParamName = "id"; + public static final String destinationGroupIdParamName = "destinationGroupId"; + public static final String clients = "clients"; + public static final String inheritDestinationGroupLoanOfficer = "inheritDestinationGroupLoanOfficer"; + public static final String newStaffIdParamName = "staffId"; + public static final String transferActiveLoans = "transferActiveLoans"; + public static final String destinationOfficeIdParamName = "destinationOfficeId"; + public static final String note = "note"; + public static final String transferDate = "transferDate"; + public static final String transferClientLoanException = "error.msg.caanot.transfer.client.as.loan.transaction.present.on.or.after.transfer.date"; + public static final String transferClientLoanExceptionMessage = "error msg caanot transfer client as loan transaction present on or after transfer date"; + public static final String transferClientSavingsException = "error.msg.caanot.transfer.client.as.savings.transaction.present.on.or.after.transfer.date"; + 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 b769212a3..5db949fd1 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 @@ -46,32 +46,32 @@ import com.google.gson.reflect.TypeToken; public final class TransfersDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set TRANSFER_CLIENTS_BETWEEN_GROUPS_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(TransferApiConstants.localeParamName, TransferApiConstants.dateFormatParamName, - TransferApiConstants.destinationGroupIdParamName, TransferApiConstants.clients, - TransferApiConstants.inheritDestinationGroupLoanOfficer, TransferApiConstants.newStaffIdParamName, - TransferApiConstants.transferActiveLoans)); + private static final Set TRANSFER_CLIENTS_BETWEEN_GROUPS_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(TransferApiConstants.localeParamName, TransferApiConstants.dateFormatParamName, + TransferApiConstants.destinationGroupIdParamName, TransferApiConstants.clients, + TransferApiConstants.inheritDestinationGroupLoanOfficer, TransferApiConstants.newStaffIdParamName, + TransferApiConstants.transferActiveLoans)); - 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)); + 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)); - 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)); + 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)); - 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) { @@ -87,8 +87,8 @@ 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<>(); 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 index 572fac2ac..a08ac5d86 100755 --- 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 @@ -76,7 +76,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, @@ -85,9 +85,9 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr final LoanRepositoryWrapper loanRepositoryWrapper, final TransfersDataValidator transfersDataValidator, final NoteWritePlatformService noteWritePlatformService, final StaffRepositoryWrapper staffRepositoryWrapper, final SavingsAccountRepositoryWrapper savingsAccountRepositoryWrapper, - final SavingsAccountWritePlatformService savingsAccountWritePlatformService, - final ClientTransferDetailsRepositoryWrapper clientTransferDetailsRepositoryWrapper, - final PlatformSecurityContext context) { + final SavingsAccountWritePlatformService savingsAccountWritePlatformService, + final ClientTransferDetailsRepositoryWrapper clientTransferDetailsRepositoryWrapper, + final PlatformSecurityContext context) { this.clientRepositoryWrapper = clientRepositoryWrapper; this.officeRepository = officeRepository; this.calendarInstanceRepository = calendarInstanceRepository; @@ -100,7 +100,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr this.savingsAccountRepositoryWrapper = savingsAccountRepositoryWrapper; this.savingsAccountWritePlatformService = savingsAccountWritePlatformService; this.clientTransferDetailsRepositoryWrapper = clientTransferDetailsRepositoryWrapper; - this.context = context; + this.context = context; } @@ -295,13 +295,13 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr final Long destinationOfficeId = jsonCommand.longValueOfParameterNamed(TransferApiConstants.destinationOfficeIdParamName); final Office office = this.officeRepository.findOneWithNotFoundDetection(destinationOfficeId); final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); - if (client.getOffice().getId().equals(destinationOfficeId)) { - throw new GeneralPlatformDomainRuleException(TransferApiConstants.transferClientToSameOfficeException, - TransferApiConstants.transferClientToSameOfficeExceptionMessage, office.getName()); + if (client.getOffice().getId().equals(destinationOfficeId)) { + throw new GeneralPlatformDomainRuleException(TransferApiConstants.transferClientToSameOfficeException, + TransferApiConstants.transferClientToSameOfficeExceptionMessage, office.getName()); - } - handleClientTransferLifecycleEvent(client, office, TransferEventType.PROPOSAL, jsonCommand); - this.clientRepositoryWrapper.save(client); + } + handleClientTransferLifecycleEvent(client, office, TransferEventType.PROPOSAL, jsonCommand); + this.clientRepositoryWrapper.save(client); return new CommandProcessingResultBuilder() // .withClientId(clientId) // .withEntityId(clientId) // @@ -417,18 +417,18 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr switch (transferEventType) { case ACCEPTANCE: this.savingsAccountWritePlatformService.acceptSavingsTransfer(savingsAccount, - savingsAccount.retrieveLastTransactionDate(), destinationOffice, staff); + savingsAccount.retrieveLastTransactionDate(), destinationOffice, staff); break; case PROPOSAL: this.savingsAccountWritePlatformService.initiateSavingsTransfer(savingsAccount, - transferDate); + transferDate); break; case REJECTION: this.savingsAccountWritePlatformService.rejectSavingsTransfer(savingsAccount); break; case WITHDRAWAL: this.savingsAccountWritePlatformService.withdrawSavingsTransfer(savingsAccount, - savingsAccount.retrieveLastTransactionDate()); + savingsAccount.retrieveLastTransactionDate()); } } } @@ -473,13 +473,13 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr client.updateProposedTransferDate(null); } - 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.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())); + } private List assembleListOfClients(final JsonCommand command) { 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 29a337cd6..a05859503 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 @@ -390,15 +390,15 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService List> dividendDetails = this.shareAccountDividendReadPlatformService.retriveDividendDetailsForPostDividents(); StringBuilder errorMsg = new StringBuilder(); for (Map dividendMap : dividendDetails) { - Long id = null ; - Long savingsId = null ; - if(dividendMap.get("id") instanceof BigInteger) { //Drizzle is returning BigInteger - id = ((BigInteger)dividendMap.get("id")).longValue() ; - savingsId = ((BigInteger)dividendMap.get("savingsAccountId")).longValue() ; - }else { //MySQL connector is returning Long - id = (Long) dividendMap.get("id") ; - savingsId = (Long) dividendMap.get("savingsAccountId") ; - } + Long id = null ; + Long savingsId = null ; + if(dividendMap.get("id") instanceof BigInteger) { //Drizzle is returning BigInteger + id = ((BigInteger)dividendMap.get("id")).longValue() ; + savingsId = ((BigInteger)dividendMap.get("savingsAccountId")).longValue() ; + }else { //MySQL connector is returning Long + id = (Long) dividendMap.get("id") ; + savingsId = (Long) dividendMap.get("savingsAccountId") ; + } try { this.shareAccountSchedularService.postDividend(id, savingsId); } catch (final PlatformApiDataValidationException e) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/template/service/TemplateMergeService.java b/fineract-provider/src/main/java/org/apache/fineract/template/service/TemplateMergeService.java index a74f6f2bc..e53f1ce07 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/template/service/TemplateMergeService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/template/service/TemplateMergeService.java @@ -44,8 +44,8 @@ import java.util.Map.Entry; @Service public class TemplateMergeService { - private final static Logger logger = LoggerFactory.getLogger(TemplateMergeService.class); - + private final static Logger logger = LoggerFactory.getLogger(TemplateMergeService.class); + // private final FromJsonHelper fromApiJsonHelper; private Map scopes; @@ -53,7 +53,7 @@ public class TemplateMergeService { public void setAuthToken(final String authToken) { - this.authToken = authToken; + this.authToken = authToken; } @@ -75,7 +75,7 @@ public class TemplateMergeService { return stringWriter.toString(); } - private Map getCompiledMapFromMappers(final Map data) { + private Map getCompiledMapFromMappers(final Map data) { final MustacheFactory mf = new DefaultMustacheFactory(); if (data != null) { @@ -91,7 +91,7 @@ public class TemplateMergeService { try { this.scopes.put(entry.getKey(), getMapFromUrl(url)); } catch (final IOException e) { - logger.error("getCompiledMapFromMappers() failed", e); + logger.error("getCompiledMapFromMappers() failed", e); } } } @@ -136,7 +136,7 @@ public class TemplateMergeService { connection.setDoInput(true); } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { - logger.error("getConnection() failed, return null", e); + logger.error("getConnection() failed, return null", e); } return connection; @@ -156,7 +156,7 @@ public class TemplateMergeService { } } catch (final IOException e) { - logger.error("getStringFromInputStream() failed", e); + logger.error("getStringFromInputStream() failed", e); } finally { if (br != null) { try { @@ -170,32 +170,32 @@ public class TemplateMergeService { return sb.toString(); } - @SuppressWarnings("unchecked") - private void expandMapArrays(Object value) { - if (value instanceof Map) { - Map valueAsMap = (Map) value; - //Map newValue = null; - Map valueAsMap_second = new HashMap<>(); - for (Entry valueAsMapEntry : valueAsMap.entrySet()) { - Object valueAsMapEntryValue = valueAsMapEntry.getValue(); - if (valueAsMapEntryValue instanceof Map) { // JSON Object - expandMapArrays(valueAsMapEntryValue); - } else if (valueAsMapEntryValue instanceof Iterable) { // JSON Array - Iterable valueAsMapEntryValueIterable = (Iterable) valueAsMapEntryValue; - String valueAsMapEntryKey = valueAsMapEntry.getKey(); - int i = 0; - for (Object object : valueAsMapEntryValueIterable) { - valueAsMap_second.put(valueAsMapEntryKey + "#" + i, object); - ++i; - expandMapArrays(object); - - } - } + @SuppressWarnings("unchecked") + private void expandMapArrays(Object value) { + if (value instanceof Map) { + Map valueAsMap = (Map) value; + //Map newValue = null; + Map valueAsMap_second = new HashMap<>(); + for (Entry valueAsMapEntry : valueAsMap.entrySet()) { + Object valueAsMapEntryValue = valueAsMapEntry.getValue(); + if (valueAsMapEntryValue instanceof Map) { // JSON Object + expandMapArrays(valueAsMapEntryValue); + } else if (valueAsMapEntryValue instanceof Iterable) { // JSON Array + Iterable valueAsMapEntryValueIterable = (Iterable) valueAsMapEntryValue; + String valueAsMapEntryKey = valueAsMapEntry.getKey(); + int i = 0; + for (Object object : valueAsMapEntryValueIterable) { + valueAsMap_second.put(valueAsMapEntryKey + "#" + i, object); + ++i; + expandMapArrays(object); + + } + } - } - valueAsMap.putAll(valueAsMap_second); + } + valueAsMap.putAll(valueAsMap_second); - } - } + } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/data/AppUserData.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/data/AppUserData.java index 7bda81147..e1bb4f315 100755 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/data/AppUserData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/data/AppUserData.java @@ -54,13 +54,13 @@ public class AppUserData { private final StaffData staff; private final Boolean isSelfServiceUser; - @SuppressWarnings("unused") + @SuppressWarnings("unused") private Set clients; - public static AppUserData importInstance(Long officeId,Long staffId,String userName, String firstName, String lastName, + public static AppUserData importInstance(Long officeId,Long staffId,String userName, String firstName, String lastName, String email,Boolean sendPasswordToEmail,Boolean passwordNeverExpires, List roleIds, Integer rowIndex){ - return new AppUserData(officeId,staffId,userName,firstName,lastName,email, + return new AppUserData(officeId,staffId,userName,firstName,lastName,email, sendPasswordToEmail,passwordNeverExpires,roleIds,rowIndex); } private AppUserData(Long officeId,Long staffId,String username, String firstname, String lastname, @@ -160,11 +160,11 @@ public class AppUserData { } public void setClients(Set clients){ - this.clients = clients; + this.clients = clients; } public boolean isSelfServiceUser() { - return this.isSelfServiceUser==null?false:this.isSelfServiceUser; - } + return this.isSelfServiceUser==null?false:this.isSelfServiceUser; + } } \ No newline at end of file diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/data/PasswordPreferencesDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/data/PasswordPreferencesDataValidator.java index 38d7509b0..cbc959044 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/data/PasswordPreferencesDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/data/PasswordPreferencesDataValidator.java @@ -42,9 +42,9 @@ import com.google.gson.reflect.TypeToken; @Component public class PasswordPreferencesDataValidator { - private final FromJsonHelper fromApiJsonHelper; - private static final Set REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(PasswordPreferencesApiConstants.VALIDATION_POLICY_ID)); + private final FromJsonHelper fromApiJsonHelper; + private static final Set REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(PasswordPreferencesApiConstants.VALIDATION_POLICY_ID)); @Autowired public PasswordPreferencesDataValidator(FromJsonHelper fromApiJsonHelper) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/AppUser.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/AppUser.java index d5bcfd522..9e6357aab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/AppUser.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/AppUser.java @@ -118,14 +118,14 @@ public class AppUser extends AbstractPersistableCustom implements Platform private boolean passwordNeverExpires; @Column(name = "is_self_service_user", nullable = false) - private boolean isSelfServiceUser; + private boolean isSelfServiceUser; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) @JoinColumn(name = "appuser_id", referencedColumnName= "id", nullable = false) private Set appUserClientMappings = new HashSet<>(); - public static AppUser fromJson(final Office userOffice, final Staff linkedStaff, final Set allRoles, - final Collection clients, final JsonCommand command) { + public static AppUser fromJson(final Office userOffice, final Staff linkedStaff, final Set allRoles, + final Collection clients, final JsonCommand command) { final String username = command.stringValueOfParameterNamed("username"); String password = command.stringValueOfParameterNamed("password"); @@ -159,7 +159,7 @@ public class AppUser extends AbstractPersistableCustom implements Platform final boolean isSelfServiceUser = command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER); return new AppUser(userOffice, user, allRoles, email, firstname, lastname, linkedStaff, passwordNeverExpire, - isSelfServiceUser, clients); + isSelfServiceUser, clients); } protected AppUser() { @@ -221,7 +221,7 @@ public class AppUser extends AbstractPersistableCustom implements Platform } public Map update(final JsonCommand command, final PlatformPasswordEncoder platformPasswordEncoder, - final Collection clients) { + final Collection clients) { final Map actualChanges = new LinkedHashMap<>(7); @@ -303,27 +303,27 @@ public class AppUser extends AbstractPersistableCustom implements Platform } if(command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER)){ - if (command.isChangeInBooleanParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER, this.isSelfServiceUser)){ + if (command.isChangeInBooleanParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER, this.isSelfServiceUser)){ final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER); actualChanges.put(AppUserConstants.IS_SELF_SERVICE_USER, newValue); this.isSelfServiceUser = newValue; - } + } } if(this.isSelfServiceUser && command.hasParameter(AppUserConstants.CLIENTS)){ - actualChanges.put(AppUserConstants.CLIENTS, command.arrayValueOfParameterNamed(AppUserConstants.CLIENTS)); - Set newClients = createAppUserClientMappings(clients); - if(this.appUserClientMappings == null){ - this.appUserClientMappings = new HashSet<>(); - }else{ - this.appUserClientMappings.retainAll(newClients); - } - this.appUserClientMappings.addAll(newClients); + actualChanges.put(AppUserConstants.CLIENTS, command.arrayValueOfParameterNamed(AppUserConstants.CLIENTS)); + Set newClients = createAppUserClientMappings(clients); + if(this.appUserClientMappings == null){ + this.appUserClientMappings = new HashSet<>(); + }else{ + this.appUserClientMappings.retainAll(newClients); + } + this.appUserClientMappings.addAll(newClients); }else if(!this.isSelfServiceUser && actualChanges.containsKey(AppUserConstants.IS_SELF_SERVICE_USER)){ - actualChanges.put(AppUserConstants.CLIENTS, new ArrayList<>()); - if(this.appUserClientMappings != null){ - this.appUserClientMappings.clear(); - } + actualChanges.put(AppUserConstants.CLIENTS, new ArrayList<>()); + if(this.appUserClientMappings != null){ + this.appUserClientMappings.clear(); + } } return actualChanges; @@ -646,23 +646,23 @@ public class AppUser extends AbstractPersistableCustom implements Platform return !isEnabled(); } - public boolean isSelfServiceUser() { - return this.isSelfServiceUser; - } - + public boolean isSelfServiceUser() { + return this.isSelfServiceUser; + } + public Set getAppUserClientMappings() { - return this.appUserClientMappings; - } + return this.appUserClientMappings; + } - private Set createAppUserClientMappings(Collection clients) { - Set newAppUserClientMappings = null; - if(clients != null && clients.size() > 0){ - newAppUserClientMappings = new HashSet<>(); - for(Client client : clients){ - newAppUserClientMappings.add(new AppUserClientMapping(client)); - } - } - return newAppUserClientMappings; - } + private Set createAppUserClientMappings(Collection clients) { + Set newAppUserClientMappings = null; + if(clients != null && clients.size() > 0){ + newAppUserClientMappings = new HashSet<>(); + for(Client client : clients){ + newAppUserClientMappings.add(new AppUserClientMapping(client)); + } + } + return newAppUserClientMappings; + } } \ No newline at end of file diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/AppUserClientMapping.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/AppUserClientMapping.java index a0aa2d7f2..417d56755 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/AppUserClientMapping.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/AppUserClientMapping.java @@ -30,51 +30,51 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity @Table(name = "m_selfservice_user_client_mapping") public class AppUserClientMapping extends AbstractPersistableCustom { - + @ManyToOne(optional = false, cascade = CascadeType.PERSIST) @JoinColumn(name = "client_id", nullable = false) private Client client; - public AppUserClientMapping(){ - - } + public AppUserClientMapping(){ + + } - public AppUserClientMapping(Client client){ - this.client = client; - } + public AppUserClientMapping(Client client){ + this.client = client; + } - public Client getClient() { - return this.client; - } - - @Override - public boolean equals(Object obj) { + public Client getClient() { + return this.client; + } + + @Override + public boolean equals(Object obj) { - if (null == obj) { - return false; - } + if (null == obj) { + return false; + } - if (this == obj) { - return true; - } + if (this == obj) { + return true; + } - if (!getClass().equals(obj.getClass())) { - return false; - } + if (!getClass().equals(obj.getClass())) { + return false; + } - AppUserClientMapping that = (AppUserClientMapping) obj; + AppUserClientMapping that = (AppUserClientMapping) obj; - return null == this.client.getId() ? false : this.client.getId().equals(that.client.getId()); - } - - @Override - public int hashCode() { + return null == this.client.getId() ? false : this.client.getId().equals(that.client.getId()); + } + + @Override + public int hashCode() { - int hashCode = 17; + int hashCode = 17; - hashCode += null == this.client ? 0 : this.client.getId().hashCode() * 31; + hashCode += null == this.client ? 0 : this.client.getId().hashCode() * 31; - return hashCode; - } + return hashCode; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/Role.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/Role.java index 0a0ad78c3..fedc7e495 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/Role.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/domain/Role.java @@ -131,7 +131,7 @@ public class Role extends AbstractPersistableCustom implements Serializabl } public String getName() { - return this.name; + return this.name; } public void disableRole() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserReadPlatformServiceImpl.java index a383ae9c1..083f02c18 100755 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserReadPlatformServiceImpl.java @@ -143,13 +143,13 @@ public class AppUserReadPlatformServiceImpl implements AppUserReadPlatformServic user.getPasswordNeverExpires(), user.isSelfServiceUser()); if(retUser.isSelfServiceUser()){ - Set clients = new HashSet<>(); - for(AppUserClientMapping clientMap : user.getAppUserClientMappings()){ - Client client = clientMap.getClient(); - clients.add(ClientData.lookup(client.getId(), client.getDisplayName(), - client.getOffice().getId(), client.getOffice().getName())); - } - retUser.setClients(clients); + Set clients = new HashSet<>(); + for(AppUserClientMapping clientMap : user.getAppUserClientMappings()){ + Client client = clientMap.getClient(); + clients.add(ClientData.lookup(client.getId(), client.getDisplayName(), + client.getOffice().getId(), client.getOffice().getName())); + } + retUser.setClients(clients); } return retUser; diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserWritePlatformServiceJpaRepositoryImpl.java index c7cf1ec4c..e01ade4e4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserWritePlatformServiceJpaRepositoryImpl.java @@ -139,14 +139,14 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit Collection clients = null; if(command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER) - && command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER) - && command.hasParameter(AppUserConstants.CLIENTS)){ - JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS); - Collection clientIds = new HashSet<>(); - for(JsonElement clientElement : clientsArray){ - clientIds.add(clientElement.getAsLong()); - } - clients = this.clientRepositoryWrapper.findAll(clientIds); + && command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER) + && command.hasParameter(AppUserConstants.CLIENTS)){ + JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS); + Collection clientIds = new HashSet<>(); + for(JsonElement clientElement : clientsArray){ + clientIds.add(clientElement.getAsLong()); + } + clients = this.clientRepositoryWrapper.findAll(clientIds); } appUser = AppUser.fromJson(userOffice, linkedStaff, allRoles, clients, command); @@ -165,7 +165,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); } catch (final JpaSystemException | PersistenceException | AuthenticationServiceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -202,17 +202,17 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit Collection clients = null; boolean isSelfServiceUser = userToUpdate.isSelfServiceUser(); if(command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER)){ - isSelfServiceUser = command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER); + isSelfServiceUser = command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER); } if(isSelfServiceUser - && command.hasParameter(AppUserConstants.CLIENTS)){ - JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS); - Collection clientIds = new HashSet<>(); - for(JsonElement clientElement : clientsArray){ - clientIds.add(clientElement.getAsLong()); - } - clients = this.clientRepositoryWrapper.findAll(clientIds); + && command.hasParameter(AppUserConstants.CLIENTS)){ + JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS); + Collection clientIds = new HashSet<>(); + for(JsonElement clientElement : clientsArray){ + clientIds.add(clientElement.getAsLong()); + } + clients = this.clientRepositoryWrapper.findAll(clientIds); } final Map changes = userToUpdate.update(command, this.platformPasswordEncoder, clients); @@ -258,7 +258,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); } catch (final JpaSystemException | PersistenceException | AuthenticationServiceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(command, throwable, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/PasswordValidationPolicyReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/PasswordValidationPolicyReadPlatformServiceImpl.java index cd7dab926..f32148238 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/PasswordValidationPolicyReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/PasswordValidationPolicyReadPlatformServiceImpl.java @@ -76,7 +76,7 @@ public class PasswordValidationPolicyReadPlatformServiceImpl implements Password public String schema() { return " pvp.id as id, pvp.active as active, pvp.description as description, pvp.`key` as `key`" - + " from m_password_validation_policy pvp"; + + " from m_password_validation_policy pvp"; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/RoleWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/RoleWritePlatformServiceJpaRepositoryImpl.java index 6cfb2b452..93aaf88c1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/RoleWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/RoleWritePlatformServiceJpaRepositoryImpl.java @@ -93,8 +93,8 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf .withCommandId(command.commandId()) // .build(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .build(); @@ -139,7 +139,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf if (!changes.isEmpty()) { this.roleRepository.saveAndFlush(role); if (changes.containsKey("name")) { - this.topicDomainService.updateTopic( previousRoleName, role, changes); + this.topicDomainService.updateTopic( previousRoleName, role, changes); } } @@ -154,8 +154,8 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf .withCommandId(command.commandId()) // .build(); }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; - handleDataIntegrityIssues(command, throwable, dve); + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + handleDataIntegrityIssues(command, throwable, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .build(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/UserDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/UserDataValidator.java index 57a72c71b..b74eace27 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/UserDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/UserDataValidator.java @@ -118,25 +118,25 @@ public final class UserDataValidator { Boolean isSelfServiceUser = null; if(this.fromApiJsonHelper.parameterExists(AppUserConstants.IS_SELF_SERVICE_USER, element)){ - isSelfServiceUser = this.fromApiJsonHelper.extractBooleanNamed(AppUserConstants.IS_SELF_SERVICE_USER, element); - if(isSelfServiceUser == null){ - baseDataValidator.reset().parameter(AppUserConstants.IS_SELF_SERVICE_USER).trueOrFalseRequired(false); - } + isSelfServiceUser = this.fromApiJsonHelper.extractBooleanNamed(AppUserConstants.IS_SELF_SERVICE_USER, element); + if(isSelfServiceUser == null){ + baseDataValidator.reset().parameter(AppUserConstants.IS_SELF_SERVICE_USER).trueOrFalseRequired(false); + } } if(this.fromApiJsonHelper.parameterExists(AppUserConstants.CLIENTS, element)){ - if(isSelfServiceUser == null || !isSelfServiceUser){ - baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).failWithCode("not.supported.when.isSelfServiceUser.is.false", - "clients parameter is not supported when isSelfServiceUser parameter is false"); - }else{ - final JsonArray clientsArray = this.fromApiJsonHelper.extractJsonArrayNamed(AppUserConstants.CLIENTS, element); - baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientsArray).jsonArrayNotEmpty(); + if(isSelfServiceUser == null || !isSelfServiceUser){ + baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).failWithCode("not.supported.when.isSelfServiceUser.is.false", + "clients parameter is not supported when isSelfServiceUser parameter is false"); + }else{ + final JsonArray clientsArray = this.fromApiJsonHelper.extractJsonArrayNamed(AppUserConstants.CLIENTS, element); + baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientsArray).jsonArrayNotEmpty(); - for(JsonElement client : clientsArray){ - Long clientId = client.getAsLong(); - baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientId).longGreaterThanZero(); - } - } + for(JsonElement client : clientsArray){ + Long clientId = client.getAsLong(); + baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientId).longGreaterThanZero(); + } + } } final String[] roles = this.fromApiJsonHelper.extractArrayNamed("roles", element); @@ -216,25 +216,25 @@ public final class UserDataValidator { Boolean isSelfServiceUser = null; if(this.fromApiJsonHelper.parameterExists(AppUserConstants.IS_SELF_SERVICE_USER, element)){ - isSelfServiceUser = this.fromApiJsonHelper.extractBooleanNamed(AppUserConstants.IS_SELF_SERVICE_USER, element); - if(isSelfServiceUser == null){ - baseDataValidator.reset().parameter(AppUserConstants.IS_SELF_SERVICE_USER).trueOrFalseRequired(false); - } + isSelfServiceUser = this.fromApiJsonHelper.extractBooleanNamed(AppUserConstants.IS_SELF_SERVICE_USER, element); + if(isSelfServiceUser == null){ + baseDataValidator.reset().parameter(AppUserConstants.IS_SELF_SERVICE_USER).trueOrFalseRequired(false); + } } if(this.fromApiJsonHelper.parameterExists(AppUserConstants.CLIENTS, element)){ - if(isSelfServiceUser != null && !isSelfServiceUser){ - baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).failWithCode("not.supported.when.isSelfServiceUser.is.false", - "clients parameter is not supported when isSelfServiceUser parameter is false"); - }else{ - final JsonArray clientsArray = this.fromApiJsonHelper.extractJsonArrayNamed(AppUserConstants.CLIENTS, element); - baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientsArray).jsonArrayNotEmpty(); + if(isSelfServiceUser != null && !isSelfServiceUser){ + baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).failWithCode("not.supported.when.isSelfServiceUser.is.false", + "clients parameter is not supported when isSelfServiceUser parameter is false"); + }else{ + final JsonArray clientsArray = this.fromApiJsonHelper.extractJsonArrayNamed(AppUserConstants.CLIENTS, element); + baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientsArray).jsonArrayNotEmpty(); - for(JsonElement client : clientsArray){ - Long clientId = client.getAsLong(); - baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientId).longGreaterThanZero(); - } - } + for(JsonElement client : clientsArray){ + Long clientId = client.getAsLong(); + baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientId).longGreaterThanZero(); + } + } } throwExceptionIfValidationWarningsExist(dataValidationErrors); diff --git a/fineract-provider/src/test/java/org/apache/fineract/accounting/common/AccountingConstantsTest.java b/fineract-provider/src/test/java/org/apache/fineract/accounting/common/AccountingConstantsTest.java index 21d81f91e..f2022872f 100644 --- a/fineract-provider/src/test/java/org/apache/fineract/accounting/common/AccountingConstantsTest.java +++ b/fineract-provider/src/test/java/org/apache/fineract/accounting/common/AccountingConstantsTest.java @@ -23,8 +23,8 @@ import org.springframework.util.Assert; public class AccountingConstantsTest { - @Test - public void testGetAllFinancialActivities() { - Assert.notEmpty(AccountingConstants.FINANCIAL_ACTIVITY.getAllFinancialActivities(), "static initialization of collection of all enums is broken"); - } + @Test + public void testGetAllFinancialActivities() { + Assert.notEmpty(AccountingConstants.FINANCIAL_ACTIVITY.getAllFinancialActivities(), "static initialization of collection of all enums is broken"); + } } diff --git a/fineract-provider/src/test/java/org/apache/fineract/common/RestAssuredFixture.java b/fineract-provider/src/test/java/org/apache/fineract/common/RestAssuredFixture.java index 92f1e7a2d..90baff46e 100644 --- a/fineract-provider/src/test/java/org/apache/fineract/common/RestAssuredFixture.java +++ b/fineract-provider/src/test/java/org/apache/fineract/common/RestAssuredFixture.java @@ -34,36 +34,36 @@ import com.jayway.restassured.specification.ResponseSpecification; */ public class RestAssuredFixture { - private final int httpPort; + private final int httpPort; - private ResponseSpecification responseSpec; - private RequestSpecification requestSpec; + private ResponseSpecification responseSpec; + private RequestSpecification requestSpec; - public RestAssuredFixture(int httpPort) { - super(); - this.httpPort = httpPort; - Utils.initializeRESTAssured(); - RestAssured.port = httpPort; - this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); - } + public RestAssuredFixture(int httpPort) { + super(); + this.httpPort = httpPort; + Utils.initializeRESTAssured(); + RestAssured.port = httpPort; + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + } - public T httpGet(String apiPath, String jsonAttributeToGetBack) { - return Utils.performServerGet(this.requestSpec, this.responseSpec, getApiPath(apiPath), jsonAttributeToGetBack); - } + public T httpGet(String apiPath, String jsonAttributeToGetBack) { + return Utils.performServerGet(this.requestSpec, this.responseSpec, getApiPath(apiPath), jsonAttributeToGetBack); + } - public T httpGet(String apiPath) { - return httpGet(apiPath, ""); - } + public T httpGet(String apiPath) { + return httpGet(apiPath, ""); + } - private String getApiPath(String apiPath) { + private String getApiPath(String apiPath) { Preconditions.checkArgument(apiPath.startsWith("/"), "trailingApiUrl must start with slash: " + apiPath); return "/fineract-provider/api/v1" + apiPath + "?tenantIdentifier=default"; - } + } - protected String getApiUrl(String apiPath) { - return "http://localhost:" + httpPort + getApiPath(apiPath); + protected String getApiUrl(String apiPath) { + return "http://localhost:" + httpPort + getApiPath(apiPath); } } diff --git a/fineract-provider/src/test/java/org/apache/fineract/infrastructure/core/boot/tests/AbstractSpringBootWithMariaDB4jIntegrationTest.java b/fineract-provider/src/test/java/org/apache/fineract/infrastructure/core/boot/tests/AbstractSpringBootWithMariaDB4jIntegrationTest.java index dbe984f86..a346b8be8 100644 --- a/fineract-provider/src/test/java/org/apache/fineract/infrastructure/core/boot/tests/AbstractSpringBootWithMariaDB4jIntegrationTest.java +++ b/fineract-provider/src/test/java/org/apache/fineract/infrastructure/core/boot/tests/AbstractSpringBootWithMariaDB4jIntegrationTest.java @@ -31,8 +31,8 @@ import org.springframework.test.context.web.WebAppConfiguration; @ActiveProfiles("basicauth") public abstract class AbstractSpringBootWithMariaDB4jIntegrationTest { - // do NOT put any helper methods here! - // it's much better to use composition instead of inheritance - // so write a test util ("fixture") and use it as a field in your test + // do NOT put any helper methods here! + // it's much better to use composition instead of inheritance + // so write a test util ("fixture") and use it as a field in your test } diff --git a/fineract-provider/src/test/java/org/apache/fineract/notification/TopicTest.java b/fineract-provider/src/test/java/org/apache/fineract/notification/TopicTest.java index a02f56af2..2255900bc 100644 --- a/fineract-provider/src/test/java/org/apache/fineract/notification/TopicTest.java +++ b/fineract-provider/src/test/java/org/apache/fineract/notification/TopicTest.java @@ -43,68 +43,68 @@ import org.mockito.Mock; @org.junit.Ignore // see FINERACT-776 public class TopicTest { - @Mock - private OfficeRepository officeRepository; - - @Mock - private RoleRepository roleRepository; - - @Mock - private TopicWritePlatformService topicWritePltfService; - - @Mock - private TopicRepository topicRepository; - - @Mock - private TopicSubscriberWritePlatformService topicSubscriberWritePltfService; - - @Mock - private AppUserRepository appUserRepository; - - @Test - public void testTopicStorage() { - Office office = officeRepository.getOne(1L); - Role role = new Role("New Member_Type", "Testing topic creation"); - - String title = role.getName() + " of " + office.getName(); - Long entityId = office.getId(); + @Mock + private OfficeRepository officeRepository; + + @Mock + private RoleRepository roleRepository; + + @Mock + private TopicWritePlatformService topicWritePltfService; + + @Mock + private TopicRepository topicRepository; + + @Mock + private TopicSubscriberWritePlatformService topicSubscriberWritePltfService; + + @Mock + private AppUserRepository appUserRepository; + + @Test + public void testTopicStorage() { + Office office = officeRepository.getOne(1L); + Role role = new Role("New Member_Type", "Testing topic creation"); + + String title = role.getName() + " of " + office.getName(); + Long entityId = office.getId(); String entityType = ""; if (office.getParent() == null) { - entityType = "OFFICE"; + entityType = "OFFICE"; } else { - entityType = "BRANCH"; + entityType = "BRANCH"; } - Topic topic = new Topic(title, true, entityId, entityType, role.getName().toUpperCase()); + Topic topic = new Topic(title, true, entityId, entityType, role.getName().toUpperCase()); - when(this.officeRepository.getOne(1L)).thenReturn(office); - when(this.roleRepository.save(role)).thenReturn(role); - when(this.topicWritePltfService.create(refEq(topic))).thenReturn(1L); - - this.roleRepository.save(role); - Long topicId = this.topicWritePltfService.create(topic); - - verify(this.roleRepository, times(1)).save(role); - verify(this.topicWritePltfService, times(1)).create(refEq(topic)); - assertEquals(topicId, new Long(1)); - - } - - @Test - public void testTopicSubscriberStorage() { - AppUser user = appUserRepository.findById(1L).get(); - Topic topic = topicRepository.findById(1L).get(); - - TopicSubscriber topicSubscriber = new TopicSubscriber(topic, user, new Date()); - - when(this.appUserRepository.getOne(1L)).thenReturn(user); - when(this.topicRepository.getOne(1L)).thenReturn(topic); - when(this.topicSubscriberWritePltfService.create(refEq(topicSubscriber))).thenReturn(1L); - - Long subscriberId = this.topicSubscriberWritePltfService.create(topicSubscriber); - - verify(this.topicSubscriberWritePltfService, times(1)).create(refEq(topicSubscriber)); - assertEquals(subscriberId, new Long(1)); - - } - + when(this.officeRepository.getOne(1L)).thenReturn(office); + when(this.roleRepository.save(role)).thenReturn(role); + when(this.topicWritePltfService.create(refEq(topic))).thenReturn(1L); + + this.roleRepository.save(role); + Long topicId = this.topicWritePltfService.create(topic); + + verify(this.roleRepository, times(1)).save(role); + verify(this.topicWritePltfService, times(1)).create(refEq(topic)); + assertEquals(topicId, new Long(1)); + + } + + @Test + public void testTopicSubscriberStorage() { + AppUser user = appUserRepository.findById(1L).get(); + Topic topic = topicRepository.findById(1L).get(); + + TopicSubscriber topicSubscriber = new TopicSubscriber(topic, user, new Date()); + + when(this.appUserRepository.getOne(1L)).thenReturn(user); + when(this.topicRepository.getOne(1L)).thenReturn(topic); + when(this.topicSubscriberWritePltfService.create(refEq(topicSubscriber))).thenReturn(1L); + + Long subscriberId = this.topicSubscriberWritePltfService.create(topicSubscriber); + + verify(this.topicSubscriberWritePltfService, times(1)).create(refEq(topicSubscriber)); + assertEquals(subscriberId, new Long(1)); + + } + }