applying format across the project and fixing all warnings

Conflicts:
	mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java
	mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanAssembler.java
	mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformService.java
	mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java
This commit is contained in:
Vishwas Babu A J
2014-03-01 04:50:17 -08:00
parent c404dfdeb1
commit 1c1e83eb5e
239 changed files with 2881 additions and 2851 deletions
@@ -109,9 +109,8 @@ public class AccountingConstants {
public static enum LOAN_PRODUCT_ACCOUNTING_DATA_PARAMS { public static enum LOAN_PRODUCT_ACCOUNTING_DATA_PARAMS {
FUND_SOURCE("fundSourceAccount"), LOAN_PORTFOLIO("loanPortfolioAccount"), INTEREST_ON_LOANS("interestOnLoanAccount"), INCOME_FROM_FEES( FUND_SOURCE("fundSourceAccount"), LOAN_PORTFOLIO("loanPortfolioAccount"), INTEREST_ON_LOANS("interestOnLoanAccount"), INCOME_FROM_FEES(
"incomeFromFeeAccount"), INCOME_FROM_PENALTIES("incomeFromPenaltyAccount"), LOSSES_WRITTEN_OFF("writeOffAccount"), OVERPAYMENT( "incomeFromFeeAccount"), INCOME_FROM_PENALTIES("incomeFromPenaltyAccount"), LOSSES_WRITTEN_OFF("writeOffAccount"), OVERPAYMENT(
"overpaymentLiabilityAccount"), INTEREST_RECEIVABLE("receivableInterestAccount"), FEES_RECEIVABLE( "overpaymentLiabilityAccount"), INTEREST_RECEIVABLE("receivableInterestAccount"), FEES_RECEIVABLE("receivableFeeAccount"), PENALTIES_RECEIVABLE(
"receivableFeeAccount"), PENALTIES_RECEIVABLE("receivablePenaltyAccount"), TRANSFERS_SUSPENSE( "receivablePenaltyAccount"), TRANSFERS_SUSPENSE("transfersInSuspenseAccount"), INCOME_ACCOUNT_ID("incomeAccount");
"transfersInSuspenseAccount"), INCOME_ACCOUNT_ID("incomeAccount");
private final String value; private final String value;
@@ -129,12 +128,10 @@ public class AccountingConstants {
} }
} }
/*** Accounting placeholders for cash based accounting for savings products ***/ /*** Accounting placeholders for cash based accounting for savings products ***/
public static enum CASH_ACCOUNTS_FOR_SAVINGS { public static enum CASH_ACCOUNTS_FOR_SAVINGS {
SAVINGS_REFERENCE(1), SAVINGS_CONTROL(2), INTEREST_ON_SAVINGS(3), INCOME_FROM_FEES(4), INCOME_FROM_PENALTIES(5), TRANSFERS_SUSPENSE( SAVINGS_REFERENCE(1), SAVINGS_CONTROL(2), INTEREST_ON_SAVINGS(3), INCOME_FROM_FEES(4), INCOME_FROM_PENALTIES(5), TRANSFERS_SUSPENSE(
10),OVERDRAFT_PORTFOLIO_CONTROL(11),INCOME_FROM_INTEREST(12), 10), OVERDRAFT_PORTFOLIO_CONTROL(11), INCOME_FROM_INTEREST(12), LOSSES_WRITTEN_OFF(13);
LOSSES_WRITTEN_OFF(13);
private final Integer value; private final Integer value;
@@ -174,8 +171,8 @@ public class AccountingConstants {
"interestOnSavingsAccountId"), PAYMENT_CHANNEL_FUND_SOURCE_MAPPING("paymentChannelToFundSourceMappings"), PAYMENT_TYPE( "interestOnSavingsAccountId"), PAYMENT_CHANNEL_FUND_SOURCE_MAPPING("paymentChannelToFundSourceMappings"), PAYMENT_TYPE(
"paymentTypeId"), FUND_SOURCE("fundSourceAccountId"), TRANSFERS_SUSPENSE("transfersInSuspenseAccountId"), FEE_INCOME_ACCOUNT_MAPPING( "paymentTypeId"), FUND_SOURCE("fundSourceAccountId"), TRANSFERS_SUSPENSE("transfersInSuspenseAccountId"), FEE_INCOME_ACCOUNT_MAPPING(
"feeToIncomeAccountMappings"), PENALTY_INCOME_ACCOUNT_MAPPING("penaltyToIncomeAccountMappings"), CHARGE_ID("chargeId"), INCOME_ACCOUNT_ID( "feeToIncomeAccountMappings"), PENALTY_INCOME_ACCOUNT_MAPPING("penaltyToIncomeAccountMappings"), CHARGE_ID("chargeId"), INCOME_ACCOUNT_ID(
"incomeAccountId"),OVERDRAFT_PORTFOLIO_CONTROL("overdraftPortfolioControlId"),INCOME_FROM_INTEREST("incomeFromInterestId"), "incomeAccountId"), OVERDRAFT_PORTFOLIO_CONTROL("overdraftPortfolioControlId"), INCOME_FROM_INTEREST("incomeFromInterestId"), LOSSES_WRITTEN_OFF(
LOSSES_WRITTEN_OFF("writeOffAccountId"); "writeOffAccountId");
private final String value; private final String value;
@@ -192,14 +189,13 @@ public class AccountingConstants {
return this.value; return this.value;
} }
} }
public static enum SAVINGS_PRODUCT_ACCOUNTING_DATA_PARAMS { public static enum SAVINGS_PRODUCT_ACCOUNTING_DATA_PARAMS {
SAVINGS_REFERENCE("savingsReferenceAccount"), SAVINGS_CONTROL("savingsControlAccount"), INCOME_FROM_FEES( SAVINGS_REFERENCE("savingsReferenceAccount"), SAVINGS_CONTROL("savingsControlAccount"), INCOME_FROM_FEES("incomeFromFeeAccount"), INCOME_FROM_PENALTIES(
"incomeFromFeeAccount"), INCOME_FROM_PENALTIES("incomeFromPenaltyAccount"), INTEREST_ON_SAVINGS( "incomeFromPenaltyAccount"), INTEREST_ON_SAVINGS("interestOnSavingsAccount"), PAYMENT_TYPE("paymentType"), FUND_SOURCE(
"interestOnSavingsAccount"), PAYMENT_TYPE("paymentType"), FUND_SOURCE("fundSourceAccount"), "fundSourceAccount"), TRANSFERS_SUSPENSE("transfersInSuspenseAccount"), PENALTY_INCOME_ACCOUNT_MAPPING(
TRANSFERS_SUSPENSE("transfersInSuspenseAccount"), PENALTY_INCOME_ACCOUNT_MAPPING("penaltyToIncomeAccountMappings"), CHARGE_ID("charge"), INCOME_ACCOUNT_ID( "penaltyToIncomeAccountMappings"), CHARGE_ID("charge"), INCOME_ACCOUNT_ID("incomeAccount"), OVERDRAFT_PORTFOLIO_CONTROL(
"incomeAccount"),OVERDRAFT_PORTFOLIO_CONTROL("overdraftPortfolioControl"),INCOME_FROM_INTEREST("incomeFromInterest"), "overdraftPortfolioControl"), INCOME_FROM_INTEREST("incomeFromInterest"), LOSSES_WRITTEN_OFF("writeOffAccount");
LOSSES_WRITTEN_OFF("writeOffAccount");
private final String value; private final String value;
@@ -217,7 +213,6 @@ public class AccountingConstants {
} }
} }
public static final String ASSESTS_TAG_OPTION_CODE_NAME = "AssetAccountTags"; public static final String ASSESTS_TAG_OPTION_CODE_NAME = "AssetAccountTags";
public static final String LIABILITIES_TAG_OPTION_CODE_NAME = "LiabilityAccountTags"; public static final String LIABILITIES_TAG_OPTION_CODE_NAME = "LiabilityAccountTags";
public static final String EQUITY_TAG_OPTION_CODE_NAME = "EquityAccountTags"; public static final String EQUITY_TAG_OPTION_CODE_NAME = "EquityAccountTags";
@@ -124,7 +124,7 @@ public class GLAccountsApiResource {
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(false, runningBalance); JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(false, runningBalance);
GLAccountData glAccountData = this.glAccountReadPlatformService.retrieveGLAccountById(glAccountId,associationParametersData); GLAccountData glAccountData = this.glAccountReadPlatformService.retrieveGLAccountById(glAccountId, associationParametersData);
if (settings.isTemplate()) { if (settings.isTemplate()) {
glAccountData = handleTemplate(glAccountData); glAccountData = handleTemplate(glAccountData);
} }
@@ -35,7 +35,6 @@ public class GLAccountData {
private final CodeValueData tagId; private final CodeValueData tagId;
private final Long organizationRunningBalance; private final Long organizationRunningBalance;
// templates // templates
final List<EnumOptionData> accountTypeOptions; final List<EnumOptionData> accountTypeOptions;
final List<EnumOptionData> usageOptions; final List<EnumOptionData> usageOptions;
@@ -52,7 +51,7 @@ public class GLAccountData {
public GLAccountData(final Long id, final String name, final Long parentId, final String glCode, final boolean disabled, public GLAccountData(final Long id, final String name, final Long parentId, final String glCode, final boolean disabled,
final boolean manualEntriesAllowed, final EnumOptionData type, final EnumOptionData usage, final String description, final boolean manualEntriesAllowed, final EnumOptionData type, final EnumOptionData usage, final String description,
final String nameDecorated, final CodeValueData tagId,final Long organizationRunningBalance) { final String nameDecorated, final CodeValueData tagId, final Long organizationRunningBalance) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.parentId = parentId; this.parentId = parentId;
@@ -97,7 +96,7 @@ public class GLAccountData {
this.description = accountData.description; this.description = accountData.description;
this.nameDecorated = accountData.nameDecorated; this.nameDecorated = accountData.nameDecorated;
this.tagId = accountData.tagId; this.tagId = accountData.tagId;
this.organizationRunningBalance = accountData.organizationRunningBalance; this.organizationRunningBalance = accountData.organizationRunningBalance;
this.accountTypeOptions = accountTypeOptions; this.accountTypeOptions = accountTypeOptions;
this.usageOptions = usageOptions; this.usageOptions = usageOptions;
this.assetHeaderAccountOptions = assetHeaderAccountOptions; this.assetHeaderAccountOptions = assetHeaderAccountOptions;
@@ -131,7 +130,8 @@ public class GLAccountData {
final CodeValueData tagId = null; final CodeValueData tagId = null;
final Long organizationRunningBalance = null; final Long organizationRunningBalance = null;
return new GLAccountData(id, name, parentId, glCode, disabled, manualEntriesAllowed, type, usage, description, nameDecorated, tagId,organizationRunningBalance); return new GLAccountData(id, name, parentId, glCode, disabled, manualEntriesAllowed, type, usage, description, nameDecorated,
tagId, organizationRunningBalance);
} }
public GLAccountData(final Long id, final String name, final String glCode) { public GLAccountData(final Long id, final String name, final String glCode) {
@@ -17,7 +17,7 @@ public interface GLAccountReadPlatformService {
List<GLAccountData> retrieveAllGLAccounts(Integer accountClassification, String searchParam, Integer usage, List<GLAccountData> retrieveAllGLAccounts(Integer accountClassification, String searchParam, Integer usage,
Boolean manualTransactionsAllowed, Boolean disabled, JournalEntryAssociationParametersData associationParametersData); Boolean manualTransactionsAllowed, Boolean disabled, JournalEntryAssociationParametersData associationParametersData);
GLAccountData retrieveGLAccountById(long glAccountId,JournalEntryAssociationParametersData associationParametersData); GLAccountData retrieveGLAccountById(long glAccountId, JournalEntryAssociationParametersData associationParametersData);
List<GLAccountData> retrieveAllEnabledDetailGLAccounts(); List<GLAccountData> retrieveAllEnabledDetailGLAccounts();
@@ -43,27 +43,27 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe
private static final class GLAccountMapper implements RowMapper<GLAccountData> { private static final class GLAccountMapper implements RowMapper<GLAccountData> {
private final JournalEntryAssociationParametersData associationParametersData; private final JournalEntryAssociationParametersData associationParametersData;
public GLAccountMapper(final JournalEntryAssociationParametersData associationParametersData) { public GLAccountMapper(final JournalEntryAssociationParametersData associationParametersData) {
if(associationParametersData == null){ if (associationParametersData == null) {
this.associationParametersData = new JournalEntryAssociationParametersData(); this.associationParametersData = new JournalEntryAssociationParametersData();
}else{ } else {
this.associationParametersData = associationParametersData; this.associationParametersData = associationParametersData;
} }
} }
public String schema() { public String schema() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(" gl.id as id, name as name, parent_id as parentId, gl_code as glCode, disabled as disabled, manual_journal_entries_allowed as manualEntriesAllowed, ") sb.append(
.append("classification_enum as classification, account_usage as accountUsage, gl.description as description, ") " gl.id as id, name as name, parent_id as parentId, gl_code as glCode, disabled as disabled, manual_journal_entries_allowed as manualEntriesAllowed, ")
.append(nameDecoratedBaseOnHierarchy).append(" as nameDecorated, ") .append("classification_enum as classification, account_usage as accountUsage, gl.description as description, ")
.append("cv.id as codeId, cv.code_value as codeValue "); .append(nameDecoratedBaseOnHierarchy).append(" as nameDecorated, ")
if(this.associationParametersData.isRunningBalanceRequired()){ .append("cv.id as codeId, cv.code_value as codeValue ");
if (this.associationParametersData.isRunningBalanceRequired()) {
sb.append(",gl_j.organization_running_balance as organizationRunningBalance "); sb.append(",gl_j.organization_running_balance as organizationRunningBalance ");
} }
sb.append("from acc_gl_account gl left join m_code_value cv on tag_id=cv.id "); sb.append("from acc_gl_account gl left join m_code_value cv on tag_id=cv.id ");
if(this.associationParametersData.isRunningBalanceRequired()){ if (this.associationParametersData.isRunningBalanceRequired()) {
sb.append("left outer Join acc_gl_journal_entry gl_j on gl_j.account_id = gl.id"); sb.append("left outer Join acc_gl_journal_entry gl_j on gl_j.account_id = gl.id");
} }
return sb.toString(); return sb.toString();
@@ -88,7 +88,7 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe
final String codeValue = rs.getString("codeValue"); final String codeValue = rs.getString("codeValue");
final CodeValueData tagId = CodeValueData.instance(codeId, codeValue); final CodeValueData tagId = CodeValueData.instance(codeId, codeValue);
Long organizationRunningBalance = null; Long organizationRunningBalance = null;
if(associationParametersData.isRunningBalanceRequired()){ if (associationParametersData.isRunningBalanceRequired()) {
organizationRunningBalance = rs.getLong("organizationRunningBalance"); organizationRunningBalance = rs.getLong("organizationRunningBalance");
} }
return new GLAccountData(id, name, parentId, glCode, disabled, manualEntriesAllowed, accountType, usage, description, return new GLAccountData(id, name, parentId, glCode, disabled, manualEntriesAllowed, accountType, usage, description,
@@ -110,9 +110,9 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe
final GLAccountMapper rm = new GLAccountMapper(associationParametersData); final GLAccountMapper rm = new GLAccountMapper(associationParametersData);
String sql = "select " + rm.schema(); String sql = "select " + rm.schema();
// append SQL statement for fetching account totals // append SQL statement for fetching account totals
if(associationParametersData.isRunningBalanceRequired()){ if (associationParametersData.isRunningBalanceRequired()) {
sql = sql + " and gl_j.id in (select t1.id from (SELECT t2.id , max(concat(t2.entry_date,t2.id)) " sql = sql + " and gl_j.id in (select t1.id from (SELECT t2.id , max(concat(t2.entry_date,t2.id)) "
+ "FROM acc_gl_journal_entry t2 WHERE is_running_balance_calculated = 1 GROUP BY t2.account_id DESC) t1)"; + "FROM acc_gl_journal_entry t2 WHERE is_running_balance_calculated = 1 GROUP BY t2.account_id DESC) t1)";
} }
final Object[] paramaterArray = new Object[3]; final Object[] paramaterArray = new Object[3];
int arrayPos = 0; int arrayPos = 0;
@@ -184,17 +184,17 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe
} }
@Override @Override
public GLAccountData retrieveGLAccountById(final long glAccountId,JournalEntryAssociationParametersData associationParametersData) { public GLAccountData retrieveGLAccountById(final long glAccountId, JournalEntryAssociationParametersData associationParametersData) {
try { try {
final GLAccountMapper rm = new GLAccountMapper(associationParametersData); final GLAccountMapper rm = new GLAccountMapper(associationParametersData);
final StringBuilder sql = new StringBuilder(); final StringBuilder sql = new StringBuilder();
sql.append("select ").append(rm.schema()); sql.append("select ").append(rm.schema());
if(associationParametersData.isRunningBalanceRequired()){ if (associationParametersData.isRunningBalanceRequired()) {
sql.append(" and gl_j.is_running_balance_calculated = 1 "); sql.append(" and gl_j.is_running_balance_calculated = 1 ");
} }
sql.append("where gl.id = ?"); sql.append("where gl.id = ?");
if(associationParametersData.isRunningBalanceRequired()){ if (associationParametersData.isRunningBalanceRequired()) {
sql.append(" ORDER BY gl_j.entry_date DESC,gl_j.id DESC LIMIT 1"); sql.append(" ORDER BY gl_j.entry_date DESC,gl_j.id DESC LIMIT 1");
} }
final GLAccountData glAccountData = this.jdbcTemplate.queryForObject(sql.toString(), rm, new Object[] { glAccountId }); final GLAccountData glAccountData = this.jdbcTemplate.queryForObject(sql.toString(), rm, new Object[] { glAccountId });
@@ -207,7 +207,8 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe
@Override @Override
public List<GLAccountData> retrieveAllEnabledDetailGLAccounts(final GLAccountType accountType) { public List<GLAccountData> retrieveAllEnabledDetailGLAccounts(final GLAccountType accountType) {
return retrieveAllGLAccounts(accountType.getValue(), null, GLAccountUsage.DETAIL.getValue(), null, false, new JournalEntryAssociationParametersData()); return retrieveAllGLAccounts(accountType.getValue(), null, GLAccountUsage.DETAIL.getValue(), null, false,
new JournalEntryAssociationParametersData());
} }
@Override @Override
@@ -236,7 +237,8 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe
@Override @Override
public List<GLAccountData> retrieveAllEnabledHeaderGLAccounts(final GLAccountType accountType) { public List<GLAccountData> retrieveAllEnabledHeaderGLAccounts(final GLAccountType accountType) {
return retrieveAllGLAccounts(accountType.getValue(), null, GLAccountUsage.HEADER.getValue(), null, false, new JournalEntryAssociationParametersData()); return retrieveAllGLAccounts(accountType.getValue(), null, GLAccountUsage.HEADER.getValue(), null, false,
new JournalEntryAssociationParametersData());
} }
@Override @Override
@@ -77,11 +77,11 @@ public class JournalEntriesApiResource {
public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("officeId") final Long officeId, public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("officeId") final Long officeId,
@QueryParam("glAccountId") final Long glAccountId, @QueryParam("manualEntriesOnly") final Boolean onlyManualEntries, @QueryParam("glAccountId") final Long glAccountId, @QueryParam("manualEntriesOnly") final Boolean onlyManualEntries,
@QueryParam("fromDate") final DateParam fromDateParam, @QueryParam("toDate") final DateParam toDateParam, @QueryParam("fromDate") final DateParam fromDateParam, @QueryParam("toDate") final DateParam toDateParam,
@QueryParam("transactionId") final String transactionId, @QueryParam("entityType") final Integer entityType, @QueryParam("offset") final Integer offset, @QueryParam("transactionId") final String transactionId, @QueryParam("entityType") final Integer entityType,
@QueryParam("limit") final Integer limit, @QueryParam("orderBy") final String orderBy, @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit,
@QueryParam("sortOrder") final String sortOrder, @QueryParam("locale") final String locale, @QueryParam("orderBy") final String orderBy, @QueryParam("sortOrder") final String sortOrder,
@QueryParam("dateFormat") final String dateFormat,@QueryParam("runningBalance") final boolean runningBalance, @QueryParam("locale") final String locale, @QueryParam("dateFormat") final String dateFormat,
@QueryParam("transactionDetails") final boolean transactionDetails) { @QueryParam("runningBalance") final boolean runningBalance, @QueryParam("transactionDetails") final boolean transactionDetails) {
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
@@ -95,7 +95,8 @@ public class JournalEntriesApiResource {
} }
final SearchParameters searchParameters = SearchParameters.forJournalEntries(officeId, offset, limit, orderBy, sortOrder); final SearchParameters searchParameters = SearchParameters.forJournalEntries(officeId, offset, limit, orderBy, sortOrder);
JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(transactionDetails, runningBalance); JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(transactionDetails,
runningBalance);
final Page<JournalEntryData> glJournalEntries = this.journalEntryReadPlatformService.retrieveAll(searchParameters, glAccountId, final Page<JournalEntryData> glJournalEntries = this.journalEntryReadPlatformService.retrieveAll(searchParameters, glAccountId,
onlyManualEntries, fromDate, toDate, transactionId, entityType, associationParametersData); onlyManualEntries, fromDate, toDate, transactionId, entityType, associationParametersData);
@@ -111,8 +112,10 @@ public class JournalEntriesApiResource {
@QueryParam("runningBalance") final boolean runningBalance, @QueryParam("transactionDetails") final boolean transactionDetails) { @QueryParam("runningBalance") final boolean runningBalance, @QueryParam("transactionDetails") final boolean transactionDetails) {
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(transactionDetails, runningBalance); JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(transactionDetails,
final JournalEntryData glJournalEntryData = this.journalEntryReadPlatformService.retrieveGLJournalEntryById(journalEntryId, associationParametersData); runningBalance);
final JournalEntryData glJournalEntryData = this.journalEntryReadPlatformService.retrieveGLJournalEntryById(journalEntryId,
associationParametersData);
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.apiJsonSerializerService.serialize(settings, glJournalEntryData, RESPONSE_DATA_PARAMETERS); return this.apiJsonSerializerService.serialize(settings, glJournalEntryData, RESPONSE_DATA_PARAMETERS);
@@ -1,28 +1,24 @@
package org.mifosplatform.accounting.journalentry.data; package org.mifosplatform.accounting.journalentry.data;
public class JournalEntryAssociationParametersData { public class JournalEntryAssociationParametersData {
private final boolean transactionDetailsRequired; private final boolean transactionDetailsRequired;
private final boolean runningBalanceRequired; private final boolean runningBalanceRequired;
public JournalEntryAssociationParametersData() { public JournalEntryAssociationParametersData() {
this.transactionDetailsRequired = false; this.transactionDetailsRequired = false;
this.runningBalanceRequired = false; this.runningBalanceRequired = false;
} }
public JournalEntryAssociationParametersData(final boolean transactionDetailsRequired , final boolean runningBalanceRequired) { public JournalEntryAssociationParametersData(final boolean transactionDetailsRequired, final boolean runningBalanceRequired) {
this.transactionDetailsRequired = transactionDetailsRequired; this.transactionDetailsRequired = transactionDetailsRequired;
this.runningBalanceRequired = runningBalanceRequired; this.runningBalanceRequired = runningBalanceRequired;
} }
public boolean isTransactionDetailsRequired() { public boolean isTransactionDetailsRequired() {
return this.transactionDetailsRequired; return this.transactionDetailsRequired;
} }
public boolean isRunningBalanceRequired() { public boolean isRunningBalanceRequired() {
return this.runningBalanceRequired; return this.runningBalanceRequired;
} }
@@ -13,7 +13,7 @@ import org.mifosplatform.organisation.monetary.data.CurrencyData;
/** /**
* Immutable object representing a General Ledger Account * Immutable object representing a General Ledger Account
* *
* Note: no getter/setters required as google will produce json from fields of * Note: no getter/setters required as google will produce json from fields of
* object. * object.
*/ */
@@ -71,7 +71,7 @@ public class JournalEntryData {
final Boolean manualEntry, final EnumOptionData entityType, final Long entityId, final Long createdByUserId, final Boolean manualEntry, final EnumOptionData entityType, final Long entityId, final Long createdByUserId,
final LocalDate createdDate, final String createdByUserName, final String comments, final Boolean reversed, final LocalDate createdDate, final String createdByUserName, final String comments, final Boolean reversed,
final String referenceNumber, final BigDecimal officeRunningBalance, final BigDecimal organizationRunningBalance, final String referenceNumber, final BigDecimal officeRunningBalance, final BigDecimal organizationRunningBalance,
final Boolean runningBalanceComputed,final TransactionDetailData transactionDetailData, final CurrencyData currency) { final Boolean runningBalanceComputed, final TransactionDetailData transactionDetailData, final CurrencyData currency) {
this.id = id; this.id = id;
this.officeId = officeId; this.officeId = officeId;
this.officeName = officeName; this.officeName = officeName;
@@ -31,7 +31,7 @@ public class SavingsTransactionDTO {
public SavingsTransactionDTO(final Long officeId, final Long paymentTypeId, final String transactionId, final Date transactionDate, public SavingsTransactionDTO(final Long officeId, final Long paymentTypeId, final String transactionId, final Date transactionDate,
final SavingsAccountTransactionEnumData transactionType, final BigDecimal amount, final boolean reversed, final SavingsAccountTransactionEnumData transactionType, final BigDecimal amount, final boolean reversed,
final List<ChargePaymentDTO> feePayments, final List<ChargePaymentDTO> penaltyPayments,final BigDecimal overdraftAmount) { final List<ChargePaymentDTO> feePayments, final List<ChargePaymentDTO> penaltyPayments, final BigDecimal overdraftAmount) {
this.paymentTypeId = paymentTypeId; this.paymentTypeId = paymentTypeId;
this.transactionId = transactionId; this.transactionId = transactionId;
this.transactionDate = transactionDate; this.transactionDate = transactionDate;
@@ -80,13 +80,12 @@ public class SavingsTransactionDTO {
return this.feePayments; return this.feePayments;
} }
public BigDecimal getOverdraftAmount() { public BigDecimal getOverdraftAmount() {
return this.overdraftAmount; return this.overdraftAmount;
} }
public boolean isOverdraftTransaction(){ public boolean isOverdraftTransaction() {
return this.overdraftAmount!=null && this.overdraftAmount.doubleValue() > 0; return this.overdraftAmount != null && this.overdraftAmount.doubleValue() > 0;
} }
} }
@@ -33,15 +33,15 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
@ManyToOne @ManyToOne
@JoinColumn(name = "office_id", nullable = false) @JoinColumn(name = "office_id", nullable = false)
private Office office; private Office office;
@ManyToOne(optional = true) @ManyToOne(optional = true)
@JoinColumn(name = "payment_details_id", nullable = true) @JoinColumn(name = "payment_details_id", nullable = true)
private PaymentDetail paymentDetail; private PaymentDetail paymentDetail;
@ManyToOne @ManyToOne
@JoinColumn(name = "account_id", nullable = false) @JoinColumn(name = "account_id", nullable = false)
private GLAccount glAccount; private GLAccount glAccount;
@Column(name = "currency_code", length = 3, nullable = false) @Column(name = "currency_code", length = 3, nullable = false)
private String currencyCode; private String currencyCode;
@@ -59,7 +59,7 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
@ManyToOne @ManyToOne
@JoinColumn(name = "savings_transaction_id", nullable = false) @JoinColumn(name = "savings_transaction_id", nullable = false)
private SavingsAccountTransaction savingsTransaction; private SavingsAccountTransaction savingsTransaction;
@Column(name = "reversed", nullable = false) @Column(name = "reversed", nullable = false)
private boolean reversed = false; private boolean reversed = false;
@@ -87,23 +87,25 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "ref_num") @Column(name = "ref_num")
private String referenceNumber; private String referenceNumber;
public static JournalEntry createNew(final Office office, final PaymentDetail paymentDetail, final GLAccount glAccount, final String currencyCode, public static JournalEntry createNew(final Office office, final PaymentDetail paymentDetail, final GLAccount glAccount,
final String transactionId, final boolean manualEntry, final Date transactionDate, final JournalEntryType journalEntryType, final String currencyCode, final String transactionId, final boolean manualEntry, final Date transactionDate,
final BigDecimal amount, final String description, final Integer entityType, final Long entityId, final String referenceNumber, final JournalEntryType journalEntryType, final BigDecimal amount, final String description, final Integer entityType,
final LoanTransaction loanTransaction, final SavingsAccountTransaction savingsTransaction) { final Long entityId, final String referenceNumber, final LoanTransaction loanTransaction,
return new JournalEntry(office, paymentDetail, glAccount, currencyCode, transactionId, manualEntry, transactionDate, journalEntryType.getValue(), final SavingsAccountTransaction savingsTransaction) {
amount, description, entityType, entityId, referenceNumber, loanTransaction, savingsTransaction); return new JournalEntry(office, paymentDetail, glAccount, currencyCode, transactionId, manualEntry, transactionDate,
journalEntryType.getValue(), amount, description, entityType, entityId, referenceNumber, loanTransaction,
savingsTransaction);
} }
protected JournalEntry() { protected JournalEntry() {
// //
} }
public JournalEntry(final Office office, final PaymentDetail paymentDetail, final GLAccount glAccount, final String currencyCode, final String transactionId, public JournalEntry(final Office office, final PaymentDetail paymentDetail, final GLAccount glAccount, final String currencyCode,
final boolean manualEntry, final Date transactionDate, final Integer type, final BigDecimal amount, final String description, final String transactionId, final boolean manualEntry, final Date transactionDate, final Integer type, final BigDecimal amount,
final Integer entityType, final Long entityId, final String referenceNumber, final LoanTransaction loanTransaction, final String description, final Integer entityType, final Long entityId, final String referenceNumber,
final SavingsAccountTransaction savingsTransaction) { final LoanTransaction loanTransaction, final SavingsAccountTransaction savingsTransaction) {
this.office = office; this.office = office;
this.glAccount = glAccount; this.glAccount = glAccount;
this.reversalJournalEntry = null; this.reversalJournalEntry = null;
@@ -118,9 +120,9 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
this.entityId = entityId; this.entityId = entityId;
this.referenceNumber = referenceNumber; this.referenceNumber = referenceNumber;
this.currencyCode = currencyCode; this.currencyCode = currencyCode;
this.loanTransaction = loanTransaction; this.loanTransaction = loanTransaction;
this.savingsTransaction = savingsTransaction; this.savingsTransaction = savingsTransaction;
this.paymentDetail=paymentDetail; this.paymentDetail = paymentDetail;
} }
public boolean isDebitEntry() { public boolean isDebitEntry() {
@@ -163,18 +165,16 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
return this.currencyCode; return this.currencyCode;
} }
public LoanTransaction getLoanTransaction() { public LoanTransaction getLoanTransaction() {
return this.loanTransaction; return this.loanTransaction;
} }
public SavingsAccountTransaction getSavingsTransaction() { public SavingsAccountTransaction getSavingsTransaction() {
return this.savingsTransaction; return this.savingsTransaction;
} }
public PaymentDetail getPaymentDetails(){ public PaymentDetail getPaymentDetails() {
return this.paymentDetail; return this.paymentDetail;
} }
} }
@@ -173,7 +173,7 @@ public class AccountingProcessorHelper {
} }
final SavingsTransactionDTO transaction = new SavingsTransactionDTO(transactionOfficeId, paymentTypeId, transactionId, final SavingsTransactionDTO transaction = new SavingsTransactionDTO(transactionOfficeId, paymentTypeId, transactionId,
transactionDate, transactionType, amount, reversed, feePayments, penaltyPayments,overdraftAmount); transactionDate, transactionType, amount, reversed, feePayments, penaltyPayments, overdraftAmount);
newSavingsTransactions.add(transaction); newSavingsTransactions.add(transaction);
@@ -49,25 +49,24 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess
if (savingsTransactionDTO.getTransactionType().isWithdrawal() && savingsTransactionDTO.isOverdraftTransaction()) { if (savingsTransactionDTO.getTransactionType().isWithdrawal() && savingsTransactionDTO.isOverdraftTransaction()) {
this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode,
CASH_ACCOUNTS_FOR_SAVINGS.OVERDRAFT_PORTFOLIO_CONTROL, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, savingsProductId, CASH_ACCOUNTS_FOR_SAVINGS.OVERDRAFT_PORTFOLIO_CONTROL, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE,
paymentTypeId, savingsId, transactionId, transactionDate, overdraftAmount, isReversal); savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, overdraftAmount, isReversal);
if(amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) == 1){ if (amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) == 1) {
this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode,
CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, savingsProductId, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, savingsProductId,
paymentTypeId, savingsId, transactionId, transactionDate, amount.subtract(overdraftAmount), isReversal); paymentTypeId, savingsId, transactionId, transactionDate, amount.subtract(overdraftAmount), isReversal);
} }
} } else if (savingsTransactionDTO.getTransactionType().isDeposit() && savingsTransactionDTO.isOverdraftTransaction()) {
else if (savingsTransactionDTO.getTransactionType().isDeposit() && savingsTransactionDTO.isOverdraftTransaction()) {
this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode,
CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, CASH_ACCOUNTS_FOR_SAVINGS.OVERDRAFT_PORTFOLIO_CONTROL, savingsProductId, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, CASH_ACCOUNTS_FOR_SAVINGS.OVERDRAFT_PORTFOLIO_CONTROL,
paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal);
if(amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) == 1){ if (amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) == 1) {
this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode,
CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, savingsProductId, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, savingsProductId,
paymentTypeId, savingsId, transactionId, transactionDate, amount.subtract(overdraftAmount), isReversal); paymentTypeId, savingsId, transactionId, transactionDate, amount.subtract(overdraftAmount), isReversal);
} }
} }
/** Handle Deposits and reversals of deposits **/ /** Handle Deposits and reversals of deposits **/
else if (savingsTransactionDTO.getTransactionType().isDeposit()) { else if (savingsTransactionDTO.getTransactionType().isDeposit()) {
this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode,
@@ -120,19 +119,17 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess
CASH_ACCOUNTS_FOR_SAVINGS.TRANSFERS_SUSPENSE, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, savingsProductId, CASH_ACCOUNTS_FOR_SAVINGS.TRANSFERS_SUSPENSE, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, savingsProductId,
paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal);
} }
/** overdraft **/ /** overdraft **/
else if (savingsTransactionDTO.getTransactionType().isOverdraftInterest()) { else if (savingsTransactionDTO.getTransactionType().isOverdraftInterest()) {
this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode,
CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, CASH_ACCOUNTS_FOR_SAVINGS.INCOME_FROM_INTEREST, savingsProductId, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, CASH_ACCOUNTS_FOR_SAVINGS.INCOME_FROM_INTEREST, savingsProductId,
paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal);
} } else if (savingsTransactionDTO.getTransactionType().isWrittenoff()) {
else if (savingsTransactionDTO.getTransactionType().isWrittenoff()) {
this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode,
CASH_ACCOUNTS_FOR_SAVINGS.LOSSES_WRITTEN_OFF, CASH_ACCOUNTS_FOR_SAVINGS.OVERDRAFT_PORTFOLIO_CONTROL, savingsProductId, CASH_ACCOUNTS_FOR_SAVINGS.LOSSES_WRITTEN_OFF, CASH_ACCOUNTS_FOR_SAVINGS.OVERDRAFT_PORTFOLIO_CONTROL,
paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal);
} } else if (savingsTransactionDTO.getTransactionType().isOverdraftFee()) {
else if (savingsTransactionDTO.getTransactionType().isOverdraftFee()) {
this.helper.createCashBasedJournalEntriesAndReversalsForSavingsCharges(office, currencyCode, this.helper.createCashBasedJournalEntriesAndReversalsForSavingsCharges(office, currencyCode,
CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, CASH_ACCOUNTS_FOR_SAVINGS.INCOME_FROM_FEES, savingsProductId, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, CASH_ACCOUNTS_FOR_SAVINGS.INCOME_FROM_FEES, savingsProductId,
paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal, feePayments); paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal, feePayments);
@@ -13,8 +13,8 @@ import org.mifosplatform.infrastructure.core.service.Page;
import org.mifosplatform.portfolio.group.service.SearchParameters; import org.mifosplatform.portfolio.group.service.SearchParameters;
public interface JournalEntryReadPlatformService { public interface JournalEntryReadPlatformService {
JournalEntryData retrieveGLJournalEntryById(long glJournalEntryId, JournalEntryAssociationParametersData associationParametersData); JournalEntryData retrieveGLJournalEntryById(long glJournalEntryId, JournalEntryAssociationParametersData associationParametersData);
Page<JournalEntryData> retrieveAll(SearchParameters searchParameters, Long glAccountId, Boolean onlyManualEntries, Date fromDate, Page<JournalEntryData> retrieveAll(SearchParameters searchParameters, Long glAccountId, Boolean onlyManualEntries, Date fromDate,
Date toDate, String transactionId, Integer entityType, JournalEntryAssociationParametersData associationParametersData); Date toDate, String transactionId, Integer entityType, JournalEntryAssociationParametersData associationParametersData);
@@ -149,7 +149,7 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry
List<JournalEntryData> entryDatas = jdbcTemplate.query(entryMapper.organizationRunningBalanceSchema(), entryMapper, List<JournalEntryData> entryDatas = jdbcTemplate.query(entryMapper.organizationRunningBalanceSchema(), entryMapper,
new Object[] { entityDate }); new Object[] { entityDate });
if(entryDatas.size()>0){ if (entryDatas.size() > 0) {
String[] updateSql = new String[entryDatas.size()]; String[] updateSql = new String[entryDatas.size()];
int i = 0; int i = 0;
for (JournalEntryData entryData : entryDatas) { for (JournalEntryData entryData : entryDatas) {
@@ -268,7 +268,7 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry
final EnumOptionData entryType = AccountingEnumerations.journalEntryType(entryTypeId); final EnumOptionData entryType = AccountingEnumerations.journalEntryType(entryTypeId);
return new JournalEntryData(id, officeId, null, null, glAccountId, null, accountType, null, entryType, amount, null, null, return new JournalEntryData(id, officeId, null, null, glAccountId, null, accountType, null, entryType, amount, null, null,
null, null, null, null, null, null, null, null, null, null, null,null, null); null, null, null, null, null, null, null, null, null, null, null, null, null);
} }
} }
@@ -85,11 +85,12 @@ public class AuditsApiResource {
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
if (parameters.isPaged()){ if (parameters.isPaged()) {
final Page<AuditData> auditEntries = this.auditReadPlatformService.retrievePaginatedAuditEntries(extraCriteria, settings.isIncludeJson(), parameters); final Page<AuditData> auditEntries = this.auditReadPlatformService.retrievePaginatedAuditEntries(extraCriteria,
return this.toApiJsonSerializer.serialize(settings, auditEntries, this.RESPONSE_DATA_PARAMETERS); settings.isIncludeJson(), parameters);
return this.toApiJsonSerializer.serialize(settings, auditEntries, this.RESPONSE_DATA_PARAMETERS);
} }
final Collection<AuditData> auditEntries = this.auditReadPlatformService.retrieveAuditEntries(extraCriteria, final Collection<AuditData> auditEntries = this.auditReadPlatformService.retrieveAuditEntries(extraCriteria,
settings.isIncludeJson()); settings.isIncludeJson());
@@ -329,10 +329,11 @@ public class CommandWrapper {
public boolean isLoanChargeResource() { public boolean isLoanChargeResource() {
return this.entityName.equalsIgnoreCase("LOANCHARGE"); return this.entityName.equalsIgnoreCase("LOANCHARGE");
} }
public boolean isLoanDisburseDetailResource() { public boolean isLoanDisburseDetailResource() {
return this.entityName.equalsIgnoreCase("DISBURSEMENTDETAIL"); return this.entityName.equalsIgnoreCase("DISBURSEMENTDETAIL");
} }
public boolean isCollateralResource() { public boolean isCollateralResource() {
return this.entityName.equalsIgnoreCase("COLLATERAL"); return this.entityName.equalsIgnoreCase("COLLATERAL");
} }
@@ -380,11 +381,11 @@ public class CommandWrapper {
public boolean isLoanWriteOff() { public boolean isLoanWriteOff() {
return this.actionName.equalsIgnoreCase("WRITEOFF") && this.entityName.equalsIgnoreCase("LOAN"); return this.actionName.equalsIgnoreCase("WRITEOFF") && this.entityName.equalsIgnoreCase("LOAN");
} }
public boolean isUndoLoanWriteOff() { public boolean isUndoLoanWriteOff() {
return this.actionName.equalsIgnoreCase("UNDOWRITEOFF") && this.entityName.equalsIgnoreCase("LOAN"); return this.actionName.equalsIgnoreCase("UNDOWRITEOFF") && this.entityName.equalsIgnoreCase("LOAN");
} }
public boolean isUpdateDisbursementDate() { public boolean isUpdateDisbursementDate() {
return this.actionName.equalsIgnoreCase("UPDATE") && this.entityName.equalsIgnoreCase("DISBURSEMENTDETAIL"); return this.actionName.equalsIgnoreCase("UPDATE") && this.entityName.equalsIgnoreCase("DISBURSEMENTDETAIL");
} }
@@ -603,7 +604,7 @@ public class CommandWrapper {
public boolean isHolidayResource() { public boolean isHolidayResource() {
return this.entityName.equalsIgnoreCase("HOLIDAY"); return this.entityName.equalsIgnoreCase("HOLIDAY");
} }
public boolean isHolidayActivation() { public boolean isHolidayActivation() {
return this.entityName.equalsIgnoreCase("HOLIDAY") && this.actionName.equalsIgnoreCase("ACTIVATE") && this.entityId != null; return this.entityName.equalsIgnoreCase("HOLIDAY") && this.actionName.equalsIgnoreCase("ACTIVATE") && this.entityId != null;
} }
@@ -15,7 +15,7 @@ import org.mifosplatform.infrastructure.core.service.Page;
public interface AuditReadPlatformService { public interface AuditReadPlatformService {
Collection<AuditData> retrieveAuditEntries(String extraCriteria, boolean includeJson); Collection<AuditData> retrieveAuditEntries(String extraCriteria, boolean includeJson);
Page<AuditData> retrievePaginatedAuditEntries(String extraCriteria, boolean includeJson, PaginationParameters parameters); Page<AuditData> retrievePaginatedAuditEntries(String extraCriteria, boolean includeJson, PaginationParameters parameters);
Collection<AuditData> retrieveAllEntriesToBeChecked(String extraCriteria, boolean includeJson); Collection<AuditData> retrieveAllEntriesToBeChecked(String extraCriteria, boolean includeJson);
@@ -159,18 +159,19 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
if (StringUtils.isNotBlank(extraCriteria)) { if (StringUtils.isNotBlank(extraCriteria)) {
updatedExtraCriteria = " where (" + extraCriteria + ")"; updatedExtraCriteria = " where (" + extraCriteria + ")";
} }
updatedExtraCriteria += " order by aud.id DESC limit " + PaginationParameters.getCheckedLimit(null); updatedExtraCriteria += " order by aud.id DESC limit " + PaginationParameters.getCheckedLimit(null);
return retrieveEntries("audit", updatedExtraCriteria, includeJson); return retrieveEntries("audit", updatedExtraCriteria, includeJson);
} }
@Override @Override
public Page<AuditData> retrievePaginatedAuditEntries(final String extraCriteria, final boolean includeJson, final PaginationParameters parameters) { public Page<AuditData> retrievePaginatedAuditEntries(final String extraCriteria, final boolean includeJson,
final PaginationParameters parameters) {
this.paginationParametersDataValidator.validateParameterValues(parameters, supportedOrderByValues, "audits"); this.paginationParametersDataValidator.validateParameterValues(parameters, supportedOrderByValues, "audits");
final AppUser currentUser = this.context.authenticatedUser(); final AppUser currentUser = this.context.authenticatedUser();
final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchy = currentUser.getOffice().getHierarchy();
String updatedExtraCriteria = ""; String updatedExtraCriteria = "";
if (StringUtils.isNotBlank(extraCriteria)) { if (StringUtils.isNotBlank(extraCriteria)) {
updatedExtraCriteria = " where (" + extraCriteria + ")"; updatedExtraCriteria = " where (" + extraCriteria + ")";
@@ -181,19 +182,19 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append("select SQL_CALC_FOUND_ROWS ");
sqlBuilder.append(rm.schema(includeJson, hierarchy)); sqlBuilder.append(rm.schema(includeJson, hierarchy));
sqlBuilder.append(' ').append(updatedExtraCriteria); sqlBuilder.append(' ').append(updatedExtraCriteria);
if (parameters.isOrderByRequested()) { if (parameters.isOrderByRequested()) {
sqlBuilder.append(' ').append(parameters.orderBySql()); sqlBuilder.append(' ').append(parameters.orderBySql());
}else { } else {
sqlBuilder.append(' ').append(' ').append(" order by aud.id DESC"); sqlBuilder.append(' ').append(' ').append(" order by aud.id DESC");
} }
if (parameters.isLimited()) { if (parameters.isLimited()) {
sqlBuilder.append(' ').append(parameters.limitSql()); sqlBuilder.append(' ').append(parameters.limitSql());
} }
logger.info("sql: " + sqlBuilder.toString()); logger.info("sql: " + sqlBuilder.toString());
final String sqlCountRows = "SELECT FOUND_ROWS()"; final String sqlCountRows = "SELECT FOUND_ROWS()";
return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), new Object[] {}, rm); return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), new Object[] {}, rm);
} }
@@ -243,7 +244,7 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
return this.jdbcTemplate.query(sql, rm, new Object[] {}); return this.jdbcTemplate.query(sql, rm, new Object[] {});
} }
@Override @Override
public AuditData retrieveAuditEntry(final Long auditId) { public AuditData retrieveAuditEntry(final Long auditId) {
@@ -59,7 +59,7 @@ public class CommandWrapperBuilder {
this.entityName = "CONFIGURATION"; this.entityName = "CONFIGURATION";
this.entityId = configId; this.entityId = configId;
this.href = "/configurations/"+configId; this.href = "/configurations/" + configId;
return this; return this;
} }
@@ -574,7 +574,7 @@ public class CommandWrapperBuilder {
this.href = "/loans/" + loanId + "/transactions/template?command=writeoff"; this.href = "/loans/" + loanId + "/transactions/template?command=writeoff";
return this; return this;
} }
public CommandWrapperBuilder undoWriteOffLoanTransaction(final Long loanId) { public CommandWrapperBuilder undoWriteOffLoanTransaction(final Long loanId) {
this.actionName = "UNDOWRITEOFF"; this.actionName = "UNDOWRITEOFF";
this.entityName = "LOAN"; this.entityName = "LOAN";
@@ -584,7 +584,6 @@ public class CommandWrapperBuilder {
return this; return this;
} }
public CommandWrapperBuilder closeLoanAsRescheduledTransaction(final Long loanId) { public CommandWrapperBuilder closeLoanAsRescheduledTransaction(final Long loanId) {
this.actionName = "CLOSEASRESCHEDULED"; this.actionName = "CLOSEASRESCHEDULED";
this.entityName = "LOAN"; this.entityName = "LOAN";
@@ -629,8 +628,8 @@ public class CommandWrapperBuilder {
this.href = "/loans/" + loanId; this.href = "/loans/" + loanId;
return this; return this;
} }
public CommandWrapperBuilder updateDisbusementDate(final Long loanId,final Long disbursementId) { public CommandWrapperBuilder updateDisbusementDate(final Long loanId, final Long disbursementId) {
this.actionName = "UPDATE"; this.actionName = "UPDATE";
this.entityName = "DISBURSEMENTDETAIL"; this.entityName = "DISBURSEMENTDETAIL";
this.entityId = disbursementId; this.entityId = disbursementId;
@@ -639,7 +638,6 @@ public class CommandWrapperBuilder {
return this; return this;
} }
public CommandWrapperBuilder deleteLoanApplication(final Long loanId) { public CommandWrapperBuilder deleteLoanApplication(final Long loanId) {
this.actionName = "DELETE"; this.actionName = "DELETE";
this.entityName = "LOAN"; this.entityName = "LOAN";
@@ -827,7 +825,6 @@ public class CommandWrapperBuilder {
return this; return this;
} }
public CommandWrapperBuilder createSavingProduct() { public CommandWrapperBuilder createSavingProduct() {
this.actionName = "CREATE"; this.actionName = "CREATE";
this.entityName = "SAVINGSPRODUCT"; this.entityName = "SAVINGSPRODUCT";
@@ -1332,7 +1329,7 @@ public class CommandWrapperBuilder {
this.href = "/holidays/template"; this.href = "/holidays/template";
return this; return this;
} }
public CommandWrapperBuilder activateHoliday(final Long holidayId) { public CommandWrapperBuilder activateHoliday(final Long holidayId) {
this.actionName = "ACTIVATE"; this.actionName = "ACTIVATE";
this.entityName = "HOLIDAY"; this.entityName = "HOLIDAY";
@@ -1340,15 +1337,15 @@ public class CommandWrapperBuilder {
this.href = "/holidays/" + holidayId + "command=activate"; this.href = "/holidays/" + holidayId + "command=activate";
return this; return this;
} }
public CommandWrapperBuilder updateHoliday(final Long holidayId) { public CommandWrapperBuilder updateHoliday(final Long holidayId) {
this.actionName = "UPDATE"; this.actionName = "UPDATE";
this.entityName = "HOLIDAY"; this.entityName = "HOLIDAY";
this.entityId = holidayId; this.entityId = holidayId;
this.href = "/holidays/" + holidayId ; this.href = "/holidays/" + holidayId;
return this; return this;
} }
public CommandWrapperBuilder deleteHoliday(final Long holidayId) { public CommandWrapperBuilder deleteHoliday(final Long holidayId) {
this.actionName = "DELETE"; this.actionName = "DELETE";
this.entityName = "HOLIDAY"; this.entityName = "HOLIDAY";
@@ -72,7 +72,6 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio
result = this.processAndLogCommandService.processAndLogCommand(wrapper, command, isApprovedByChecker); result = this.processAndLogCommandService.processAndLogCommand(wrapper, command, isApprovedByChecker);
} catch (final RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { } catch (final RollbackTransactionAsCommandIsNotApprovedByCheckerException e) {
result = this.processAndLogCommandService.logCommand(e.getCommandSourceResult()); result = this.processAndLogCommandService.logCommand(e.getCommandSourceResult());
} }
@@ -362,11 +362,11 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else if (wrapper.isPayLoanCharge()) { } else if (wrapper.isPayLoanCharge()) {
handler = this.applicationContext.getBean("payLoanChargeCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("payLoanChargeCommandHandler", NewCommandSourceHandler.class);
} }
} else if(wrapper.isLoanDisburseDetailResource()){ } else if (wrapper.isLoanDisburseDetailResource()) {
if(wrapper.isUpdateDisbursementDate()){ if (wrapper.isUpdateDisbursementDate()) {
handler = this.applicationContext.getBean("updateLoanDisbuseDateCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("updateLoanDisbuseDateCommandHandler", NewCommandSourceHandler.class);
} }
}else if (wrapper.isGLAccountResource()) { } else if (wrapper.isGLAccountResource()) {
if (wrapper.isCreate()) { if (wrapper.isCreate()) {
handler = this.applicationContext.getBean("createGLAccountCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("createGLAccountCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUpdate()) { } else if (wrapper.isUpdate()) {
@@ -391,9 +391,9 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
handler = this.applicationContext.getBean("createJournalEntryCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("createJournalEntryCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isRevertJournalEntry()) { } else if (wrapper.isRevertJournalEntry()) {
handler = this.applicationContext.getBean("reverseJournalEntryCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("reverseJournalEntryCommandHandler", NewCommandSourceHandler.class);
}else if(wrapper.isUpdateRunningbalance()){ } else if (wrapper.isUpdateRunningbalance()) {
handler = this.applicationContext.getBean("updateRunningBalanceCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("updateRunningBalanceCommandHandler", NewCommandSourceHandler.class);
}else { } else {
throw new UnsupportedCommandException(wrapper.commandName()); throw new UnsupportedCommandException(wrapper.commandName());
} }
} else if (wrapper.isSavingsProductResource()) { } else if (wrapper.isSavingsProductResource()) {
@@ -435,9 +435,12 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
handler = this.applicationContext.getBean("calculateInterestSavingsAccountCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("calculateInterestSavingsAccountCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isSavingsAccountInterestPosting()) { } else if (wrapper.isSavingsAccountInterestPosting()) {
handler = this.applicationContext.getBean("postInterestSavingsAccountCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("postInterestSavingsAccountCommandHandler", NewCommandSourceHandler.class);
} /*else if (wrapper.isSavingsAccountApplyAnnualFee()) { } /*
handler = this.applicationContext.getBean("applyAnnualFeeSavingsAccountCommandHandler", NewCommandSourceHandler.class); * else if (wrapper.isSavingsAccountApplyAnnualFee()) { handler =
} */else if (wrapper.isSavingsAccountUndoTransaction()) { * this.applicationContext.getBean(
* "applyAnnualFeeSavingsAccountCommandHandler",
* NewCommandSourceHandler.class); }
*/else if (wrapper.isSavingsAccountUndoTransaction()) {
handler = this.applicationContext.getBean("undoTransactionSavingsAccountCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("undoTransactionSavingsAccountCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isAdjustSavingsAccountTransaction()) { } else if (wrapper.isAdjustSavingsAccountTransaction()) {
handler = this.applicationContext.getBean("savingsTransactionAdjustmentCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("savingsTransactionAdjustmentCommandHandler", NewCommandSourceHandler.class);
@@ -51,12 +51,11 @@ public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPl
final String name = rs.getString("name"); final String name = rs.getString("name");
final boolean enabled = rs.getBoolean("enabled"); final boolean enabled = rs.getBoolean("enabled");
final Long value = rs.getLong("value"); final Long value = rs.getLong("value");
final Long id = rs.getLong("id"); final Long id = rs.getLong("id");
return new GlobalConfigurationPropertyData(name, enabled,value,id); return new GlobalConfigurationPropertyData(name, enabled, value, id);
} }
} }
} }
@@ -28,7 +28,7 @@ import com.google.gson.reflect.TypeToken;
/** /**
* Immutable representation of a command. * Immutable representation of a command.
* *
* Wraps the provided JSON with convenience functions for extracting parameter * Wraps the provided JSON with convenience functions for extracting parameter
* values and checking for changes against an existing value. * values and checking for changes against an existing value.
*/ */
@@ -317,9 +317,9 @@ public final class JsonCommand {
} }
public Map<String, String> mapValueOfParameterNamed(final String json) { public Map<String, String> mapValueOfParameterNamed(final String json) {
final Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType(); final Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
final Map<String, String> value = this.fromApiJsonHelper.extractDataMap(typeOfMap, json); final Map<String, String> value = this.fromApiJsonHelper.extractDataMap(typeOfMap, json);
return value; return value;
} }
public boolean isChangeInBigDecimalParameterNamedDefaultingZeroToNull(final String parameterName, final BigDecimal existingValue) { public boolean isChangeInBigDecimalParameterNamedDefaultingZeroToNull(final String parameterName, final BigDecimal existingValue) {
@@ -364,17 +364,17 @@ public class DataValidatorBuilder {
} }
return this; return this;
} }
public DataValidatorBuilder integerGreaterThanNumber(Integer number) { public DataValidatorBuilder integerGreaterThanNumber(Integer number) {
if (this.value == null && this.ignoreNullValue) { return this; } if (this.value == null && this.ignoreNullValue) { return this; }
if (this.value != null) { if (this.value != null) {
final Integer intValue = Integer.valueOf(this.value.toString()); final Integer intValue = Integer.valueOf(this.value.toString());
if (intValue < number+1) { if (intValue < number + 1) {
final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".")
.append(this.parameter).append(".not.greater.than.specified.number"); .append(this.parameter).append(".not.greater.than.specified.number");
final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter)
" must be greater than ").append(number); .append(" must be greater than ").append(number);
final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
defaultEnglishMessage.toString(), this.parameter, intValue, number); defaultEnglishMessage.toString(), this.parameter, intValue, number);
this.dataValidationErrors.add(error); this.dataValidationErrors.add(error);
@@ -382,7 +382,7 @@ public class DataValidatorBuilder {
} }
return this; return this;
} }
public DataValidatorBuilder integerSameAsNumber(Integer number) { public DataValidatorBuilder integerSameAsNumber(Integer number) {
if (this.value == null && this.ignoreNullValue) { return this; } if (this.value == null && this.ignoreNullValue) { return this; }
@@ -391,8 +391,8 @@ public class DataValidatorBuilder {
if (intValue != number) { if (intValue != number) {
final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".")
.append(this.parameter).append(".not.equal.to.specified.number"); .append(this.parameter).append(".not.equal.to.specified.number");
final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter)
" must be same as").append(number); .append(" must be same as").append(number);
final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
defaultEnglishMessage.toString(), this.parameter, intValue, number); defaultEnglishMessage.toString(), this.parameter, intValue, number);
this.dataValidationErrors.add(error); this.dataValidationErrors.add(error);
@@ -401,7 +401,6 @@ public class DataValidatorBuilder {
return this; return this;
} }
/* /*
* should be used with .notNull() before it * should be used with .notNull() before it
*/ */
@@ -19,17 +19,17 @@ public class PaginationParameters {
private final Integer limit; private final Integer limit;
private final String orderBy; private final String orderBy;
private final String sortOrder; private final String sortOrder;
public static PaginationParameters instance (Boolean paged, Integer offset, Integer limit, String orderBy, String sortOrder){ public static PaginationParameters instance(Boolean paged, Integer offset, Integer limit, String orderBy, String sortOrder) {
if( null == paged) { if (null == paged) {
paged = false; paged = false;
} }
final Integer maxLimitAllowed = getCheckedLimit(limit); final Integer maxLimitAllowed = getCheckedLimit(limit);
return new PaginationParameters(paged, offset, maxLimitAllowed, orderBy, sortOrder); return new PaginationParameters(paged, offset, maxLimitAllowed, orderBy, sortOrder);
} }
private PaginationParameters(boolean paged, Integer offset, Integer limit, String orderBy, String sortOrder) { private PaginationParameters(boolean paged, Integer offset, Integer limit, String orderBy, String sortOrder) {
this.paged = paged; this.paged = paged;
this.offset = offset; this.offset = offset;
@@ -37,7 +37,7 @@ public class PaginationParameters {
this.orderBy = orderBy; this.orderBy = orderBy;
this.sortOrder = sortOrder; this.sortOrder = sortOrder;
} }
public static Integer getCheckedLimit(final Integer limit) { public static Integer getCheckedLimit(final Integer limit) {
final Integer maxLimitAllowed = 200; final Integer maxLimitAllowed = 200;
@@ -53,27 +53,27 @@ public class PaginationParameters {
return checkedLimit; return checkedLimit;
} }
public boolean isPaged() { public boolean isPaged() {
return this.paged; return this.paged;
} }
public Integer getOffset() { public Integer getOffset() {
return this.offset; return this.offset;
} }
public Integer getLimit() { public Integer getLimit() {
return this.limit; return this.limit;
} }
public String getOrderBy() { public String getOrderBy() {
return this.orderBy; return this.orderBy;
} }
public String getSortOrder() { public String getSortOrder() {
return this.sortOrder; return this.sortOrder;
} }
public boolean isOrderByRequested() { public boolean isOrderByRequested() {
return StringUtils.isNotBlank(this.orderBy); return StringUtils.isNotBlank(this.orderBy);
} }
@@ -81,7 +81,7 @@ public class PaginationParameters {
public boolean isSortOrderProvided() { public boolean isSortOrderProvided() {
return StringUtils.isNotBlank(this.sortOrder); return StringUtils.isNotBlank(this.sortOrder);
} }
public boolean isLimited() { public boolean isLimited() {
return this.limit != null && this.limit.intValue() > 0; return this.limit != null && this.limit.intValue() > 0;
} }
@@ -89,10 +89,10 @@ public class PaginationParameters {
public boolean isOffset() { public boolean isOffset() {
return this.offset != null; return this.offset != null;
} }
public String orderBySql(){ public String orderBySql() {
final StringBuffer sql = new StringBuffer(); final StringBuffer sql = new StringBuffer();
if (this.isOrderByRequested()) { if (this.isOrderByRequested()) {
sql.append(" order by ").append(this.getOrderBy()); sql.append(" order by ").append(this.getOrderBy());
if (this.isSortOrderProvided()) { if (this.isSortOrderProvided()) {
@@ -101,15 +101,15 @@ public class PaginationParameters {
} }
return sql.toString(); return sql.toString();
} }
public String limitSql(){ public String limitSql() {
final StringBuffer sql = new StringBuffer(); final StringBuffer sql = new StringBuffer();
if (this.isLimited()) { if (this.isLimited()) {
sql.append(" limit ").append(this.getLimit()); sql.append(" limit ").append(this.getLimit());
if (this.isOffset()) { if (this.isOffset()) {
sql.append(" offset ").append(this.getOffset()); sql.append(" offset ").append(this.getOffset());
} }
} }
return sql.toString(); return sql.toString();
} }
} }
@@ -16,25 +16,31 @@ import org.springframework.stereotype.Component;
@Component @Component
public class PaginationParametersDataValidator { public class PaginationParametersDataValidator {
public static Set<String> sortOrderValues = new HashSet<String>(Arrays.asList("ASC", "DESC")); public static Set<String> sortOrderValues = new HashSet<String>(Arrays.asList("ASC", "DESC"));
public void validateParameterValues(PaginationParameters parameters, final Set<String> supportedOrdeByValues, final String resourceName) { public void validateParameterValues(PaginationParameters parameters, final Set<String> supportedOrdeByValues, final String resourceName) {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
if (parameters.isOrderByRequested() && !supportedOrdeByValues.contains(parameters.getOrderBy())){ if (parameters.isOrderByRequested() && !supportedOrdeByValues.contains(parameters.getOrderBy())) {
final String defaultUserMessage = "The orderBy value '" + parameters.getOrderBy() + "' is not supported. The supported orderBy values are " + supportedOrdeByValues.toString(); final String defaultUserMessage = "The orderBy value '" + parameters.getOrderBy()
final ApiParameterError error = ApiParameterError.parameterError("validation.msg."+resourceName+".orderBy.value.is.not.supported", + "' is not supported. The supported orderBy values are " + supportedOrdeByValues.toString();
defaultUserMessage, "orderBy", parameters.getOrderBy(), supportedOrdeByValues.toString()); final ApiParameterError error = ApiParameterError.parameterError("validation.msg." + resourceName
+ ".orderBy.value.is.not.supported", defaultUserMessage, "orderBy", parameters.getOrderBy(),
supportedOrdeByValues.toString());
dataValidationErrors.add(error); dataValidationErrors.add(error);
} }
if (parameters.isSortOrderProvided() && !sortOrderValues.contains(parameters.getSortOrder().toUpperCase())){ if (parameters.isSortOrderProvided() && !sortOrderValues.contains(parameters.getSortOrder().toUpperCase())) {
final String defaultUserMessage = "The sortOrder value '" + parameters.getSortOrder() + "' is not supported. The supported sortOrder values are " + sortOrderValues.toString(); final String defaultUserMessage = "The sortOrder value '" + parameters.getSortOrder()
final ApiParameterError error = ApiParameterError.parameterError("validation.msg."+resourceName+".sortOrder.value.is.not.supported", + "' is not supported. The supported sortOrder values are " + sortOrderValues.toString();
defaultUserMessage, "sortOrder", parameters.getSortOrder(), sortOrderValues.toString()); final ApiParameterError error = ApiParameterError.parameterError("validation.msg." + resourceName
+ ".sortOrder.value.is.not.supported", defaultUserMessage, "sortOrder", parameters.getSortOrder(),
sortOrderValues.toString());
dataValidationErrors.add(error); dataValidationErrors.add(error);
} }
throwExceptionIfValidationWarningsExist(dataValidationErrors); throwExceptionIfValidationWarningsExist(dataValidationErrors);
} }
@@ -148,7 +148,7 @@ public class FromJsonHelper {
public MonthDay extractMonthDayNamed(final String parameterName, final JsonElement element) { public MonthDay extractMonthDayNamed(final String parameterName, final JsonElement element) {
return this.helperDelegator.extractMonthDayNamed(parameterName, element); return this.helperDelegator.extractMonthDayNamed(parameterName, element);
} }
public MonthDay extractMonthDayNamed(final String parameterName, final JsonObject object, final String dateFormat, public MonthDay extractMonthDayNamed(final String parameterName, final JsonObject object, final String dateFormat,
final Locale clientApplicationLocale) { final Locale clientApplicationLocale) {
return this.helperDelegator.extractMonthDayNamed(parameterName, object, dateFormat, clientApplicationLocale); return this.helperDelegator.extractMonthDayNamed(parameterName, object, dateFormat, clientApplicationLocale);
@@ -220,7 +220,7 @@ public class FromJsonHelper {
public String extractDateFormatParameter(final JsonObject element) { public String extractDateFormatParameter(final JsonObject element) {
return this.helperDelegator.extractDateFormatParameter(element); return this.helperDelegator.extractDateFormatParameter(element);
} }
public String extractMonthDayFormatParameter(final JsonObject element) { public String extractMonthDayFormatParameter(final JsonObject element) {
return this.helperDelegator.extractMonthDayFormatParameter(element); return this.helperDelegator.extractMonthDayFormatParameter(element);
} }
@@ -36,7 +36,7 @@ import com.google.gson.JsonPrimitive;
public class JsonParserHelper { public class JsonParserHelper {
public boolean parameterExists(final String parameterName, final JsonElement element) { public boolean parameterExists(final String parameterName, final JsonElement element) {
if (element == null) {return false;} if (element == null) { return false; }
return element.getAsJsonObject().has(parameterName); return element.getAsJsonObject().has(parameterName);
} }
@@ -144,10 +144,10 @@ public class JsonParserHelper {
/** /**
* Method used to extract integers from unformatted strings. Ex: "1" , * Method used to extract integers from unformatted strings. Ex: "1" ,
* "100002" etc * "100002" etc
* *
* Please note that this method does not support extracting Integers from * Please note that this method does not support extracting Integers from
* locale specific formatted strings Ex "1,000" etc * locale specific formatted strings Ex "1,000" etc
* *
* @param parameterName * @param parameterName
* @param element * @param element
* @param parametersPassedInRequest * @param parametersPassedInRequest
@@ -514,9 +514,9 @@ public class JsonParserHelper {
final NumberFormatter numberFormatter = new NumberFormatter(); final NumberFormatter numberFormatter = new NumberFormatter();
final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale); final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale);
if(parsedNumber instanceof BigDecimal){ if (parsedNumber instanceof BigDecimal) {
number = (BigDecimal)parsedNumber; number = (BigDecimal) parsedNumber;
}else{ } else {
number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue())); number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue()));
} }
} }
@@ -64,7 +64,7 @@ public class DateUtils {
return formattedSqlDate; return formattedSqlDate;
} }
public static boolean isDateInTheFuture(final LocalDate localDate){ public static boolean isDateInTheFuture(final LocalDate localDate) {
return localDate.isAfter(getLocalDateOfTenant()); return localDate.isAfter(getLocalDateOfTenant());
} }
} }
@@ -159,7 +159,7 @@ public final class ResultsetColumnHeaderData {
private boolean isBigInt() { private boolean isBigInt() {
return "bigint".equalsIgnoreCase(this.columnType); return "bigint".equalsIgnoreCase(this.columnType);
} }
private boolean isBit() { private boolean isBit() {
return "bit".equalsIgnoreCase(this.columnType); return "bit".equalsIgnoreCase(this.columnType);
} }
@@ -826,7 +826,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ
+ datatableName.toLowerCase().replaceAll("\\s", "_") + "_%'"; + datatableName.toLowerCase().replaceAll("\\s", "_") + "_%'";
sqlArray = new String[2]; sqlArray = new String[2];
sqlArray[1] = deleteColumnCodeSql; sqlArray[1] = deleteColumnCodeSql;
}else{ } else {
sqlArray = new String[1]; sqlArray = new String[1];
} }
final String sql = "DROP TABLE `" + datatableName + "`"; final String sql = "DROP TABLE `" + datatableName + "`";
@@ -73,9 +73,7 @@ public class ImageReadPlatformServiceImpl implements ImageReadPlatformService {
final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(imageData.storageType()); final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(imageData.storageType());
final ImageData result = contentRepository.fetchImage(imageData); final ImageData result = contentRepository.fetchImage(imageData);
if (result.getContent() == null) { if (result.getContent() == null) { throw new ImageNotFoundException("clients", clientId); }
throw new ImageNotFoundException("clients", clientId);
}
return result; return result;
} catch (final EmptyResultDataAccessException e) { } catch (final EmptyResultDataAccessException e) {
@@ -38,7 +38,7 @@ import org.springframework.stereotype.Service;
* Service class to create and load batch jobs to Scheduler using * Service class to create and load batch jobs to Scheduler using
* {@link SchedulerFactoryBean} ,{@link MethodInvokingJobDetailFactoryBean} and * {@link SchedulerFactoryBean} ,{@link MethodInvokingJobDetailFactoryBean} and
* {@link CronTriggerFactoryBean} * {@link CronTriggerFactoryBean}
* *
*/ */
@Service @Service
public class JobRegisterServiceImpl implements JobRegisterService { public class JobRegisterServiceImpl implements JobRegisterService {
@@ -41,7 +41,7 @@ public class SmsMessage extends AbstractPersistable<Long> {
@Column(name = "status_enum", nullable = false) @Column(name = "status_enum", nullable = false)
private Integer statusType; private Integer statusType;
@Column(name = "mobile_no", nullable = false, length=50) @Column(name = "mobile_no", nullable = false, length = 50)
private String mobileNo; private String mobileNo;
@Column(name = "message", nullable = false) @Column(name = "message", nullable = false)
@@ -30,10 +30,8 @@ public class SmsMessageAssembler {
private final FromJsonHelper fromApiJsonHelper; private final FromJsonHelper fromApiJsonHelper;
@Autowired @Autowired
public SmsMessageAssembler(final SmsMessageRepository smsMessageRepository, public SmsMessageAssembler(final SmsMessageRepository smsMessageRepository, final GroupRepositoryWrapper groupRepositoryWrapper,
final GroupRepositoryWrapper groupRepositoryWrapper, final ClientRepositoryWrapper clientRepository, final StaffRepositoryWrapper staffRepository,
final ClientRepositoryWrapper clientRepository,
final StaffRepositoryWrapper staffRepository,
final FromJsonHelper fromApiJsonHelper) { final FromJsonHelper fromApiJsonHelper) {
this.smsMessageRepository = smsMessageRepository; this.smsMessageRepository = smsMessageRepository;
this.groupRepository = groupRepositoryWrapper; this.groupRepository = groupRepositoryWrapper;
@@ -14,24 +14,29 @@ public class SmsMessageEnumerations {
} }
public static EnumOptionData status(final SmsMessageStatusType status) { public static EnumOptionData status(final SmsMessageStatusType status) {
EnumOptionData optionData = new EnumOptionData(SmsMessageStatusType.INVALID.getValue().longValue(), SmsMessageStatusType.INVALID.getCode(), EnumOptionData optionData = new EnumOptionData(SmsMessageStatusType.INVALID.getValue().longValue(),
"Invalid"); SmsMessageStatusType.INVALID.getCode(), "Invalid");
switch (status) { switch (status) {
case INVALID: case INVALID:
optionData = new EnumOptionData(SmsMessageStatusType.INVALID.getValue().longValue(), SmsMessageStatusType.INVALID.getCode(), "Invalid"); optionData = new EnumOptionData(SmsMessageStatusType.INVALID.getValue().longValue(),
SmsMessageStatusType.INVALID.getCode(), "Invalid");
break; break;
case PENDING: case PENDING:
optionData = new EnumOptionData(SmsMessageStatusType.PENDING.getValue().longValue(), SmsMessageStatusType.PENDING.getCode(), "Pending"); optionData = new EnumOptionData(SmsMessageStatusType.PENDING.getValue().longValue(),
SmsMessageStatusType.PENDING.getCode(), "Pending");
break; break;
case SENT: case SENT:
optionData = new EnumOptionData(SmsMessageStatusType.SENT.getValue().longValue(), SmsMessageStatusType.SENT.getCode(), "Sent"); optionData = new EnumOptionData(SmsMessageStatusType.SENT.getValue().longValue(), SmsMessageStatusType.SENT.getCode(),
break; "Sent");
break;
case DELIVERED: case DELIVERED:
optionData = new EnumOptionData(SmsMessageStatusType.DELIVERED.getValue().longValue(), SmsMessageStatusType.DELIVERED.getCode(), "Delivered"); optionData = new EnumOptionData(SmsMessageStatusType.DELIVERED.getValue().longValue(),
break; SmsMessageStatusType.DELIVERED.getCode(), "Delivered");
break;
case FAILED: case FAILED:
optionData = new EnumOptionData(SmsMessageStatusType.FAILED.getValue().longValue(), SmsMessageStatusType.FAILED.getCode(), "Failed"); optionData = new EnumOptionData(SmsMessageStatusType.FAILED.getValue().longValue(), SmsMessageStatusType.FAILED.getCode(),
break; "Failed");
break;
} }
@@ -48,8 +48,11 @@ public class SmsWritePlatformServiceJpaRepositoryImpl implements SmsWritePlatfor
final SmsMessage message = this.assembler.assembleFromJson(command); final SmsMessage message = this.assembler.assembleFromJson(command);
// TODO: at this point we also want to fire off request using third party service to send SMS. // TODO: at this point we also want to fire off request using third
// TODO: decision to be made on wheter we 'wait' for response or use 'future/promise' to capture response and update the SmsMessage table // party service to send SMS.
// TODO: decision to be made on wheter we 'wait' for response or use
// 'future/promise' to capture response and update the SmsMessage
// table
this.repository.save(message); this.repository.save(message);
return new CommandProcessingResultBuilder() // return new CommandProcessingResultBuilder() //
@@ -108,9 +111,8 @@ public class SmsWritePlatformServiceJpaRepositoryImpl implements SmsWritePlatfor
private void handleDataIntegrityIssues(@SuppressWarnings("unused") final JsonCommand command, final DataIntegrityViolationException dve) { private void handleDataIntegrityIssues(@SuppressWarnings("unused") final JsonCommand command, final DataIntegrityViolationException dve) {
final Throwable realCause = dve.getMostSpecificCause(); final Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("mobile_no")) { if (realCause.getMessage().contains("mobile_no")) { throw new PlatformDataIntegrityException("error.msg.sms.no.mobile.no.exists",
throw new PlatformDataIntegrityException("error.msg.sms.no.mobile.no.exists", "The group, client or staff provided has no mobile no.", "id"); "The group, client or staff provided has no mobile no.", "id"); }
}
logger.error(dve.getMessage(), dve); logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.sms.unknown.data.integrity.issue", throw new PlatformDataIntegrityException("error.msg.sms.unknown.data.integrity.issue",
@@ -25,8 +25,10 @@ public class HolidayApiConstants {
public static final String status = "status"; public static final String status = "status";
public static final Set<String> HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(localeParamName, public static final Set<String> HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(localeParamName,
dateFormatParamName, nameParamName, fromDateParamName, toDateParamName, descriptionParamName, officesParamName, repaymentsRescheduledToParamName)); dateFormatParamName, nameParamName, fromDateParamName, toDateParamName, descriptionParamName, officesParamName,
repaymentsRescheduledToParamName));
public static final Set<String> HOLIDAY_RESPONSE_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(idParamName, nameParamName, public static final Set<String> HOLIDAY_RESPONSE_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(idParamName, nameParamName,
fromDateParamName, descriptionParamName, toDateParamName, repaymentsRescheduledToParamName, localeParamName, dateFormatParamName, status)); fromDateParamName, descriptionParamName, toDateParamName, repaymentsRescheduledToParamName, localeParamName,
dateFormatParamName, status));
} }
@@ -70,7 +70,7 @@ public class HolidaysApiResource {
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@POST @POST
@Path("{holidayId}") @Path("{holidayId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@@ -95,7 +95,7 @@ public class HolidaysApiResource {
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@GET @GET
@Path("{holidayId}") @Path("{holidayId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@@ -103,29 +103,27 @@ public class HolidaysApiResource {
public String retrieveOne(@PathParam("holidayId") final Long holidayId, @Context final UriInfo uriInfo) { public String retrieveOne(@PathParam("holidayId") final Long holidayId, @Context final UriInfo uriInfo) {
this.context.authenticatedUser().validateHasReadPermission(HOLIDAY_RESOURCE_NAME); this.context.authenticatedUser().validateHasReadPermission(HOLIDAY_RESOURCE_NAME);
final HolidayData holidayData = this.holidayReadPlatformService.retrieveHoliday(holidayId); final HolidayData holidayData = this.holidayReadPlatformService.retrieveHoliday(holidayId);
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.toApiJsonSerializer.serialize(settings, holidayData, HOLIDAY_RESPONSE_DATA_PARAMETERS); return this.toApiJsonSerializer.serialize(settings, holidayData, HOLIDAY_RESPONSE_DATA_PARAMETERS);
} }
@PUT @PUT
@Path("{holidayId}") @Path("{holidayId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String update(@PathParam("holidayId") final Long holidayId, final String jsonRequestBody) { public String update(@PathParam("holidayId") final Long holidayId, final String jsonRequestBody) {
final CommandWrapper commandRequest = new CommandWrapperBuilder().updateHoliday(holidayId) final CommandWrapper commandRequest = new CommandWrapperBuilder().updateHoliday(holidayId).withJson(jsonRequestBody).build();
.withJson(jsonRequestBody).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 @DELETE
@Path("{holidayId}") @Path("{holidayId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@@ -38,7 +38,8 @@ public class HolidayDataValidator {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType(); final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, HolidayApiConstants.HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
HolidayApiConstants.HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS);
final JsonElement element = this.fromApiJsonHelper.parse(json); final JsonElement element = this.fromApiJsonHelper.parse(json);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
@@ -55,14 +56,15 @@ public class HolidayDataValidator {
final LocalDate toDate = this.fromApiJsonHelper.extractLocalDateNamed(HolidayApiConstants.toDateParamName, element); final LocalDate toDate = this.fromApiJsonHelper.extractLocalDateNamed(HolidayApiConstants.toDateParamName, element);
baseDataValidator.reset().parameter(HolidayApiConstants.toDateParamName).value(toDate).notNull(); baseDataValidator.reset().parameter(HolidayApiConstants.toDateParamName).value(toDate).notNull();
final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper.extractLocalDateNamed(HolidayApiConstants.repaymentsRescheduledToParamName, final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper.extractLocalDateNamed(
element); HolidayApiConstants.repaymentsRescheduledToParamName, element);
baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledToParamName).value(repaymentsRescheduledTo).notNull(); baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledToParamName).value(repaymentsRescheduledTo).notNull();
Set<Long> offices = null; Set<Long> offices = null;
final JsonObject topLevelJsonElement = element.getAsJsonObject(); final JsonObject topLevelJsonElement = element.getAsJsonObject();
if (topLevelJsonElement.has(HolidayApiConstants.officesParamName) && topLevelJsonElement.get(HolidayApiConstants.officesParamName).isJsonArray()) { if (topLevelJsonElement.has(HolidayApiConstants.officesParamName)
&& topLevelJsonElement.get(HolidayApiConstants.officesParamName).isJsonArray()) {
final JsonArray array = topLevelJsonElement.get(HolidayApiConstants.officesParamName).getAsJsonArray(); final JsonArray array = topLevelJsonElement.get(HolidayApiConstants.officesParamName).getAsJsonArray();
if (array.size() > 0) { if (array.size() > 0) {
@@ -78,7 +80,7 @@ public class HolidayDataValidator {
baseDataValidator.reset().parameter(HolidayApiConstants.officesParamName).value(offices).notNull(); baseDataValidator.reset().parameter(HolidayApiConstants.officesParamName).value(offices).notNull();
throwExceptionIfValidationWarningsExist(dataValidationErrors); throwExceptionIfValidationWarningsExist(dataValidationErrors);
} }
public void validateForUpdate(final String json) { public void validateForUpdate(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
@@ -111,13 +113,15 @@ public class HolidayDataValidator {
if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.repaymentsRescheduledToParamName, element)) { if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.repaymentsRescheduledToParamName, element)) {
final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper.extractLocalDateNamed( final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper.extractLocalDateNamed(
HolidayApiConstants.repaymentsRescheduledToParamName, element); HolidayApiConstants.repaymentsRescheduledToParamName, element);
baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledToParamName).value(repaymentsRescheduledTo).notNull(); baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledToParamName).value(repaymentsRescheduledTo)
.notNull();
} }
Set<Long> offices = null; Set<Long> offices = null;
final JsonObject topLevelJsonElement = element.getAsJsonObject(); final JsonObject topLevelJsonElement = element.getAsJsonObject();
if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.officesParamName, element)) { if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.officesParamName, element)) {
if (topLevelJsonElement.has(HolidayApiConstants.officesParamName) && topLevelJsonElement.get(HolidayApiConstants.officesParamName).isJsonArray()) { if (topLevelJsonElement.has(HolidayApiConstants.officesParamName)
&& topLevelJsonElement.get(HolidayApiConstants.officesParamName).isJsonArray()) {
final JsonArray array = topLevelJsonElement.get(HolidayApiConstants.officesParamName).getAsJsonArray(); final JsonArray array = topLevelJsonElement.get(HolidayApiConstants.officesParamName).getAsJsonArray();
if (array.size() > 0) { if (array.size() > 0) {
@@ -66,7 +66,7 @@ public class Holiday extends AbstractPersistable<Long> {
@Column(name = "status_enum", nullable = false) @Column(name = "status_enum", nullable = false)
private Integer status; private Integer status;
@Column(name = "processed", nullable = false) @Column(name = "processed", nullable = false)
private boolean processed; private boolean processed;
@@ -81,20 +81,20 @@ public class Holiday extends AbstractPersistable<Long> {
final String name = command.stringValueOfParameterNamed(HolidayApiConstants.nameParamName); final String name = command.stringValueOfParameterNamed(HolidayApiConstants.nameParamName);
final LocalDate fromDate = command.localDateValueOfParameterNamed(HolidayApiConstants.fromDateParamName); final LocalDate fromDate = command.localDateValueOfParameterNamed(HolidayApiConstants.fromDateParamName);
final LocalDate toDate = command.localDateValueOfParameterNamed(HolidayApiConstants.toDateParamName); final LocalDate toDate = command.localDateValueOfParameterNamed(HolidayApiConstants.toDateParamName);
final LocalDate repaymentsRescheduledTo = command.localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledToParamName); final LocalDate repaymentsRescheduledTo = command
.localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledToParamName);
final Integer status = HolidayStatusType.PENDING_FOR_ACTIVATION.getValue(); final Integer status = HolidayStatusType.PENDING_FOR_ACTIVATION.getValue();
final boolean processed = false;// default it to false. Only batch job final boolean processed = false;// default it to false. Only batch job
// should update this field. // should update this field.
final String description = command.stringValueOfParameterNamed(HolidayApiConstants.descriptionParamName); final String description = command.stringValueOfParameterNamed(HolidayApiConstants.descriptionParamName);
return new Holiday(name, fromDate, toDate, repaymentsRescheduledTo, status, processed, description, offices); return new Holiday(name, fromDate, toDate, repaymentsRescheduledTo, status, processed, description, offices);
} }
public Map<String, Object> update(final JsonCommand command) { public Map<String, Object> update(final JsonCommand command) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(7); final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(7);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("holiday" + ".update");
.resource("holiday" + ".update");
final HolidayStatusType currentStatus = HolidayStatusType.fromInt(this.status); final HolidayStatusType currentStatus = HolidayStatusType.fromInt(this.status);
@@ -106,7 +106,7 @@ public class Holiday extends AbstractPersistable<Long> {
actualChanges.put(nameParamName, newValue); actualChanges.put(nameParamName, newValue);
this.name = StringUtils.defaultIfEmpty(newValue, null); this.name = StringUtils.defaultIfEmpty(newValue, null);
} }
if (command.isChangeInStringParameterNamed(descriptionParamName, this.description)) { if (command.isChangeInStringParameterNamed(descriptionParamName, this.description)) {
final String newValue = command.stringValueOfParameterNamed(descriptionParamName); final String newValue = command.stringValueOfParameterNamed(descriptionParamName);
actualChanges.put(descriptionParamName, newValue); actualChanges.put(descriptionParamName, newValue);
@@ -171,7 +171,7 @@ public class Holiday extends AbstractPersistable<Long> {
return actualChanges; return actualChanges;
} }
public boolean update(final Set<Office> newOffices) { public boolean update(final Set<Office> newOffices) {
if (newOffices == null) { return false; } if (newOffices == null) { return false; }
@@ -260,21 +260,20 @@ public class Holiday extends AbstractPersistable<Long> {
public void processed() { public void processed() {
this.processed = true; this.processed = true;
} }
public void activate() { public void activate() {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("holiday" + ".activate");
.resource("holiday" + ".activate");
final HolidayStatusType currentStatus = HolidayStatusType.fromInt(this.status); final HolidayStatusType currentStatus = HolidayStatusType.fromInt(this.status);
if (!currentStatus.isPendingActivation()) { if (!currentStatus.isPendingActivation()) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("not.in.pending.for.activation.state"); baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("not.in.pending.for.activation.state");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
} }
this.status = HolidayStatusType.ACTIVE.getValue(); this.status = HolidayStatusType.ACTIVE.getValue();
} }
public void delete() { public void delete() {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("holiday" + ".delete"); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("holiday" + ".delete");
@@ -16,7 +16,8 @@ import org.springframework.data.repository.query.Param;
public interface HolidayRepository extends JpaRepository<Holiday, Long>, JpaSpecificationExecutor<Holiday> { public interface HolidayRepository extends JpaRepository<Holiday, Long>, JpaSpecificationExecutor<Holiday> {
@Query("select holiday from Holiday holiday, IN(holiday.offices) office where (holiday.fromDate >= :date OR :date <= holiday.toDate) and holiday.status = :status and office.id = :officeId") @Query("select holiday from Holiday holiday, IN(holiday.offices) office where (holiday.fromDate >= :date OR :date <= holiday.toDate) and holiday.status = :status and office.id = :officeId")
List<Holiday> findByOfficeIdAndGreaterThanDate(@Param("officeId") Long officeId, @Param("date") Date date, @Param("status") Integer status); List<Holiday> findByOfficeIdAndGreaterThanDate(@Param("officeId") Long officeId, @Param("date") Date date,
@Param("status") Integer status);
@Query("from Holiday holiday where holiday.processed = false and holiday.status = :status") @Query("from Holiday holiday where holiday.processed = false and holiday.status = :status")
List<Holiday> findUnprocessed(@Param("status") Integer status); List<Holiday> findUnprocessed(@Param("status") Integer status);
@@ -37,8 +37,8 @@ public class HolidayRepositoryWrapper {
public void save(final Holiday holiday) { public void save(final Holiday holiday) {
this.repository.save(holiday); this.repository.save(holiday);
} }
public void save(final Iterable<Holiday> holidays){ public void save(final Iterable<Holiday> holidays) {
this.repository.save(holidays); this.repository.save(holidays);
} }
@@ -5,7 +5,6 @@
*/ */
package org.mifosplatform.organisation.holiday.domain; package org.mifosplatform.organisation.holiday.domain;
/** /**
* Enum representation of {@link Holiday} status states. * Enum representation of {@link Holiday} status states.
*/ */
@@ -15,7 +14,7 @@ public enum HolidayStatusType {
PENDING_FOR_ACTIVATION(100, "holidayStatusType.pending.for.activation"), // PENDING_FOR_ACTIVATION(100, "holidayStatusType.pending.for.activation"), //
ACTIVE(300, "holidayStatusType.active"), // ACTIVE(300, "holidayStatusType.active"), //
DELETED(600, "savingsAccountStatusType.transfer.in.progress"); DELETED(600, "savingsAccountStatusType.transfer.in.progress");
private final Integer value; private final Integer value;
private final String code; private final String code;
@@ -26,10 +26,12 @@ public class HolidayEnumerations {
HolidayStatusType.PENDING_FOR_ACTIVATION.getCode(), "Pending for activation"); HolidayStatusType.PENDING_FOR_ACTIVATION.getCode(), "Pending for activation");
break; break;
case ACTIVE: case ACTIVE:
optionData = new EnumOptionData(HolidayStatusType.ACTIVE.getValue().longValue(), HolidayStatusType.ACTIVE.getCode(), "Active"); optionData = new EnumOptionData(HolidayStatusType.ACTIVE.getValue().longValue(), HolidayStatusType.ACTIVE.getCode(),
"Active");
break; break;
case DELETED: case DELETED:
optionData = new EnumOptionData(HolidayStatusType.DELETED.getValue().longValue(), HolidayStatusType.DELETED.getCode(), "Deleted"); optionData = new EnumOptionData(HolidayStatusType.DELETED.getValue().longValue(), HolidayStatusType.DELETED.getCode(),
"Deleted");
break; break;
} }
return optionData; return optionData;
@@ -8,6 +8,6 @@ import org.mifosplatform.organisation.holiday.data.HolidayData;
public interface HolidayReadPlatformService { public interface HolidayReadPlatformService {
Collection<HolidayData> retrieveAllHolidaysBySearchParamerters(final Long officeId, Date fromDate, Date toDate); Collection<HolidayData> retrieveAllHolidaysBySearchParamerters(final Long officeId, Date fromDate, Date toDate);
HolidayData retrieveHoliday(final Long holidayId); HolidayData retrieveHoliday(final Long holidayId);
} }
@@ -115,5 +115,5 @@ public class HolidayReadPlatformServiceImpl implements HolidayReadPlatformServic
throw new HolidayNotFoundException(holidayId); throw new HolidayNotFoundException(holidayId);
} }
} }
} }
@@ -7,14 +7,14 @@ import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface HolidayWritePlatformService { public interface HolidayWritePlatformService {
CommandProcessingResult createHoliday(JsonCommand command); CommandProcessingResult createHoliday(JsonCommand command);
CommandProcessingResult updateHoliday(JsonCommand command); CommandProcessingResult updateHoliday(JsonCommand command);
CommandProcessingResult activateHoliday(final Long holidayId); CommandProcessingResult activateHoliday(final Long holidayId);
CommandProcessingResult deleteHoliday(final Long holidayId); CommandProcessingResult deleteHoliday(final Long holidayId);
boolean isHoliday(Long officeId, LocalDate transactionDate); boolean isHoliday(Long officeId, LocalDate transactionDate);
boolean isTransactionAllowedOnHoliday(); boolean isTransactionAllowedOnHoliday();
} }
@@ -51,8 +51,9 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit
@Autowired @Autowired
public HolidayWritePlatformServiceJpaRepositoryImpl(final HolidayDataValidator fromApiJsonDeserializer, public HolidayWritePlatformServiceJpaRepositoryImpl(final HolidayDataValidator fromApiJsonDeserializer,
final HolidayRepositoryWrapper holidayRepository, final PlatformSecurityContext context, final OfficeRepository officeRepository, final HolidayRepositoryWrapper holidayRepository, final PlatformSecurityContext context,
final FromJsonHelper fromApiJsonHelper, final WorkingDaysRepositoryWrapper daysRepositoryWrapper, final ConfigurationDomainService configurationDomainService) { final OfficeRepository officeRepository, final FromJsonHelper fromApiJsonHelper,
final WorkingDaysRepositoryWrapper daysRepositoryWrapper, final ConfigurationDomainService configurationDomainService) {
this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.fromApiJsonDeserializer = fromApiJsonDeserializer;
this.holidayRepository = holidayRepository; this.holidayRepository = holidayRepository;
this.context = context; this.context = context;
@@ -84,7 +85,7 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit
return CommandProcessingResult.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public CommandProcessingResult updateHoliday(final JsonCommand command) { public CommandProcessingResult updateHoliday(final JsonCommand command) {
@@ -114,19 +115,18 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit
return CommandProcessingResult.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public CommandProcessingResult activateHoliday(final Long holidayId) { public CommandProcessingResult activateHoliday(final Long holidayId) {
this.context.authenticatedUser(); this.context.authenticatedUser();
final Holiday holiday = this.holidayRepository.findOneWithNotFoundDetection(holidayId); final Holiday holiday = this.holidayRepository.findOneWithNotFoundDetection(holidayId);
holiday.activate(); holiday.activate();
this.holidayRepository.saveAndFlush(holiday); this.holidayRepository.saveAndFlush(holiday);
return new CommandProcessingResultBuilder() return new CommandProcessingResultBuilder().withEntityId(holiday.getId()).build();
.withEntityId(holiday.getId()).build();
} }
@Transactional @Transactional
@Override @Override
public CommandProcessingResult deleteHoliday(final Long holidayId) { public CommandProcessingResult deleteHoliday(final Long holidayId) {
@@ -134,14 +134,14 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit
final Holiday holiday = this.holidayRepository.findOneWithNotFoundDetection(holidayId); final Holiday holiday = this.holidayRepository.findOneWithNotFoundDetection(holidayId);
holiday.delete(); holiday.delete();
this.holidayRepository.saveAndFlush(holiday); this.holidayRepository.saveAndFlush(holiday);
return new CommandProcessingResultBuilder() return new CommandProcessingResultBuilder().withEntityId(holidayId).build();
.withEntityId(holidayId).build();
} }
private Set<Office> getSelectedOffices(final JsonCommand command) { private Set<Office> getSelectedOffices(final JsonCommand command) {
Set<Office> offices = null; Set<Office> offices = null;
final JsonObject topLevelJsonElement = this.fromApiJsonHelper.parse(command.json()).getAsJsonObject(); final JsonObject topLevelJsonElement = this.fromApiJsonHelper.parse(command.json()).getAsJsonObject();
if (topLevelJsonElement.has(HolidayApiConstants.officesParamName) && topLevelJsonElement.get(HolidayApiConstants.officesParamName).isJsonArray()) { if (topLevelJsonElement.has(HolidayApiConstants.officesParamName)
&& topLevelJsonElement.get(HolidayApiConstants.officesParamName).isJsonArray()) {
final JsonArray array = topLevelJsonElement.get(HolidayApiConstants.officesParamName).getAsJsonArray(); final JsonArray array = topLevelJsonElement.get(HolidayApiConstants.officesParamName).getAsJsonArray();
offices = new HashSet<Office>(array.size()); offices = new HashSet<Office>(array.size());
@@ -172,11 +172,13 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit
private void validateInputDates(final JsonCommand command) { private void validateInputDates(final JsonCommand command) {
final LocalDate fromDate = command.localDateValueOfParameterNamed(HolidayApiConstants.fromDateParamName); final LocalDate fromDate = command.localDateValueOfParameterNamed(HolidayApiConstants.fromDateParamName);
final LocalDate toDate = command.localDateValueOfParameterNamed(HolidayApiConstants.toDateParamName); final LocalDate toDate = command.localDateValueOfParameterNamed(HolidayApiConstants.toDateParamName);
final LocalDate repaymentsRescheduledTo = command.localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledToParamName); final LocalDate repaymentsRescheduledTo = command
.localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledToParamName);
this.validateInputDates(fromDate, toDate, repaymentsRescheduledTo); this.validateInputDates(fromDate, toDate, repaymentsRescheduledTo);
} }
private void validateInputDates(final LocalDate fromDate, final LocalDate toDate, final LocalDate repaymentsRescheduledTo) { private void validateInputDates(final LocalDate fromDate, final LocalDate toDate, final LocalDate repaymentsRescheduledTo) {
String defaultUserMessage = ""; String defaultUserMessage = "";
if (toDate.isBefore(fromDate)) { if (toDate.isBefore(fromDate)) {
@@ -226,5 +228,5 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit
public boolean isTransactionAllowedOnHoliday() { public boolean isTransactionAllowedOnHoliday() {
return this.configurationDomainService.allowTransactionsOnHolidayEnabled(); return this.configurationDomainService.allowTransactionsOnHolidayEnabled();
} }
} }
@@ -78,7 +78,7 @@ public class StaffApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveStaff(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") final String sqlSearch, public String retrieveStaff(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") final String sqlSearch,
@QueryParam("officeId") final Long officeId, @QueryParam("officeId") final Long officeId,
@DefaultValue("false") @QueryParam("staffInOfficeHierarchy") final boolean staffInOfficeHierarchy, @DefaultValue("false") @QueryParam("staffInOfficeHierarchy") final boolean staffInOfficeHierarchy,
@DefaultValue("false") @QueryParam("loanOfficersOnly") final boolean loanOfficersOnly, @DefaultValue("false") @QueryParam("loanOfficersOnly") final boolean loanOfficersOnly,
@DefaultValue("active") @QueryParam("status") final String status) { @DefaultValue("active") @QueryParam("status") final String status) {
@@ -121,7 +121,7 @@ public class StaffApiResource {
if (settings.isTemplate()) { if (settings.isTemplate()) {
final Collection<OfficeData> allowedOffices = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); final Collection<OfficeData> allowedOffices = this.officeReadPlatformService.retrieveAllOfficesForDropdown();
staff = StaffData.templateData(staff, allowedOffices); staff = StaffData.templateData(staff, allowedOffices);
} }
return this.toApiJsonSerializer.serialize(settings, staff, this.RESPONSE_DATA_PARAMETERS); return this.toApiJsonSerializer.serialize(settings, staff, this.RESPONSE_DATA_PARAMETERS);
} }
@@ -38,8 +38,10 @@ public class StaffData {
} }
public static StaffData instance(final Long id, final String firstname, final String lastname, final String displayName, public static StaffData instance(final Long id, final String firstname, final String lastname, final String displayName,
final Long officeId, final String officeName, final Boolean isLoanOfficer, final String externalId, final String mobileNo, final boolean isActive) { final Long officeId, final String officeName, final Boolean isLoanOfficer, final String externalId, final String mobileNo,
return new StaffData(id, firstname, lastname, displayName, officeId, officeName, isLoanOfficer, externalId, mobileNo, null, isActive); final boolean isActive) {
return new StaffData(id, firstname, lastname, displayName, officeId, officeName, isLoanOfficer, externalId, mobileNo, null,
isActive);
} }
private StaffData(final Long id, final String firstname, final String lastname, final String displayName, final Long officeId, private StaffData(final Long id, final String firstname, final String lastname, final String displayName, final Long officeId,
@@ -51,8 +51,8 @@ public class Staff extends AbstractPersistable<Long> {
@Column(name = "organisational_role_enum", nullable = true) @Column(name = "organisational_role_enum", nullable = true)
private Integer organisationalRoleType; private Integer organisationalRoleType;
@Column (name="is_active" , nullable = false) @Column(name = "is_active", nullable = false)
private boolean active; private boolean active;
@ManyToOne @ManyToOne
@@ -75,7 +75,7 @@ public class Staff extends AbstractPersistable<Long> {
final String isLoanOfficerParamName = "isLoanOfficer"; final String isLoanOfficerParamName = "isLoanOfficer";
final boolean isLoanOfficer = command.booleanPrimitiveValueOfParameterNamed(isLoanOfficerParamName); final boolean isLoanOfficer = command.booleanPrimitiveValueOfParameterNamed(isLoanOfficerParamName);
final String isActiveParamName = "isActive"; final String isActiveParamName = "isActive";
final Boolean isActive = command.booleanObjectValueOfParameterNamed(isActiveParamName); final Boolean isActive = command.booleanObjectValueOfParameterNamed(isActiveParamName);
@@ -162,7 +162,7 @@ public class Staff extends AbstractPersistable<Long> {
actualChanges.put(isLoanOfficerParamName, newValue); actualChanges.put(isLoanOfficerParamName, newValue);
this.loanOfficer = newValue; this.loanOfficer = newValue;
} }
final String isActiveParamName = "isActive"; final String isActiveParamName = "isActive";
if (command.isChangeInBooleanParameterNamed(isActiveParamName, this.active)) { if (command.isChangeInBooleanParameterNamed(isActiveParamName, this.active)) {
final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(isActiveParamName); final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(isActiveParamName);
@@ -180,11 +180,11 @@ public class Staff extends AbstractPersistable<Long> {
public boolean isLoanOfficer() { public boolean isLoanOfficer() {
return this.loanOfficer; return this.loanOfficer;
} }
public boolean isNotActive() { public boolean isNotActive() {
return !isActive(); return !isActive();
} }
public boolean isActive() { public boolean isActive() {
return this.active; return this.active;
} }
@@ -72,7 +72,7 @@ public final class StaffCommandFromApiJsonDeserializer {
final Boolean loanOfficerFlag = this.fromApiJsonHelper.extractBooleanNamed("isLoanOfficer", element); final Boolean loanOfficerFlag = this.fromApiJsonHelper.extractBooleanNamed("isLoanOfficer", element);
baseDataValidator.reset().parameter("isLoanOfficer").value(loanOfficerFlag).notNull(); baseDataValidator.reset().parameter("isLoanOfficer").value(loanOfficerFlag).notNull();
} }
if (this.fromApiJsonHelper.parameterExists("isActive", element)) { if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
final Boolean activeFlag = this.fromApiJsonHelper.extractBooleanNamed("isActive", element); final Boolean activeFlag = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
baseDataValidator.reset().parameter("isActive").value(activeFlag).notNull(); baseDataValidator.reset().parameter("isActive").value(activeFlag).notNull();
@@ -115,12 +115,12 @@ public final class StaffCommandFromApiJsonDeserializer {
final Boolean loanOfficerFlag = this.fromApiJsonHelper.extractBooleanNamed("isLoanOfficer", element); final Boolean loanOfficerFlag = this.fromApiJsonHelper.extractBooleanNamed("isLoanOfficer", element);
baseDataValidator.reset().parameter("isLoanOfficer").value(loanOfficerFlag).notNull(); baseDataValidator.reset().parameter("isLoanOfficer").value(loanOfficerFlag).notNull();
} }
if (this.fromApiJsonHelper.parameterExists("isActive", element)) { if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
final Boolean activeFlag = this.fromApiJsonHelper.extractBooleanNamed("isActive", element); final Boolean activeFlag = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
baseDataValidator.reset().parameter("isActive").value(activeFlag).notNull(); baseDataValidator.reset().parameter("isActive").value(activeFlag).notNull();
} }
throwExceptionIfValidationWarningsExist(dataValidationErrors); throwExceptionIfValidationWarningsExist(dataValidationErrors);
} }
@@ -57,7 +57,8 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
final String mobileNo = rs.getString("mobileNo"); final String mobileNo = rs.getString("mobileNo");
final boolean isActive = rs.getBoolean("isActive"); final boolean isActive = rs.getBoolean("isActive");
return StaffData.instance(id, firstname, lastname, displayName, officeId, officeName, isLoanOfficer, externalId, mobileNo, isActive); return StaffData.instance(id, firstname, lastname, displayName, officeId, officeName, isLoanOfficer, externalId, mobileNo,
isActive);
} }
} }
@@ -66,7 +67,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
public String schema(final boolean loanOfficersOnly) { public String schema(final boolean loanOfficersOnly) {
final StringBuilder sqlBuilder = new StringBuilder(200); final StringBuilder sqlBuilder = new StringBuilder(200);
sqlBuilder.append("s.id as id, s.office_id as officeId, ohierarchy.name as officeName,"); sqlBuilder.append("s.id as id, s.office_id as officeId, ohierarchy.name as officeName,");
sqlBuilder.append("s.firstname as firstname, s.lastname as lastname,"); sqlBuilder.append("s.firstname as firstname, s.lastname as lastname,");
sqlBuilder.append("s.display_name as displayName, s.is_loan_officer as isLoanOfficer, s.external_id as externalId, "); sqlBuilder.append("s.display_name as displayName, s.is_loan_officer as isLoanOfficer, s.external_id as externalId, ");
@@ -98,7 +99,8 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
final String mobileNo = rs.getString("mobileNo"); final String mobileNo = rs.getString("mobileNo");
final boolean isActive = rs.getBoolean("isActive"); final boolean isActive = rs.getBoolean("isActive");
return StaffData.instance(id, firstname, lastname, displayName, officeId, officeName, isLoanOfficer, externalId, mobileNo, isActive); return StaffData.instance(id, firstname, lastname, displayName, officeId, officeName, isLoanOfficer, externalId, mobileNo,
isActive);
} }
} }
@@ -165,7 +167,8 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
} }
@Override @Override
public Collection<StaffData> retrieveAllStaff(final String sqlSearch, final Long officeId, final boolean loanOfficersOnly, final String status) { public Collection<StaffData> retrieveAllStaff(final String sqlSearch, final Long officeId, final boolean loanOfficersOnly,
final String status) {
final String extraCriteria = getStaffCriteria(sqlSearch, officeId, loanOfficersOnly, status); final String extraCriteria = getStaffCriteria(sqlSearch, officeId, loanOfficersOnly, status);
return retrieveAllStaff(extraCriteria); return retrieveAllStaff(extraCriteria);
} }
@@ -190,17 +193,17 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
} }
if (officeId != null) { if (officeId != null) {
extraCriteria.append(" and office_id = ").append(officeId).append(" "); extraCriteria.append(" and office_id = ").append(officeId).append(" ");
} }
if (loanOfficersOnly) { if (loanOfficersOnly) {
extraCriteria.append(" and s.is_loan_officer is true "); extraCriteria.append(" and s.is_loan_officer is true ");
} }
// Passing status parameter to get ACTIVE (By Default), INACTIVE or ALL (Both active and Inactive) employees // Passing status parameter to get ACTIVE (By Default), INACTIVE or ALL
// (Both active and Inactive) employees
if (status.equalsIgnoreCase("active")) { if (status.equalsIgnoreCase("active")) {
extraCriteria.append(" and is_active = 1 "); extraCriteria.append(" and is_active = 1 ");
} else if (status.equalsIgnoreCase("inActive")) { } else if (status.equalsIgnoreCase("inActive")) {
extraCriteria.append(" and is_active = 0 "); extraCriteria.append(" and is_active = 0 ");
} else if (status.equalsIgnoreCase("all")) {} } else if (status.equalsIgnoreCase("all")) {} else {
else {
throw new UnrecognizedQueryParamException("status", status, new Object[] { "all", "active", "inactive" }); throw new UnrecognizedQueryParamException("status", status, new Object[] { "all", "active", "inactive" });
} }
@@ -208,7 +211,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
extraCriteria.delete(0, 4); extraCriteria.delete(0, 4);
} }
//remove begin four letter including a space from the string. // remove begin four letter including a space from the string.
return extraCriteria.toString(); return extraCriteria.toString();
} }
@@ -100,6 +100,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla
return CommandProcessingResult.empty(); return CommandProcessingResult.empty();
} }
} }
/* /*
* Guaranteed to throw an exception no matter what the data integrity issue * Guaranteed to throw an exception no matter what the data integrity issue
* is. * is.
@@ -3,8 +3,8 @@ package org.mifosplatform.organisation.workingdays.service;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
public interface WorkingDaysWritePlatformService { public interface WorkingDaysWritePlatformService {
boolean isWorkingDay(LocalDate transactionDate); boolean isWorkingDay(LocalDate transactionDate);
boolean isTransactionAllowedOnNonWorkingDay(); boolean isTransactionAllowedOnNonWorkingDay();
} }
@@ -98,7 +98,8 @@ public class AccountTransfersApiResource {
this.context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); this.context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME);
final SearchParameters searchParameters = SearchParameters.forAccountTransfer(sqlSearch, externalId, offset, limit, orderBy, sortOrder); final SearchParameters searchParameters = SearchParameters.forAccountTransfer(sqlSearch, externalId, offset, limit, orderBy,
sortOrder);
final Page<AccountTransferData> transfers = this.accountTransfersReadPlatformService.retrieveAll(searchParameters); final Page<AccountTransferData> transfers = this.accountTransfersReadPlatformService.retrieveAll(searchParameters);
@@ -28,7 +28,8 @@ public class AccountTransferDTO {
public AccountTransferDTO(final LocalDate transactionDate, final BigDecimal transactionAmount, public AccountTransferDTO(final LocalDate transactionDate, final BigDecimal transactionAmount,
final PortfolioAccountType fromAccountType, final PortfolioAccountType toAccountType, final Long fromAccountId, final PortfolioAccountType fromAccountType, final PortfolioAccountType toAccountType, final Long fromAccountId,
final Long toAccountId, final String description, final Locale locale, final DateTimeFormatter fmt, final Long toAccountId, final String description, final Locale locale, final DateTimeFormatter fmt,
final PaymentDetail paymentDetail, final Integer fromTransferType, final Integer toTransferType, final Long chargeId, Integer loanInstallmentNumber) { final PaymentDetail paymentDetail, final Integer fromTransferType, final Integer toTransferType, final Long chargeId,
Integer loanInstallmentNumber) {
this.transactionDate = transactionDate; this.transactionDate = transactionDate;
this.transactionAmount = transactionAmount; this.transactionAmount = transactionAmount;
this.fromAccountType = fromAccountType; this.fromAccountType = fromAccountType;
@@ -97,7 +98,6 @@ public class AccountTransferDTO {
return this.chargeId; return this.chargeId;
} }
public Integer getLoanInstallmentNumber() { public Integer getLoanInstallmentNumber() {
return this.loanInstallmentNumber; return this.loanInstallmentNumber;
} }
@@ -176,7 +176,6 @@ public class AccountTransfer extends AbstractPersistable<Long> {
return this.fromAccount; return this.fromAccount;
} }
public void updateToLoanTransaction(LoanTransaction toLoanTransaction) { public void updateToLoanTransaction(LoanTransaction toLoanTransaction) {
this.toLoanTransaction = toLoanTransaction; this.toLoanTransaction = toLoanTransaction;
} }
@@ -19,7 +19,7 @@ public interface AccountTransferRepository extends JpaRepository<AccountTransfer
@Query("from AccountTransfer at where (at.fromLoanAccount.id= :accountNumber or at.toLoanAccount.id=:accountNumber) and at.reversed=false") @Query("from AccountTransfer at where (at.fromLoanAccount.id= :accountNumber or at.toLoanAccount.id=:accountNumber) and at.reversed=false")
List<AccountTransfer> findAllByLoanId(@Param("accountNumber") Long accountNumber); List<AccountTransfer> findAllByLoanId(@Param("accountNumber") Long accountNumber);
@Query("from AccountTransfer at where at.toLoanTransaction.id= :loanTransactionId and at.reversed=false") @Query("from AccountTransfer at where at.toLoanTransaction.id= :loanTransactionId and at.reversed=false")
AccountTransfer findByToLoanTransactionId(@Param("loanTransactionId") Long loanTransactionId); AccountTransfer findByToLoanTransactionId(@Param("loanTransactionId") Long loanTransactionId);
} }
@@ -229,7 +229,8 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
final LoanTransaction loanRepaymentTransaction = this.loanAccountDomainService.makeChargePayment(toLoanAccount, final LoanTransaction loanRepaymentTransaction = this.loanAccountDomainService.makeChargePayment(toLoanAccount,
accountTransferDTO.getChargeId(), accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(), accountTransferDTO.getChargeId(), accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(),
accountTransferDTO.getPaymentDetail(), null, null, accountTransferDTO.getToTransferType(), accountTransferDTO.getLoanInstallmentNumber()); accountTransferDTO.getPaymentDetail(), null, null, accountTransferDTO.getToTransferType(),
accountTransferDTO.getLoanInstallmentNumber());
final AccountTransfer transferTransaction = this.accountTransferAssembler.assembleSavingsToLoanTransfer(accountTransferDTO, final AccountTransfer transferTransaction = this.accountTransferAssembler.assembleSavingsToLoanTransfer(accountTransferDTO,
fromSavingsAccount, toLoanAccount, withdrawal, loanRepaymentTransaction); fromSavingsAccount, toLoanAccount, withdrawal, loanRepaymentTransaction);
@@ -239,12 +240,12 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
return transferTransactionId; return transferTransactionId;
} }
@Override @Override
@Transactional @Transactional
public void updateLoanTransaction(final Long loanTransactionId,final LoanTransaction newLoanTransaction){ public void updateLoanTransaction(final Long loanTransactionId, final LoanTransaction newLoanTransaction) {
final AccountTransfer transferTransaction = this.accountTransferRepository.findByToLoanTransactionId(loanTransactionId); final AccountTransfer transferTransaction = this.accountTransferRepository.findByToLoanTransactionId(loanTransactionId);
if(transferTransaction!=null){ if (transferTransaction != null) {
transferTransaction.updateToLoanTransaction(newLoanTransaction); transferTransaction.updateToLoanTransaction(newLoanTransaction);
this.accountTransferRepository.save(transferTransaction); this.accountTransferRepository.save(transferTransaction);
} }
@@ -181,7 +181,7 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou
final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf");
final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf,
currencyDisplaySymbol, currencyNameCode); currencyDisplaySymbol, currencyNameCode);
final LocalDate submittedOnDate = JdbcSupport.getLocalDate(rs, "submittedOnDate"); final LocalDate submittedOnDate = JdbcSupport.getLocalDate(rs, "submittedOnDate");
final String submittedByUsername = rs.getString("submittedByUsername"); final String submittedByUsername = rs.getString("submittedByUsername");
final String submittedByFirstname = rs.getString("submittedByFirstname"); final String submittedByFirstname = rs.getString("submittedByFirstname");
@@ -10,7 +10,8 @@ import java.util.Set;
public class CalendarConstants { public class CalendarConstants {
public static final String CALENDAR_RESOURCE_NAME = "calendar"; public static final String CALENDAR_RESOURCE_NAME = "calendar";
public static enum CALENDAR_SUPPORTED_PARAMETERS { public static enum CALENDAR_SUPPORTED_PARAMETERS {
CALENDAR_ID("id"), ENTITY_TYPE("entityType"), ENTITY_ID("entityId"), TITLE("title"), DESCRIPTION("description"), LOCATION( CALENDAR_ID("id"), ENTITY_TYPE("entityType"), ENTITY_ID("entityId"), TITLE("title"), DESCRIPTION("description"), LOCATION(
"location"), START_DATE("startDate"), END_DATE("endDate"), CREATED_DATE("createdDate"), DURATION("duration"), TYPE_ID( "location"), START_DATE("startDate"), END_DATE("endDate"), CREATED_DATE("createdDate"), DURATION("duration"), TYPE_ID(
@@ -55,12 +55,12 @@ public class CalendarsApiResource {
/** /**
* The set of parameters that are supported in response for {@link Calendar} * The set of parameters that are supported in response for {@link Calendar}
*/ */
private final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<String>( private final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<String>(Arrays.asList("id", "entityId", "entityType", "title",
Arrays.asList("id", "entityId", "entityType", "title", "description", "location", "startDate", "endDate", "duration", "type", "description", "location", "startDate", "endDate", "duration", "type", "repeating", "recurrence", "frequency", "interval",
"repeating", "recurrence", "frequency", "interval", "repeatsOnDay", "remindBy", "firstReminder", "secondReminder", "repeatsOnDay", "remindBy", "firstReminder", "secondReminder", "humanReadable", "createdDate", "lastUpdatedDate",
"humanReadable", "createdDate", "lastUpdatedDate", "createdByUserId", "createdByUsername", "lastUpdatedByUserId", "createdByUserId", "createdByUsername", "lastUpdatedByUserId", "lastUpdatedByUsername", "recurringDates",
"lastUpdatedByUsername", "recurringDates", "nextTenRecurringDates", "entityTypeOptions", "calendarTypeOptions", "nextTenRecurringDates", "entityTypeOptions", "calendarTypeOptions", "remindByOptions", "frequencyOptions",
"remindByOptions", "frequencyOptions", "repeatsOnDayOptions")); "repeatsOnDayOptions"));
private final String resourceNameForPermissions = "CALENDAR"; private final String resourceNameForPermissions = "CALENDAR";
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
@@ -60,12 +60,13 @@ public class CalendarData {
final List<EnumOptionData> frequencyOptions; final List<EnumOptionData> frequencyOptions;
final List<EnumOptionData> repeatsOnDayOptions; final List<EnumOptionData> repeatsOnDayOptions;
public static CalendarData instance(final Long id, final Long calendarInstanceId, final Long entityId, final EnumOptionData entityType, final String title, public static CalendarData instance(final Long id, final Long calendarInstanceId, final Long entityId, final EnumOptionData entityType,
final String description, final String location, final LocalDate startDate, final LocalDate endDate, final Integer duration, final String title, final String description, final String location, final LocalDate startDate, final LocalDate endDate,
final EnumOptionData type, final boolean repeating, final String recurrence, final EnumOptionData frequency, final Integer duration, final EnumOptionData type, final boolean repeating, final String recurrence,
final Integer interval, final EnumOptionData repeatsOnDay, final EnumOptionData remindBy, final Integer firstReminder, final EnumOptionData frequency, final Integer interval, final EnumOptionData repeatsOnDay, final EnumOptionData remindBy,
final Integer secondReminder, final String humanReadable, final LocalDate createdDate, final LocalDate lastUpdatedDate, final Integer firstReminder, final Integer secondReminder, final String humanReadable, final LocalDate createdDate,
final Long createdByUserId, final String createdByUsername, final Long lastUpdatedByUserId, final String lastUpdatedByUsername) { final LocalDate lastUpdatedDate, final Long createdByUserId, final String createdByUsername, final Long lastUpdatedByUserId,
final String lastUpdatedByUsername) {
final Collection<LocalDate> recurringDates = null; final Collection<LocalDate> recurringDates = null;
final Collection<LocalDate> nextTenRecurringDates = null; final Collection<LocalDate> nextTenRecurringDates = null;
@@ -77,8 +78,8 @@ public class CalendarData {
final List<EnumOptionData> frequencyOptions = null; final List<EnumOptionData> frequencyOptions = null;
final List<EnumOptionData> repeatsOnDayOptions = null; final List<EnumOptionData> repeatsOnDayOptions = null;
return new CalendarData(id, calendarInstanceId, entityId, entityType, title, description, location, startDate, endDate, duration, type, repeating, return new CalendarData(id, calendarInstanceId, entityId, entityType, title, description, location, startDate, endDate, duration,
recurrence, frequency, interval, repeatsOnDay, remindBy, firstReminder, secondReminder, recurringDates, type, repeating, recurrence, frequency, interval, repeatsOnDay, remindBy, firstReminder, secondReminder, recurringDates,
nextTenRecurringDates, humanReadable, recentEligibleMeetingDate, createdDate, lastUpdatedDate, createdByUserId, nextTenRecurringDates, humanReadable, recentEligibleMeetingDate, createdDate, lastUpdatedDate, createdByUserId,
createdByUsername, lastUpdatedByUserId, lastUpdatedByUsername, entityTypeOptions, calendarTypeOptions, remindByOptions, createdByUsername, lastUpdatedByUserId, lastUpdatedByUsername, entityTypeOptions, calendarTypeOptions, remindByOptions,
frequencyOptions, repeatsOnDayOptions); frequencyOptions, repeatsOnDayOptions);
@@ -86,27 +87,27 @@ public class CalendarData {
public static CalendarData withRecurringDates(final CalendarData calendarData, final Collection<LocalDate> recurringDates, public static CalendarData withRecurringDates(final CalendarData calendarData, final Collection<LocalDate> recurringDates,
final Collection<LocalDate> nextTenRecurringDates, final LocalDate recentEligibleMeetingDate) { final Collection<LocalDate> nextTenRecurringDates, final LocalDate recentEligibleMeetingDate) {
return new CalendarData(calendarData.id, calendarData.calendarInstanceId, calendarData.entityId, calendarData.entityType, calendarData.title, return new CalendarData(calendarData.id, calendarData.calendarInstanceId, calendarData.entityId, calendarData.entityType,
calendarData.description, calendarData.location, calendarData.startDate, calendarData.endDate, calendarData.duration, calendarData.title, calendarData.description, calendarData.location, calendarData.startDate, calendarData.endDate,
calendarData.type, calendarData.repeating, calendarData.recurrence, calendarData.frequency, calendarData.interval, calendarData.duration, calendarData.type, calendarData.repeating, calendarData.recurrence, calendarData.frequency,
calendarData.repeatsOnDay, calendarData.remindBy, calendarData.firstReminder, calendarData.secondReminder, recurringDates, calendarData.interval, calendarData.repeatsOnDay, calendarData.remindBy, calendarData.firstReminder,
nextTenRecurringDates, calendarData.humanReadable, recentEligibleMeetingDate, calendarData.createdDate, calendarData.secondReminder, recurringDates, nextTenRecurringDates, calendarData.humanReadable, recentEligibleMeetingDate,
calendarData.lastUpdatedDate, calendarData.createdByUserId, calendarData.createdByUsername, calendarData.createdDate, calendarData.lastUpdatedDate, calendarData.createdByUserId, calendarData.createdByUsername,
calendarData.lastUpdatedByUserId, calendarData.lastUpdatedByUsername, calendarData.entityTypeOptions, calendarData.lastUpdatedByUserId, calendarData.lastUpdatedByUsername, calendarData.entityTypeOptions,
calendarData.calendarTypeOptions, calendarData.remindByOptions, calendarData.frequencyOptions, calendarData.calendarTypeOptions, calendarData.remindByOptions, calendarData.frequencyOptions,
calendarData.repeatsOnDayOptions); calendarData.repeatsOnDayOptions);
} }
public static CalendarData withRecentEligibleMeetingDate(final CalendarData calendarData, final LocalDate recentEligibleMeetingDate) { public static CalendarData withRecentEligibleMeetingDate(final CalendarData calendarData, final LocalDate recentEligibleMeetingDate) {
return new CalendarData(calendarData.id, calendarData.calendarInstanceId, calendarData.entityId, calendarData.entityType, calendarData.title, return new CalendarData(calendarData.id, calendarData.calendarInstanceId, calendarData.entityId, calendarData.entityType,
calendarData.description, calendarData.location, calendarData.startDate, calendarData.endDate, calendarData.duration, calendarData.title, calendarData.description, calendarData.location, calendarData.startDate, calendarData.endDate,
calendarData.type, calendarData.repeating, calendarData.recurrence, calendarData.frequency, calendarData.interval, calendarData.duration, calendarData.type, calendarData.repeating, calendarData.recurrence, calendarData.frequency,
calendarData.repeatsOnDay, calendarData.remindBy, calendarData.firstReminder, calendarData.secondReminder, calendarData.recurringDates, calendarData.interval, calendarData.repeatsOnDay, calendarData.remindBy, calendarData.firstReminder,
calendarData.nextTenRecurringDates, calendarData.humanReadable, recentEligibleMeetingDate, calendarData.createdDate, calendarData.secondReminder, calendarData.recurringDates, calendarData.nextTenRecurringDates, calendarData.humanReadable,
calendarData.lastUpdatedDate, calendarData.createdByUserId, calendarData.createdByUsername, recentEligibleMeetingDate, calendarData.createdDate, calendarData.lastUpdatedDate, calendarData.createdByUserId,
calendarData.lastUpdatedByUserId, calendarData.lastUpdatedByUsername, calendarData.entityTypeOptions, calendarData.createdByUsername, calendarData.lastUpdatedByUserId, calendarData.lastUpdatedByUsername,
calendarData.calendarTypeOptions, calendarData.remindByOptions, calendarData.frequencyOptions, calendarData.entityTypeOptions, calendarData.calendarTypeOptions, calendarData.remindByOptions,
calendarData.repeatsOnDayOptions); calendarData.frequencyOptions, calendarData.repeatsOnDayOptions);
} }
public static CalendarData sensibleDefaultsForNewCalendarCreation() { public static CalendarData sensibleDefaultsForNewCalendarCreation() {
@@ -147,8 +148,8 @@ public class CalendarData {
final Long lastUpdatedByUserId = null; final Long lastUpdatedByUserId = null;
final String lastUpdatedByUsername = null; final String lastUpdatedByUsername = null;
return new CalendarData(id, calendarInstanceId, entityId, entityType, title, description, location, startDate, endDate, duration, type, repeating, return new CalendarData(id, calendarInstanceId, entityId, entityType, title, description, location, startDate, endDate, duration,
recurrence, frequency, interval, repeatsOnDay, remindBy, firstReminder, secondReminder, recurringDates, type, repeating, recurrence, frequency, interval, repeatsOnDay, remindBy, firstReminder, secondReminder, recurringDates,
nextTenRecurringDates, humanReadable, recentEligibleMeetingDate, createdDate, lastUpdatedDate, createdByUserId, nextTenRecurringDates, humanReadable, recentEligibleMeetingDate, createdDate, lastUpdatedDate, createdByUserId,
createdByUsername, lastUpdatedByUserId, lastUpdatedByUsername, entityTypeOptions, calendarTypeOptions, remindByOptions, createdByUsername, lastUpdatedByUserId, lastUpdatedByUsername, entityTypeOptions, calendarTypeOptions, remindByOptions,
frequencyOptions, repeatsOnDayOptions); frequencyOptions, repeatsOnDayOptions);
@@ -158,26 +159,27 @@ public class CalendarData {
final List<EnumOptionData> calendarTypeOptions, final List<EnumOptionData> remindByOptions, final List<EnumOptionData> calendarTypeOptions, final List<EnumOptionData> remindByOptions,
final List<EnumOptionData> repeatsOptions, final List<EnumOptionData> repeatsOnDayOptions) { final List<EnumOptionData> repeatsOptions, final List<EnumOptionData> repeatsOnDayOptions) {
return new CalendarData(calendarData.id, calendarData.calendarInstanceId, calendarData.entityId, calendarData.entityType, calendarData.title, return new CalendarData(calendarData.id, calendarData.calendarInstanceId, calendarData.entityId, calendarData.entityType,
calendarData.description, calendarData.location, calendarData.startDate, calendarData.endDate, calendarData.duration, calendarData.title, calendarData.description, calendarData.location, calendarData.startDate, calendarData.endDate,
calendarData.type, calendarData.repeating, calendarData.recurrence, calendarData.frequency, calendarData.interval, calendarData.duration, calendarData.type, calendarData.repeating, calendarData.recurrence, calendarData.frequency,
calendarData.repeatsOnDay, calendarData.remindBy, calendarData.firstReminder, calendarData.secondReminder, calendarData.interval, calendarData.repeatsOnDay, calendarData.remindBy, calendarData.firstReminder,
calendarData.recurringDates, calendarData.nextTenRecurringDates, calendarData.humanReadable, calendarData.secondReminder, calendarData.recurringDates, calendarData.nextTenRecurringDates, calendarData.humanReadable,
calendarData.recentEligibleMeetingDate, calendarData.createdDate, calendarData.lastUpdatedDate, calendarData.recentEligibleMeetingDate, calendarData.createdDate, calendarData.lastUpdatedDate,
calendarData.createdByUserId, calendarData.createdByUsername, calendarData.lastUpdatedByUserId, calendarData.lastUpdatedByUsername, calendarData.createdByUserId, calendarData.createdByUsername, calendarData.lastUpdatedByUserId,
entityTypeOptions, calendarTypeOptions, remindByOptions, repeatsOptions, repeatsOnDayOptions); calendarData.lastUpdatedByUsername, entityTypeOptions, calendarTypeOptions, remindByOptions, repeatsOptions,
repeatsOnDayOptions);
} }
private CalendarData(final Long id, final Long calendarInstanceId, final Long entityId, final EnumOptionData entityType, final String title, final String description, private CalendarData(final Long id, final Long calendarInstanceId, final Long entityId, final EnumOptionData entityType,
final String location, final LocalDate startDate, final LocalDate endDate, final Integer duration, final EnumOptionData type, final String title, final String description, final String location, final LocalDate startDate, final LocalDate endDate,
final boolean repeating, final String recurrence, final EnumOptionData frequency, final Integer interval, final Integer duration, final EnumOptionData type, final boolean repeating, final String recurrence,
final EnumOptionData repeatsOnDay, final EnumOptionData remindBy, final Integer firstReminder, final Integer secondReminder, final EnumOptionData frequency, final Integer interval, final EnumOptionData repeatsOnDay, final EnumOptionData remindBy,
final Collection<LocalDate> recurringDates, final Collection<LocalDate> nextTenRecurringDates, final String humanReadable, final Integer firstReminder, final Integer secondReminder, final Collection<LocalDate> recurringDates,
final LocalDate recentEligibleMeetingDate, final LocalDate createdDate, final LocalDate lastUpdatedDate, final Collection<LocalDate> nextTenRecurringDates, final String humanReadable, final LocalDate recentEligibleMeetingDate,
final Long createdByUserId, final String createdByUsername, final Long lastUpdatedByUserId, final String lastUpdatedByUsername, final LocalDate createdDate, final LocalDate lastUpdatedDate, final Long createdByUserId, final String createdByUsername,
final List<EnumOptionData> entityTypeOptions, final List<EnumOptionData> calendarTypeOptions, final Long lastUpdatedByUserId, final String lastUpdatedByUsername, final List<EnumOptionData> entityTypeOptions,
final List<EnumOptionData> remindByOptions, final List<EnumOptionData> repeatsOptions, final List<EnumOptionData> calendarTypeOptions, final List<EnumOptionData> remindByOptions,
final List<EnumOptionData> repeatsOnDayOptions) { final List<EnumOptionData> repeatsOptions, final List<EnumOptionData> repeatsOnDayOptions) {
this.id = id; this.id = id;
this.calendarInstanceId = calendarInstanceId; this.calendarInstanceId = calendarInstanceId;
this.entityId = entityId; this.entityId = entityId;
@@ -294,18 +296,17 @@ public class CalendarData {
return this.humanReadable; return this.humanReadable;
} }
public Long getCalendarInstanceId() { public Long getCalendarInstanceId() {
return this.calendarInstanceId; return this.calendarInstanceId;
} }
public boolean isStartDateBeforeOrEqual(final LocalDate compareDate) { public boolean isStartDateBeforeOrEqual(final LocalDate compareDate) {
if (this.startDate != null && compareDate != null) { if (this.startDate != null && compareDate != null) {
if (this.startDate.isBefore(compareDate) || this.startDate.equals(compareDate)) { return true; } if (this.startDate.isBefore(compareDate) || this.startDate.equals(compareDate)) { return true; }
} }
return false; return false;
} }
public boolean isEndDateAfterOrEqual(final LocalDate compareDate) { public boolean isEndDateAfterOrEqual(final LocalDate compareDate) {
if (this.endDate != null && compareDate != null) { if (this.endDate != null && compareDate != null) {
if (this.endDate.isAfter(compareDate) || this.endDate.isEqual(compareDate)) { return true; } if (this.endDate.isAfter(compareDate) || this.endDate.isEqual(compareDate)) { return true; }
@@ -313,15 +314,13 @@ public class CalendarData {
return false; return false;
} }
public boolean isBetweenStartAndEndDate(final LocalDate compareDate){ public boolean isBetweenStartAndEndDate(final LocalDate compareDate) {
if (isStartDateBeforeOrEqual(compareDate)){ if (isStartDateBeforeOrEqual(compareDate)) {
if (this.endDate == null || isEndDateAfterOrEqual(compareDate)){ if (this.endDate == null || isEndDateAfterOrEqual(compareDate)) { return true; }
return true;
}
} }
return false; return false;
} }
public boolean isValidRecurringDate(final LocalDate compareDate) { public boolean isValidRecurringDate(final LocalDate compareDate) {
if (isBetweenStartAndEndDate(compareDate)) { return CalendarUtils.isValidRedurringDate(this.getRecurrence(), this.getStartDate(), if (isBetweenStartAndEndDate(compareDate)) { return CalendarUtils.isValidRedurringDate(this.getRecurrence(), this.getStartDate(),
compareDate); } compareDate); }
@@ -84,7 +84,7 @@ public class Calendar extends AbstractAuditableCustom<AppUser, Long> {
@OneToMany(fetch = FetchType.EAGER) @OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "calendar_id") @JoinColumn(name = "calendar_id")
private Set<CalendarHistory> calendarHistory = new HashSet<CalendarHistory>(); private Set<CalendarHistory> calendarHistory = new HashSet<CalendarHistory>();
protected Calendar() { protected Calendar() {
} }
@@ -182,13 +182,13 @@ public class Calendar extends AbstractAuditableCustom<AppUser, Long> {
final String valueAsInput = command.stringValueOfParameterNamed(startDateParamName); final String valueAsInput = command.stringValueOfParameterNamed(startDateParamName);
final LocalDate newValue = command.localDateValueOfParameterNamed(startDateParamName); final LocalDate newValue = command.localDateValueOfParameterNamed(startDateParamName);
final LocalDate currentDate = DateUtils.getLocalDateOfTenant(); final LocalDate currentDate = DateUtils.getLocalDateOfTenant();
if (newValue.isBefore(currentDate)) { if (newValue.isBefore(currentDate)) {
final String defaultUserMessage = "New meeting effective from date cannot be in past"; final String defaultUserMessage = "New meeting effective from date cannot be in past";
throw new CalendarDateException("new.start.date.cannot.be.in.past", defaultUserMessage, newValue, throw new CalendarDateException("new.start.date.cannot.be.in.past", defaultUserMessage, newValue, getStartDateLocalDate());
getStartDateLocalDate()); } else if (isStartDateAfter(newValue) && isStartDateBeforeOrEqual(currentDate)) {
}else if (isStartDateAfter(newValue) && isStartDateBeforeOrEqual(currentDate)) { // new meeting date should be on or after start date or current
//new meeting date should be on or after start date or current date // date
final String defaultUserMessage = "New meeting effective from date cannot be a date before existing meeting start date"; final String defaultUserMessage = "New meeting effective from date cannot be a date before existing meeting start date";
throw new CalendarDateException("new.start.date.before.existing.date", defaultUserMessage, newValue, throw new CalendarDateException("new.start.date.before.existing.date", defaultUserMessage, newValue,
getStartDateLocalDate()); getStartDateLocalDate());
@@ -244,8 +244,8 @@ public class Calendar extends AbstractAuditableCustom<AppUser, Long> {
this.repeating = newValue; this.repeating = newValue;
} }
//if repeating is false then update recurrence to NULL // if repeating is false then update recurrence to NULL
if(!this.repeating) this.recurrence = null; if (!this.repeating) this.recurrence = null;
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CALENDAR_RESOURCE_NAME); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CALENDAR_RESOURCE_NAME);
@@ -256,7 +256,7 @@ public class Calendar extends AbstractAuditableCustom<AppUser, Long> {
.failWithCodeNoParameterAddedToErrorCode("must.repeat.for.collection.calendar"); .failWithCodeNoParameterAddedToErrorCode("must.repeat.for.collection.calendar");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
} }
final String newRecurrence = Calendar.constructRecurrence(command, this); final String newRecurrence = Calendar.constructRecurrence(command, this);
if (!StringUtils.isBlank(this.recurrence) && !newRecurrence.equalsIgnoreCase(this.recurrence)) { if (!StringUtils.isBlank(this.recurrence) && !newRecurrence.equalsIgnoreCase(this.recurrence)) {
@@ -365,7 +365,7 @@ public class Calendar extends AbstractAuditableCustom<AppUser, Long> {
} }
return endDateLocalDate; return endDateLocalDate;
} }
public Set<CalendarHistory> history() { public Set<CalendarHistory> history() {
return this.calendarHistory; return this.calendarHistory;
} }
@@ -374,38 +374,36 @@ public class Calendar extends AbstractAuditableCustom<AppUser, Long> {
if (this.startDate != null && compareDate != null && getStartDateLocalDate().isBefore(compareDate)) { return true; } if (this.startDate != null && compareDate != null && getStartDateLocalDate().isBefore(compareDate)) { return true; }
return false; return false;
} }
public boolean isStartDateBeforeOrEqual(final LocalDate compareDate) { public boolean isStartDateBeforeOrEqual(final LocalDate compareDate) {
if (this.startDate != null && compareDate != null) { if (this.startDate != null && compareDate != null) {
if (getStartDateLocalDate().isBefore(compareDate) || getStartDateLocalDate().equals(compareDate)) { return true; } if (getStartDateLocalDate().isBefore(compareDate) || getStartDateLocalDate().equals(compareDate)) { return true; }
} }
return false; return false;
} }
public boolean isStartDateAfter(final LocalDate compareDate) { public boolean isStartDateAfter(final LocalDate compareDate) {
if (this.startDate != null && compareDate != null && getStartDateLocalDate().isAfter(compareDate)) { return true; } if (this.startDate != null && compareDate != null && getStartDateLocalDate().isAfter(compareDate)) { return true; }
return false; return false;
} }
public boolean isStartDateAfterOrEqual(final LocalDate compareDate) { public boolean isStartDateAfterOrEqual(final LocalDate compareDate) {
if (this.startDate != null && compareDate != null) { if (this.startDate != null && compareDate != null) {
if (getStartDateLocalDate().isAfter(compareDate) || getStartDateLocalDate().isEqual(compareDate)) { return true; } if (getStartDateLocalDate().isAfter(compareDate) || getStartDateLocalDate().isEqual(compareDate)) { return true; }
} }
return false; return false;
} }
public boolean isEndDateAfterOrEqual(final LocalDate compareDate) { public boolean isEndDateAfterOrEqual(final LocalDate compareDate) {
if (this.endDate != null && compareDate != null) { if (this.endDate != null && compareDate != null) {
if (getEndDateLocalDate().isAfter(compareDate) || getEndDateLocalDate().isEqual(compareDate)) { return true; } if (getEndDateLocalDate().isAfter(compareDate) || getEndDateLocalDate().isEqual(compareDate)) { return true; }
} }
return false; return false;
} }
public boolean isBetweenStartAndEndDate(final LocalDate compareDate){ public boolean isBetweenStartAndEndDate(final LocalDate compareDate) {
if (isStartDateBeforeOrEqual(compareDate)){ if (isStartDateBeforeOrEqual(compareDate)) {
if (getEndDateLocalDate() == null || isEndDateAfterOrEqual(compareDate)){ if (getEndDateLocalDate() == null || isEndDateAfterOrEqual(compareDate)) { return true; }
return true;
}
} }
return false; return false;
} }
@@ -443,7 +441,7 @@ public class Calendar extends AbstractAuditableCustom<AppUser, Long> {
} }
return ""; return "";
} }
public boolean isValidRecurringDate(final LocalDate compareDate) { public boolean isValidRecurringDate(final LocalDate compareDate) {
if (isBetweenStartAndEndDate(compareDate)) { return CalendarUtils.isValidRedurringDate(getRecurrence(), getStartDateLocalDate(), if (isBetweenStartAndEndDate(compareDate)) { return CalendarUtils.isValidRedurringDate(getRecurrence(), getStartDateLocalDate(),
@@ -82,7 +82,7 @@ public enum CalendarEntityType {
public static boolean isCenter(final String name) { public static boolean isCenter(final String name) {
return CalendarEntityType.CENTERS.name().equalsIgnoreCase(name) ? true : false; return CalendarEntityType.CENTERS.name().equalsIgnoreCase(name) ? true : false;
} }
public static boolean isLoan(final Integer value) { public static boolean isLoan(final Integer value) {
return CalendarEntityType.LOANS.value.equals(value) ? true : false; return CalendarEntityType.LOANS.value.equals(value) ? true : false;
} }
@@ -90,7 +90,7 @@ public enum CalendarEntityType {
public static boolean isLoan(final String name) { public static boolean isLoan(final String name) {
return CalendarEntityType.LOANS.name().equalsIgnoreCase(name) ? true : false; return CalendarEntityType.LOANS.name().equalsIgnoreCase(name) ? true : false;
} }
public static boolean isClient(final Integer value) { public static boolean isClient(final Integer value) {
return CalendarEntityType.CLIENTS.value.equals(value) ? true : false; return CalendarEntityType.CLIENTS.value.equals(value) ? true : false;
} }
@@ -98,19 +98,19 @@ public enum CalendarEntityType {
public static boolean isClient(final String name) { public static boolean isClient(final String name) {
return CalendarEntityType.CLIENTS.name().equalsIgnoreCase(name) ? true : false; return CalendarEntityType.CLIENTS.name().equalsIgnoreCase(name) ? true : false;
} }
public boolean isCenter() { public boolean isCenter() {
return this.value.equals(CalendarEntityType.CENTERS.getValue()); return this.value.equals(CalendarEntityType.CENTERS.getValue());
} }
public boolean isGroup() { public boolean isGroup() {
return this.value.equals(CalendarEntityType.GROUPS.getValue()); return this.value.equals(CalendarEntityType.GROUPS.getValue());
} }
public boolean isLoan() { public boolean isLoan() {
return this.value.equals(CalendarEntityType.LOANS.getValue()); return this.value.equals(CalendarEntityType.LOANS.getValue());
} }
public boolean isClient() { public boolean isClient() {
return this.value.equals(CalendarEntityType.CLIENTS.getValue()); return this.value.equals(CalendarEntityType.CLIENTS.getValue());
} }
@@ -40,7 +40,7 @@ public enum CalendarFrequencyType {
intToEnumMap.put(type.value, type); intToEnumMap.put(type.value, type);
} }
} }
public static CalendarFrequencyType fromInt(final int i) { public static CalendarFrequencyType fromInt(final int i) {
final CalendarFrequencyType type = intToEnumMap.get(Integer.valueOf(i)); final CalendarFrequencyType type = intToEnumMap.get(Integer.valueOf(i));
return type; return type;
@@ -63,7 +63,7 @@ public enum CalendarFrequencyType {
return frequency; return frequency;
} }
public static int getMinValue() { public static int getMinValue() {
return minValue; return minValue;
} }
@@ -76,12 +76,12 @@ public enum CalendarFrequencyType {
public String toString() { public String toString() {
return name().toString(); return name().toString();
} }
public boolean isWeekly(){ public boolean isWeekly() {
return this.value.equals(CalendarFrequencyType.WEEKLY.value); return this.value.equals(CalendarFrequencyType.WEEKLY.value);
} }
public boolean isInvalid(){ public boolean isInvalid() {
return this.value.equals(CalendarFrequencyType.INVALID.value); return this.value.equals(CalendarFrequencyType.INVALID.value);
} }
} }
@@ -21,12 +21,12 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity @Entity
@Table(name = "m_calendar_history") @Table(name = "m_calendar_history")
public class CalendarHistory extends AbstractPersistable<Long>{ public class CalendarHistory extends AbstractPersistable<Long> {
@ManyToOne(optional = false) @ManyToOne(optional = false)
@JoinColumn(name = "calendar_id", referencedColumnName = "id", nullable = false) @JoinColumn(name = "calendar_id", referencedColumnName = "id", nullable = false)
private Calendar calendar; private Calendar calendar;
@Column(name = "title", length = 50, nullable = false) @Column(name = "title", length = 50, nullable = false)
private String title; private String title;
@@ -75,7 +75,8 @@ public class CalendarHistory extends AbstractPersistable<Long>{
this.description = calendar.getDescription(); this.description = calendar.getDescription();
this.location = calendar.getLocation(); this.location = calendar.getLocation();
this.startDate = startDate; this.startDate = startDate;
this.endDate = calendar.getStartDate();//Calendar start date become end date for history data. this.endDate = calendar.getStartDate();// Calendar start date become end
// date for history data.
this.duration = calendar.getDuration(); this.duration = calendar.getDuration();
this.typeId = calendar.getTypeId(); this.typeId = calendar.getTypeId();
this.repeating = calendar.isRepeating(); this.repeating = calendar.isRepeating();
@@ -84,7 +85,7 @@ public class CalendarHistory extends AbstractPersistable<Long>{
this.firstReminder = calendar.getFirstReminder(); this.firstReminder = calendar.getFirstReminder();
this.secondReminder = calendar.getSecondReminder(); this.secondReminder = calendar.getSecondReminder();
} }
public String getRecurrence() { public String getRecurrence() {
return this.recurrence; return this.recurrence;
} }
@@ -119,16 +120,14 @@ public class CalendarHistory extends AbstractPersistable<Long>{
return false; return false;
} }
public boolean isBetweenStartAndEndDate(final LocalDate compareDate){ public boolean isBetweenStartAndEndDate(final LocalDate compareDate) {
if (isStartDateBeforeOrEqual(compareDate)){ if (isStartDateBeforeOrEqual(compareDate)) {
if (getEndDateLocalDate() == null || isEndDateAfterOrEqual(compareDate)){ if (getEndDateLocalDate() == null || isEndDateAfterOrEqual(compareDate)) { return true; }
return true;
}
} }
return false; return false;
} }
public void updateEndDate(Date historyCalEndDate){ public void updateEndDate(Date historyCalEndDate) {
this.endDate = historyCalEndDate; this.endDate = historyCalEndDate;
} }
} }
@@ -66,8 +66,8 @@ public enum CalendarType {
public String toString() { public String toString() {
return name().toString(); return name().toString();
} }
public boolean isCollection(){ public boolean isCollection() {
return this.value.equals(CalendarType.COLLECTION.value); return this.value.equals(CalendarType.COLLECTION.value);
} }
} }
@@ -35,14 +35,13 @@ public enum CalendarWeekDaysType {
private static final Map<Integer, CalendarWeekDaysType> intToEnumMap = new HashMap<Integer, CalendarWeekDaysType>(); private static final Map<Integer, CalendarWeekDaysType> intToEnumMap = new HashMap<Integer, CalendarWeekDaysType>();
private static int minValue = CalendarWeekDaysType.MO.value; private static int minValue = CalendarWeekDaysType.MO.value;
private static int maxValue = CalendarWeekDaysType.SU.value; private static int maxValue = CalendarWeekDaysType.SU.value;
static { static {
for (final CalendarWeekDaysType type : CalendarWeekDaysType.values()) { for (final CalendarWeekDaysType type : CalendarWeekDaysType.values()) {
intToEnumMap.put(type.value, type); intToEnumMap.put(type.value, type);
} }
} }
public static CalendarWeekDaysType fromInt(final int i) { public static CalendarWeekDaysType fromInt(final int i) {
final CalendarWeekDaysType type = intToEnumMap.get(Integer.valueOf(i)); final CalendarWeekDaysType type = intToEnumMap.get(Integer.valueOf(i));
return type; return type;
@@ -60,11 +59,11 @@ public enum CalendarWeekDaysType {
public String toString() { public String toString() {
return name().toString(); return name().toString();
} }
public boolean isInvalid(){ public boolean isInvalid() {
return this.value.equals(CalendarWeekDaysType.INVALID.value); return this.value.equals(CalendarWeekDaysType.INVALID.value);
} }
public static CalendarWeekDaysType fromString(final String weekDayString) { public static CalendarWeekDaysType fromString(final String weekDayString) {
CalendarWeekDaysType weekDay = CalendarWeekDaysType.INVALID; CalendarWeekDaysType weekDay = CalendarWeekDaysType.INVALID;
@@ -151,8 +151,8 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD
if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue(), element)) { if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue(), element)) {
final Integer interval = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( final Integer interval = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(
CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue(), element); CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue(), element);
baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue()).value(interval) baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue()).value(interval).notNull()
.notNull().integerGreaterThanZero(); .integerGreaterThanZero();
} }
if (CalendarFrequencyType.fromInt(frequency).isWeekly()) { if (CalendarFrequencyType.fromInt(frequency).isWeekly()) {
final Integer repeatsOnDay = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( final Integer repeatsOnDay = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(
@@ -261,8 +261,8 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD
if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue(), element)) { if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue(), element)) {
final Integer interval = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( final Integer interval = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(
CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue(), element); CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue(), element);
baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue()).value(interval) baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.INTERVAL.getValue()).value(interval).notNull()
.notNull().integerGreaterThanZero(); .integerGreaterThanZero();
} }
if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.REPEATS_ON_DAY.getValue(), element)) { if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.REPEATS_ON_DAY.getValue(), element)) {
@@ -16,9 +16,9 @@ public interface CalendarDropdownReadPlatformService {
List<EnumOptionData> retrieveCalendarTypeOptions(); List<EnumOptionData> retrieveCalendarTypeOptions();
List<EnumOptionData> retrieveCalendarRemindByOptions(); List<EnumOptionData> retrieveCalendarRemindByOptions();
List<EnumOptionData> retrieveCalendarFrequencyTypeOptions(); List<EnumOptionData> retrieveCalendarFrequencyTypeOptions();
List<EnumOptionData> retrieveCalendarWeekDaysTypeOptions(); List<EnumOptionData> retrieveCalendarWeekDaysTypeOptions();
} }
@@ -41,5 +41,5 @@ public class CalendarDropdownReadPlatformServiceImpl implements CalendarDropdown
@Override @Override
public List<EnumOptionData> retrieveCalendarWeekDaysTypeOptions() { public List<EnumOptionData> retrieveCalendarWeekDaysTypeOptions() {
return CalendarEnumerations.calendarWeekDaysType(CalendarWeekDaysType.values()); return CalendarEnumerations.calendarWeekDaysType(CalendarWeekDaysType.values());
} }
} }
@@ -67,39 +67,41 @@ public class CalendarEnumerations {
} }
return optionDatas; return optionDatas;
} }
public static EnumOptionData calendarFrequencyType(final int id) { public static EnumOptionData calendarFrequencyType(final int id) {
return calendarFrequencyType(CalendarFrequencyType.fromInt(id)); return calendarFrequencyType(CalendarFrequencyType.fromInt(id));
} }
public static EnumOptionData calendarFrequencyType(final CalendarFrequencyType calendarFrequencyType) { public static EnumOptionData calendarFrequencyType(final CalendarFrequencyType calendarFrequencyType) {
final EnumOptionData optionData = new EnumOptionData(calendarFrequencyType.getValue().longValue(), calendarFrequencyType.getCode(), calendarFrequencyType.toString()); final EnumOptionData optionData = new EnumOptionData(calendarFrequencyType.getValue().longValue(), calendarFrequencyType.getCode(),
calendarFrequencyType.toString());
return optionData; return optionData;
} }
public static List<EnumOptionData> calendarFrequencyType(final CalendarFrequencyType[] calendarFrequencyTypes) { public static List<EnumOptionData> calendarFrequencyType(final CalendarFrequencyType[] calendarFrequencyTypes) {
final List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>(); final List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>();
for (final CalendarFrequencyType calendarFrequencyType : calendarFrequencyTypes) { for (final CalendarFrequencyType calendarFrequencyType : calendarFrequencyTypes) {
if(!calendarFrequencyType.isInvalid()){ if (!calendarFrequencyType.isInvalid()) {
optionDatas.add(calendarFrequencyType(calendarFrequencyType)); optionDatas.add(calendarFrequencyType(calendarFrequencyType));
} }
} }
return optionDatas; return optionDatas;
} }
public static EnumOptionData calendarWeekDaysType(final int id) { public static EnumOptionData calendarWeekDaysType(final int id) {
return calendarWeekDaysType(CalendarWeekDaysType.fromInt(id)); return calendarWeekDaysType(CalendarWeekDaysType.fromInt(id));
} }
public static EnumOptionData calendarWeekDaysType(final CalendarWeekDaysType calendarWeekDaysType) { public static EnumOptionData calendarWeekDaysType(final CalendarWeekDaysType calendarWeekDaysType) {
final EnumOptionData optionData = new EnumOptionData(calendarWeekDaysType.getValue().longValue(), calendarWeekDaysType.getCode(), calendarWeekDaysType.toString()); final EnumOptionData optionData = new EnumOptionData(calendarWeekDaysType.getValue().longValue(), calendarWeekDaysType.getCode(),
calendarWeekDaysType.toString());
return optionData; return optionData;
} }
public static List<EnumOptionData> calendarWeekDaysType(final CalendarWeekDaysType[] calendarWeekDaysTypes) { public static List<EnumOptionData> calendarWeekDaysType(final CalendarWeekDaysType[] calendarWeekDaysTypes) {
final List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>(); final List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>();
for (final CalendarWeekDaysType calendarWeekDaysType : calendarWeekDaysTypes) { for (final CalendarWeekDaysType calendarWeekDaysType : calendarWeekDaysTypes) {
if(!calendarWeekDaysType.isInvalid()){ if (!calendarWeekDaysType.isInvalid()) {
optionDatas.add(calendarWeekDaysType(calendarWeekDaysType)); optionDatas.add(calendarWeekDaysType(calendarWeekDaysType));
} }
} }
@@ -34,7 +34,7 @@ public interface CalendarReadPlatformService {
CalendarData retrieveLoanCalendar(final Long loanId); CalendarData retrieveLoanCalendar(final Long loanId);
CalendarData retrieveCollctionCalendarByEntity(final Long entityId, final Integer entityTypeId); CalendarData retrieveCollctionCalendarByEntity(final Long entityId, final Integer entityTypeId);
LocalDate generateNextEligibleMeetingDateForCollection(CalendarData calendarData, MeetingData lastMeetingData); LocalDate generateNextEligibleMeetingDateForCollection(CalendarData calendarData, MeetingData lastMeetingData);
} }
@@ -207,7 +207,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ
return generateRecurringDate(calendarData, DateUtils.getLocalDateOfTenant(), tillDate, 10); return generateRecurringDate(calendarData, DateUtils.getLocalDateOfTenant(), tillDate, 10);
} }
private Collection<LocalDate> generateRecurringDate(final CalendarData calendarData, final LocalDate fromDate, final LocalDate tillDate, final int maxCount) { private Collection<LocalDate> generateRecurringDate(final CalendarData calendarData, final LocalDate fromDate,
final LocalDate tillDate, final int maxCount) {
if (!calendarData.isRepeating()) { return null; } if (!calendarData.isRepeating()) { return null; }
final String rrule = calendarData.getRecurrence(); final String rrule = calendarData.getRecurrence();
@@ -235,13 +236,13 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ
private LocalDate getPeriodStartDate(final LocalDate seedDate, final LocalDate recurrenceStartDate, final LocalDate fromDate) { private LocalDate getPeriodStartDate(final LocalDate seedDate, final LocalDate recurrenceStartDate, final LocalDate fromDate) {
LocalDate periodStartDate = null; LocalDate periodStartDate = null;
if(fromDate != null) { if (fromDate != null) {
periodStartDate = fromDate; periodStartDate = fromDate;
}else { } else {
final LocalDate currentDate = DateUtils.getLocalDateOfTenant(); final LocalDate currentDate = DateUtils.getLocalDateOfTenant();
if (seedDate.isBefore(currentDate.minusYears(1))) { if (seedDate.isBefore(currentDate.minusYears(1))) {
periodStartDate = currentDate.minusYears(1); periodStartDate = currentDate.minusYears(1);
}else{ } else {
periodStartDate = recurrenceStartDate; periodStartDate = recurrenceStartDate;
} }
} }
@@ -286,17 +286,17 @@ public class CalendarUtils {
final Recur recur = CalendarUtils.getICalRecur(recurringRule); final Recur recur = CalendarUtils.getICalRecur(recurringRule);
return recur.getInterval(); return recur.getInterval();
} }
public static CalendarFrequencyType getFrequency(final String recurringRule){ public static CalendarFrequencyType getFrequency(final String recurringRule) {
final Recur recur = CalendarUtils.getICalRecur(recurringRule); final Recur recur = CalendarUtils.getICalRecur(recurringRule);
return CalendarFrequencyType.fromString(recur.getFrequency()); return CalendarFrequencyType.fromString(recur.getFrequency());
} }
public static CalendarWeekDaysType getRepeatsOnDay(final String recurringRule){ public static CalendarWeekDaysType getRepeatsOnDay(final String recurringRule) {
final Recur recur = CalendarUtils.getICalRecur(recurringRule); final Recur recur = CalendarUtils.getICalRecur(recurringRule);
final WeekDayList weekDays = recur.getDayList(); final WeekDayList weekDays = recur.getDayList();
if(weekDays.isEmpty()) return CalendarWeekDaysType.INVALID; if (weekDays.isEmpty()) return CalendarWeekDaysType.INVALID;
//supports only one day // supports only one day
WeekDay weekDay = (WeekDay) weekDays.get(0); WeekDay weekDay = (WeekDay) weekDays.get(0);
return CalendarWeekDaysType.fromString(weekDay.getDay()); return CalendarWeekDaysType.fromString(weekDay.getDay());
} }
@@ -131,7 +131,7 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr
} }
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
this.calendarRepository.save(newCalendar); this.calendarRepository.save(newCalendar);
final CalendarInstance newCalendarInstance = CalendarInstance.fromJson(newCalendar, command); final CalendarInstance newCalendarInstance = CalendarInstance.fromJson(newCalendar, command);
@@ -154,27 +154,29 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr
if (calendarForUpdate == null) { throw new CalendarNotFoundException(calendarId); } if (calendarForUpdate == null) { throw new CalendarNotFoundException(calendarId); }
final Date oldStartDate = calendarForUpdate.getStartDate(); final Date oldStartDate = calendarForUpdate.getStartDate();
final LocalDate currentDate = DateUtils.getLocalDateOfTenant(); final LocalDate currentDate = DateUtils.getLocalDateOfTenant();
//create calendar history before updating calendar // create calendar history before updating calendar
final CalendarHistory calendarHistory = new CalendarHistory(calendarForUpdate, oldStartDate); final CalendarHistory calendarHistory = new CalendarHistory(calendarForUpdate, oldStartDate);
final Map<String, Object> changes = calendarForUpdate.update(command); final Map<String, Object> changes = calendarForUpdate.update(command);
if (!changes.isEmpty()) { if (!changes.isEmpty()) {
//update calendar history table only if there is a change in calendar start date. // update calendar history table only if there is a change in
if(currentDate.isAfter(new LocalDate(oldStartDate))){ // calendar start date.
if (currentDate.isAfter(new LocalDate(oldStartDate))) {
final Date endDate = calendarForUpdate.getStartDateLocalDate().minusDays(1).toDate(); final Date endDate = calendarForUpdate.getStartDateLocalDate().minusDays(1).toDate();
calendarHistory.updateEndDate(endDate); calendarHistory.updateEndDate(endDate);
this.calendarHistoryRepository.save(calendarHistory); this.calendarHistoryRepository.save(calendarHistory);
} }
this.calendarRepository.saveAndFlush(calendarForUpdate); this.calendarRepository.saveAndFlush(calendarForUpdate);
if (this.configurationDomainService.isRescheduleFutureRepaymentsEnabled() && calendarForUpdate.isRepeating()) { if (this.configurationDomainService.isRescheduleFutureRepaymentsEnabled() && calendarForUpdate.isRepeating()) {
//fetch all loan calendar instances associated with modifying calendar. // fetch all loan calendar instances associated with modifying
// calendar.
final Collection<CalendarInstance> loanCalendarInstances = this.calendarInstanceRepository.findByCalendarIdAndEntityTypeId( final Collection<CalendarInstance> loanCalendarInstances = this.calendarInstanceRepository.findByCalendarIdAndEntityTypeId(
calendarId, CalendarEntityType.LOANS.getValue()); calendarId, CalendarEntityType.LOANS.getValue());
if (!CollectionUtils.isEmpty(loanCalendarInstances)) { if (!CollectionUtils.isEmpty(loanCalendarInstances)) {
//update all loans associated with modifying calendar // update all loans associated with modifying calendar
this.loanWritePlatformService.applyMeetingDateChanges(calendarForUpdate, loanCalendarInstances); this.loanWritePlatformService.applyMeetingDateChanges(calendarForUpdate, loanCalendarInstances);
} }
} }
@@ -42,9 +42,9 @@ public class ChargeData implements Comparable<ChargeData>, Serializable {
private final List<EnumOptionData> chargeAppliesToOptions;// private final List<EnumOptionData> chargeAppliesToOptions;//
private final List<EnumOptionData> chargeTimeTypeOptions;// private final List<EnumOptionData> chargeTimeTypeOptions;//
private final List<EnumOptionData> chargePaymetModeOptions;// private final List<EnumOptionData> chargePaymetModeOptions;//
private final List<EnumOptionData> loanChargeCalculationTypeOptions; private final List<EnumOptionData> loanChargeCalculationTypeOptions;
private final List<EnumOptionData> loanChargeTimeTypeOptions; private final List<EnumOptionData> loanChargeTimeTypeOptions;
private final List<EnumOptionData> savingsChargeCalculationTypeOptions; private final List<EnumOptionData> savingsChargeCalculationTypeOptions;
private final List<EnumOptionData> savingsChargeTimeTypeOptions; private final List<EnumOptionData> savingsChargeTimeTypeOptions;
@@ -56,22 +56,23 @@ public class ChargeData implements Comparable<ChargeData>, Serializable {
return new ChargeData(null, null, null, null, null, null, null, null, false, false, currencyOptions, chargeCalculationTypeOptions, return new ChargeData(null, null, null, null, null, null, null, null, false, false, currencyOptions, chargeCalculationTypeOptions,
chargeAppliesToOptions, chargeTimeTypeOptions, chargePaymentModeOptions, loansChargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, chargePaymentModeOptions, loansChargeCalculationTypeOptions,
loansChargeTimeTypeOptions, savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, null, null,null,null); loansChargeTimeTypeOptions, savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, null, null, null, null);
} }
public static ChargeData withTemplate(final ChargeData charge, final ChargeData template) { public static ChargeData withTemplate(final ChargeData charge, final ChargeData template) {
return new ChargeData(charge.id, charge.name, charge.amount, charge.currency, charge.chargeTimeType, charge.chargeAppliesTo, return new ChargeData(charge.id, charge.name, charge.amount, charge.currency, charge.chargeTimeType, charge.chargeAppliesTo,
charge.chargeCalculationType, charge.chargePaymentMode, charge.penalty, charge.active,template.currencyOptions, charge.chargeCalculationType, charge.chargePaymentMode, charge.penalty, charge.active, template.currencyOptions,
template.chargeCalculationTypeOptions, template.chargeAppliesToOptions, template.chargeTimeTypeOptions, template.chargeCalculationTypeOptions, template.chargeAppliesToOptions, template.chargeTimeTypeOptions,
template.chargePaymetModeOptions, template.loanChargeCalculationTypeOptions, template.loanChargeTimeTypeOptions, template.chargePaymetModeOptions, template.loanChargeCalculationTypeOptions, template.loanChargeTimeTypeOptions,
template.savingsChargeCalculationTypeOptions, template.savingsChargeTimeTypeOptions, charge.feeOnMonthDay, charge.feeInterval,charge.minCap,charge.maxCap); template.savingsChargeCalculationTypeOptions, template.savingsChargeTimeTypeOptions, charge.feeOnMonthDay,
charge.feeInterval, charge.minCap, charge.maxCap);
} }
public static ChargeData instance(final Long id, final String name, final BigDecimal amount, final CurrencyData currency, public static ChargeData instance(final Long id, final String name, final BigDecimal amount, final CurrencyData currency,
final EnumOptionData chargeTimeType, final EnumOptionData chargeAppliesTo, final EnumOptionData chargeCalculationType, final EnumOptionData chargeTimeType, final EnumOptionData chargeAppliesTo, final EnumOptionData chargeCalculationType,
final EnumOptionData chargePaymentMode, final MonthDay feeOnMonthDay, final Integer feeInterval, final boolean penalty, final boolean active, final EnumOptionData chargePaymentMode, final MonthDay feeOnMonthDay, final Integer feeInterval, final boolean penalty,
final BigDecimal minCap, final BigDecimal maxCap) { final boolean active, final BigDecimal minCap, final BigDecimal maxCap) {
final Collection<CurrencyData> currencyOptions = null; final Collection<CurrencyData> currencyOptions = null;
final List<EnumOptionData> chargeCalculationTypeOptions = null; final List<EnumOptionData> chargeCalculationTypeOptions = null;
final List<EnumOptionData> chargeAppliesToOptions = null; final List<EnumOptionData> chargeAppliesToOptions = null;
@@ -81,11 +82,11 @@ public class ChargeData implements Comparable<ChargeData>, Serializable {
final List<EnumOptionData> loansChargeTimeTypeOptions = null; final List<EnumOptionData> loansChargeTimeTypeOptions = null;
final List<EnumOptionData> savingsChargeCalculationTypeOptions = null; final List<EnumOptionData> savingsChargeCalculationTypeOptions = null;
final List<EnumOptionData> savingsChargeTimeTypeOptions = null; final List<EnumOptionData> savingsChargeTimeTypeOptions = null;
return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode, return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode,
penalty, active, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, penalty, active, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions,
chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions, chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions,
savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, feeOnMonthDay, feeInterval,minCap,maxCap); savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, feeOnMonthDay, feeInterval, minCap, maxCap);
} }
public static ChargeData lookup(final Long id, final String name, final boolean isPenalty) { public static ChargeData lookup(final Long id, final String name, final boolean isPenalty) {
@@ -110,11 +111,11 @@ public class ChargeData implements Comparable<ChargeData>, Serializable {
final List<EnumOptionData> loansChargeTimeTypeOptions = null; final List<EnumOptionData> loansChargeTimeTypeOptions = null;
final List<EnumOptionData> savingsChargeCalculationTypeOptions = null; final List<EnumOptionData> savingsChargeCalculationTypeOptions = null;
final List<EnumOptionData> savingsChargeTimeTypeOptions = null; final List<EnumOptionData> savingsChargeTimeTypeOptions = null;
return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode, return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode,
penalty, active, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, penalty, active, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions,
chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions, chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions,
savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, feeOnMonthDay, feeInterval,minCap,maxCap); savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, feeOnMonthDay, feeInterval, minCap, maxCap);
} }
private ChargeData(final Long id, final String name, final BigDecimal amount, final CurrencyData currency, private ChargeData(final Long id, final String name, final BigDecimal amount, final CurrencyData currency,
@@ -125,7 +126,7 @@ public class ChargeData implements Comparable<ChargeData>, Serializable {
final List<EnumOptionData> chargePaymentModeOptions, final List<EnumOptionData> loansChargeCalculationTypeOptions, final List<EnumOptionData> chargePaymentModeOptions, final List<EnumOptionData> loansChargeCalculationTypeOptions,
final List<EnumOptionData> loansChargeTimeTypeOptions, final List<EnumOptionData> savingsChargeCalculationTypeOptions, final List<EnumOptionData> loansChargeTimeTypeOptions, final List<EnumOptionData> savingsChargeCalculationTypeOptions,
final List<EnumOptionData> savingsChargeTimeTypeOptions, final MonthDay feeOnMonthDay, final Integer feeInterval, final List<EnumOptionData> savingsChargeTimeTypeOptions, final MonthDay feeOnMonthDay, final Integer feeInterval,
final BigDecimal minCap,final BigDecimal maxCap) { final BigDecimal minCap, final BigDecimal maxCap) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.amount = amount; this.amount = amount;
@@ -177,7 +178,7 @@ public class ChargeData implements Comparable<ChargeData>, Serializable {
} }
return LoanChargeData.newLoanChargeDetails(this.id, this.name, this.currency, this.amount, percentage, this.chargeTimeType, return LoanChargeData.newLoanChargeDetails(this.id, this.name, this.currency, this.amount, percentage, this.chargeTimeType,
this.chargeCalculationType, this.penalty, this.chargePaymentMode,this.minCap,this.maxCap); this.chargeCalculationType, this.penalty, this.chargePaymentMode, this.minCap, this.maxCap);
} }
public SavingsAccountChargeData toSavingsAccountChargeData() { public SavingsAccountChargeData toSavingsAccountChargeData() {
@@ -193,8 +194,9 @@ public class ChargeData implements Comparable<ChargeData>, Serializable {
final Collection<ChargeData> chargeOptions = null; final Collection<ChargeData> chargeOptions = null;
final LocalDate dueAsOfDate = null; final LocalDate dueAsOfDate = null;
return SavingsAccountChargeData.instance(savingsChargeId, this.id, savingsAccountId, this.name, this.currency, this.amount, amountPaid, amountWaived, return SavingsAccountChargeData.instance(savingsChargeId, this.id, savingsAccountId, this.name, this.currency, this.amount,
amountWrittenOff, amountOutstanding, this.chargeTimeType, dueAsOfDate, this.chargeCalculationType, percentage, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, this.chargeTimeType, dueAsOfDate,
amountPercentageAppliedTo, chargeOptions, this.penalty, this.feeOnMonthDay, this.feeInterval); this.chargeCalculationType, percentage, amountPercentageAppliedTo, chargeOptions, this.penalty, this.feeOnMonthDay,
this.feeInterval);
} }
} }
@@ -124,7 +124,6 @@ public class Charge extends AbstractPersistable<Long> {
this.active = active; this.active = active;
this.chargePaymentMode = paymentMode == null ? null : paymentMode.getValue(); this.chargePaymentMode = paymentMode == null ? null : paymentMode.getValue();
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charges"); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charges");
@@ -161,7 +160,7 @@ public class Charge extends AbstractPersistable<Long> {
.failWithCodeNoParameterAddedToErrorCode("not.allowed.charge.time.for.loan"); .failWithCodeNoParameterAddedToErrorCode("not.allowed.charge.time.for.loan");
} }
} }
if(isPercentageOfAmount()){ if (isPercentageOfAmount()) {
this.minCap = minCap; this.minCap = minCap;
this.maxCap = maxCap; this.maxCap = maxCap;
} }
@@ -425,7 +424,7 @@ public class Charge extends AbstractPersistable<Long> {
/** /**
* Delete is a <i>soft delete</i>. Updates flag on charge so it wont appear * Delete is a <i>soft delete</i>. Updates flag on charge so it wont appear
* in query/report results. * in query/report results.
* *
* Any fields with unique constraints and prepended with id of record. * Any fields with unique constraints and prepended with id of record.
*/ */
public void delete() { public void delete() {
@@ -5,7 +5,6 @@
*/ */
package org.mifosplatform.portfolio.charge.domain; package org.mifosplatform.portfolio.charge.domain;
public enum ChargeAppliesTo { public enum ChargeAppliesTo {
INVALID(0, "chargeAppliesTo.invalid"), // INVALID(0, "chargeAppliesTo.invalid"), //
@@ -57,6 +56,6 @@ public enum ChargeAppliesTo {
} }
public static Object[] validValues() { public static Object[] validValues() {
return new Object[] {ChargeAppliesTo.LOAN.getValue(), ChargeAppliesTo.SAVINGS.getValue()}; return new Object[] { ChargeAppliesTo.LOAN.getValue(), ChargeAppliesTo.SAVINGS.getValue() };
} }
} }
@@ -31,9 +31,9 @@ public enum ChargeCalculationType {
public static Object[] validValuesForLoan() { public static Object[] validValuesForLoan() {
return new Integer[] { ChargeCalculationType.FLAT.getValue(), ChargeCalculationType.PERCENT_OF_AMOUNT.getValue(), return new Integer[] { ChargeCalculationType.FLAT.getValue(), ChargeCalculationType.PERCENT_OF_AMOUNT.getValue(),
ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST.getValue(),ChargeCalculationType.PERCENT_OF_INTEREST.getValue() }; ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST.getValue(), ChargeCalculationType.PERCENT_OF_INTEREST.getValue() };
} }
public static Object[] validValuesForSavings() { public static Object[] validValuesForSavings() {
return new Integer[] { ChargeCalculationType.FLAT.getValue(), ChargeCalculationType.PERCENT_OF_AMOUNT.getValue() }; return new Integer[] { ChargeCalculationType.FLAT.getValue(), ChargeCalculationType.PERCENT_OF_AMOUNT.getValue() };
} }
@@ -76,8 +76,8 @@ public enum ChargeCalculationType {
public boolean isAllowedSavingsChargeCalculationType() { public boolean isAllowedSavingsChargeCalculationType() {
return isFlat() || isPercentageOfAmount(); return isFlat() || isPercentageOfAmount();
} }
public boolean isPercentageBased(){ public boolean isPercentageBased() {
return isPercentageOfAmount() || isPercentageOfAmountAndInterest() || isPercentageOfInterest(); return isPercentageOfAmount() || isPercentageOfAmountAndInterest() || isPercentageOfInterest();
} }
} }
@@ -17,9 +17,10 @@ public enum ChargeTimeType {
WITHDRAWAL_FEE(5, "chargeTimeType.withdrawalFee"), // only for savings WITHDRAWAL_FEE(5, "chargeTimeType.withdrawalFee"), // only for savings
ANNUAL_FEE(6, "chargeTimeType.annualFee"), // only for savings ANNUAL_FEE(6, "chargeTimeType.annualFee"), // only for savings
MONTHLY_FEE(7, "chargeTimeType.monthlyFee"), // only for savings MONTHLY_FEE(7, "chargeTimeType.monthlyFee"), // only for savings
INSTALMENT_FEE(8, "chargeTimeType.instalmentFee"),// only for loan charges INSTALMENT_FEE(8, "chargeTimeType.instalmentFee"), // only for loan charges
OVERDUE_INSTALLMENT(9, "chargeTimeType.overdueInstallment"), // only for loan charges OVERDUE_INSTALLMENT(9, "chargeTimeType.overdueInstallment"), // only for
OVERDRAFT_FEE(10,"chargeTimeType.overdraftFee");// only for savings // loan charges
OVERDRAFT_FEE(10, "chargeTimeType.overdraftFee");// only for savings
private final Integer value; private final Integer value;
private final String code; private final String code;
@@ -39,13 +40,13 @@ public enum ChargeTimeType {
public static Object[] validLoanValues() { public static Object[] validLoanValues() {
return new Integer[] { ChargeTimeType.DISBURSEMENT.getValue(), ChargeTimeType.SPECIFIED_DUE_DATE.getValue(), return new Integer[] { ChargeTimeType.DISBURSEMENT.getValue(), ChargeTimeType.SPECIFIED_DUE_DATE.getValue(),
ChargeTimeType.INSTALMENT_FEE.getValue(),ChargeTimeType.OVERDUE_INSTALLMENT.getValue() }; ChargeTimeType.INSTALMENT_FEE.getValue(), ChargeTimeType.OVERDUE_INSTALLMENT.getValue() };
} }
public static Object[] validSavingsValues() { public static Object[] validSavingsValues() {
return new Integer[] { ChargeTimeType.SPECIFIED_DUE_DATE.getValue(), ChargeTimeType.SAVINGS_ACTIVATION.getValue(), return new Integer[] { ChargeTimeType.SPECIFIED_DUE_DATE.getValue(), ChargeTimeType.SAVINGS_ACTIVATION.getValue(),
ChargeTimeType.SAVINGS_CLOSURE.getValue(), ChargeTimeType.WITHDRAWAL_FEE.getValue(), ChargeTimeType.ANNUAL_FEE.getValue(), ChargeTimeType.SAVINGS_CLOSURE.getValue(), ChargeTimeType.WITHDRAWAL_FEE.getValue(), ChargeTimeType.ANNUAL_FEE.getValue(),
ChargeTimeType.MONTHLY_FEE.getValue(),ChargeTimeType.OVERDRAFT_FEE.getValue() }; ChargeTimeType.MONTHLY_FEE.getValue(), ChargeTimeType.OVERDRAFT_FEE.getValue() };
} }
public static ChargeTimeType fromInt(final Integer chargeTime) { public static ChargeTimeType fromInt(final Integer chargeTime) {
@@ -122,7 +123,7 @@ public enum ChargeTimeType {
return this.value.equals(ChargeTimeType.INSTALMENT_FEE.getValue()); return this.value.equals(ChargeTimeType.INSTALMENT_FEE.getValue());
} }
public boolean isOverdueInstallment(){ public boolean isOverdueInstallment() {
return this.value.equals(ChargeTimeType.OVERDUE_INSTALLMENT.getValue()); return this.value.equals(ChargeTimeType.OVERDUE_INSTALLMENT.getValue());
} }
@@ -134,10 +135,9 @@ public enum ChargeTimeType {
return isOnSpecifiedDueDate() || isSavingsActivation() || isSavingsClosure() || isWithdrawalFee() || isAnnualFee() return isOnSpecifiedDueDate() || isSavingsActivation() || isSavingsClosure() || isWithdrawalFee() || isAnnualFee()
|| isMonthlyFee() || isOverdraftFee(); || isMonthlyFee() || isOverdraftFee();
} }
public boolean isOverdraftFee() { public boolean isOverdraftFee() {
return this.value.equals(ChargeTimeType.OVERDRAFT_FEE.getValue()); return this.value.equals(ChargeTimeType.OVERDRAFT_FEE.getValue());
} }
} }
@@ -11,7 +11,7 @@ public class LoanChargeCannotBePayedException extends AbstractPlatformDomainRule
/*** enum of reasons of why Loan Charge cannot be waived **/ /*** enum of reasons of why Loan Charge cannot be waived **/
public static enum LOAN_CHARGE_CANNOT_BE_PAYED_REASON { public static enum LOAN_CHARGE_CANNOT_BE_PAYED_REASON {
ALREADY_PAID, ALREADY_WAIVED, LOAN_INACTIVE, CHARGE_NOT_ACCOUNT_TRANSFER,CHARGE_NOT_PAYABLE; ALREADY_PAID, ALREADY_WAIVED, LOAN_INACTIVE, CHARGE_NOT_ACCOUNT_TRANSFER, CHARGE_NOT_PAYABLE;
public String errorMessage() { public String errorMessage() {
if (name().toString().equalsIgnoreCase("ALREADY_PAID")) { if (name().toString().equalsIgnoreCase("ALREADY_PAID")) {
@@ -21,10 +21,8 @@ public class LoanChargeCannotBePayedException extends AbstractPlatformDomainRule
} else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) { } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) {
return "This loan charge can be payed as the loan associated with it is currently inactive"; return "This loan charge can be payed as the loan associated with it is currently inactive";
} else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) { } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) {
return "This loan charge can be payed as the charge payment mode is not account transfer"; return "This loan charge can be payed as the charge payment mode is not account transfer";
}else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { return "This loan charge is not Payable through account transfer"; }
return "This loan charge is not Payable through account transfer";
}
return name().toString(); return name().toString();
} }
@@ -37,10 +35,8 @@ public class LoanChargeCannotBePayedException extends AbstractPlatformDomainRule
} else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) { } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) {
return "error.msg.loan.charge.associated.loan.inactive"; return "error.msg.loan.charge.associated.loan.inactive";
} else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) { } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) {
return "error.msg.loan.charge.payment.mode.not.account.transfer"; return "error.msg.loan.charge.payment.mode.not.account.transfer";
}else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { return "error.msg.loan.charge.payment.not.allowed.account.transfer"; }
return "error.msg.loan.charge.payment.not.allowed.account.transfer";
}
return name().toString(); return name().toString();
} }
} }
@@ -18,9 +18,7 @@ public class LoanChargeCannotBeUpdatedException extends AbstractPlatformDomainRu
return "This loan charge has been partially/completely paid"; return "This loan charge has been partially/completely paid";
} else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) {
return "This loan charge has already been waived"; return "This loan charge has already been waived";
} else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "This charge cannot be updated as the loan it is associated with is not in submitted and pending approval stage"; }
return "This charge cannot be updated as the loan it is associated with is not in submitted and pending approval stage";
}
return name().toString(); return name().toString();
} }
@@ -29,9 +27,7 @@ public class LoanChargeCannotBeUpdatedException extends AbstractPlatformDomainRu
return "error.msg.loan.charge.already.paid"; return "error.msg.loan.charge.already.paid";
} else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) {
return "error.msg.loan.charge.already.waived"; return "error.msg.loan.charge.already.waived";
} else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "error.msg.loan.charge.associated.loan.not.in.submitted.and.pending.approval.stage"; }
return "error.msg.loan.charge.associated.loan.not.in.submitted.and.pending.approval.stage";
}
return name().toString(); return name().toString();
} }
} }
@@ -18,12 +18,10 @@ public class LoanChargeCannotBeWaivedException extends AbstractPlatformDomainRul
return "This loan charge has been completely paid"; return "This loan charge has been completely paid";
} else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) {
return "This loan charge has already been waived"; return "This loan charge has already been waived";
} else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) { } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) {
return "This loan charge can be waived as the loan associated with it is currently inactive"; return "This loan charge can be waived as the loan associated with it is currently inactive";
} else if(name().toString().equalsIgnoreCase("WAIVE_NOT_ALLOWED_FOR_CHARGE")){ } else if (name().toString().equalsIgnoreCase("WAIVE_NOT_ALLOWED_FOR_CHARGE")) { return "This loan charge can be waived"; }
return "This loan charge can be waived";
}
return name().toString(); return name().toString();
} }
@@ -32,11 +30,9 @@ public class LoanChargeCannotBeWaivedException extends AbstractPlatformDomainRul
return "error.msg.loan.charge.already.paid"; return "error.msg.loan.charge.already.paid";
} else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) {
return "error.msg.loan.charge.already.waived"; return "error.msg.loan.charge.already.waived";
} else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) { } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) {
return "error.msg.loan.charge.associated.loan.inactive"; return "error.msg.loan.charge.associated.loan.inactive";
} else if(name().toString().equalsIgnoreCase("WAIVE_NOT_ALLOWED_FOR_CHARGE")) { } else if (name().toString().equalsIgnoreCase("WAIVE_NOT_ALLOWED_FOR_CHARGE")) { return "error.msg.loan.charge.waive.not.allowed"; }
return "error.msg.loan.charge.waive.not.allowed";
}
return name().toString(); return name().toString();
} }
} }
@@ -76,17 +76,21 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element); final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull(); baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
if (chargeTimeType != null) { if (chargeTimeType != null) {
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).isOneOfTheseValues(ChargeTimeType.validLoanValues()); baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
.isOneOfTheseValues(ChargeTimeType.validLoanValues());
} }
final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargePaymentMode", element); final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargePaymentMode", element);
baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode).notNull().isOneOfTheseValues(ChargePaymentMode.validValues()); baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode).notNull()
.isOneOfTheseValues(ChargePaymentMode.validValues());
if (chargePaymentMode != null) { if (chargePaymentMode != null) {
baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode).isOneOfTheseValues(ChargePaymentMode.validValues()); baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode)
.isOneOfTheseValues(ChargePaymentMode.validValues());
} }
if (chargeCalculationType != null) { if (chargeCalculationType != null) {
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType).isOneOfTheseValues(ChargeCalculationType.validValuesForLoan()); baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
.isOneOfTheseValues(ChargeCalculationType.validValuesForLoan());
} }
} else if (appliesTo.isSavingsCharge()) { } else if (appliesTo.isSavingsCharge()) {
@@ -94,7 +98,8 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element); final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull(); baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
if (chargeTimeType != null) { if (chargeTimeType != null) {
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).isOneOfTheseValues(ChargeTimeType.validSavingsValues()); baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
.isOneOfTheseValues(ChargeTimeType.validSavingsValues());
} }
final ChargeTimeType ctt = ChargeTimeType.fromInt(chargeTimeType); final ChargeTimeType ctt = ChargeTimeType.fromInt(chargeTimeType);
@@ -110,9 +115,10 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed("feeOnMonthDay", element); final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed("feeOnMonthDay", element);
baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).notNull(); baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).notNull();
} }
if (chargeCalculationType != null) { if (chargeCalculationType != null) {
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType).isOneOfTheseValues(ChargeCalculationType.validValuesForSavings()); baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
.isOneOfTheseValues(ChargeCalculationType.validValuesForSavings());
} }
} }
@@ -18,13 +18,13 @@ public interface ChargeDropdownReadPlatformService {
List<EnumOptionData> retrieveCollectionTimeTypes(); List<EnumOptionData> retrieveCollectionTimeTypes();
List<EnumOptionData> retrivePaymentModes(); List<EnumOptionData> retrivePaymentModes();
List<EnumOptionData> retrieveLoanCalculationTypes(); List<EnumOptionData> retrieveLoanCalculationTypes();
List<EnumOptionData> retrieveLoanCollectionTimeTypes(); List<EnumOptionData> retrieveLoanCollectionTimeTypes();
List<EnumOptionData> retrieveSavingsCalculationTypes(); List<EnumOptionData> retrieveSavingsCalculationTypes();
List<EnumOptionData> retrieveSavingsCollectionTimeTypes(); List<EnumOptionData> retrieveSavingsCollectionTimeTypes();
} }
@@ -26,9 +26,8 @@ public class ChargeDropdownReadPlatformServiceImpl implements ChargeDropdownRead
return Arrays.asList(chargeCalculationType(ChargeCalculationType.FLAT), return Arrays.asList(chargeCalculationType(ChargeCalculationType.FLAT),
chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT), chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT),
chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST), chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST),
chargeCalculationType(ChargeCalculationType.PERCENT_OF_INTEREST) chargeCalculationType(ChargeCalculationType.PERCENT_OF_INTEREST));
);
} }
@Override @Override
@@ -62,12 +61,16 @@ public class ChargeDropdownReadPlatformServiceImpl implements ChargeDropdownRead
@Override @Override
public List<EnumOptionData> retrieveLoanCalculationTypes() { public List<EnumOptionData> retrieveLoanCalculationTypes() {
return Arrays.asList(chargeCalculationType(ChargeCalculationType.FLAT), chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT), chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST), chargeCalculationType(ChargeCalculationType.PERCENT_OF_INTEREST)); return Arrays.asList(chargeCalculationType(ChargeCalculationType.FLAT),
chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT),
chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST),
chargeCalculationType(ChargeCalculationType.PERCENT_OF_INTEREST));
} }
@Override @Override
public List<EnumOptionData> retrieveLoanCollectionTimeTypes() { public List<EnumOptionData> retrieveLoanCollectionTimeTypes() {
return Arrays.asList(chargeTimeType(ChargeTimeType.DISBURSEMENT), chargeTimeType(ChargeTimeType.SPECIFIED_DUE_DATE),chargeTimeType(ChargeTimeType.INSTALMENT_FEE),chargeTimeType(ChargeTimeType.OVERDUE_INSTALLMENT)); return Arrays.asList(chargeTimeType(ChargeTimeType.DISBURSEMENT), chargeTimeType(ChargeTimeType.SPECIFIED_DUE_DATE),
chargeTimeType(ChargeTimeType.INSTALMENT_FEE), chargeTimeType(ChargeTimeType.OVERDUE_INSTALLMENT));
} }
@Override @Override
@@ -79,9 +82,8 @@ public class ChargeDropdownReadPlatformServiceImpl implements ChargeDropdownRead
@Override @Override
public List<EnumOptionData> retrieveSavingsCollectionTimeTypes() { public List<EnumOptionData> retrieveSavingsCollectionTimeTypes() {
return Arrays.asList(chargeTimeType(ChargeTimeType.SPECIFIED_DUE_DATE), chargeTimeType(ChargeTimeType.SAVINGS_ACTIVATION), return Arrays.asList(chargeTimeType(ChargeTimeType.SPECIFIED_DUE_DATE), chargeTimeType(ChargeTimeType.SAVINGS_ACTIVATION),
//chargeTimeType(ChargeTimeType.SAVINGS_CLOSURE), // chargeTimeType(ChargeTimeType.SAVINGS_CLOSURE),
chargeTimeType(ChargeTimeType.WITHDRAWAL_FEE), chargeTimeType(ChargeTimeType.WITHDRAWAL_FEE), chargeTimeType(ChargeTimeType.ANNUAL_FEE),
chargeTimeType(ChargeTimeType.ANNUAL_FEE), chargeTimeType(ChargeTimeType.MONTHLY_FEE), chargeTimeType(ChargeTimeType.MONTHLY_FEE), chargeTimeType(ChargeTimeType.OVERDRAFT_FEE));
chargeTimeType(ChargeTimeType.OVERDRAFT_FEE));
} }
} }
@@ -29,29 +29,37 @@ public class ChargeEnumerations {
ChargeTimeType.SPECIFIED_DUE_DATE.getCode(), "Specified due date"); ChargeTimeType.SPECIFIED_DUE_DATE.getCode(), "Specified due date");
break; break;
case SAVINGS_ACTIVATION: case SAVINGS_ACTIVATION:
optionData = new EnumOptionData(ChargeTimeType.SAVINGS_ACTIVATION.getValue().longValue(), ChargeTimeType.SAVINGS_ACTIVATION.getCode(), "Savings Activation"); optionData = new EnumOptionData(ChargeTimeType.SAVINGS_ACTIVATION.getValue().longValue(),
ChargeTimeType.SAVINGS_ACTIVATION.getCode(), "Savings Activation");
break; break;
case SAVINGS_CLOSURE: case SAVINGS_CLOSURE:
optionData = new EnumOptionData(ChargeTimeType.SAVINGS_CLOSURE.getValue().longValue(), ChargeTimeType.SAVINGS_CLOSURE.getCode(), "Savings Closure"); optionData = new EnumOptionData(ChargeTimeType.SAVINGS_CLOSURE.getValue().longValue(),
ChargeTimeType.SAVINGS_CLOSURE.getCode(), "Savings Closure");
break; break;
case WITHDRAWAL_FEE: case WITHDRAWAL_FEE:
optionData = new EnumOptionData(ChargeTimeType.WITHDRAWAL_FEE.getValue().longValue(), ChargeTimeType.WITHDRAWAL_FEE.getCode(), "Withdrawal Fee"); optionData = new EnumOptionData(ChargeTimeType.WITHDRAWAL_FEE.getValue().longValue(),
ChargeTimeType.WITHDRAWAL_FEE.getCode(), "Withdrawal Fee");
break; break;
case ANNUAL_FEE: case ANNUAL_FEE:
optionData = new EnumOptionData(ChargeTimeType.ANNUAL_FEE.getValue().longValue(), ChargeTimeType.ANNUAL_FEE.getCode(), "Annual Fee"); optionData = new EnumOptionData(ChargeTimeType.ANNUAL_FEE.getValue().longValue(), ChargeTimeType.ANNUAL_FEE.getCode(),
"Annual Fee");
break; break;
case MONTHLY_FEE: case MONTHLY_FEE:
optionData = new EnumOptionData(ChargeTimeType.MONTHLY_FEE.getValue().longValue(), ChargeTimeType.MONTHLY_FEE.getCode(), "Monthly Fee"); optionData = new EnumOptionData(ChargeTimeType.MONTHLY_FEE.getValue().longValue(), ChargeTimeType.MONTHLY_FEE.getCode(),
"Monthly Fee");
break; break;
case INSTALMENT_FEE: case INSTALMENT_FEE:
optionData = new EnumOptionData(ChargeTimeType.INSTALMENT_FEE.getValue().longValue(), ChargeTimeType.INSTALMENT_FEE.getCode(), "Instalment Fee"); optionData = new EnumOptionData(ChargeTimeType.INSTALMENT_FEE.getValue().longValue(),
ChargeTimeType.INSTALMENT_FEE.getCode(), "Instalment Fee");
break; break;
case OVERDUE_INSTALLMENT: case OVERDUE_INSTALLMENT:
optionData = new EnumOptionData(ChargeTimeType.OVERDUE_INSTALLMENT.getValue().longValue(),ChargeTimeType.OVERDUE_INSTALLMENT.getCode(),"overdue fees") ; optionData = new EnumOptionData(ChargeTimeType.OVERDUE_INSTALLMENT.getValue().longValue(),
ChargeTimeType.OVERDUE_INSTALLMENT.getCode(), "overdue fees");
break; break;
case OVERDRAFT_FEE: case OVERDRAFT_FEE:
optionData = new EnumOptionData(ChargeTimeType.OVERDRAFT_FEE.getValue().longValue(), ChargeTimeType.OVERDRAFT_FEE.getCode(), "Overdraft Fee"); optionData = new EnumOptionData(ChargeTimeType.OVERDRAFT_FEE.getValue().longValue(),
break; ChargeTimeType.OVERDRAFT_FEE.getCode(), "Overdraft Fee");
break;
default: default:
optionData = new EnumOptionData(ChargeTimeType.INVALID.getValue().longValue(), ChargeTimeType.INVALID.getCode(), "Invalid"); optionData = new EnumOptionData(ChargeTimeType.INVALID.getValue().longValue(), ChargeTimeType.INVALID.getCode(), "Invalid");
break; break;
@@ -141,12 +141,11 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService
return "c.id as id, c.name as name, c.amount as amount, c.currency_code as currencyCode, " return "c.id as id, c.name as name, c.amount as amount, c.currency_code as currencyCode, "
+ "c.charge_applies_to_enum as chargeAppliesTo, c.charge_time_enum as chargeTime, " + "c.charge_applies_to_enum as chargeAppliesTo, c.charge_time_enum as chargeTime, "
+ "c.charge_payment_mode_enum as chargePaymentMode, " + "c.charge_payment_mode_enum as chargePaymentMode, "
+ "c.charge_calculation_enum as chargeCalculation, c.is_penalty as penalty, " + "c.charge_calculation_enum as chargeCalculation, c.is_penalty as penalty, "
+ "c.is_active as active, oc.name as currencyName, oc.decimal_places as currencyDecimalPlaces, " + "c.is_active as active, oc.name as currencyName, oc.decimal_places as currencyDecimalPlaces, "
+ "oc.currency_multiplesof as inMultiplesOf, oc.display_symbol as currencyDisplaySymbol, " + "oc.currency_multiplesof as inMultiplesOf, oc.display_symbol as currencyDisplaySymbol, "
+ "oc.internationalized_name_code as currencyNameCode, c.fee_on_day as feeOnDay, c.fee_on_month as feeOnMonth, " + "oc.internationalized_name_code as currencyNameCode, c.fee_on_day as feeOnDay, c.fee_on_month as feeOnMonth, "
+ "c.fee_interval as feeInterval,c.min_cap as minCap,c.max_cap as maxCap " + "c.fee_interval as feeInterval,c.min_cap as minCap,c.max_cap as maxCap " + "from m_charge c "
+ "from m_charge c "
+ "join m_organisation_currency oc on c.currency_code = oc.code"; + "join m_organisation_currency oc on c.currency_code = oc.code";
} }
@@ -198,9 +197,9 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService
} }
final BigDecimal minCap = rs.getBigDecimal("minCap"); final BigDecimal minCap = rs.getBigDecimal("minCap");
final BigDecimal maxCap = rs.getBigDecimal("maxCap"); final BigDecimal maxCap = rs.getBigDecimal("maxCap");
return ChargeData.instance(id, name, amount, currency, chargeTimeType, chargeAppliesToType, chargeCalculationType, return ChargeData.instance(id, name, amount, currency, chargeTimeType, chargeAppliesToType, chargeCalculationType,
chargePaymentMode, feeOnMonthDay, feeInterval, penalty, active,minCap,maxCap); chargePaymentMode, feeOnMonthDay, feeInterval, penalty, active, minCap, maxCap);
} }
} }
@@ -83,26 +83,23 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP
final Map<String, Object> changes = chargeForUpdate.update(command); final Map<String, Object> changes = chargeForUpdate.update(command);
// MIFOSX-900: Check if the Charge has been active before and now is deactivated: // MIFOSX-900: Check if the Charge has been active before and now is
// deactivated:
if (changes.containsKey("active")) { if (changes.containsKey("active")) {
// IF the key exists then it has changed (otherwise it would have been filtered), so check current state: // IF the key exists then it has changed (otherwise it would
if(!chargeForUpdate.isActive()) // have been filtered), so check current state:
{ if (!chargeForUpdate.isActive()) {
// TODO: Change this function to only check the mappings!!! // TODO: Change this function to only check the mappings!!!
final Boolean isChargeExistWithLoans = isAnyLoanProductsAssociateWithThisCharge(chargeId); final Boolean isChargeExistWithLoans = isAnyLoanProductsAssociateWithThisCharge(chargeId);
final Boolean isChargeExistWithSavings = isAnySavingsProductsAssociateWithThisCharge(chargeId); final Boolean isChargeExistWithSavings = isAnySavingsProductsAssociateWithThisCharge(chargeId);
if(isChargeExistWithLoans || isChargeExistWithSavings) if (isChargeExistWithLoans || isChargeExistWithSavings) { throw new ChargeCannotBeUpdatedException(
{ "error.msg.charge.cannot.be.updated.it.is.used.in.loan", "This charge cannot be updated, it is used in loan"); }
throw new ChargeCannotBeUpdatedException(
"error.msg.charge.cannot.be.updated.it.is.used.in.loan",
"This charge cannot be updated, it is used in loan");
}
} }
} }
if (!changes.isEmpty()) { if (!changes.isEmpty()) {
this.chargeRepository.save(chargeForUpdate); this.chargeRepository.save(chargeForUpdate);
} }
@@ -124,7 +121,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP
final Collection<LoanProduct> loanProducts = this.loanProductRepository.retrieveLoanProductsByChargeId(chargeId); final Collection<LoanProduct> loanProducts = this.loanProductRepository.retrieveLoanProductsByChargeId(chargeId);
final Boolean isChargeExistWithLoans = isAnyLoansAssociateWithThisCharge(chargeId); final Boolean isChargeExistWithLoans = isAnyLoansAssociateWithThisCharge(chargeId);
final Boolean isChargeExistWithSavings = isAnySavingsAssociateWithThisCharge(chargeId); final Boolean isChargeExistWithSavings = isAnySavingsAssociateWithThisCharge(chargeId);
// TODO: Change error messages around: // TODO: Change error messages around:
if (!loanProducts.isEmpty() || isChargeExistWithLoans || isChargeExistWithSavings) { throw new ChargeCannotBeDeletedException( if (!loanProducts.isEmpty() || isChargeExistWithLoans || isChargeExistWithSavings) { throw new ChargeCannotBeDeletedException(
"error.msg.charge.cannot.be.deleted.it.is.already.used.in.loan", "error.msg.charge.cannot.be.deleted.it.is.already.used.in.loan",
@@ -161,22 +158,21 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP
final String isLoansUsingCharge = this.jdbcTemplate.queryForObject(sql, String.class, new Object[] { chargeId }); final String isLoansUsingCharge = this.jdbcTemplate.queryForObject(sql, String.class, new Object[] { chargeId });
return new Boolean(isLoansUsingCharge); return new Boolean(isLoansUsingCharge);
} }
private boolean isAnySavingsAssociateWithThisCharge(final Long chargeId) { private boolean isAnySavingsAssociateWithThisCharge(final Long chargeId) {
final String sql = "select if((exists (select 1 from m_savings_account_charge sc where sc.charge_id = ?)) = 1, 'true', 'false')"; final String sql = "select if((exists (select 1 from m_savings_account_charge sc where sc.charge_id = ?)) = 1, 'true', 'false')";
final String isSavingsUsingCharge = this.jdbcTemplate.queryForObject(sql, String.class, new Object[] { chargeId }); final String isSavingsUsingCharge = this.jdbcTemplate.queryForObject(sql, String.class, new Object[] { chargeId });
return new Boolean(isSavingsUsingCharge); return new Boolean(isSavingsUsingCharge);
} }
private boolean isAnyLoanProductsAssociateWithThisCharge(final Long chargeId) {
private boolean isAnyLoanProductsAssociateWithThisCharge(final Long chargeId) {
final String sql = "select if((exists (select 1 from m_product_loan_charge lc where lc.charge_id = ?)) = 1, 'true', 'false')"; final String sql = "select if((exists (select 1 from m_product_loan_charge lc where lc.charge_id = ?)) = 1, 'true', 'false')";
final String isLoansUsingCharge = this.jdbcTemplate.queryForObject(sql, String.class, new Object[] { chargeId }); final String isLoansUsingCharge = this.jdbcTemplate.queryForObject(sql, String.class, new Object[] { chargeId });
return new Boolean(isLoansUsingCharge); return new Boolean(isLoansUsingCharge);
} }
private boolean isAnySavingsProductsAssociateWithThisCharge(final Long chargeId) { private boolean isAnySavingsProductsAssociateWithThisCharge(final Long chargeId) {
final String sql = "select if((exists (select 1 from m_savings_product_charge sc where sc.charge_id = ?)) = 1, 'true', 'false')"; final String sql = "select if((exists (select 1 from m_savings_product_charge sc where sc.charge_id = ?)) = 1, 'true', 'false')";
@@ -37,8 +37,8 @@ public class ClientApiConstants {
public static final String staffIdParamName = "staffId"; public static final String staffIdParamName = "staffId";
public static final String closureDateParamName = "closureDate"; public static final String closureDateParamName = "closureDate";
public static final String closureReasonIdParamName = "closureReasonId"; public static final String closureReasonIdParamName = "closureReasonId";
public static final String submittedOnDateParamName="submittedOnDate"; public static final String submittedOnDateParamName = "submittedOnDate";
public static final String savingsProductIdParamName="savingsProductId"; public static final String savingsProductIdParamName = "savingsProductId";
// response parameters // response parameters
public static final String statusParamName = "status"; public static final String statusParamName = "status";
public static final String hierarchyParamName = "hierarchy"; public static final String hierarchyParamName = "hierarchy";
@@ -63,11 +63,11 @@ public class ClientApiConstants {
public static final Set<String> CLIENT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(localeParamName, public static final Set<String> CLIENT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(localeParamName,
dateFormatParamName, groupIdParamName, accountNoParamName, externalIdParamName, mobileNoParamName, firstnameParamName, dateFormatParamName, groupIdParamName, accountNoParamName, externalIdParamName, mobileNoParamName, firstnameParamName,
middlenameParamName, lastnameParamName, fullnameParamName, officeIdParamName, activeParamName, activationDateParamName, middlenameParamName, lastnameParamName, fullnameParamName, officeIdParamName, activeParamName, activationDateParamName,
staffIdParamName,submittedOnDateParamName,savingsProductIdParamName)); staffIdParamName, submittedOnDateParamName, savingsProductIdParamName));
public static final Set<String> CLIENT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(localeParamName, public static final Set<String> CLIENT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(localeParamName,
dateFormatParamName, accountNoParamName, externalIdParamName, mobileNoParamName, firstnameParamName, middlenameParamName, dateFormatParamName, accountNoParamName, externalIdParamName, mobileNoParamName, firstnameParamName, middlenameParamName,
lastnameParamName, fullnameParamName, activeParamName, activationDateParamName, staffIdParamName,savingsProductIdParamName)); lastnameParamName, fullnameParamName, activeParamName, activationDateParamName, staffIdParamName, savingsProductIdParamName));
/** /**
* These parameters will match the class level parameters of * These parameters will match the class level parameters of
@@ -135,7 +135,6 @@ public class ClientsApiResource {
clientData = ClientData.templateOnTop(clientData, templateData); clientData = ClientData.templateOnTop(clientData, templateData);
} }
return this.toApiJsonSerializer.serialize(settings, clientData, ClientApiConstants.CLIENT_RESPONSE_DATA_PARAMETERS); return this.toApiJsonSerializer.serialize(settings, clientData, ClientApiConstants.CLIENT_RESPONSE_DATA_PARAMETERS);
} }
@@ -50,7 +50,7 @@ final public class ClientData implements Comparable<ClientData> {
private final Long staffId; private final Long staffId;
private final String staffName; private final String staffName;
private final ClientTimelineData timeline; private final ClientTimelineData timeline;
private final Long savingsProductId; private final Long savingsProductId;
private final String savingsProductName; private final String savingsProductName;
@@ -68,7 +68,7 @@ final public class ClientData implements Comparable<ClientData> {
final Collection<StaffData> staffOptions, final Collection<CodeValueData> closureReasons, final Collection<StaffData> staffOptions, final Collection<CodeValueData> closureReasons,
final Collection<SavingsProductData> savingProductOptions) { final Collection<SavingsProductData> savingProductOptions) {
return new ClientData(null, null, officeId, null, null, null, null, null, null, null, null, null, null, null, joinedDate, null, return new ClientData(null, null, officeId, null, null, null, null, null, null, null, null, null, null, null, joinedDate, null,
null, null, officeOptions, null, staffOptions, closureReasons,null, savingProductOptions,null,null); null, null, officeOptions, null, staffOptions, closureReasons, null, savingProductOptions, null, null);
} }
@@ -78,8 +78,8 @@ final public class ClientData implements Comparable<ClientData> {
clientData.transferToOfficeId, clientData.transferToOfficeName, clientData.id, clientData.firstname, clientData.middlename, clientData.transferToOfficeId, clientData.transferToOfficeName, clientData.id, clientData.firstname, clientData.middlename,
clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo, clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo,
clientData.activationDate, clientData.imageId, clientData.staffId, clientData.staffName, templateData.officeOptions, clientData.activationDate, clientData.imageId, clientData.staffId, clientData.staffName, templateData.officeOptions,
clientData.groups, templateData.staffOptions, null,null, templateData.savingProductOptions, clientData.groups, templateData.staffOptions, null, null, templateData.savingProductOptions, clientData.savingsProductId,
clientData.savingsProductId, clientData.savingsProductName); clientData.savingsProductName);
} }
@@ -88,7 +88,7 @@ final public class ClientData implements Comparable<ClientData> {
clientData.transferToOfficeId, clientData.transferToOfficeName, clientData.id, clientData.firstname, clientData.middlename, clientData.transferToOfficeId, clientData.transferToOfficeName, clientData.id, clientData.firstname, clientData.middlename,
clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo, clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo,
clientData.activationDate, clientData.imageId, clientData.staffId, clientData.staffName, clientData.officeOptions, clientData.activationDate, clientData.imageId, clientData.staffId, clientData.staffName, clientData.officeOptions,
parentGroups, clientData.staffOptions, null,clientData.timeline, clientData.savingProductOptions, parentGroups, clientData.staffOptions, null, clientData.timeline, clientData.savingProductOptions,
clientData.savingsProductId, clientData.savingsProductName); clientData.savingsProductId, clientData.savingsProductName);
} }
@@ -98,13 +98,13 @@ final public class ClientData implements Comparable<ClientData> {
final String officeName) { final String officeName) {
return new ClientData(accountNo, status, officeId, officeName, null, null, id, firstname, middlename, lastname, fullname, return new ClientData(accountNo, status, officeId, officeName, null, null, id, firstname, middlename, lastname, fullname,
displayName, null, null, null, null, null, null, null, null, null, null,null, null,null,null); displayName, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
} }
public static ClientData lookup(final Long id, final String displayName, final Long officeId, final String officeName) { public static ClientData lookup(final Long id, final String displayName, final Long officeId, final String officeName) {
return new ClientData(null, null, officeId, officeName, null, null, id, null, null, null, null, displayName, null, null, null, return new ClientData(null, null, officeId, officeName, null, null, id, null, null, null, null, displayName, null, null, null,
null, null, null, null, null, null, null,null, null,null,null); null, null, null, null, null, null, null, null, null, null, null);
} }
@@ -112,20 +112,20 @@ final public class ClientData implements Comparable<ClientData> {
final Long transferToOfficeId, final String transferToOfficeName, final Long id, final String firstname, final Long transferToOfficeId, final String transferToOfficeName, final Long id, final String firstname,
final String middlename, final String lastname, final String fullname, final String displayName, final String externalId, final String middlename, final String lastname, final String fullname, final String displayName, final String externalId,
final String mobileNo, final LocalDate activationDate, final Long imageId, final Long staffId, final String staffName, final String mobileNo, final LocalDate activationDate, final Long imageId, final Long staffId, final String staffName,
final ClientTimelineData timeline,final Long savingsProductId,final String savingsProductName) { final ClientTimelineData timeline, final Long savingsProductId, final String savingsProductName) {
return new ClientData(accountNo, status, officeId, officeName, transferToOfficeId, transferToOfficeName, id, firstname, middlename, return new ClientData(accountNo, status, officeId, officeName, transferToOfficeId, transferToOfficeName, id, firstname, middlename,
lastname, fullname, displayName, externalId, mobileNo, activationDate, imageId, staffId, staffName, null, null, null, null, lastname, fullname, displayName, externalId, mobileNo, activationDate, imageId, staffId, staffName, null, null, null, null,
timeline, null,savingsProductId,savingsProductName); timeline, null, savingsProductId, savingsProductName);
} }
private ClientData(final String accountNo, final EnumOptionData status, final Long officeId, final String officeName, private ClientData(final String accountNo, final EnumOptionData status, final Long officeId, final String officeName,
final Long transferToOfficeId, final String transferToOfficeName, final Long id, final String firstname, final Long transferToOfficeId, final String transferToOfficeName, final Long id, final String firstname,
final String middlename, final String lastname, final String fullname, final String displayName, final String externalId, final String middlename, final String lastname, final String fullname, final String displayName, final String externalId,
final String mobileNo, final LocalDate activationDate, final Long imageId, final Long staffId, final String staffName, final String mobileNo, final LocalDate activationDate, final Long imageId, final Long staffId, final String staffName,
final Collection<OfficeData> allowedOffices, final Collection<GroupGeneralData> groups, final Collection<OfficeData> allowedOffices, final Collection<GroupGeneralData> groups,
final Collection<StaffData> staffOptions, final Collection<CodeValueData> closureReasons,final ClientTimelineData timeline, final Collection<StaffData> staffOptions, final Collection<CodeValueData> closureReasons, final ClientTimelineData timeline,
final Collection<SavingsProductData> savingProductOptions,final Long savingsProductId, final String savingsProductName) { final Collection<SavingsProductData> savingProductOptions, final Long savingsProductId, final String savingsProductName) {
this.accountNo = accountNo; this.accountNo = accountNo;
this.status = status; this.status = status;
if (status != null) { if (status != null) {
@@ -68,10 +68,11 @@ public final class ClientDataValidator {
final String accountNo = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.accountNoParamName, element); final String accountNo = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.accountNoParamName, element);
baseDataValidator.reset().parameter(ClientApiConstants.accountNoParamName).value(accountNo).notBlank().notExceedingLengthOf(20); baseDataValidator.reset().parameter(ClientApiConstants.accountNoParamName).value(accountNo).notBlank().notExceedingLengthOf(20);
} }
if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.savingsProductIdParamName, element)) { if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.savingsProductIdParamName, element)) {
final Long savingsProductId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.savingsProductIdParamName, element); final Long savingsProductId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.savingsProductIdParamName, element);
baseDataValidator.reset().parameter(ClientApiConstants.savingsProductIdParamName).value(savingsProductId).ignoreIfNull().longGreaterThanZero(); baseDataValidator.reset().parameter(ClientApiConstants.savingsProductIdParamName).value(savingsProductId).ignoreIfNull()
.longGreaterThanZero();
} }
if (isFullnameProvided(element) || isIndividualNameProvided(element)) { if (isFullnameProvided(element) || isIndividualNameProvided(element)) {
@@ -137,9 +138,9 @@ public final class ClientDataValidator {
baseDataValidator.reset().parameter(ClientApiConstants.activeParamName).value(active).trueOrFalseRequired(false); baseDataValidator.reset().parameter(ClientApiConstants.activeParamName).value(active).trueOrFalseRequired(false);
} }
if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.submittedOnDateParamName, element)) if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.submittedOnDateParamName, element)) {
{ final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.submittedOnDateParamName,
final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.submittedOnDateParamName, element); element);
baseDataValidator.reset().parameter(ClientApiConstants.submittedOnDateParamName).value(submittedOnDate).notNull(); baseDataValidator.reset().parameter(ClientApiConstants.submittedOnDateParamName).value(submittedOnDate).notNull();
} }
@@ -310,10 +311,11 @@ public final class ClientDataValidator {
final Long staffId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.staffIdParamName, element); final Long staffId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.staffIdParamName, element);
baseDataValidator.reset().parameter(ClientApiConstants.staffIdParamName).value(staffId).ignoreIfNull().longGreaterThanZero(); baseDataValidator.reset().parameter(ClientApiConstants.staffIdParamName).value(staffId).ignoreIfNull().longGreaterThanZero();
} }
if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.savingsProductIdParamName, element)) { if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.savingsProductIdParamName, element)) {
final Long savingsProductId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.savingsProductIdParamName, element); final Long savingsProductId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.savingsProductIdParamName, element);
baseDataValidator.reset().parameter(ClientApiConstants.savingsProductIdParamName).value(savingsProductId).ignoreIfNull().longGreaterThanZero(); baseDataValidator.reset().parameter(ClientApiConstants.savingsProductIdParamName).value(savingsProductId).ignoreIfNull()
.longGreaterThanZero();
} }
if (!atLeastOneParameterPassedForUpdate) { if (!atLeastOneParameterPassedForUpdate) {
@@ -33,12 +33,10 @@ public class ClientTimelineData {
private final String closedByFirstname; private final String closedByFirstname;
private final String closedByLastname; private final String closedByLastname;
public ClientTimelineData(final LocalDate submittedOnDate, final String submittedByUsername, final String submittedByFirstname,
public ClientTimelineData(final LocalDate submittedOnDate, final String submittedByUsername, final String submittedByLastname, final LocalDate activatedOnDate, final String activatedByUsername,
final String submittedByFirstname, final String submittedByLastname, final LocalDate activatedOnDate, final String activatedByFirstname, final String activatedByLastname, final LocalDate closedOnDate,
final String activatedByUsername, final String activatedByFirstname, final String activatedByLastname, final String closedByUsername, final String closedByFirstname, final String closedByLastname) {
final LocalDate closedOnDate, final String closedByUsername, final String closedByFirstname,
final String closedByLastname) {
this.submittedOnDate = submittedOnDate; this.submittedOnDate = submittedOnDate;
this.submittedByUsername = submittedByUsername; this.submittedByUsername = submittedByUsername;
this.submittedByFirstname = submittedByFirstname; this.submittedByFirstname = submittedByFirstname;
@@ -56,5 +54,4 @@ public class ClientTimelineData {
} }
} }
@@ -139,7 +139,7 @@ public final class Client extends AbstractPersistable<Long> {
@ManyToOne(optional = true) @ManyToOne(optional = true)
@JoinColumn(name = "activatedon_userid", nullable = true) @JoinColumn(name = "activatedon_userid", nullable = true)
private AppUser activatedBy; private AppUser activatedBy;
@ManyToOne @ManyToOne
@JoinColumn(name = "default_savings_product", nullable = true) @JoinColumn(name = "default_savings_product", nullable = true)
private SavingsProduct savingsProduct; private SavingsProduct savingsProduct;
@@ -179,7 +179,7 @@ public final class Client extends AbstractPersistable<Long> {
} }
return new Client(currentUser, status, clientOffice, clientParentGroup, accountNo, firstname, middlename, lastname, fullname, return new Client(currentUser, status, clientOffice, clientParentGroup, accountNo, firstname, middlename, lastname, fullname,
activationDate, officeJoiningDate, externalId, mobileNo, staff, submittedOnDate,savingsProduct); activationDate, officeJoiningDate, externalId, mobileNo, staff, submittedOnDate, savingsProduct);
} }
protected Client() { protected Client() {
@@ -404,7 +404,7 @@ public final class Client extends AbstractPersistable<Long> {
final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.savingsProductIdParamName); final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.savingsProductIdParamName);
actualChanges.put(ClientApiConstants.savingsProductIdParamName, newValue); actualChanges.put(ClientApiConstants.savingsProductIdParamName, newValue);
} }
final String dateFormatAsInput = command.dateFormat(); final String dateFormatAsInput = command.dateFormat();
final String localeAsInput = command.locale(); final String localeAsInput = command.locale();
@@ -640,7 +640,6 @@ public final class Client extends AbstractPersistable<Long> {
return false; return false;
} }
private Long savingsProductId() { private Long savingsProductId() {
Long savingsProductId = null; Long savingsProductId = null;
if (this.savingsProduct != null) { if (this.savingsProduct != null) {
@@ -649,17 +648,14 @@ public final class Client extends AbstractPersistable<Long> {
return savingsProductId; return savingsProductId;
} }
public SavingsProduct SavingsProduct() { public SavingsProduct SavingsProduct() {
return this.savingsProduct; return this.savingsProduct;
} }
public void updateSavingsProduct(SavingsProduct savingsProduct) { public void updateSavingsProduct(SavingsProduct savingsProduct) {
this.savingsProduct = savingsProduct; this.savingsProduct = savingsProduct;
} }
public AppUser activatedBy() { public AppUser activatedBy() {
return this.activatedBy; return this.activatedBy;
} }
@@ -4,8 +4,9 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul
public class ClientActiveForUpdateException extends AbstractPlatformDomainRuleException { public class ClientActiveForUpdateException extends AbstractPlatformDomainRuleException {
public ClientActiveForUpdateException(final Long clientId,final String parameterName) { public ClientActiveForUpdateException(final Long clientId, final String parameterName) {
super("error.msg.client.active.for.update.parameter."+parameterName, "The Client with id `" + clientId + "` is active,can't update parameter "+parameterName, clientId,parameterName); super("error.msg.client.active.for.update.parameter." + parameterName, "The Client with id `" + clientId
+ "` is active,can't update parameter " + parameterName, clientId, parameterName);
} }
} }

Some files were not shown because too many files have changed in this diff Show More