remove invalid suppression of warnings which were shown as warnings in eclipse indigo but fixed in eclipse juno and kepler.

This commit is contained in:
Keith Woodlock
2013-08-08 00:17:54 +01:00
parent cc684e02c3
commit f260591ea9
29 changed files with 972 additions and 986 deletions
@@ -33,7 +33,6 @@ public class GLClosure extends AbstractAuditableCustom<AppUser, Long> {
@JoinColumn(name = "office_id", nullable = false)
private Office office;
@SuppressWarnings("unused")
@Column(name = "is_deleted", nullable = false)
private boolean deleted = true;
@@ -35,20 +35,16 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
@JoinColumn(name = "account_id", nullable = false)
private GLAccount glAccount;
@SuppressWarnings("unused")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "reversal_id")
private JournalEntry reversalJournalEntry;
@SuppressWarnings("unused")
@Column(name = "transaction_id", nullable = false, length = 50)
private String transactionId;
@SuppressWarnings("unused")
@Column(name = "reversed", nullable = false)
private boolean reversed = false;
@SuppressWarnings("unused")
@Column(name = "manual_entry", nullable = false)
private boolean manualEntry = false;
@@ -62,15 +58,12 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "amount", scale = 6, precision = 19, nullable = false)
private BigDecimal amount;
@SuppressWarnings("unused")
@Column(name = "description", length = 500)
private String description;
@SuppressWarnings("unused")
@Column(name = "entity_type_enum", length = 50)
private Integer entityType;
@SuppressWarnings("unused")
@Column(name = "entity_id")
private Long entityId;
@@ -20,7 +20,6 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "acc_rule_tags", uniqueConstraints = { @UniqueConstraint(columnNames = { "acc_rule_id", "tag_id", "acc_type_enum" }, name = "UNIQUE_ACCOUNT_RULE_TAGS") })
public class AccountingTagRule extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "acc_rule_id", nullable = false)
private AccountingRule accountingRule;
@@ -25,171 +25,175 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "m_portfolio_command_source")
public class CommandSource extends AbstractPersistable<Long> {
@Column(name = "action_name", nullable = true, length = 100)
private String actionName;
@Column(name = "action_name", nullable = true, length = 100)
private String actionName;
@Column(name = "entity_name", nullable = true, length = 100)
private String entityName;
@Column(name = "entity_name", nullable = true, length = 100)
private String entityName;
@SuppressWarnings("unused")
@Column(name = "office_id")
private Long officeId;
@Column(name = "office_id")
private Long officeId;
@SuppressWarnings("unused")
@Column(name = "group_id")
private Long groupId;
@Column(name = "group_id")
private Long groupId;
@SuppressWarnings("unused")
@Column(name = "client_id")
private Long clientId;
@Column(name = "client_id")
private Long clientId;
@SuppressWarnings("unused")
@Column(name = "loan_id")
private Long loanId;
@Column(name = "loan_id")
private Long loanId;
@SuppressWarnings("unused")
@Column(name = "savings_account_id")
private Long savingsId;
@Column(name = "savings_account_id")
private Long savingsId;
@Column(name = "api_get_url", length = 100)
private String resourceGetUrl;
@Column(name = "api_get_url", length = 100)
private String resourceGetUrl;
@Column(name = "resource_id")
private Long resourceId;
@Column(name = "resource_id")
private Long resourceId;
@Column(name = "subresource_id")
private Long subresourceId;
@Column(name = "subresource_id")
private Long subresourceId;
@Column(name = "command_as_json", length = 1000)
private String commandAsJson;
@Column(name = "command_as_json", length = 1000)
private String commandAsJson;
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "maker_id", nullable = false)
private AppUser maker;
@ManyToOne
@JoinColumn(name = "maker_id", nullable = false)
private AppUser maker;
@SuppressWarnings("unused")
@Column(name = "made_on_date", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date madeOnDate;
@Column(name = "made_on_date", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date madeOnDate;
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "checker_id", nullable = true)
private AppUser checker;
@ManyToOne
@JoinColumn(name = "checker_id", nullable = true)
private AppUser checker;
@SuppressWarnings("unused")
@Column(name = "checked_on_date", nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date checkedOnDate;
@Column(name = "checked_on_date", nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date checkedOnDate;
@Column(name = "processing_result_enum", nullable = false)
private Integer processingResult;
@Column(name = "product_id")
private Long productId;
@Column(name = "processing_result_enum", nullable = false)
private Integer processingResult;
public static CommandSource fullEntryFrom(final CommandWrapper wrapper, final JsonCommand command, final AppUser maker) {
return new CommandSource(wrapper.actionName(), wrapper.entityName(), wrapper.getHref(), command.entityId(), command.subentityId(),
command.json(), maker, DateTime.now());
}
@Column(name = "product_id")
private Long productId;
protected CommandSource() {
//
}
public static CommandSource fullEntryFrom(final CommandWrapper wrapper,
final JsonCommand command, final AppUser maker) {
return new CommandSource(wrapper.actionName(), wrapper.entityName(),
wrapper.getHref(), command.entityId(), command.subentityId(),
command.json(), maker, DateTime.now());
}
private CommandSource(final String actionName, final String entityName, final String href, final Long resourceId,
final Long subresourceId, final String commandSerializedAsJson, final AppUser maker, final DateTime madeOnDateTime) {
this.actionName = actionName;
this.entityName = entityName;
this.resourceGetUrl = href;
this.resourceId = resourceId;
this.subresourceId = subresourceId;
this.commandAsJson = commandSerializedAsJson;
this.maker = maker;
this.madeOnDate = madeOnDateTime.toDate();
this.processingResult = CommandProcessingResultType.PROCESSED.getValue();
}
protected CommandSource() {
//
}
public void markAsChecked(final AppUser checker, final DateTime checkedOnDate) {
this.checker = checker;
this.checkedOnDate = checkedOnDate.toDate();
this.processingResult = CommandProcessingResultType.PROCESSED.getValue();
}
private CommandSource(final String actionName, final String entityName,
final String href, final Long resourceId, final Long subresourceId,
final String commandSerializedAsJson, final AppUser maker,
final DateTime madeOnDateTime) {
this.actionName = actionName;
this.entityName = entityName;
this.resourceGetUrl = href;
this.resourceId = resourceId;
this.subresourceId = subresourceId;
this.commandAsJson = commandSerializedAsJson;
this.maker = maker;
this.madeOnDate = madeOnDateTime.toDate();
this.processingResult = CommandProcessingResultType.PROCESSED
.getValue();
}
public void updateResourceId(final Long resourceId) {
this.resourceId = resourceId;
}
public void markAsChecked(final AppUser checker,
final DateTime checkedOnDate) {
this.checker = checker;
this.checkedOnDate = checkedOnDate.toDate();
this.processingResult = CommandProcessingResultType.PROCESSED
.getValue();
}
public void updateSubresourceId(final Long subresourceId) {
this.subresourceId = subresourceId;
}
public void updateResourceId(final Long resourceId) {
this.resourceId = resourceId;
}
public void updateJsonTo(final String json) {
this.commandAsJson = json;
}
public void updateSubresourceId(final Long subresourceId) {
this.subresourceId = subresourceId;
}
public Long resourceId() {
return this.resourceId;
}
public void updateJsonTo(final String json) {
this.commandAsJson = json;
}
public Long subresourceId() {
return this.subresourceId;
}
public Long resourceId() {
return this.resourceId;
}
public boolean hasJson() {
return StringUtils.isNotBlank(this.commandAsJson);
}
public Long subresourceId() {
return this.subresourceId;
}
public String json() {
return this.commandAsJson;
}
public boolean hasJson() {
return StringUtils.isNotBlank(this.commandAsJson);
}
public String getActionName() {
return this.actionName;
}
public String json() {
return this.commandAsJson;
}
public String getEntityName() {
return this.entityName;
}
public String getActionName() {
return this.actionName;
}
public String getPermissionCode() {
return this.actionName + "_" + this.entityName;
}
public String getEntityName() {
return this.entityName;
}
public Long getResourceId() {
return this.resourceId;
}
public String getPermissionCode() {
return this.actionName + "_" + this.entityName;
}
public Long getSubresourceId() {
return this.subresourceId;
}
public Long getResourceId() {
return this.resourceId;
}
public void markAsAwaitingApproval() {
this.processingResult = CommandProcessingResultType.AWAITING_APPROVAL.getValue();
}
public Long getSubresourceId() {
return this.subresourceId;
}
public boolean isMarkedAsAwaitingApproval() {
if (this.processingResult.equals(CommandProcessingResultType.AWAITING_APPROVAL.getValue())) return true;
public void markAsAwaitingApproval() {
this.processingResult = CommandProcessingResultType.AWAITING_APPROVAL
.getValue();
}
return false;
}
public boolean isMarkedAsAwaitingApproval() {
if (this.processingResult
.equals(CommandProcessingResultType.AWAITING_APPROVAL
.getValue())) {
return true;
}
public void updateForAudit(final Long officeId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId,
final Long productId) {
this.officeId = officeId;
this.groupId = groupId;
this.clientId = clientId;
this.loanId = loanId;
this.savingsId = savingsId;
this.productId = productId;
}
return false;
}
public String getResourceGetUrl() {
return this.resourceGetUrl;
}
public void updateForAudit(final Long officeId, final Long groupId,
final Long clientId, final Long loanId, final Long savingsId,
final Long productId) {
this.officeId = officeId;
this.groupId = groupId;
this.clientId = clientId;
this.loanId = loanId;
this.savingsId = savingsId;
this.productId = productId;
}
public Long getProductId() {
return this.productId;
}
public String getResourceGetUrl() {
return this.resourceGetUrl;
}
public Long getProductId() {
return this.productId;
}
}
@@ -22,72 +22,85 @@ import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "m_code_value", uniqueConstraints = { @UniqueConstraint(columnNames = { "code_id", "code_value" }, name = "code_value_duplicate") })
@Table(name = "m_code_value", uniqueConstraints = { @UniqueConstraint(columnNames = {
"code_id", "code_value" }, name = "code_value_duplicate") })
public class CodeValue extends AbstractPersistable<Long> {
@Column(name = "code_value", length = 100)
private String label;
@Column(name = "code_value", length = 100)
private String label;
@Column(name = "order_position")
private int position;
@Column(name = "order_position")
private int position;
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "code_id", nullable = false)
private Code code;
@ManyToOne
@JoinColumn(name = "code_id", nullable = false)
private Code code;
public static CodeValue createNew(Code code, final String label, final int position) {
return new CodeValue(code, label, position);
}
public static CodeValue createNew(final Code code, final String label,
final int position) {
return new CodeValue(code, label, position);
}
protected CodeValue() {
//
}
protected CodeValue() {
//
}
private CodeValue(final Code code, final String label, final int position) {
this.code = code;
this.label = StringUtils.defaultIfEmpty(label, null);
this.position = position;
}
private CodeValue(final Code code, final String label, final int position) {
this.code = code;
this.label = StringUtils.defaultIfEmpty(label, null);
this.position = position;
}
public String label() {
return label;
}
public String label() {
return this.label;
}
public int position() {
return position;
}
public static CodeValue fromJson(Code code, final JsonCommand command) {
public int position() {
return this.position;
}
final String label = command.stringValueOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.NAME.getValue());
Integer position = command.integerValueSansLocaleOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue());
if(position == null) position = new Integer(0);
return new CodeValue(code, label, position.intValue());
}
public Map<String, Object> update(final JsonCommand command) {
public static CodeValue fromJson(final Code code, final JsonCommand command) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(2);
final String label = command
.stringValueOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.NAME
.getValue());
Integer position = command
.integerValueSansLocaleOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.POSITION
.getValue());
if (position == null) {
position = new Integer(0);
}
return new CodeValue(code, label, position.intValue());
}
final String labelParamName = CODEVALUE_JSON_INPUT_PARAMS.NAME.getValue();
if (command.isChangeInStringParameterNamed(labelParamName, this.label)) {
final String newValue = command.stringValueOfParameterNamed(labelParamName);
actualChanges.put(labelParamName, newValue);
this.label = StringUtils.defaultIfEmpty(newValue, null);
}
final String positionParamName = CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue();
if (command.isChangeInIntegerSansLocaleParameterNamed(positionParamName, this.position)) {
final Integer newValue = command.integerValueSansLocaleOfParameterNamed(positionParamName);
actualChanges.put(positionParamName, newValue);
this.position = newValue.intValue();
}
return actualChanges;
}
public Map<String, Object> update(final JsonCommand command) {
public CodeValueData toData() {
return CodeValueData.instance(this.getId(), this.label, this.position);
}
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(
2);
final String labelParamName = CODEVALUE_JSON_INPUT_PARAMS.NAME
.getValue();
if (command.isChangeInStringParameterNamed(labelParamName, this.label)) {
final String newValue = command
.stringValueOfParameterNamed(labelParamName);
actualChanges.put(labelParamName, newValue);
this.label = StringUtils.defaultIfEmpty(newValue, null);
}
final String positionParamName = CODEVALUE_JSON_INPUT_PARAMS.POSITION
.getValue();
if (command.isChangeInIntegerSansLocaleParameterNamed(
positionParamName, this.position)) {
final Integer newValue = command
.integerValueSansLocaleOfParameterNamed(positionParamName);
actualChanges.put(positionParamName, newValue);
this.position = newValue.intValue();
}
return actualChanges;
}
public CodeValueData toData() {
return CodeValueData.instance(getId(), this.label, this.position);
}
}
@@ -14,10 +14,9 @@ import javax.persistence.UniqueConstraint;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "c_external_service", uniqueConstraints = { @UniqueConstraint(columnNames = ("name")) })
@Table(name = "c_external_service", uniqueConstraints = { @UniqueConstraint(columnNames = "name") })
public class ExternalService extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@Column(name = "name", nullable = false)
private String name;
@@ -15,7 +15,6 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "c_configuration")
public class GlobalConfigurationProperty extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@Column(name = "name", nullable = false)
private final String name;
@@ -28,7 +28,6 @@ public class ScheduledJobDetail extends AbstractPersistable<Long> {
@Column(name = "cron_expression")
private String cronExpression;
@SuppressWarnings("unused")
@Column(name = "create_time")
@Temporal(TemporalType.TIMESTAMP)
private Date createTime;
@@ -39,12 +38,10 @@ public class ScheduledJobDetail extends AbstractPersistable<Long> {
@Column(name = "group_name")
private String groupName;
@SuppressWarnings("unused")
@Column(name = "previous_run_start_time")
@Temporal(TemporalType.TIMESTAMP)
private Date previousRunStartTime;
@SuppressWarnings("unused")
@Column(name = "next_run_time")
@Temporal(TemporalType.TIMESTAMP)
private Date nextRunTime;
@@ -52,7 +49,6 @@ public class ScheduledJobDetail extends AbstractPersistable<Long> {
@Column(name = "job_key")
private String jobKey;
@SuppressWarnings("unused")
@Column(name = "initializing_errorlog")
private String errorLog;
@@ -62,7 +58,6 @@ public class ScheduledJobDetail extends AbstractPersistable<Long> {
@Column(name = "currently_running")
private boolean currentlyRunning;
@SuppressWarnings("unused")
@Column(name = "updates_allowed")
private boolean updatesAllowed;
@@ -113,7 +108,7 @@ public class ScheduledJobDetail extends AbstractPersistable<Long> {
this.nextRunTime = nextRunTime;
}
public void updateJobKey(String jobKey) {
public void updateJobKey(final String jobKey) {
this.jobKey = jobKey;
}
@@ -125,7 +120,7 @@ public class ScheduledJobDetail extends AbstractPersistable<Long> {
return this.currentlyRunning;
}
public void updateCurrentlyRunningStatus(boolean currentlyRunning) {
public void updateCurrentlyRunningStatus(final boolean currentlyRunning) {
this.currentlyRunning = currentlyRunning;
}
@@ -16,38 +16,30 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "job_run_history")
public class ScheduledJobRunHistory extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "job_id")
private ScheduledJobDetail scheduledJobDetail;
@SuppressWarnings("unused")
@Column(name = "version")
private Long version;
@SuppressWarnings("unused")
@Column(name = "start_time")
@Temporal(TemporalType.TIMESTAMP)
private Date startTime;
@SuppressWarnings("unused")
@Column(name = "end_time")
@Temporal(TemporalType.TIMESTAMP)
private Date endTime;
@SuppressWarnings("unused")
@Column(name = "status")
private String status;
@SuppressWarnings("unused")
@Column(name = "error_message")
private String errorMessage;
@SuppressWarnings("unused")
@Column(name = "trigger_type")
private String triggerType;
@SuppressWarnings("unused")
@Column(name = "error_log")
private String errorLog;
@@ -30,7 +30,6 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "m_holiday", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "holiday_name") })
public class Holiday extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@Column(name = "name", unique = true, nullable = false, length = 100)
private String name;
@@ -49,7 +48,6 @@ public class Holiday extends AbstractPersistable<Long> {
@Column(name = "processed", nullable = false)
private boolean processed;
@SuppressWarnings("unused")
@Column(name = "description", length = 100)
private String description;
@@ -28,30 +28,24 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "m_office_transaction")
public class OfficeTransaction extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "from_office_id")
private Office from;
@SuppressWarnings("unused")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "to_office_id")
private Office to;
@SuppressWarnings("unused")
@Column(name = "transaction_date", nullable = false)
@Temporal(TemporalType.DATE)
private Date transactionDate;
@SuppressWarnings("unused")
@Embedded
private MonetaryCurrency currency;
@SuppressWarnings("unused")
@Column(name = "transaction_amount", scale = 6, precision = 19, nullable = false)
private BigDecimal transactionAmount;
@SuppressWarnings("unused")
@Column(name = "description", nullable = true, length = 100)
private String description;
@@ -18,23 +18,18 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "m_organisation_currency")
public class OrganisationCurrency extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@Column(name = "code", nullable = false, length = 3)
private final String code;
@SuppressWarnings("unused")
@Column(name = "decimal_places", nullable = false)
private final Integer decimalPlaces;
@SuppressWarnings("unused")
@Column(name = "name", nullable = false, length = 50)
private final String name;
@SuppressWarnings("unused")
@Column(name = "internationalized_name_code", nullable = false, length = 50)
private final String nameCode;
@SuppressWarnings("unused")
@Column(name = "display_symbol", nullable = true, length = 10)
private final String displaySymbol;
@@ -50,7 +50,6 @@ public class Staff extends AbstractPersistable<Long> {
@Column(name = "organisational_role_enum", nullable = true)
private Integer organisationalRoleType;
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "organisational_role_parent_staff_id", nullable = true)
private Staff organisationalRoleParentStaff;
@@ -58,13 +57,13 @@ public class Staff extends AbstractPersistable<Long> {
public static Staff fromJson(final Office staffOffice, final JsonCommand command) {
final String firstnameParamName = "firstname";
String firstname = command.stringValueOfParameterNamed(firstnameParamName);
final String firstname = command.stringValueOfParameterNamed(firstnameParamName);
final String lastnameParamName = "lastname";
String lastname = command.stringValueOfParameterNamed(lastnameParamName);
final String lastname = command.stringValueOfParameterNamed(lastnameParamName);
final String externalIdParamName = "externalId";
String externalId = command.stringValueOfParameterNamedAllowingNull(externalIdParamName);
final String externalId = command.stringValueOfParameterNamedAllowingNull(externalIdParamName);
final String isLoanOfficerParamName = "isLoanOfficer";
final boolean isLoanOfficer = command.booleanPrimitiveValueOfParameterNamed(isLoanOfficerParamName);
@@ -96,11 +96,9 @@ public final class Client extends AbstractPersistable<Long> {
@Transient
private boolean accountNumberRequiresAutoGeneration = false;
@SuppressWarnings("unused")
@Column(name = "closure_reason_cv_id", nullable = true)
private Long closureReasonId;
@SuppressWarnings("unused")
@Column(name = "closedon_date", nullable = true)
@Temporal(TemporalType.DATE)
private Date closureDate;
@@ -464,7 +462,7 @@ public final class Client extends AbstractPersistable<Long> {
}
public Integer getStatus() {
return status;
return this.status;
}
public boolean isActivatedAfter(final LocalDate submittedOn) {
@@ -23,78 +23,89 @@ import org.mifosplatform.useradministration.domain.AppUser;
@Entity
@Table(name = "m_client_identifier", uniqueConstraints = {
@UniqueConstraint(columnNames = { "document_type_id", "document_key" }, name = "unique_identifier_key"),
@UniqueConstraint(columnNames = { "client_id", "document_type_id" }, name = "unique_client_identifier") })
@UniqueConstraint(columnNames = { "document_type_id", "document_key" }, name = "unique_identifier_key"),
@UniqueConstraint(columnNames = { "client_id", "document_type_id" }, name = "unique_client_identifier") })
public class ClientIdentifier extends AbstractAuditableCustom<AppUser, Long> {
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "client_id", nullable = false)
private Client client;
@ManyToOne
@JoinColumn(name = "client_id", nullable = false)
private Client client;
@ManyToOne
@JoinColumn(name = "document_type_id", nullable = false)
private CodeValue documentType;
@ManyToOne
@JoinColumn(name = "document_type_id", nullable = false)
private CodeValue documentType;
@Column(name = "document_key", length = 1000)
private String documentKey;
@Column(name = "document_key", length = 1000)
private String documentKey;
@Column(name = "description", length = 1000)
private String description;
@Column(name = "description", length = 1000)
private String description;
public static ClientIdentifier fromJson(final Client client, final CodeValue documentType, final JsonCommand command) {
final String documentKey = command.stringValueOfParameterNamed("documentKey");
final String description = command.stringValueOfParameterNamed("description");
return new ClientIdentifier(client, documentType, documentKey, description);
}
public static ClientIdentifier fromJson(final Client client,
final CodeValue documentType, final JsonCommand command) {
final String documentKey = command
.stringValueOfParameterNamed("documentKey");
final String description = command
.stringValueOfParameterNamed("description");
return new ClientIdentifier(client, documentType, documentKey,
description);
}
protected ClientIdentifier() {
//
}
protected ClientIdentifier() {
//
}
private ClientIdentifier(final Client client, final CodeValue documentType, final String documentKey, final String description) {
this.client = client;
this.documentType = documentType;
this.documentKey = StringUtils.defaultIfEmpty(documentKey, null);
this.description = StringUtils.defaultIfEmpty(description, null);
}
private ClientIdentifier(final Client client, final CodeValue documentType,
final String documentKey, final String description) {
this.client = client;
this.documentType = documentType;
this.documentKey = StringUtils.defaultIfEmpty(documentKey, null);
this.description = StringUtils.defaultIfEmpty(description, null);
}
public void update(final CodeValue documentType) {
this.documentType = documentType;
}
public void update(final CodeValue documentType) {
this.documentType = documentType;
}
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 String documentTypeIdParamName = "documentTypeId";
if (command.isChangeInLongParameterNamed(documentTypeIdParamName, this.documentType.getId())) {
final Long newValue = command.longValueOfParameterNamed(documentTypeIdParamName);
actualChanges.put(documentTypeIdParamName, newValue);
}
final String documentTypeIdParamName = "documentTypeId";
if (command.isChangeInLongParameterNamed(documentTypeIdParamName,
this.documentType.getId())) {
final Long newValue = command
.longValueOfParameterNamed(documentTypeIdParamName);
actualChanges.put(documentTypeIdParamName, newValue);
}
final String documentKeyParamName = "documentKey";
if (command.isChangeInStringParameterNamed(documentKeyParamName, this.documentKey)) {
final String newValue = command.stringValueOfParameterNamed(documentKeyParamName);
actualChanges.put(documentKeyParamName, newValue);
this.documentKey = StringUtils.defaultIfEmpty(newValue, null);
}
final String documentKeyParamName = "documentKey";
if (command.isChangeInStringParameterNamed(documentKeyParamName,
this.documentKey)) {
final String newValue = command
.stringValueOfParameterNamed(documentKeyParamName);
actualChanges.put(documentKeyParamName, newValue);
this.documentKey = StringUtils.defaultIfEmpty(newValue, null);
}
final String descriptionParamName = "description";
if (command.isChangeInStringParameterNamed(descriptionParamName, this.description)) {
final String newValue = command.stringValueOfParameterNamed(descriptionParamName);
actualChanges.put(descriptionParamName, newValue);
this.description = StringUtils.defaultIfEmpty(newValue, null);
}
final String descriptionParamName = "description";
if (command.isChangeInStringParameterNamed(descriptionParamName,
this.description)) {
final String newValue = command
.stringValueOfParameterNamed(descriptionParamName);
actualChanges.put(descriptionParamName, newValue);
this.description = StringUtils.defaultIfEmpty(newValue, null);
}
return actualChanges;
}
return actualChanges;
}
public String documentKey() {
return this.documentKey;
}
public String documentKey() {
return this.documentKey;
}
public Long documentTypeId() {
return this.documentType.getId();
}
public Long documentTypeId() {
return this.documentType.getId();
}
}
@@ -30,7 +30,6 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "m_loan_collateral")
public class LoanCollateral extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@ManyToOne(optional = false)
@JoinColumn(name = "loan_id", nullable = false)
private Loan loan;
@@ -105,10 +104,10 @@ public class LoanCollateral extends AbstractPersistable<Long> {
public CollateralData toData() {
final CodeValueData typeData = this.type.toData();
return CollateralData.instance(this.getId(), typeData, this.value, this.description, null);
return CollateralData.instance(getId(), typeData, this.value, this.description, null);
}
public void setCollateralType(CodeValue type) {
public void setCollateralType(final CodeValue type) {
this.type = type;
}
@@ -117,9 +116,9 @@ public class LoanCollateral extends AbstractPersistable<Long> {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj.getClass() != getClass()) { return false; }
LoanCollateral rhs = (LoanCollateral) obj;
final LoanCollateral rhs = (LoanCollateral) obj;
return new EqualsBuilder().appendSuper(super.equals(obj)) //
.append(this.getId(), rhs.getId()) //
.append(getId(), rhs.getId()) //
.append(this.type.getId(), rhs.type.getId()) //
.append(this.description, rhs.description) //
.append(this.value, this.value)//
@@ -129,7 +128,7 @@ public class LoanCollateral extends AbstractPersistable<Long> {
@Override
public int hashCode() {
return new HashCodeBuilder(3, 5) //
.append(this.getId()) //
.append(getId()) //
.append(this.type.getId()) //
.append(this.description) //
.append(this.value)//
@@ -19,7 +19,6 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "m_group_roles")
public class GroupRole extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "group_id")
private Group group;
@@ -149,27 +149,22 @@ public class Loan extends AbstractPersistable<Long> {
@Column(name = "submittedon_date")
private Date submittedOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "submittedon_userid", nullable = true)
private AppUser submittedBy;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "rejectedon_date")
private Date rejectedOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "rejectedon_userid", nullable = true)
private AppUser rejectedBy;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "withdrawnon_date")
private Date withdrawnOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "withdrawnon_userid", nullable = true)
private AppUser withdrawnBy;
@@ -178,7 +173,6 @@ public class Loan extends AbstractPersistable<Long> {
@Column(name = "approvedon_date")
private Date approvedOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "approvedon_userid", nullable = true)
private AppUser approvedBy;
@@ -191,7 +185,6 @@ public class Loan extends AbstractPersistable<Long> {
@Column(name = "disbursedon_date")
private Date actualDisbursementDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "disbursedon_userid", nullable = true)
private AppUser disbursedBy;
@@ -200,12 +193,10 @@ public class Loan extends AbstractPersistable<Long> {
@Column(name = "closedon_date")
private Date closedOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "closedon_userid", nullable = true)
private AppUser closedBy;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "writtenoffon_date")
private Date writtenOffOnDate;
@@ -214,12 +205,10 @@ public class Loan extends AbstractPersistable<Long> {
@Column(name = "rescheduledon_date")
private Date rescheduledOnDate;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "expected_maturedon_date")
private Date expectedMaturityDate;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "maturedon_date")
private Date actualMaturityDate;
@@ -232,7 +221,6 @@ public class Loan extends AbstractPersistable<Long> {
@Column(name = "interest_calculated_from_date")
private Date interestChargedFromDate;
@SuppressWarnings("unused")
@Column(name = "total_overpaid_derived", scale = 6, precision = 19)
private BigDecimal totalOverpaid;
@@ -382,7 +370,7 @@ public class Loan extends AbstractPersistable<Long> {
Money chargesDue = Money.of(getCurrency(), BigDecimal.ZERO);
for (LoanCharge charge : setOfLoanCharges()) {
for (final LoanCharge charge : setOfLoanCharges()) {
if (charge.isDueAtDisbursement()) {
chargesDue = chargesDue.plus(charge.amount());
}
@@ -392,14 +380,14 @@ public class Loan extends AbstractPersistable<Long> {
}
private Set<LoanCharge> associateChargesWithThisLoan(final Set<LoanCharge> loanCharges) {
for (LoanCharge loanCharge : loanCharges) {
for (final LoanCharge loanCharge : loanCharges) {
loanCharge.update(this);
}
return loanCharges;
}
private Set<LoanCollateral> associateWithThisLoan(final Set<LoanCollateral> collateral) {
for (LoanCollateral item : collateral) {
for (final LoanCollateral item : collateral) {
item.associateWith(this);
}
return collateral;
@@ -455,13 +443,13 @@ public class Loan extends AbstractPersistable<Long> {
final List<LoanTransaction> allNonContraTransactionsPostDisbursement = retreiveListOfTransactionsPostDisbursement();
changedTransactionDetail = loanRepaymentScheduleTransactionProcessor.handleTransaction(getDisbursementDate(),
allNonContraTransactionsPostDisbursement, getCurrency(), this.repaymentScheduleInstallments, setOfLoanCharges());
for (LoanTransaction transaction : changedTransactionDetail.getNewTransactions()) {
for (final LoanTransaction transaction : changedTransactionDetail.getNewTransactions()) {
transaction.updateLoan(this);
}
this.loanTransactions.addAll(changedTransactionDetail.getNewTransactions());
} else {
// just reprocess the loan schedule only for now.
LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper();
final LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper();
wrapper.reprocess(getCurrency(), getDisbursementDate(), this.repaymentScheduleInstallments, setOfLoanCharges());
}
@@ -497,7 +485,7 @@ public class Loan extends AbstractPersistable<Long> {
transactionDate = suppliedTransactionDate;
} else {
transactionDate = loanCharge.getDueLocalDate();
LocalDate currentDate = DateUtils.getLocalDateOfTenant();
final LocalDate currentDate = DateUtils.getLocalDateOfTenant();
// if loan charge is to be applied on a future date, the loan
// transaction would show todays date as applied date
@@ -549,7 +537,7 @@ public class Loan extends AbstractPersistable<Long> {
// if you want ability to remove loan charges that are waived.
validateLoanChargeIsNotWaived(loanCharge);
boolean removed = setOfLoanCharges().remove(loanCharge);
final boolean removed = setOfLoanCharges().remove(loanCharge);
if (removed) {
updateSummaryWithTotalFeeChargesDueAtDisbursement(deriveSumTotalOfChargesDueAtDisbursement());
}
@@ -578,7 +566,7 @@ public class Loan extends AbstractPersistable<Long> {
private void removeOrModifyTransactionAssociatedWithLoanChargeIfDueAtDisbursement(final LoanCharge loanCharge) {
if (loanCharge.isDueAtDisbursement()) {
LoanTransaction transactionToRemove = null;
for (LoanTransaction transaction : this.loanTransactions) {
for (final LoanTransaction transaction : this.loanTransactions) {
if (transaction.isRepaymentAtDisbursement()) {
final MonetaryCurrency currency = loanCurrency();
@@ -630,7 +618,7 @@ public class Loan extends AbstractPersistable<Long> {
getCurrency(), this.repaymentScheduleInstallments, setOfLoanCharges());
} else {
// reprocess loan schedule based on charge been waived.
LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper();
final LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper();
wrapper.reprocess(getCurrency(), getDisbursementDate(), this.repaymentScheduleInstallments, setOfLoanCharges());
}
@@ -687,7 +675,7 @@ public class Loan extends AbstractPersistable<Long> {
getCurrency(), this.repaymentScheduleInstallments, setOfLoanCharges());
} else {
// reprocess loan schedule based on charge been waived.
LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper();
final LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper();
wrapper.reprocess(getCurrency(), getDisbursementDate(), this.repaymentScheduleInstallments, setOfLoanCharges());
}
@@ -732,12 +720,12 @@ public class Loan extends AbstractPersistable<Long> {
}
public void updateLoanOfficerOnLoanApplication(final Staff newLoanOfficer) {
if (!this.isSubmittedAndPendingApproval()) {
if (!isSubmittedAndPendingApproval()) {
Long loanOfficerId = null;
if (this.loanOfficer != null) {
loanOfficerId = this.loanOfficer.getId();
}
throw new LoanOfficerAssignmentException(this.getId(), loanOfficerId);
throw new LoanOfficerAssignmentException(getId(), loanOfficerId);
}
this.loanOfficer = newLoanOfficer;
}
@@ -763,15 +751,15 @@ public class Loan extends AbstractPersistable<Long> {
public void updateLoanSchedule(final LoanScheduleModel modifiedLoanSchedule) {
this.repaymentScheduleInstallments.clear();
for (LoanScheduleModelPeriod scheduledLoanInstallment : modifiedLoanSchedule.getPeriods()) {
for (final LoanScheduleModelPeriod scheduledLoanInstallment : modifiedLoanSchedule.getPeriods()) {
if (scheduledLoanInstallment.isRepaymentPeriod()) {
LoanRepaymentScheduleInstallment installment = new LoanRepaymentScheduleInstallment(this,
final LoanRepaymentScheduleInstallment installment = new LoanRepaymentScheduleInstallment(this,
scheduledLoanInstallment.periodNumber(), scheduledLoanInstallment.periodFromDate(),
scheduledLoanInstallment.periodDueDate(), scheduledLoanInstallment.principalDue(),
scheduledLoanInstallment.interestDue(), scheduledLoanInstallment.feeChargesDue(),
scheduledLoanInstallment.penaltyChargesDue());
this.addRepaymentScheduleInstallment(installment);
addRepaymentScheduleInstallment(installment);
}
}
@@ -812,7 +800,7 @@ public class Loan extends AbstractPersistable<Long> {
final Map<String, Object> actualChanges = this.loanRepaymentScheduleDetail.updateLoanApplicationAttributes(command, aprCalculator);
if (!actualChanges.isEmpty()) {
boolean recalculateLoanSchedule = !(actualChanges.size() == 1 && actualChanges.containsKey("inArrearsTolerance"));
final boolean recalculateLoanSchedule = !(actualChanges.size() == 1 && actualChanges.containsKey("inArrearsTolerance"));
actualChanges.put("recalculateLoanSchedule", recalculateLoanSchedule);
}
@@ -962,14 +950,14 @@ public class Loan extends AbstractPersistable<Long> {
throw new InvalidLoanStateTransitionException("submittal", "cannot.be.a.future.date", errorMessage, getSubmittedOnDate());
}
if (!(client == null)) {
if (getSubmittedOnDate().isBefore(client.getActivationLocalDate())) {
if (!(this.client == null)) {
if (getSubmittedOnDate().isBefore(this.client.getActivationLocalDate())) {
final String errorMessage = "The date on which a loan is submitted cannot be earlier than client's activation date.";
throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.client.activation.date", errorMessage,
getSubmittedOnDate());
}
} else if (!(group == null)) {
if (getSubmittedOnDate().isBefore(group.getActivationLocalDate())) {
} else if (!(this.group == null)) {
if (getSubmittedOnDate().isBefore(this.group.getActivationLocalDate())) {
final String errorMessage = "The date on which a loan is submitted cannot be earlier than groups's activation date.";
throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.group.activation.date", errorMessage,
getSubmittedOnDate());
@@ -994,7 +982,7 @@ public class Loan extends AbstractPersistable<Long> {
actualChanges.put(chargesParamName, getLoanCharges(possiblyModifedLoanCharges));
actualChanges.put("recalculateLoanSchedule", true);
for (LoanCharge loanCharge : possiblyModifedLoanCharges) {
for (final LoanCharge loanCharge : possiblyModifedLoanCharges) {
validateChargeHasValidSpecifiedDateIfApplicable(loanCharge, getDisbursementDate(), getLastRepaymentPeriodDueDate());
}
}
@@ -1038,10 +1026,10 @@ public class Loan extends AbstractPersistable<Long> {
CollateralData[] existingLoanCollateral = null;
List<CollateralData> loanCollateralList = new ArrayList<CollateralData>();
for (LoanCollateral loanCollateral : setOfLoanCollateral) {
final List<CollateralData> loanCollateralList = new ArrayList<CollateralData>();
for (final LoanCollateral loanCollateral : setOfLoanCollateral) {
CollateralData data = loanCollateral.toData();
final CollateralData data = loanCollateral.toData();
loanCollateralList.add(data);
}
@@ -1055,8 +1043,8 @@ public class Loan extends AbstractPersistable<Long> {
LoanChargeCommand[] existingLoanCharges = null;
List<LoanChargeCommand> loanChargesList = new ArrayList<LoanChargeCommand>();
for (LoanCharge loanCharge : setOfLoanCharges) {
final List<LoanChargeCommand> loanChargesList = new ArrayList<LoanChargeCommand>();
for (final LoanCharge loanCharge : setOfLoanCharges) {
loanChargesList.add(loanCharge.toCommand());
}
@@ -1066,9 +1054,9 @@ public class Loan extends AbstractPersistable<Long> {
}
private void removeFirstDisbursementTransaction() {
for (LoanTransaction loanTransaction : loanTransactions) {
for (final LoanTransaction loanTransaction : this.loanTransactions) {
if (loanTransaction.isDisbursement()) {
loanTransactions.remove(loanTransaction);
this.loanTransactions.remove(loanTransaction);
break;
}
}
@@ -1086,7 +1074,7 @@ public class Loan extends AbstractPersistable<Long> {
from = LoanStatus.fromInt(this.loanStatus);
}
LoanStatus statusEnum = lifecycleStateMachine.transition(LoanEvent.LOAN_CREATED, from);
final LoanStatus statusEnum = lifecycleStateMachine.transition(LoanEvent.LOAN_CREATED, from);
this.loanStatus = statusEnum.getValue();
this.externalId = externalId;
@@ -1105,11 +1093,11 @@ public class Loan extends AbstractPersistable<Long> {
throw new InvalidLoanStateTransitionException("submittal", "cannot.be.a.future.date", errorMessage, submittedOn);
}
if (client != null && client.isActivatedAfter(submittedOn)) {
if (this.client != null && this.client.isActivatedAfter(submittedOn)) {
final String errorMessage = "The date on which a loan is submitted cannot be earlier than client's activation date.";
throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.client.activation.date", errorMessage, submittedOn);
}
if (group != null && group.isActivatedAfter(submittedOn)) {
if (this.group != null && this.group.isActivatedAfter(submittedOn)) {
final String errorMessage = "The date on which a loan is submitted cannot be earlier than groups's activation date.";
throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.group.activation.date", errorMessage, submittedOn);
}
@@ -1122,7 +1110,7 @@ public class Loan extends AbstractPersistable<Long> {
}
// charges are optional
for (LoanCharge loanCharge : setOfLoanCharges()) {
for (final LoanCharge loanCharge : setOfLoanCharges()) {
validateChargeHasValidSpecifiedDateIfApplicable(loanCharge, getDisbursementDate(), getLastRepaymentPeriodDueDate());
}
@@ -1132,7 +1120,7 @@ public class Loan extends AbstractPersistable<Long> {
}
private LocalDate determineExpectedMaturityDate() {
int numberOfInstallments = this.repaymentScheduleInstallments.size();
final int numberOfInstallments = this.repaymentScheduleInstallments.size();
return this.repaymentScheduleInstallments.get(numberOfInstallments - 1).getDueDate();
}
@@ -1146,7 +1134,7 @@ public class Loan extends AbstractPersistable<Long> {
this.loanStatus = statusEnum.getValue();
actualChanges.put("status", LoanEnumerations.status(this.loanStatus));
LocalDate rejectedOn = command.localDateValueOfParameterNamed("rejectedOnDate");
final LocalDate rejectedOn = command.localDateValueOfParameterNamed("rejectedOnDate");
final Locale locale = new Locale(command.locale());
final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
@@ -1294,9 +1282,9 @@ public class Loan extends AbstractPersistable<Long> {
private Collection<Long> findExistingTransactionIds() {
Collection<Long> ids = new ArrayList<Long>();
final Collection<Long> ids = new ArrayList<Long>();
for (LoanTransaction transaction : this.loanTransactions) {
for (final LoanTransaction transaction : this.loanTransactions) {
ids.add(transaction.getId());
}
@@ -1307,7 +1295,7 @@ public class Loan extends AbstractPersistable<Long> {
final Collection<Long> ids = new ArrayList<Long>();
for (LoanTransaction transaction : this.loanTransactions) {
for (final LoanTransaction transaction : this.loanTransactions) {
if (transaction.isReversed()) {
ids.add(transaction.getId());
}
@@ -1324,7 +1312,7 @@ public class Loan extends AbstractPersistable<Long> {
updateLoanToPreDisbursalState();
final LoanStatus statusEnum = loanLifecycleStateMachine.transition(LoanEvent.LOAN_DISBURSED, LoanStatus.fromInt(this.loanStatus));
final LoanStatus statusEnum = this.loanLifecycleStateMachine.transition(LoanEvent.LOAN_DISBURSED, LoanStatus.fromInt(this.loanStatus));
if (!statusEnum.hasStateOf(LoanStatus.fromInt(this.loanStatus))) {
existingTransactionIds.addAll(findExistingTransactionIds());
@@ -1358,7 +1346,7 @@ public class Loan extends AbstractPersistable<Long> {
updateLoanSummaryDerivedFields();
}
Money interestApplied = Money.of(this.getCurrency(), this.summary.getTotalInterestCharged());
final Money interestApplied = Money.of(getCurrency(), this.summary.getTotalInterestCharged());
final LoanTransaction interestAppliedTransaction = LoanTransaction.applyInterest(this, interestApplied, actualDisbursementDate);
this.loanTransactions.add(interestAppliedTransaction);
}
@@ -1368,8 +1356,8 @@ public class Loan extends AbstractPersistable<Long> {
private void updateLoanRepaymentPeriodsDerivedFields(final LocalDate actualDisbursementDate) {
for (LoanRepaymentScheduleInstallment repaymentPeriod : this.repaymentScheduleInstallments) {
repaymentPeriod.updateDerivedFields(this.loanCurrency(), actualDisbursementDate);
for (final LoanRepaymentScheduleInstallment repaymentPeriod : this.repaymentScheduleInstallments) {
repaymentPeriod.updateDerivedFields(loanCurrency(), actualDisbursementDate);
}
}
@@ -1389,11 +1377,11 @@ public class Loan extends AbstractPersistable<Long> {
final Integer loanTermFrequency = this.termFrequency;
final PeriodFrequencyType loanTermPeriodFrequencyType = PeriodFrequencyType.fromInt(this.termPeriodFrequencyType);
LoanApplicationTerms loanApplicationTerms = LoanApplicationTerms.assembleFrom(applicationCurrency, loanTermFrequency,
final LoanApplicationTerms loanApplicationTerms = LoanApplicationTerms.assembleFrom(applicationCurrency, loanTermFrequency,
loanTermPeriodFrequencyType, getDisbursementDate(), getExpectedFirstRepaymentOnDate(), calculatedRepaymentsStartingFromDate, getInArrearsTolerance(),
this.loanRepaymentScheduleDetail);
LoanScheduleModel loanSchedule = loanScheduleGenerator.generate(mc, applicationCurrency, loanApplicationTerms, this.charges, isHolidayEnabled, holidays, workingDays);
final LoanScheduleModel loanSchedule = loanScheduleGenerator.generate(mc, applicationCurrency, loanApplicationTerms, this.charges, isHolidayEnabled, holidays, workingDays);
updateLoanSchedule(loanSchedule);
}
@@ -1415,8 +1403,8 @@ public class Loan extends AbstractPersistable<Long> {
final Money totalFeeChargesDueAtDisbursement = this.summary.getTotalFeeChargesDueAtDisbursement(loanCurrency());
if (totalFeeChargesDueAtDisbursement.isGreaterThanZero()) {
LoanTransaction chargesPayment = LoanTransaction.repaymentAtDisbursement(totalFeeChargesDueAtDisbursement, null, disbursedOn, txnExternalId);
Money zero = Money.zero(getCurrency());
final LoanTransaction chargesPayment = LoanTransaction.repaymentAtDisbursement(totalFeeChargesDueAtDisbursement, null, disbursedOn, txnExternalId);
final Money zero = Money.zero(getCurrency());
chargesPayment.updateComponents(zero, zero, totalFeeChargesDueAtDisbursement, zero);
chargesPayment.updateLoan(this);
this.loanTransactions.add(chargesPayment);
@@ -1426,11 +1414,11 @@ public class Loan extends AbstractPersistable<Long> {
* "APPLY Charge" transactions are created for all other fees (
* which are created during disbursal but not repaid)
**/
for (LoanCharge charge : setOfLoanCharges()) {
for (final LoanCharge charge : setOfLoanCharges()) {
if (charge.isDueAtDisbursement()) {
charge.markAsFullyPaid();
// Add "Loan Charge Paid By" details to this transaction
LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(chargesPayment, charge, charge.amount());
final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(chargesPayment, charge, charge.amount());
chargesPayment.getLoanChargesPaid().add(loanChargePaidBy);
} else {
handleChargeAppliedTransaction(charge, disbursedOn);
@@ -1481,7 +1469,7 @@ public class Loan extends AbstractPersistable<Long> {
private final void reverseExistingTransactions() {
for (LoanTransaction transaction : this.loanTransactions) {
for (final LoanTransaction transaction : this.loanTransactions) {
transaction.reverse();
}
}
@@ -1489,15 +1477,15 @@ public class Loan extends AbstractPersistable<Long> {
private void updateLoanToPreDisbursalState() {
this.actualDisbursementDate = null;
for (LoanCharge charge : setOfLoanCharges()) {
for (final LoanCharge charge : setOfLoanCharges()) {
charge.resetToOriginal(loanCurrency());
}
for (LoanRepaymentScheduleInstallment currentInstallment : this.repaymentScheduleInstallments) {
for (final LoanRepaymentScheduleInstallment currentInstallment : this.repaymentScheduleInstallments) {
currentInstallment.resetDerivedComponents();
}
LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper();
final LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper();
wrapper.reprocess(getCurrency(), getDisbursementDate(), this.repaymentScheduleInstallments, setOfLoanCharges());
updateLoanSummaryDerivedFields();
@@ -1510,7 +1498,7 @@ public class Loan extends AbstractPersistable<Long> {
existingTransactionIds.addAll(findExistingTransactionIds());
existingReversedTransactionIds.addAll(findExistingReversedTransactionIds());
ChangedTransactionDetail changedTransactionDetail = handleRepaymentOrWaiverTransaction(waiveInterestTransaction,
final ChangedTransactionDetail changedTransactionDetail = handleRepaymentOrWaiverTransaction(waiveInterestTransaction,
loanLifecycleStateMachine, null);
return changedTransactionDetail;
@@ -1527,7 +1515,7 @@ public class Loan extends AbstractPersistable<Long> {
existingTransactionIds.addAll(findExistingTransactionIds());
existingReversedTransactionIds.addAll(findExistingReversedTransactionIds());
ChangedTransactionDetail changedTransactionDetail = handleRepaymentOrWaiverTransaction(repaymentTransaction,
final ChangedTransactionDetail changedTransactionDetail = handleRepaymentOrWaiverTransaction(repaymentTransaction,
loanLifecycleStateMachine, null);
return changedTransactionDetail;
@@ -1544,7 +1532,7 @@ public class Loan extends AbstractPersistable<Long> {
loanTransaction.updateLoan(this);
boolean isTransactionChronologicallyLatest = isChronologicallyLatestRepaymentOrWaiver(loanTransaction, this.loanTransactions);
final boolean isTransactionChronologicallyLatest = isChronologicallyLatestRepaymentOrWaiver(loanTransaction, this.loanTransactions);
if (loanTransaction.isNotZero(loanCurrency())) {
this.loanTransactions.add(loanTransaction);
@@ -1555,12 +1543,12 @@ public class Loan extends AbstractPersistable<Long> {
throw new InvalidLoanTransactionTypeException("transaction", "is.not.a.repayment.or.waiver.transaction", errorMessage);
}
LocalDate loanTransactionDate = loanTransaction.getTransactionDate();
if (loanTransactionDate.isBefore(this.getDisbursementDate())) {
final LocalDate loanTransactionDate = loanTransaction.getTransactionDate();
if (loanTransactionDate.isBefore(getDisbursementDate())) {
final String errorMessage = "The transaction date cannot be before the loan disbursement date: "
+ getApprovedOnDate().toString();
throw new InvalidLoanStateTransitionException("transaction", "cannot.be.before.disbursement.date", errorMessage,
loanTransactionDate, this.getDisbursementDate());
loanTransactionDate, getDisbursementDate());
}
if (loanTransactionDate.isAfter(DateUtils.getLocalDateOfTenant())) {
@@ -1589,7 +1577,7 @@ public class Loan extends AbstractPersistable<Long> {
final List<LoanTransaction> allNonContraTransactionsPostDisbursement = retreiveListOfTransactionsPostDisbursement();
changedTransactionDetail = loanRepaymentScheduleTransactionProcessor.handleTransaction(getDisbursementDate(),
allNonContraTransactionsPostDisbursement, getCurrency(), this.repaymentScheduleInstallments, setOfLoanCharges());
for (LoanTransaction newLoanTransaction : changedTransactionDetail.getNewTransactions()) {
for (final LoanTransaction newLoanTransaction : changedTransactionDetail.getNewTransactions()) {
newLoanTransaction.updateLoan(this);
}
this.loanTransactions.addAll(changedTransactionDetail.getNewTransactions());
@@ -1603,20 +1591,20 @@ public class Loan extends AbstractPersistable<Long> {
}
private List<LoanTransaction> retreiveListOfTransactionsPostDisbursement() {
List<LoanTransaction> repaymentsOrWaivers = new ArrayList<LoanTransaction>();
for (LoanTransaction transaction : this.loanTransactions) {
final List<LoanTransaction> repaymentsOrWaivers = new ArrayList<LoanTransaction>();
for (final LoanTransaction transaction : this.loanTransactions) {
if (!transaction.isDisbursement() && transaction.isNotReversed()) {
repaymentsOrWaivers.add(transaction);
}
}
LoanTransactionComparator transactionComparator = new LoanTransactionComparator();
final LoanTransactionComparator transactionComparator = new LoanTransactionComparator();
Collections.sort(repaymentsOrWaivers, transactionComparator);
return repaymentsOrWaivers;
}
private void doPostLoanTransactionChecks(final LocalDate transactionDate, final LoanLifecycleStateMachine loanLifecycleStateMachine) {
if (this.isOverPaid()) {
if (isOverPaid()) {
// FIXME - kw - update account balance to negative amount.
handleLoanOverpayment(loanLifecycleStateMachine);
} else if (this.summary.isRepaidInFull(loanCurrency())) {
@@ -1626,7 +1614,7 @@ public class Loan extends AbstractPersistable<Long> {
private void handleLoanRepaymentInFull(final LocalDate transactionDate, final LoanLifecycleStateMachine loanLifecycleStateMachine) {
LoanStatus statusEnum = loanLifecycleStateMachine.transition(LoanEvent.REPAID_IN_FULL, LoanStatus.fromInt(this.loanStatus));
final LoanStatus statusEnum = loanLifecycleStateMachine.transition(LoanEvent.REPAID_IN_FULL, LoanStatus.fromInt(this.loanStatus));
this.loanStatus = statusEnum.getValue();
this.closedOnDate = transactionDate.toDate();
@@ -1635,7 +1623,7 @@ public class Loan extends AbstractPersistable<Long> {
private void handleLoanOverpayment(final LoanLifecycleStateMachine loanLifecycleStateMachine) {
LoanStatus statusEnum = loanLifecycleStateMachine.transition(LoanEvent.LOAN_OVERPAYMENT, LoanStatus.fromInt(this.loanStatus));
final LoanStatus statusEnum = loanLifecycleStateMachine.transition(LoanEvent.LOAN_OVERPAYMENT, LoanStatus.fromInt(this.loanStatus));
this.loanStatus = statusEnum.getValue();
this.closedOnDate = null;
@@ -1647,8 +1635,8 @@ public class Loan extends AbstractPersistable<Long> {
boolean isChronologicallyLatestRepaymentOrWaiver = true;
LocalDate currentTransactionDate = loanTransaction.getTransactionDate();
for (LoanTransaction previousTransaction : loanTransactions) {
final LocalDate currentTransactionDate = loanTransaction.getTransactionDate();
for (final LoanTransaction previousTransaction : loanTransactions) {
if (!previousTransaction.isDisbursement() && previousTransaction.isNotReversed()) {
if (currentTransactionDate.isBefore(previousTransaction.getTransactionDate())
|| currentTransactionDate.isEqual(previousTransaction.getTransactionDate())) {
@@ -1665,8 +1653,8 @@ public class Loan extends AbstractPersistable<Long> {
boolean isChronologicallyLatestRepaymentOrWaiver = true;
LocalDate currentTransactionDate = loanTransaction.getTransactionDate();
for (LoanTransaction previousTransaction : loanTransactions) {
final LocalDate currentTransactionDate = loanTransaction.getTransactionDate();
for (final LoanTransaction previousTransaction : loanTransactions) {
if (previousTransaction.isNotReversed()) {
if (currentTransactionDate.isBefore(previousTransaction.getTransactionDate())
|| currentTransactionDate.isEqual(previousTransaction.getTransactionDate())) {
@@ -1681,7 +1669,7 @@ public class Loan extends AbstractPersistable<Long> {
public LocalDate possibleNextRepaymentDate() {
LocalDate earliestUnpaidInstallmentDate = new LocalDate();
for (LoanRepaymentScheduleInstallment installment : this.repaymentScheduleInstallments) {
for (final LoanRepaymentScheduleInstallment installment : this.repaymentScheduleInstallments) {
if (installment.isNotFullyPaidOff()) {
earliestUnpaidInstallmentDate = installment.getDueDate();
break;
@@ -1689,7 +1677,7 @@ public class Loan extends AbstractPersistable<Long> {
}
LocalDate lastTransactionDate = null;
for (LoanTransaction transaction : this.loanTransactions) {
for (final LoanTransaction transaction : this.loanTransactions) {
if (transaction.isRepayment() && transaction.isNonZero()) {
lastTransactionDate = transaction.getTransactionDate();
}
@@ -1704,10 +1692,10 @@ public class Loan extends AbstractPersistable<Long> {
}
public Money possibleNextRepaymentAmount() {
MonetaryCurrency currency = this.loanRepaymentScheduleDetail.getPrincipal().getCurrency();
final MonetaryCurrency currency = this.loanRepaymentScheduleDetail.getPrincipal().getCurrency();
Money possibleNextRepaymentAmount = Money.zero(currency);
for (LoanRepaymentScheduleInstallment installment : this.repaymentScheduleInstallments) {
for (final LoanRepaymentScheduleInstallment installment : this.repaymentScheduleInstallments) {
if (installment.isNotFullyPaidOff()) {
possibleNextRepaymentAmount = installment.getTotalOutstanding(currency);
break;
@@ -1726,7 +1714,7 @@ public class Loan extends AbstractPersistable<Long> {
if (totalInterestOutstanding.isGreaterThanZero()) {
// find earliest known instance of overdue interest and default to
// that
for (LoanRepaymentScheduleInstallment scheduledRepayment : this.repaymentScheduleInstallments) {
for (final LoanRepaymentScheduleInstallment scheduledRepayment : this.repaymentScheduleInstallments) {
final Money outstandingForPeriod = scheduledRepayment.getInterestOutstanding(loanCurrency());
if (scheduledRepayment.isOverdueOn(new LocalDate()) && scheduledRepayment.isNotFullyPaidOff()
@@ -1765,7 +1753,7 @@ public class Loan extends AbstractPersistable<Long> {
if (isClosedWrittenOff()) {
// find write off transaction and reverse it
LoanTransaction writeOffTransaction = findWriteOffTransaction();
final LoanTransaction writeOffTransaction = findWriteOffTransaction();
writeOffTransaction.reverse();
}
@@ -1784,7 +1772,7 @@ public class Loan extends AbstractPersistable<Long> {
private LoanTransaction findWriteOffTransaction() {
LoanTransaction writeOff = null;
for (LoanTransaction transaction : this.loanTransactions) {
for (final LoanTransaction transaction : this.loanTransactions) {
if (!transaction.isReversed() && transaction.isWriteOff()) {
writeOff = transaction;
}
@@ -1805,7 +1793,7 @@ public class Loan extends AbstractPersistable<Long> {
Money cumulativeTotalPaidOnInstallments = Money.zero(currency);
Money cumulativeTotalWaivedOnInstallments = Money.zero(currency);
for (LoanRepaymentScheduleInstallment scheduledRepayment : this.repaymentScheduleInstallments) {
for (final LoanRepaymentScheduleInstallment scheduledRepayment : this.repaymentScheduleInstallments) {
cumulativeTotalPaidOnInstallments = cumulativeTotalPaidOnInstallments
.plus(scheduledRepayment.getPrincipalCompleted(currency).plus(scheduledRepayment.getInterestPaid(currency)))
@@ -1847,7 +1835,7 @@ public class Loan extends AbstractPersistable<Long> {
changes.put("closedOnDate", command.stringValueOfParameterNamed("transactionDate"));
changes.put("writtenOffOnDate", command.stringValueOfParameterNamed("transactionDate"));
if (writtenOffOnLocalDate.isBefore(this.getDisbursementDate())) {
if (writtenOffOnLocalDate.isBefore(getDisbursementDate())) {
final String errorMessage = "The date on which a loan is written off cannot be before the loan disbursement date: "
+ getDisbursementDate().toString();
throw new InvalidLoanStateTransitionException("writeoff", "cannot.be.before.submittal.date", errorMessage,
@@ -1860,7 +1848,7 @@ public class Loan extends AbstractPersistable<Long> {
}
loanTransaction = LoanTransaction.writeoff(this, writtenOffOnLocalDate, txnExternalId);
final boolean isLastTransaction = isChronologicallyLatestTransaction(loanTransaction, loanTransactions);
final boolean isLastTransaction = isChronologicallyLatestTransaction(loanTransaction, this.loanTransactions);
if (!isLastTransaction) {
final String errorMessage = "The date of the writeoff transaction must occur on or before previous transactions.";
throw new InvalidLoanStateTransitionException("writeoff", "must.occur.on.or.after.other.transaction.dates", errorMessage,
@@ -1891,7 +1879,7 @@ public class Loan extends AbstractPersistable<Long> {
this.closedOnDate = closureDate.toDate();
changes.put("closedOnDate", command.stringValueOfParameterNamed("transactionDate"));
if (closureDate.isBefore(this.getDisbursementDate())) {
if (closureDate.isBefore(getDisbursementDate())) {
final String errorMessage = "The date on which a loan is closed cannot be before the loan disbursement date: "
+ getDisbursementDate().toString();
throw new InvalidLoanStateTransitionException("close", "cannot.be.before.submittal.date", errorMessage, closureDate,
@@ -1917,7 +1905,7 @@ public class Loan extends AbstractPersistable<Long> {
this.closedOnDate = closureDate.toDate();
loanTransaction = LoanTransaction.writeoff(this, closureDate, txnExternalId);
boolean isLastTransaction = isChronologicallyLatestTransaction(loanTransaction, loanTransactions);
final boolean isLastTransaction = isChronologicallyLatestTransaction(loanTransaction, this.loanTransactions);
if (!isLastTransaction) {
final String errorMessage = "The closing date of the loan must be on or after latest transaction date.";
throw new InvalidLoanStateTransitionException("close.loan", "must.occur.on.or.after.latest.transaction.date",
@@ -1981,8 +1969,8 @@ public class Loan extends AbstractPersistable<Long> {
changes.put("closedOnDate", command.stringValueOfParameterNamed("transactionDate"));
changes.put("rescheduledOnDate", command.stringValueOfParameterNamed("transactionDate"));
LocalDate rescheduledOnLocalDate = new LocalDate(rescheduledOnDate);
if (rescheduledOnLocalDate.isBefore(this.getDisbursementDate())) {
final LocalDate rescheduledOnLocalDate = new LocalDate(this.rescheduledOnDate);
if (rescheduledOnLocalDate.isBefore(getDisbursementDate())) {
final String errorMessage = "The date on which a loan is rescheduled cannot be before the loan disbursement date: "
+ getDisbursementDate().toString();
throw new InvalidLoanStateTransitionException("close.reschedule", "cannot.be.before.submittal.date", errorMessage,
@@ -2009,7 +1997,7 @@ public class Loan extends AbstractPersistable<Long> {
}
private boolean isNotDisbursed() {
return !this.isDisbursed();
return !isDisbursed();
}
private boolean isDisbursed() {
@@ -2017,7 +2005,7 @@ public class Loan extends AbstractPersistable<Long> {
}
private boolean isClosed() {
return status().isClosed() || this.isCancelled();
return status().isClosed() || isCancelled();
}
private boolean isClosedObligationsMet() {
@@ -2033,7 +2021,7 @@ public class Loan extends AbstractPersistable<Long> {
}
private boolean isCancelled() {
return this.isRejected() || this.isWithdrawn();
return isRejected() || isWithdrawn();
}
private boolean isWithdrawn() {
@@ -2050,7 +2038,7 @@ public class Loan extends AbstractPersistable<Long> {
private boolean hasDisbursementTransaction() {
boolean hasRepaymentTransaction = false;
for (LoanTransaction loanTransaction : this.loanTransactions) {
for (final LoanTransaction loanTransaction : this.loanTransactions) {
if (loanTransaction.isDisbursement() && loanTransaction.isNotReversed()) {
hasRepaymentTransaction = true;
break;
@@ -2060,7 +2048,7 @@ public class Loan extends AbstractPersistable<Long> {
}
public boolean isSubmittedOnDateAfter(final LocalDate compareDate) {
return this.submittedOnDate == null ? false : (new LocalDate(submittedOnDate)).isAfter(compareDate);
return this.submittedOnDate == null ? false : new LocalDate(this.submittedOnDate).isAfter(compareDate);
}
public LocalDate getSubmittedOnDate() {
@@ -2115,7 +2103,7 @@ public class Loan extends AbstractPersistable<Long> {
private Money getTotalPaidInRepayments() {
Money cumulativePaid = Money.zero(loanCurrency());
for (LoanTransaction repayment : this.loanTransactions) {
for (final LoanTransaction repayment : this.loanTransactions) {
if (repayment.isRepayment()) {
cumulativePaid = cumulativePaid.plus(repayment.getAmount(loanCurrency()));
}
@@ -2127,7 +2115,7 @@ public class Loan extends AbstractPersistable<Long> {
private Money getTotalInterestOutstandingOnLoan() {
Money cumulativeInterest = Money.zero(loanCurrency());
for (LoanRepaymentScheduleInstallment scheduledRepayment : this.repaymentScheduleInstallments) {
for (final LoanRepaymentScheduleInstallment scheduledRepayment : this.repaymentScheduleInstallments) {
cumulativeInterest = cumulativeInterest.plus(scheduledRepayment.getInterestOutstanding(loanCurrency()));
}
@@ -2138,7 +2126,7 @@ public class Loan extends AbstractPersistable<Long> {
private Money getTotalInterestOverdueOnLoan() {
Money cumulativeInterestOverdue = Money.zero(this.loanRepaymentScheduleDetail.getPrincipal().getCurrency());
for (LoanRepaymentScheduleInstallment scheduledRepayment : this.repaymentScheduleInstallments) {
for (final LoanRepaymentScheduleInstallment scheduledRepayment : this.repaymentScheduleInstallments) {
final Money interestOutstandingForPeriod = scheduledRepayment.getInterestOutstanding(loanCurrency());
if (scheduledRepayment.isOverdueOn(new LocalDate())) {
@@ -2154,7 +2142,7 @@ public class Loan extends AbstractPersistable<Long> {
}
public boolean hasIdentifyOf(final Long loanId) {
return loanId.equals(this.getId());
return loanId.equals(getId());
}
public boolean hasLoanOfficer(final Staff fromLoanOfficer) {
@@ -2199,7 +2187,7 @@ public class Loan extends AbstractPersistable<Long> {
final LoanOfficerAssignmentHistory lastAssignmentRecord = findLastAssignmentHistoryRecord(newLoanOfficer);
// assignment date should not be less than loan submitted date
if (this.isSubmittedOnDateAfter(assignmentDate)) {
if (isSubmittedOnDateAfter(assignmentDate)) {
final String errorMessage = "The Loan Officer assignment date (" + assignmentDate.toString()
+ ") cannot be before loan submitted date (" + getSubmittedOnDate().toString() + ").";
@@ -2227,8 +2215,8 @@ public class Loan extends AbstractPersistable<Long> {
latestHistoryRecord.updateLoanOfficer(newLoanOfficer);
this.loanOfficer = newLoanOfficer;
} else if (latestHistoryRecord != null && latestHistoryRecord.hasStartDateBefore(assignmentDate)) {
final String errorMessage = "Loan with identifier " + this.getId() + " was already assigned before date " + assignmentDate;
throw new LoanOfficerAssignmentDateException("is.before.last.assignment.date", errorMessage, this.getId(), assignmentDate);
final String errorMessage = "Loan with identifier " + getId() + " was already assigned before date " + assignmentDate;
throw new LoanOfficerAssignmentDateException("is.before.last.assignment.date", errorMessage, getId(), assignmentDate);
} else {
if (latestHistoryRecord != null) {
// loan officer correctly changed from previous loan officer to
@@ -2237,7 +2225,7 @@ public class Loan extends AbstractPersistable<Long> {
}
this.loanOfficer = newLoanOfficer;
if (this.isNotSubmittedAndPendingApproval()) {
if (isNotSubmittedAndPendingApproval()) {
final LoanOfficerAssignmentHistory loanOfficerAssignmentHistory = LoanOfficerAssignmentHistory.createNew(this,
this.loanOfficer, assignmentDate);
this.loanOfficerHistory.add(loanOfficerAssignmentHistory);
@@ -2266,8 +2254,7 @@ public class Loan extends AbstractPersistable<Long> {
final String errorMessage = "The Loan officer Unassign date(" + unassignDate + ") cannot be before its assignment date ("
+ latestHistoryRecord.getStartDate() + ").";
throw new LoanOfficerUnassignmentDateException("cannot.be.before.assignment.date", errorMessage, this.getId(), this
.getLoanOfficer().getId(), latestHistoryRecord.getStartDate(), unassignDate);
throw new LoanOfficerUnassignmentDateException("cannot.be.before.assignment.date", errorMessage, getId(), getLoanOfficer().getId(), latestHistoryRecord.getStartDate(), unassignDate);
} else if (unassignDate.isAfter(today)) {
@@ -2280,7 +2267,7 @@ public class Loan extends AbstractPersistable<Long> {
private LoanOfficerAssignmentHistory findLatestIncompleteHistoryRecord() {
LoanOfficerAssignmentHistory latestRecordWithNoEndDate = null;
for (LoanOfficerAssignmentHistory historyRecord : this.loanOfficerHistory) {
for (final LoanOfficerAssignmentHistory historyRecord : this.loanOfficerHistory) {
if (historyRecord.isCurrentRecord()) {
latestRecordWithNoEndDate = historyRecord;
break;
@@ -2292,7 +2279,7 @@ public class Loan extends AbstractPersistable<Long> {
private LoanOfficerAssignmentHistory findLastAssignmentHistoryRecord(final Staff newLoanOfficer) {
LoanOfficerAssignmentHistory lastAssignmentRecordLatestEndDate = null;
for (LoanOfficerAssignmentHistory historyRecord : this.loanOfficerHistory) {
for (final LoanOfficerAssignmentHistory historyRecord : this.loanOfficerHistory) {
if (historyRecord.isCurrentRecord() && !historyRecord.isSameLoanOfficer(newLoanOfficer)) {
lastAssignmentRecordLatestEndDate = historyRecord;
@@ -2363,15 +2350,15 @@ public class Loan extends AbstractPersistable<Long> {
final List<Long> existingReversedTransactionIds) {
final Map<String, Object> accountingBridgeData = new LinkedHashMap<String, Object>();
accountingBridgeData.put("loanId", this.getId());
accountingBridgeData.put("loanProductId", this.productId());
accountingBridgeData.put("officeId", this.getOfficeId());
accountingBridgeData.put("loanId", getId());
accountingBridgeData.put("loanProductId", productId());
accountingBridgeData.put("officeId", getOfficeId());
accountingBridgeData.put("calculatedInterest", this.summary.getTotalInterestCharged());
accountingBridgeData.put("cashBasedAccountingEnabled", this.isCashBasedAccountingEnabledOnLoanProduct());
accountingBridgeData.put("accrualBasedAccountingEnabled", this.isAccrualBasedAccountingEnabledOnLoanProduct());
accountingBridgeData.put("cashBasedAccountingEnabled", isCashBasedAccountingEnabledOnLoanProduct());
accountingBridgeData.put("accrualBasedAccountingEnabled", isAccrualBasedAccountingEnabledOnLoanProduct());
final List<Map<String, Object>> newLoanTransactions = new ArrayList<Map<String, Object>>();
for (LoanTransaction transaction : this.loanTransactions) {
for (final LoanTransaction transaction : this.loanTransactions) {
if (transaction.isReversed() && !existingReversedTransactionIds.contains(transaction.getId())) {
newLoanTransactions.add(transaction.toMapData(currencyData));
} else if (!existingTransactionIds.contains(transaction.getId())) {
@@ -2401,9 +2388,9 @@ public class Loan extends AbstractPersistable<Long> {
public void updateLoanRepaymentScheduleDates(final LocalDate meetingStartDate, final String recuringRule,
final boolean isHolidayEnabled, final List<Holiday> holidays, final WorkingDays workingDays) {
//update repayment dates of repayment schedule installaments
LocalDate tmpFromDate = this.getDisbursementDate();//first repayment's from date is same as disbursement date.
LocalDate tmpFromDate = getDisbursementDate();//first repayment's from date is same as disbursement date.
LocalDate newRepaymentDate = null;
for (LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : this.repaymentScheduleInstallments) {
for (final LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : this.repaymentScheduleInstallments) {
final LocalDate oldDueDate = loanRepaymentScheduleInstallment.getDueDate();
// FIXME: AA this won't update repayment dates before current date.
if (oldDueDate.isAfter(meetingStartDate) && oldDueDate.isAfter(DateUtils.getLocalDateOfTenant())) {
@@ -2430,9 +2417,9 @@ public class Loan extends AbstractPersistable<Long> {
public void applyHolidayToRepaymentScheduleDates(final Holiday holiday) {
// first repayment's from date is same as disbursement date.
LocalDate tmpFromDate = this.getDisbursementDate();
LocalDate tmpFromDate = getDisbursementDate();
// Loop through all loanRepayments
for (LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : this.repaymentScheduleInstallments) {
for (final LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : this.repaymentScheduleInstallments) {
final LocalDate oldDueDate = loanRepaymentScheduleInstallment.getDueDate();
// update from date if it's not same as previous installament's due
@@ -2440,10 +2427,12 @@ public class Loan extends AbstractPersistable<Long> {
if (!loanRepaymentScheduleInstallment.getFromDate().isEqual(tmpFromDate)) {
loanRepaymentScheduleInstallment.updateFromDate(tmpFromDate);
}
if (oldDueDate.isAfter(holiday.getToDateLocalDate())) break;
if (oldDueDate.isAfter(holiday.getToDateLocalDate())) {
break;
}
if (oldDueDate.equals(holiday.getFromDateLocalDate()) || oldDueDate.equals(holiday.getToDateLocalDate())
|| (oldDueDate.isAfter(holiday.getFromDateLocalDate()) && oldDueDate.isBefore(holiday.getToDateLocalDate()))) {
|| oldDueDate.isAfter(holiday.getFromDateLocalDate()) && oldDueDate.isBefore(holiday.getToDateLocalDate())) {
//FIXME: AA do we need to apply non-working days.
//Assuming holiday's repayment reschedule to date cannot be created on a non-working day.
final LocalDate newRepaymentDate = holiday.getRepaymentsRescheduledToLocalDate();
@@ -25,7 +25,6 @@ import org.mifosplatform.useradministration.domain.AppUser;
@Table(name = "m_loan_officer_assignment_history")
public class LoanOfficerAssignmentHistory extends AbstractAuditableCustom<AppUser, Long> {
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "loan_id", nullable = false)
private Loan loan;
@@ -74,7 +73,7 @@ public class LoanOfficerAssignmentHistory extends AbstractAuditableCustom<AppUse
}
public LocalDate getStartDate() {
return new LocalDate(startDate);
return new LocalDate(this.startDate);
}
public boolean hasStartDateBefore(final LocalDate matchingDate) {
@@ -91,7 +90,7 @@ public class LoanOfficerAssignmentHistory extends AbstractAuditableCustom<AppUse
* @return
*/
public boolean isEndDateAfter(final LocalDate compareDate){
return this.endDate == null ? false : (new LocalDate(endDate)).isAfter(compareDate);
return this.endDate == null ? false : new LocalDate(this.endDate).isAfter(compareDate);
}
public LocalDate getEndDate(){
@@ -95,7 +95,6 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus
@Column(name = "completed_derived", nullable = false)
private boolean obligationsMet;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "obligations_met_on_date")
private Date obligationsMetOnDate;
@@ -376,10 +375,10 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus
}
public Money waiveInterestComponent(final LocalDate transactionDate, final Money transactionAmountRemaining) {
MonetaryCurrency currency = transactionAmountRemaining.getCurrency();
final MonetaryCurrency currency = transactionAmountRemaining.getCurrency();
Money waivedInterestPortionOfTransaction = Money.zero(currency);
Money interestDue = getInterestOutstanding(currency);
final Money interestDue = getInterestOutstanding(currency);
if (transactionAmountRemaining.isGreaterThanOrEqualTo(interestDue)) {
this.interestWaived = getInterestWaived(currency).plus(interestDue).getAmount();
waivedInterestPortionOfTransaction = waivedInterestPortionOfTransaction.plus(interestDue);
@@ -396,10 +395,10 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus
}
public Money waivePenaltyChargesComponent(final LocalDate transactionDate, final Money transactionAmountRemaining) {
MonetaryCurrency currency = transactionAmountRemaining.getCurrency();
final MonetaryCurrency currency = transactionAmountRemaining.getCurrency();
Money waivedPenaltyChargesPortionOfTransaction = Money.zero(currency);
Money penanltiesDue = getPenaltyChargesOutstanding(currency);
final Money penanltiesDue = getPenaltyChargesOutstanding(currency);
if (transactionAmountRemaining.isGreaterThanOrEqualTo(penanltiesDue)) {
this.penaltyChargesWaived = getPenaltyChargesWaived(currency).plus(penanltiesDue).getAmount();
waivedPenaltyChargesPortionOfTransaction = waivedPenaltyChargesPortionOfTransaction.plus(penanltiesDue);
@@ -416,10 +415,10 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus
}
public Money waiveFeeChargesComponent(final LocalDate transactionDate, final Money transactionAmountRemaining) {
MonetaryCurrency currency = transactionAmountRemaining.getCurrency();
final MonetaryCurrency currency = transactionAmountRemaining.getCurrency();
Money waivedFeeChargesPortionOfTransaction = Money.zero(currency);
Money feesDue = getPenaltyChargesOutstanding(currency);
final Money feesDue = getPenaltyChargesOutstanding(currency);
if (transactionAmountRemaining.isGreaterThanOrEqualTo(feesDue)) {
this.feeChargesWaived = getFeeChargesWaived(currency).plus(feesDue).getAmount();
waivedFeeChargesPortionOfTransaction = waivedFeeChargesPortionOfTransaction.plus(feesDue);
@@ -474,7 +473,7 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus
}
public boolean isOverdueOn(final LocalDate date) {
return this.getDueDate().isBefore(date);
return getDueDate().isBefore(date);
}
public void updateChargePortion(final Money feeChargesDue, final Money feeChargesWaived, final Money feeChargesWrittenOff,
@@ -84,27 +84,21 @@ public final class LoanSummary {
@Column(name = "penalty_charges_outstanding_derived", scale = 6, precision = 19)
private BigDecimal totalPenaltyChargesOutstanding;
@SuppressWarnings("unused")
@Column(name = "total_expected_repayment_derived", scale = 6, precision = 19)
private BigDecimal totalExpectedRepayment;
@SuppressWarnings("unused")
@Column(name = "total_repayment_derived", scale = 6, precision = 19)
private BigDecimal totalRepayment;
@SuppressWarnings("unused")
@Column(name = "total_expected_costofloan_derived", scale = 6, precision = 19)
private BigDecimal totalExpectedCostOfLoan;
@SuppressWarnings("unused")
@Column(name = "total_costofloan_derived", scale = 6, precision = 19)
private BigDecimal totalCostOfLoan;
@SuppressWarnings("unused")
@Column(name = "total_waived_derived", scale = 6, precision = 19)
private BigDecimal totalWaived;
@SuppressWarnings("unused")
@Column(name = "total_writtenoff_derived", scale = 6, precision = 19)
private BigDecimal totalWrittenOff;
@@ -185,7 +179,7 @@ public final class LoanSummary {
this.totalPrincipalWrittenOff = summaryWrapper.calculateTotalPrincipalWrittenOff(repaymentScheduleInstallments, currency)
.getAmount();
this.totalPrincipalOutstanding = principal.minus(totalPrincipalRepaid).minus(totalPrincipalWrittenOff).getAmount();
this.totalPrincipalOutstanding = principal.minus(this.totalPrincipalRepaid).minus(this.totalPrincipalWrittenOff).getAmount();
final Money totalInterestCharged = summaryWrapper.calculateTotalInterestCharged(repaymentScheduleInstallments, currency);
this.totalInterestCharged = totalInterestCharged.getAmount();
@@ -63,12 +63,10 @@ public final class LoanSummaryArrearsAging implements Persistable<Long> {
@Column(name = "total_overdue_derived", scale = 6, precision = 19)
private BigDecimal totalOverdue;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "overdue_since_date_derived")
private Date overdueSinceDate;
@SuppressWarnings("unused")
@OneToOne(optional = false)
@PrimaryKeyJoinColumn
private Loan loan;
@@ -70,10 +70,9 @@ public class NotesApiResource {
public String retrieveNotesByResource(@PathParam("resourceType") final String resourceType,
@PathParam("resourceId") final Long resourceId, @Context final UriInfo uriInfo) {
NoteType noteType = NoteType.fromApiUrl(resourceType);
final NoteType noteType = NoteType.fromApiUrl(resourceType);
if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); }
;
this.context.authenticatedUser().validateHasReadPermission(getResourceNameForPermissions(noteType));
@@ -92,10 +91,9 @@ public class NotesApiResource {
public String retrieveNote(@PathParam("resourceType") final String resourceType, @PathParam("resourceId") final Long resourceId,
@PathParam("noteId") final Long noteId, @Context final UriInfo uriInfo) {
NoteType noteType = NoteType.fromApiUrl(resourceType);
final NoteType noteType = NoteType.fromApiUrl(resourceType);
if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); }
;
this.context.authenticatedUser().validateHasReadPermission(getResourceNameForPermissions(noteType));
@@ -113,10 +111,9 @@ public class NotesApiResource {
public String addNewNote(@PathParam("resourceType") final String resourceType, @PathParam("resourceId") final Long resourceId,
final String apiRequestBodyAsJson) {
NoteType noteType = NoteType.fromApiUrl(resourceType);
final NoteType noteType = NoteType.fromApiUrl(resourceType);
if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); }
;
final String resourceNameForPermissions = getResourceNameForPermissions(noteType);
final CommandWrapper commandRequest = new CommandWrapperBuilder().createNote(resourceNameForPermissions, resourceType, resourceId)
@@ -134,10 +131,9 @@ public class NotesApiResource {
public String updateNote(@PathParam("resourceType") final String resourceType, @PathParam("resourceId") final Long resourceId,
@PathParam("noteId") final Long noteId, final String apiRequestBodyAsJson) {
NoteType noteType = NoteType.fromApiUrl(resourceType);
final NoteType noteType = NoteType.fromApiUrl(resourceType);
if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); }
;
final String resourceNameForPermissions = getResourceNameForPermissions(noteType);
@@ -156,10 +152,9 @@ public class NotesApiResource {
public String deleteNote(@PathParam("resourceType") final String resourceType, @PathParam("resourceId") final Long resourceId,
@PathParam("noteId") final Long noteId) {
NoteType noteType = NoteType.fromApiUrl(resourceType);
final NoteType noteType = NoteType.fromApiUrl(resourceType);
if (noteType == null) { throw new NoteResourceNotSupportedException(resourceType); }
;
final String resourceNameForPermissions = getResourceNameForPermissions(noteType);
@@ -32,17 +32,14 @@ public class Note extends AbstractAuditableCustom<AppUser, Long> {
@JoinColumn(name = "client_id", nullable = true)
private final Client client;
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "group_id", nullable = true)
private Group group;
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "loan_id", nullable = true)
private Loan loan;
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "loan_transaction_id", nullable = true)
private LoanTransaction loanTransaction;
@@ -50,11 +47,9 @@ public class Note extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "note", length = 1000)
private String note;
@SuppressWarnings("unused")
@Column(name = "note_type_enum")
private final Integer noteTypeId;
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "savings_account_id", nullable = true)
private SavingsAccount savingsAccount;
@@ -106,7 +106,6 @@ public class SavingsAccount extends AbstractPersistable<Long> {
@Column(name = "status_enum", nullable = false)
private Integer status;
@SuppressWarnings("unused")
@Column(name = "account_type_enum", nullable = false)
private Integer accountType;
@@ -114,27 +113,22 @@ public class SavingsAccount extends AbstractPersistable<Long> {
@Column(name = "submittedon_date", nullable = true)
private Date submittedOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "submittedon_userid", nullable = true)
private AppUser submittedBy;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "rejectedon_date")
private Date rejectedOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "rejectedon_userid", nullable = true)
private AppUser rejectedBy;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "withdrawnon_date")
private Date withdrawnOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "withdrawnon_userid", nullable = true)
private AppUser withdrawnBy;
@@ -143,7 +137,6 @@ public class SavingsAccount extends AbstractPersistable<Long> {
@Column(name = "approvedon_date")
private Date approvedOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "approvedon_userid", nullable = true)
private AppUser approvedBy;
@@ -152,17 +145,14 @@ public class SavingsAccount extends AbstractPersistable<Long> {
@Column(name = "activatedon_date", nullable = true)
private Date activatedOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "activatedon_userid", nullable = true)
private AppUser activatedBy;
@SuppressWarnings("unused")
@Temporal(TemporalType.DATE)
@Column(name = "closedon_date")
private Date closedOnDate;
@SuppressWarnings("unused")
@ManyToOne(optional = true)
@JoinColumn(name = "closedon_userid", nullable = true)
private AppUser closedBy;
@@ -361,7 +351,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
existingTransactionIds.addAll(findExistingTransactionIds());
existingReversedTransactionIds.addAll(findExistingReversedTransactionIds());
for (PostingPeriod interestPostingPeriod : postingPeriods) {
for (final PostingPeriod interestPostingPeriod : postingPeriods) {
final LocalDate interestPostingTransactionDate = interestPostingPeriod.dateOfPostingTransaction();
final Money interestEarnedToBePostedForPeriod = interestPostingPeriod.getInterestEarned();
@@ -370,14 +360,14 @@ public class SavingsAccount extends AbstractPersistable<Long> {
interestPostedToDate = interestPostedToDate.plus(interestEarnedToBePostedForPeriod);
SavingsAccountTransaction postingTransaction = findInterestPostingTransactionFor(interestPostingTransactionDate);
final SavingsAccountTransaction postingTransaction = findInterestPostingTransactionFor(interestPostingTransactionDate);
if (postingTransaction == null) {
final SavingsAccountTransaction newPostingTransaction = SavingsAccountTransaction.interestPosting(this,
interestPostingTransactionDate, interestEarnedToBePostedForPeriod);
this.transactions.add(newPostingTransaction);
recalucateDailyBalanceDetails = true;
} else {
boolean correctionRequired = postingTransaction.hasNotAmount(interestEarnedToBePostedForPeriod);
final boolean correctionRequired = postingTransaction.hasNotAmount(interestEarnedToBePostedForPeriod);
if (correctionRequired) {
postingTransaction.reverse();
final SavingsAccountTransaction newPostingTransaction = SavingsAccountTransaction.interestPosting(this,
@@ -407,7 +397,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
SavingsAccountTransaction postingTransation = null;
for (SavingsAccountTransaction transaction : this.transactions) {
for (final SavingsAccountTransaction transaction : this.transactions) {
if (transaction.isInterestPostingAndNotReversed() && transaction.occursOn(postingDate)) {
postingTransation = transaction;
break;
@@ -454,19 +444,19 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final SavingsInterestCalculationDaysInYearType daysInYearType = SavingsInterestCalculationDaysInYearType
.fromInt(this.interestCalculationDaysInYearType);
List<LocalDateInterval> postingPeriodIntervals = savingsHelper.determineInterestPostingPeriods(getActivationLocalDate(),
final List<LocalDateInterval> postingPeriodIntervals = this.savingsHelper.determineInterestPostingPeriods(getActivationLocalDate(),
upToInterestCalculationDate, postingPeriodType);
List<PostingPeriod> allPostingPeriods = new ArrayList<PostingPeriod>();
final List<PostingPeriod> allPostingPeriods = new ArrayList<PostingPeriod>();
Money periodStartingBalance = Money.zero(this.currency);
final SavingsInterestCalculationType interestCalculationType = SavingsInterestCalculationType.fromInt(this.interestCalculationType);
BigDecimal interestRateAsFraction = nominalAnnualInterestRate.divide(BigDecimal.valueOf(100l), mc);
for (LocalDateInterval periodInterval : postingPeriodIntervals) {
final BigDecimal interestRateAsFraction = this.nominalAnnualInterestRate.divide(BigDecimal.valueOf(100l), mc);
for (final LocalDateInterval periodInterval : postingPeriodIntervals) {
PostingPeriod postingPeriod = PostingPeriod.createFrom(periodInterval, periodStartingBalance,
retreiveOrderedListOfTransactions(), currency, compoundingPeriodType, interestCalculationType, interestRateAsFraction,
final PostingPeriod postingPeriod = PostingPeriod.createFrom(periodInterval, periodStartingBalance,
retreiveOrderedListOfTransactions(), this.currency, compoundingPeriodType, interestCalculationType, interestRateAsFraction,
daysInYearType.getValue());
periodStartingBalance = postingPeriod.closingBalance();
@@ -474,20 +464,20 @@ public class SavingsAccount extends AbstractPersistable<Long> {
allPostingPeriods.add(postingPeriod);
}
savingsHelper.calculateInterestForAllPostingPeriods(currency, allPostingPeriods);
this.savingsHelper.calculateInterestForAllPostingPeriods(this.currency, allPostingPeriods);
this.summary.updateFromInterestPeriodSummaries(currency, allPostingPeriods);
this.summary.updateFromInterestPeriodSummaries(this.currency, allPostingPeriods);
this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions);
return allPostingPeriods;
}
private List<SavingsAccountTransaction> retreiveOrderedListOfTransactions() {
List<SavingsAccountTransaction> listOfTransactionsSorted = retreiveListOfTransactions();
final List<SavingsAccountTransaction> listOfTransactionsSorted = retreiveListOfTransactions();
List<SavingsAccountTransaction> orderedNonInterestPostingTransactions = new ArrayList<SavingsAccountTransaction>();
final List<SavingsAccountTransaction> orderedNonInterestPostingTransactions = new ArrayList<SavingsAccountTransaction>();
for (SavingsAccountTransaction transaction : listOfTransactionsSorted) {
for (final SavingsAccountTransaction transaction : listOfTransactionsSorted) {
if (!transaction.isInterestPostingAndNotReversed() && transaction.isNotReversed()) {
orderedNonInterestPostingTransactions.add(transaction);
}
@@ -497,12 +487,12 @@ public class SavingsAccount extends AbstractPersistable<Long> {
}
private List<SavingsAccountTransaction> retreiveListOfTransactions() {
List<SavingsAccountTransaction> listOfTransactionsSorted = new ArrayList<SavingsAccountTransaction>();
for (SavingsAccountTransaction transaction : this.transactions) {
final List<SavingsAccountTransaction> listOfTransactionsSorted = new ArrayList<SavingsAccountTransaction>();
for (final SavingsAccountTransaction transaction : this.transactions) {
listOfTransactionsSorted.add(transaction);
}
SavingsAccountTransactionComparator transactionComparator = new SavingsAccountTransactionComparator();
final SavingsAccountTransactionComparator transactionComparator = new SavingsAccountTransactionComparator();
Collections.sort(listOfTransactionsSorted, transactionComparator);
return listOfTransactionsSorted;
@@ -512,9 +502,9 @@ public class SavingsAccount extends AbstractPersistable<Long> {
Money runningBalance = openingAccountBalance.copy();
List<SavingsAccountTransaction> accountTransactionsSorted = retreiveListOfTransactions();
final List<SavingsAccountTransaction> accountTransactionsSorted = retreiveListOfTransactions();
for (SavingsAccountTransaction transaction : accountTransactionsSorted) {
for (final SavingsAccountTransaction transaction : accountTransactionsSorted) {
if (transaction.isReversed()) {
transaction.zeroBalanceFields();
} else {
@@ -533,7 +523,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
// loop over transactions in reverse
LocalDate endOfBalanceDate = DateUtils.getLocalDateOfTenant();
for (int i = accountTransactionsSorted.size() - 1; i >= 0; i--) {
SavingsAccountTransaction transaction = accountTransactionsSorted.get(i);
final SavingsAccountTransaction transaction = accountTransactionsSorted.get(i);
if (transaction.isNotReversed()) {
transaction.updateCumulativeBalanceAndDates(this.currency, endOfBalanceDate);
@@ -698,7 +688,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
boolean transactionBeforeLastInterestPosting = false;
for (SavingsAccountTransaction transaction : retreiveListOfTransactions()) {
for (final SavingsAccountTransaction transaction : retreiveListOfTransactions()) {
if (transaction.isInterestPostingAndNotReversed() && transaction.isAfter(transactionDate)) {
transactionBeforeLastInterestPosting = true;
break;
@@ -713,7 +703,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
Money runningBalance = Money.zero(this.currency);
for (SavingsAccountTransaction transaction : transactionsSortedByDate) {
for (final SavingsAccountTransaction transaction : transactionsSortedByDate) {
if (transaction.isNotReversed() && transaction.isCredit()) {
runningBalance = runningBalance.plus(transaction.getAmount(this.currency));
} else if (transaction.isNotReversed() && transaction.isDebit()) {
@@ -733,7 +723,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
Money runningBalance = Money.zero(this.currency);
for (SavingsAccountTransaction transaction : transactionsSortedByDate) {
for (final SavingsAccountTransaction transaction : transactionsSortedByDate) {
if (transaction.isNotReversed() && transaction.isCredit()) {
runningBalance = runningBalance.plus(transaction.getAmount(this.currency));
} else if (transaction.isNotReversed() && transaction.isDebit()) {
@@ -767,7 +757,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
LocalDate nextAnnualFeeDueDate = getNextAnnualFeeDueDate();
final LocalDate nextAnnualFeeDueDate = getNextAnnualFeeDueDate();
if (nextAnnualFeeDueDate == null || annualFeeSettingsNotSet()) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("no.annualfee.settings");
@@ -806,7 +796,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
existingReversedTransactionIds.addAll(findExistingReversedTransactionIds());
final Money annualFee = Money.of(this.currency, this.annualFeeAmount);
SavingsAccountTransaction annualFeeTransaction = SavingsAccountTransaction.annualFee(this, annualFeeTransactionDate, annualFee);
final SavingsAccountTransaction annualFeeTransaction = SavingsAccountTransaction.annualFee(this, annualFeeTransactionDate, annualFee);
this.transactions.add(annualFeeTransaction);
this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions);
@@ -815,7 +805,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
currentAnnualFeeNextDueDate = findLatestAnnualFeeTransactionDueDate();
if (currentAnnualFeeNextDueDate != null) {
LocalDate newAnnualFeeNextDueDate = new LocalDate(currentAnnualFeeNextDueDate).withMonthOfYear(this.annualFeeOnMonth)
final LocalDate newAnnualFeeNextDueDate = new LocalDate(currentAnnualFeeNextDueDate).withMonthOfYear(this.annualFeeOnMonth)
.withDayOfMonth(this.annualFeeOnDay).plusYears(1);
this.annualFeeNextDueDate = newAnnualFeeNextDueDate.toDate();
} else {
@@ -847,7 +837,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
}
private void updateToNextAnnualFeeDueDateFrom(final LocalDate startingDate) {
LocalDate nextDueLocalDate = startingDate.withMonthOfYear(this.annualFeeOnMonth).withDayOfMonth(this.annualFeeOnDay);
final LocalDate nextDueLocalDate = startingDate.withMonthOfYear(this.annualFeeOnMonth).withDayOfMonth(this.annualFeeOnDay);
this.annualFeeNextDueDate = nextDueLocalDate.toDate();
}
@@ -902,7 +892,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.modifyApplicationAction);
SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state");
@@ -1124,16 +1114,16 @@ public class SavingsAccount extends AbstractPersistable<Long> {
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME);
if (this.lockinPeriodFrequency == null) {
baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).ignoreIfNull()
baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(this.lockinPeriodFrequencyType).ignoreIfNull()
.inMinMaxRange(0, 3);
if (this.lockinPeriodFrequencyType != null) {
baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).notNull()
baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(this.lockinPeriodFrequency).notNull()
.integerZeroOrGreater();
}
} else {
baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequencyType).integerZeroOrGreater();
baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull()
baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(this.lockinPeriodFrequencyType).integerZeroOrGreater();
baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(this.lockinPeriodFrequencyType).notNull()
.inMinMaxRange(0, 3);
}
@@ -1144,14 +1134,14 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final List<Long> existingReversedTransactionIds) {
final Map<String, Object> accountingBridgeData = new LinkedHashMap<String, Object>();
accountingBridgeData.put("savingsId", this.getId());
accountingBridgeData.put("savingsProductId", this.productId());
accountingBridgeData.put("officeId", this.officeId());
accountingBridgeData.put("cashBasedAccountingEnabled", this.isCashBasedAccountingEnabledOnSavingsProduct());
accountingBridgeData.put("accrualBasedAccountingEnabled", this.isAccrualBasedAccountingEnabledOnSavingsProduct());
accountingBridgeData.put("savingsId", getId());
accountingBridgeData.put("savingsProductId", productId());
accountingBridgeData.put("officeId", officeId());
accountingBridgeData.put("cashBasedAccountingEnabled", isCashBasedAccountingEnabledOnSavingsProduct());
accountingBridgeData.put("accrualBasedAccountingEnabled", isAccrualBasedAccountingEnabledOnSavingsProduct());
final List<Map<String, Object>> newLoanTransactions = new ArrayList<Map<String, Object>>();
for (SavingsAccountTransaction transaction : this.transactions) {
for (final SavingsAccountTransaction transaction : this.transactions) {
if (transaction.isReversed() && !existingReversedTransactionIds.contains(transaction.getId())) {
newLoanTransactions.add(transaction.toMapData(currencyData));
} else if (!existingTransactionIds.contains(transaction.getId())) {
@@ -1165,9 +1155,9 @@ public class SavingsAccount extends AbstractPersistable<Long> {
private Collection<Long> findExistingTransactionIds() {
Collection<Long> ids = new ArrayList<Long>();
final Collection<Long> ids = new ArrayList<Long>();
for (SavingsAccountTransaction transaction : this.transactions) {
for (final SavingsAccountTransaction transaction : this.transactions) {
ids.add(transaction.getId());
}
@@ -1178,7 +1168,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final Collection<Long> ids = new ArrayList<Long>();
for (SavingsAccountTransaction transaction : this.transactions) {
for (final SavingsAccountTransaction transaction : this.transactions) {
if (transaction.isReversed()) {
ids.add(transaction.getId());
}
@@ -1279,12 +1269,12 @@ public class SavingsAccount extends AbstractPersistable<Long> {
.failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date");
}
if (client != null && client.isActivatedAfter(submittedOn)) {
baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(client.getActivationLocalDate())
if (this.client != null && this.client.isActivatedAfter(submittedOn)) {
baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(this.client.getActivationLocalDate())
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.client.activation.date");
} else if (group != null && group.isActivatedAfter(submittedOn)) {
} else if (this.group != null && this.group.isActivatedAfter(submittedOn)) {
baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(group.getActivationLocalDate())
baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(this.group.getActivationLocalDate())
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.client.activation.date");
}
@@ -1319,7 +1309,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.approvalAction);
SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName)
.failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state");
@@ -1331,8 +1321,8 @@ public class SavingsAccount extends AbstractPersistable<Long> {
actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status));
// only do below if status has changed in the 'approval' case
LocalDate approvedOn = command.localDateValueOfParameterNamed(SavingsApiConstants.approvedOnDateParamName);
String approvedOnDateChange = command.stringValueOfParameterNamed(SavingsApiConstants.approvedOnDateParamName);
final LocalDate approvedOn = command.localDateValueOfParameterNamed(SavingsApiConstants.approvedOnDateParamName);
final String approvedOnDateChange = command.stringValueOfParameterNamed(SavingsApiConstants.approvedOnDateParamName);
this.approvedOnDate = approvedOn.toDate();
this.approvedBy = currentUser;
@@ -1378,7 +1368,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.undoApprovalAction);
SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.APPROVED.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName)
@@ -1410,7 +1400,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final LocalDate upToInterestCalculationDate) {
SavingsAccountTransaction transactionToUndo = null;
for (SavingsAccountTransaction transaction : this.transactions) {
for (final SavingsAccountTransaction transaction : this.transactions) {
if (transaction.isIdentifiedBy(transactionId)) {
transactionToUndo = transaction;
}
@@ -1428,7 +1418,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
if (this.annualFeeNextDueDate == null) {
updateToNextAnnualFeeDueDateFrom(getActivationLocalDate());
} else {
LocalDate newAnnualFeeNextDueDate = new LocalDate(this.annualFeeNextDueDate).withMonthOfYear(this.annualFeeOnMonth)
final LocalDate newAnnualFeeNextDueDate = new LocalDate(this.annualFeeNextDueDate).withMonthOfYear(this.annualFeeOnMonth)
.withDayOfMonth(this.annualFeeOnDay).plusYears(1);
this.annualFeeNextDueDate = newAnnualFeeNextDueDate.toDate();
}
@@ -1445,7 +1435,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
Date nextDueDate = null;
LocalDate lastAnnualFeeTransactionDate = null;
for (SavingsAccountTransaction transaction : retreiveOrderedListOfTransactions()) {
for (final SavingsAccountTransaction transaction : retreiveOrderedListOfTransactions()) {
if (transaction.isAnnualFeeAndNotReversed()) {
if (lastAnnualFeeTransactionDate == null) {
lastAnnualFeeTransactionDate = transaction.transactionLocalDate();
@@ -1470,7 +1460,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.rejectAction);
SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.rejectedOnDateParamName)
@@ -1482,7 +1472,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
this.status = SavingsAccountStatusType.REJECTED.getValue();
actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status));
LocalDate rejectedOn = command.localDateValueOfParameterNamed(SavingsApiConstants.rejectedOnDateParamName);
final LocalDate rejectedOn = command.localDateValueOfParameterNamed(SavingsApiConstants.rejectedOnDateParamName);
final String rejectedOnAsString = command.stringValueOfParameterNamed(SavingsApiConstants.rejectedOnDateParamName);
this.rejectedOnDate = rejectedOn.toDate();
@@ -1528,7 +1518,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.withdrawnByApplicantAction);
SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.withdrawnOnDateParamName)
@@ -1587,7 +1577,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.activateAction);
SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.APPROVED.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName)
@@ -1622,7 +1612,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
if (this.client != null && this.client.isActivatedAfter(activationDate)) {
final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat()).withLocale(command.extractLocale());
final String dateAsString = formatter.print(client.getActivationLocalDate());
final String dateAsString = formatter.print(this.client.getActivationLocalDate());
baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(dateAsString)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.client.activation.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
@@ -1630,7 +1620,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
if (this.group != null && this.group.isActivatedAfter(activationDate)) {
final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat()).withLocale(command.extractLocale());
final String dateAsString = formatter.print(client.getActivationLocalDate());
final String dateAsString = formatter.print(this.client.getActivationLocalDate());
baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(dateAsString)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.group.activation.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
@@ -28,7 +28,6 @@ public final class SavingsAccountSummary {
@Column(name = "total_withdrawals_derived", scale = 6, precision = 19)
private BigDecimal totalWithdrawals;
@SuppressWarnings("unused")
@Column(name = "total_interest_earned_derived", scale = 6, precision = 19)
private BigDecimal totalInterestEarned;
@@ -65,7 +64,7 @@ public final class SavingsAccountSummary {
Money totalEarned = Money.zero(currency);
for (PostingPeriod period : allPostingPeriods) {
for (final PostingPeriod period : allPostingPeriods) {
totalEarned = totalEarned.plus(period.interest());
}
@@ -38,7 +38,6 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "m_savings_account_transaction")
public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@ManyToOne(optional = false)
@JoinColumn(name = "savings_account_id", nullable = false)
private SavingsAccount savingsAccount;
@@ -63,7 +62,6 @@ public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
@Column(name = "running_balance_derived", scale = 6, precision = 19, nullable = false)
private BigDecimal runningBalance;
@SuppressWarnings("unused")
@Column(name = "cumulative_balance_derived", scale = 6, precision = 19, nullable = false)
private BigDecimal cumulativeBalance;
@@ -221,10 +219,10 @@ public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
final SavingsAccountTransactionEnumData transactionType = SavingsEnumerations.transactionType(this.typeOf);
thisTransactionData.put("id", this.getId());
thisTransactionData.put("id", getId());
thisTransactionData.put("type", transactionType);
thisTransactionData.put("reversed", Boolean.valueOf(this.isReversed()));
thisTransactionData.put("date", this.getTransactionLocalDate());
thisTransactionData.put("reversed", Boolean.valueOf(isReversed()));
thisTransactionData.put("date", getTransactionLocalDate());
thisTransactionData.put("currency", currencyData);
thisTransactionData.put("amount", this.amount);
@@ -236,20 +234,20 @@ public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
}
public boolean isAfter(final LocalDate transactionDate) {
return this.getTransactionLocalDate().isAfter(transactionDate);
return getTransactionLocalDate().isAfter(transactionDate);
}
public EndOfDayBalance toEndOfDayBalance(final LocalDateInterval periodInterval, final MonetaryCurrency currency) {
Money endOfDayBalance = Money.of(currency, this.runningBalance);
Money openingBalance = endOfDayBalance;
final Money endOfDayBalance = Money.of(currency, this.runningBalance);
final Money openingBalance = endOfDayBalance;
LocalDate balanceDate = periodInterval.startDate();
int numberOfDays = periodInterval.daysInPeriodInclusiveOfEndDate();
if (periodInterval.contains(getTransactionLocalDate())) {
balanceDate = getTransactionLocalDate();
LocalDateInterval newInterval = LocalDateInterval.create(getTransactionLocalDate(), periodInterval.endDate());
final LocalDateInterval newInterval = LocalDateInterval.create(getTransactionLocalDate(), periodInterval.endDate());
numberOfDays = newInterval.daysInPeriodInclusiveOfEndDate();
}
@@ -258,7 +256,7 @@ public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
public EndOfDayBalance toEndOfDayBalance(final Money openingBalance, final LocalDate nextTransactionDate) {
MonetaryCurrency currency = openingBalance.getCurrency();
final MonetaryCurrency currency = openingBalance.getCurrency();
Money endOfDayBalance = openingBalance.copy();
if (isDeposit()) {
endOfDayBalance = openingBalance.plus(getAmount(currency));
@@ -274,7 +272,7 @@ public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
}
public EndOfDayBalance toEndOfDayBalance(final Money openingBalance) {
MonetaryCurrency currency = openingBalance.getCurrency();
final MonetaryCurrency currency = openingBalance.getCurrency();
Money endOfDayBalance = openingBalance.copy();
if (isDeposit()) {
endOfDayBalance = openingBalance.plus(getAmount(currency));
@@ -287,7 +285,7 @@ public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
public EndOfDayBalance toEndOfDayBalanceBoundedBy(final Money openingBalance, final LocalDateInterval boundedBy) {
MonetaryCurrency currency = openingBalance.getCurrency();
final MonetaryCurrency currency = openingBalance.getCurrency();
Money endOfDayBalance = openingBalance.copy();
int numberOfDaysOfBalance = this.balanceNumberOfDays;
@@ -297,7 +295,7 @@ public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
if (boundedBy.startDate().isAfter(balanceStartDate)) {
balanceStartDate = boundedBy.startDate();
LocalDateInterval spanOfBalance = LocalDateInterval.create(balanceStartDate, balanceEndDate);
final LocalDateInterval spanOfBalance = LocalDateInterval.create(balanceStartDate, balanceEndDate);
numberOfDaysOfBalance = spanOfBalance.daysInPeriodInclusiveOfEndDate();
} else {
if (isDeposit()) {
@@ -309,7 +307,7 @@ public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
if (balanceEndDate.isAfter(boundedBy.endDate())) {
balanceEndDate = boundedBy.endDate();
LocalDateInterval spanOfBalance = LocalDateInterval.create(balanceStartDate, balanceEndDate);
final LocalDateInterval spanOfBalance = LocalDateInterval.create(balanceStartDate, balanceEndDate);
numberOfDaysOfBalance = spanOfBalance.daysInPeriodInclusiveOfEndDate();
}
@@ -321,17 +319,17 @@ public final class SavingsAccountTransaction extends AbstractPersistable<Long> {
}
public boolean fallsWithin(final LocalDateInterval periodInterval) {
LocalDateInterval balanceInterval = LocalDateInterval.create(getTransactionLocalDate(), getEndOfBalanceLocalDate());
final LocalDateInterval balanceInterval = LocalDateInterval.create(getTransactionLocalDate(), getEndOfBalanceLocalDate());
return periodInterval.contains(balanceInterval);
}
public boolean spansAnyPortionOf(final LocalDateInterval periodInterval) {
LocalDateInterval balanceInterval = LocalDateInterval.create(getTransactionLocalDate(), getEndOfBalanceLocalDate());
final LocalDateInterval balanceInterval = LocalDateInterval.create(getTransactionLocalDate(), getEndOfBalanceLocalDate());
return balanceInterval.containsPortionOf(periodInterval);
}
public boolean isIdentifiedBy(final Long transactionId) {
return this.getId().equals(transactionId);
return getId().equals(transactionId);
}
public boolean isCredit() {
@@ -42,445 +42,491 @@ import org.springframework.security.core.userdetails.User;
@Table(name = "m_appuser", uniqueConstraints = @UniqueConstraint(columnNames = { "username" }, name = "username_org"))
public class AppUser extends AbstractPersistable<Long> implements PlatformUser {
private final static Logger logger = LoggerFactory.getLogger(AppUser.class);
@Column(name = "email", nullable = false, length = 100)
private String email;
@Column(name = "username", nullable = false, length = 100)
private String username;
@Column(name = "firstname", nullable = false, length = 100)
private String firstname;
@Column(name = "lastname", nullable = false, length = 100)
private String lastname;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "nonexpired", nullable = false)
private boolean accountNonExpired;
@Column(name = "nonlocked", nullable = false)
private final boolean accountNonLocked;
@Column(name = "nonexpired_credentials", nullable = false)
private final boolean credentialsNonExpired;
@Column(name = "enabled", nullable = false)
private boolean enabled;
@SuppressWarnings("unused")
@Column(name = "firsttime_login_remaining", nullable = false)
private boolean firstTimeLoginRemaining;
@Column(name = "is_deleted", nullable = false)
private boolean deleted;
@ManyToOne
@JoinColumn(name = "office_id", nullable = false)
private Office office;
@ManyToOne
@JoinColumn(name = "staff_id", nullable = true)
private Staff staff;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "m_appuser_role", joinColumns = @JoinColumn(name = "appuser_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
public static AppUser fromJson(final Office userOffice, final Set<Role> allRoles, final JsonCommand command) {
final String username = command.stringValueOfParameterNamed("username");
String password = command.stringValueOfParameterNamed("password");
final Boolean sendPasswordToEmail = command.booleanObjectValueOfParameterNamed("sendPasswordToEmail");
if (sendPasswordToEmail.booleanValue()) {
password = new RandomPasswordGenerator(13).generate();
}
boolean userEnabled = true;
boolean userAccountNonExpired = true;
boolean userCredentialsNonExpired = true;
boolean userAccountNonLocked = true;
Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION"));
User user = new User(username, password, userEnabled, userAccountNonExpired, userCredentialsNonExpired, userAccountNonLocked,
authorities);
final String email = command.stringValueOfParameterNamed("email");
final String firstname = command.stringValueOfParameterNamed("firstname");
final String lastname = command.stringValueOfParameterNamed("lastname");
return new AppUser(userOffice, user, allRoles, email, firstname, lastname);
}
protected AppUser() {
this.accountNonLocked = false;
this.credentialsNonExpired = false;
this.roles = new HashSet<Role>();
}
public AppUser(final Office office, final User user, final Set<Role> roles, final String email, final String firstname,
final String lastname) {
this.office = office;
this.email = email.trim();
this.username = user.getUsername().trim();
this.firstname = firstname.trim();
this.lastname = lastname.trim();
this.password = user.getPassword().trim();
this.accountNonExpired = user.isAccountNonExpired();
this.accountNonLocked = user.isAccountNonLocked();
this.credentialsNonExpired = user.isCredentialsNonExpired();
this.enabled = user.isEnabled();
this.roles = roles;
this.firstTimeLoginRemaining = true;
}
public EnumOptionData organisationalRoleData() {
EnumOptionData organisationalRole = null;
if (this.staff != null) {
organisationalRole = this.staff.organisationalRoleData();
}
return organisationalRole;
}
public void updatePassword(final String encodePassword) {
this.password = encodePassword;
this.firstTimeLoginRemaining = false;
}
public void changeOffice(final Office differentOffice) {
this.office = differentOffice;
}
public void updateRoles(final Set<Role> allRoles) {
if (!allRoles.isEmpty()) {
this.roles.clear();
this.roles = allRoles;
}
}
public Map<String, Object> update(final JsonCommand command, final PlatformPasswordEncoder platformPasswordEncoder) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(7);
// unencoded password provided
final String passwordParamName = "password";
final String passwordEncodedParamName = "passwordEncoded";
if (command.hasParameter(passwordParamName)) {
if (command.isChangeInPasswordParameterNamed(passwordParamName, this.password, platformPasswordEncoder, this.getId())) {
final String passwordEncodedValue = command.passwordValueOfParameterNamed(passwordParamName, platformPasswordEncoder,
this.getId());
actualChanges.put(passwordEncodedParamName, passwordEncodedValue);
updatePassword(passwordEncodedValue);
}
}
if (command.hasParameter(passwordEncodedParamName)) {
if (command.isChangeInStringParameterNamed(passwordEncodedParamName, this.password)) {
final String newValue = command.stringValueOfParameterNamed(passwordEncodedParamName);
actualChanges.put(passwordEncodedParamName, newValue);
updatePassword(newValue);
}
}
final String officeIdParamName = "officeId";
if (command.isChangeInLongParameterNamed(officeIdParamName, this.office.getId())) {
final Long newValue = command.longValueOfParameterNamed(officeIdParamName);
actualChanges.put(officeIdParamName, newValue);
}
final String rolesParamName = "roles";
if (command.isChangeInArrayParameterNamed(rolesParamName, getRolesAsIdStringArray())) {
final String[] newValue = command.arrayValueOfParameterNamed(rolesParamName);
actualChanges.put(rolesParamName, newValue);
}
final String usernameParamName = "username";
if (command.isChangeInStringParameterNamed(usernameParamName, this.username)) {
final String newValue = command.stringValueOfParameterNamed(usernameParamName);
actualChanges.put(usernameParamName, newValue);
this.username = newValue;
}
final String firstnameParamName = "firstname";
if (command.isChangeInStringParameterNamed(firstnameParamName, this.firstname)) {
final String newValue = command.stringValueOfParameterNamed(firstnameParamName);
actualChanges.put(firstnameParamName, newValue);
this.firstname = newValue;
}
final String lastnameParamName = "lastname";
if (command.isChangeInStringParameterNamed(lastnameParamName, this.lastname)) {
final String newValue = command.stringValueOfParameterNamed(lastnameParamName);
actualChanges.put(lastnameParamName, newValue);
this.lastname = newValue;
}
final String emailParamName = "email";
if (command.isChangeInStringParameterNamed(emailParamName, this.email)) {
final String newValue = command.stringValueOfParameterNamed(emailParamName);
actualChanges.put(emailParamName, newValue);
this.email = newValue;
}
return actualChanges;
}
private String[] getRolesAsIdStringArray() {
List<String> roleIds = new ArrayList<String>();
for (Role role : this.roles) {
roleIds.add(role.getId().toString());
}
return roleIds.toArray(new String[roleIds.size()]);
}
/**
* Delete is a <i>soft delete</i>. Updates flag so it wont appear in
* query/report results.
*
* Any fields with unique constraints and prepended with id of record.
*/
public void delete() {
this.deleted = true;
this.enabled = false;
this.accountNonExpired = false;
this.firstTimeLoginRemaining = true;
this.username = this.getId() + "_DELETED_" + this.username;
}
public boolean isDeleted() {
return deleted;
}
@Override
public Collection<GrantedAuthority> getAuthorities() {
return this.populateGrantedAuthorities();
}
private List<GrantedAuthority> populateGrantedAuthorities() {
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
for (Role role : this.roles) {
Collection<Permission> permissions = role.getPermissions();
for (Permission permission : permissions) {
grantedAuthorities.add(new SimpleGrantedAuthority(permission.getCode()));
}
}
return grantedAuthorities;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return this.accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return this.accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return this.credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return this.enabled;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public String getEmail() {
return this.email;
}
public Set<Role> getRoles() {
return this.roles;
}
public Office getOffice() {
return this.office;
}
public boolean canNotApproveLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "APPROVEINPAST_LOAN");
}
public boolean canNotRejectLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REJECTINPAST_LOAN");
}
public boolean canNotWithdrawByClientLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "WITHDRAWINPAST_LOAN");
}
public boolean canNotDisburseLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "DISBURSEINPAST_LOAN");
}
public boolean canNotMakeRepaymentOnLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REPAYMENTINPAST_LOAN");
}
public boolean hasNotPermissionForReport(final String reportName) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", "REPORTING_SUPER_USER", "READ_" + reportName)) return true;
return false;
}
public boolean hasNotPermissionForDatatable(final String datatable, final String accessType) {
String matchPermission = accessType + "_" + datatable;
if (accessType.equalsIgnoreCase("READ")) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission)) return true;
return false;
}
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) return true;
return false;
}
public boolean hasNotPermissionForAnyOf(final String... permissionCodes) {
boolean hasNotPermission = true;
for (String permissionCode : permissionCodes) {
boolean checkPermission = this.hasPermissionTo(permissionCode);
if (checkPermission) {
hasNotPermission = false;
break;
}
}
return hasNotPermission;
}
public void validateHasReadPermission(final String resourceType) {
final String authorizationMessage = "User has no authority to view " + resourceType.toLowerCase() + "s";
final String matchPermission = "READ_" + resourceType.toUpperCase();
if (!(hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission))) return;
throw new NoAuthorizationException(authorizationMessage);
}
private boolean hasNotPermissionTo(final String permissionCode) {
return !hasPermissionTo(permissionCode);
}
private boolean hasPermissionTo(final String permissionCode) {
boolean hasPermission = hasAllFunctionsPermission();
if (!hasPermission) {
for (Role role : this.roles) {
if (role.hasPermissionTo(permissionCode)) {
hasPermission = true;
break;
}
}
}
return hasPermission;
}
private boolean hasAllFunctionsPermission() {
boolean match = false;
for (Role role : this.roles) {
if (role.hasPermissionTo("ALL_FUNCTIONS")) {
match = true;
break;
}
}
return match;
}
public boolean hasIdOf(final Long userId) {
return getId().equals(userId);
}
private boolean hasNotAnyPermission(final List<String> permissions) {
return !hasAnyPermission(permissions);
}
private boolean hasAnyPermission(final List<String> permissions) {
boolean hasAtLeastOneOf = false;
for (final String permissionCode : permissions) {
if (hasPermissionTo(permissionCode)) {
hasAtLeastOneOf = true;
break;
}
}
return hasAtLeastOneOf;
}
public void validateHasPermissionTo(final String function, final List<String> allowedPermissions) {
if (hasNotAnyPermission(allowedPermissions)) {
final String authorizationMessage = "User has no authority to: " + function;
throw new NoAuthorizationException(authorizationMessage);
}
}
public void validateHasPermissionTo(final String function) {
if (hasNotPermissionTo(function)) {
final String authorizationMessage = "User has no authority to: " + function;
logger.info("Unauthorized access: userId: " + this.getId() + " action: " + function + " allowed: " + getAuthorities());
throw new NoAuthorizationException(authorizationMessage);
}
}
public void validateHasCheckerPermissionTo(final String function) {
final String checkerPermissionName = function.toUpperCase() + "_CHECKER";
if (hasNotPermissionTo("CHECKER_SUPER_USER") && hasNotPermissionTo(checkerPermissionName)) {
final String authorizationMessage = "User has no authority to be a checker for: " + function;
throw new NoAuthorizationException(authorizationMessage);
}
}
public void validateHasDatatableReadPermission(final String datatable) {
if (hasNotPermissionForDatatable(datatable, "READ")) { throw new NoAuthorizationException("Not authorised to read datatable: "
+ datatable); }
}
public Long getStaffId() {
Long staffId = null;
if (this.staff != null) {
staffId = this.staff.getId();
}
return staffId;
}
public String getStaffDisplayName() {
String staffDisplayName = null;
if (this.staff != null) {
staffDisplayName = this.staff.displayName();
}
return staffDisplayName;
}
private final static Logger logger = LoggerFactory.getLogger(AppUser.class);
@Column(name = "email", nullable = false, length = 100)
private String email;
@Column(name = "username", nullable = false, length = 100)
private String username;
@Column(name = "firstname", nullable = false, length = 100)
private String firstname;
@Column(name = "lastname", nullable = false, length = 100)
private String lastname;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "nonexpired", nullable = false)
private boolean accountNonExpired;
@Column(name = "nonlocked", nullable = false)
private final boolean accountNonLocked;
@Column(name = "nonexpired_credentials", nullable = false)
private final boolean credentialsNonExpired;
@Column(name = "enabled", nullable = false)
private boolean enabled;
@Column(name = "firsttime_login_remaining", nullable = false)
private boolean firstTimeLoginRemaining;
@Column(name = "is_deleted", nullable = false)
private boolean deleted;
@ManyToOne
@JoinColumn(name = "office_id", nullable = false)
private Office office;
@ManyToOne
@JoinColumn(name = "staff_id", nullable = true)
private Staff staff;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "m_appuser_role", joinColumns = @JoinColumn(name = "appuser_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
public static AppUser fromJson(final Office userOffice,
final Set<Role> allRoles, final JsonCommand command) {
final String username = command.stringValueOfParameterNamed("username");
String password = command.stringValueOfParameterNamed("password");
final Boolean sendPasswordToEmail = command
.booleanObjectValueOfParameterNamed("sendPasswordToEmail");
if (sendPasswordToEmail.booleanValue()) {
password = new RandomPasswordGenerator(13).generate();
}
final boolean userEnabled = true;
final boolean userAccountNonExpired = true;
final boolean userCredentialsNonExpired = true;
final boolean userAccountNonLocked = true;
final Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(
"DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION"));
final User user = new User(username, password, userEnabled,
userAccountNonExpired, userCredentialsNonExpired,
userAccountNonLocked, authorities);
final String email = command.stringValueOfParameterNamed("email");
final String firstname = command
.stringValueOfParameterNamed("firstname");
final String lastname = command.stringValueOfParameterNamed("lastname");
return new AppUser(userOffice, user, allRoles, email, firstname,
lastname);
}
protected AppUser() {
this.accountNonLocked = false;
this.credentialsNonExpired = false;
this.roles = new HashSet<Role>();
}
public AppUser(final Office office, final User user, final Set<Role> roles,
final String email, final String firstname, final String lastname) {
this.office = office;
this.email = email.trim();
this.username = user.getUsername().trim();
this.firstname = firstname.trim();
this.lastname = lastname.trim();
this.password = user.getPassword().trim();
this.accountNonExpired = user.isAccountNonExpired();
this.accountNonLocked = user.isAccountNonLocked();
this.credentialsNonExpired = user.isCredentialsNonExpired();
this.enabled = user.isEnabled();
this.roles = roles;
this.firstTimeLoginRemaining = true;
}
public EnumOptionData organisationalRoleData() {
EnumOptionData organisationalRole = null;
if (this.staff != null) {
organisationalRole = this.staff.organisationalRoleData();
}
return organisationalRole;
}
public void updatePassword(final String encodePassword) {
this.password = encodePassword;
this.firstTimeLoginRemaining = false;
}
public void changeOffice(final Office differentOffice) {
this.office = differentOffice;
}
public void updateRoles(final Set<Role> allRoles) {
if (!allRoles.isEmpty()) {
this.roles.clear();
this.roles = allRoles;
}
}
public Map<String, Object> update(final JsonCommand command,
final PlatformPasswordEncoder platformPasswordEncoder) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(
7);
// unencoded password provided
final String passwordParamName = "password";
final String passwordEncodedParamName = "passwordEncoded";
if (command.hasParameter(passwordParamName)) {
if (command.isChangeInPasswordParameterNamed(passwordParamName,
this.password, platformPasswordEncoder, getId())) {
final String passwordEncodedValue = command
.passwordValueOfParameterNamed(passwordParamName,
platformPasswordEncoder, getId());
actualChanges.put(passwordEncodedParamName,
passwordEncodedValue);
updatePassword(passwordEncodedValue);
}
}
if (command.hasParameter(passwordEncodedParamName)) {
if (command.isChangeInStringParameterNamed(
passwordEncodedParamName, this.password)) {
final String newValue = command
.stringValueOfParameterNamed(passwordEncodedParamName);
actualChanges.put(passwordEncodedParamName, newValue);
updatePassword(newValue);
}
}
final String officeIdParamName = "officeId";
if (command.isChangeInLongParameterNamed(officeIdParamName,
this.office.getId())) {
final Long newValue = command
.longValueOfParameterNamed(officeIdParamName);
actualChanges.put(officeIdParamName, newValue);
}
final String rolesParamName = "roles";
if (command.isChangeInArrayParameterNamed(rolesParamName,
getRolesAsIdStringArray())) {
final String[] newValue = command
.arrayValueOfParameterNamed(rolesParamName);
actualChanges.put(rolesParamName, newValue);
}
final String usernameParamName = "username";
if (command.isChangeInStringParameterNamed(usernameParamName,
this.username)) {
final String newValue = command
.stringValueOfParameterNamed(usernameParamName);
actualChanges.put(usernameParamName, newValue);
this.username = newValue;
}
final String firstnameParamName = "firstname";
if (command.isChangeInStringParameterNamed(firstnameParamName,
this.firstname)) {
final String newValue = command
.stringValueOfParameterNamed(firstnameParamName);
actualChanges.put(firstnameParamName, newValue);
this.firstname = newValue;
}
final String lastnameParamName = "lastname";
if (command.isChangeInStringParameterNamed(lastnameParamName,
this.lastname)) {
final String newValue = command
.stringValueOfParameterNamed(lastnameParamName);
actualChanges.put(lastnameParamName, newValue);
this.lastname = newValue;
}
final String emailParamName = "email";
if (command.isChangeInStringParameterNamed(emailParamName, this.email)) {
final String newValue = command
.stringValueOfParameterNamed(emailParamName);
actualChanges.put(emailParamName, newValue);
this.email = newValue;
}
return actualChanges;
}
private String[] getRolesAsIdStringArray() {
final List<String> roleIds = new ArrayList<String>();
for (final Role role : this.roles) {
roleIds.add(role.getId().toString());
}
return roleIds.toArray(new String[roleIds.size()]);
}
/**
* Delete is a <i>soft delete</i>. Updates flag so it wont appear in
* query/report results.
*
* Any fields with unique constraints and prepended with id of record.
*/
public void delete() {
this.deleted = true;
this.enabled = false;
this.accountNonExpired = false;
this.firstTimeLoginRemaining = true;
this.username = getId() + "_DELETED_" + this.username;
}
public boolean isDeleted() {
return this.deleted;
}
@Override
public Collection<GrantedAuthority> getAuthorities() {
return populateGrantedAuthorities();
}
private List<GrantedAuthority> populateGrantedAuthorities() {
final List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
for (final Role role : this.roles) {
final Collection<Permission> permissions = role.getPermissions();
for (final Permission permission : permissions) {
grantedAuthorities.add(new SimpleGrantedAuthority(permission
.getCode()));
}
}
return grantedAuthorities;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return this.accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return this.accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return this.credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return this.enabled;
}
public String getFirstname() {
return this.firstname;
}
public String getLastname() {
return this.lastname;
}
public String getEmail() {
return this.email;
}
public Set<Role> getRoles() {
return this.roles;
}
public Office getOffice() {
return this.office;
}
public boolean canNotApproveLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "APPROVEINPAST_LOAN");
}
public boolean canNotRejectLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REJECTINPAST_LOAN");
}
public boolean canNotWithdrawByClientLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "WITHDRAWINPAST_LOAN");
}
public boolean canNotDisburseLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "DISBURSEINPAST_LOAN");
}
public boolean canNotMakeRepaymentOnLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REPAYMENTINPAST_LOAN");
}
public boolean hasNotPermissionForReport(final String reportName) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ",
"REPORTING_SUPER_USER", "READ_" + reportName)) {
return true;
}
return false;
}
public boolean hasNotPermissionForDatatable(final String datatable,
final String accessType) {
final String matchPermission = accessType + "_" + datatable;
if (accessType.equalsIgnoreCase("READ")) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ",
matchPermission)) {
return true;
}
return false;
}
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) {
return true;
}
return false;
}
public boolean hasNotPermissionForAnyOf(final String... permissionCodes) {
boolean hasNotPermission = true;
for (final String permissionCode : permissionCodes) {
final boolean checkPermission = hasPermissionTo(permissionCode);
if (checkPermission) {
hasNotPermission = false;
break;
}
}
return hasNotPermission;
}
public void validateHasReadPermission(final String resourceType) {
final String authorizationMessage = "User has no authority to view "
+ resourceType.toLowerCase() + "s";
final String matchPermission = "READ_" + resourceType.toUpperCase();
if (!hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ",
matchPermission)) {
return;
}
throw new NoAuthorizationException(authorizationMessage);
}
private boolean hasNotPermissionTo(final String permissionCode) {
return !hasPermissionTo(permissionCode);
}
private boolean hasPermissionTo(final String permissionCode) {
boolean hasPermission = hasAllFunctionsPermission();
if (!hasPermission) {
for (final Role role : this.roles) {
if (role.hasPermissionTo(permissionCode)) {
hasPermission = true;
break;
}
}
}
return hasPermission;
}
private boolean hasAllFunctionsPermission() {
boolean match = false;
for (final Role role : this.roles) {
if (role.hasPermissionTo("ALL_FUNCTIONS")) {
match = true;
break;
}
}
return match;
}
public boolean hasIdOf(final Long userId) {
return getId().equals(userId);
}
private boolean hasNotAnyPermission(final List<String> permissions) {
return !hasAnyPermission(permissions);
}
private boolean hasAnyPermission(final List<String> permissions) {
boolean hasAtLeastOneOf = false;
for (final String permissionCode : permissions) {
if (hasPermissionTo(permissionCode)) {
hasAtLeastOneOf = true;
break;
}
}
return hasAtLeastOneOf;
}
public void validateHasPermissionTo(final String function,
final List<String> allowedPermissions) {
if (hasNotAnyPermission(allowedPermissions)) {
final String authorizationMessage = "User has no authority to: "
+ function;
throw new NoAuthorizationException(authorizationMessage);
}
}
public void validateHasPermissionTo(final String function) {
if (hasNotPermissionTo(function)) {
final String authorizationMessage = "User has no authority to: "
+ function;
logger.info("Unauthorized access: userId: " + getId() + " action: "
+ function + " allowed: " + getAuthorities());
throw new NoAuthorizationException(authorizationMessage);
}
}
public void validateHasCheckerPermissionTo(final String function) {
final String checkerPermissionName = function.toUpperCase()
+ "_CHECKER";
if (hasNotPermissionTo("CHECKER_SUPER_USER")
&& hasNotPermissionTo(checkerPermissionName)) {
final String authorizationMessage = "User has no authority to be a checker for: "
+ function;
throw new NoAuthorizationException(authorizationMessage);
}
}
public void validateHasDatatableReadPermission(final String datatable) {
if (hasNotPermissionForDatatable(datatable, "READ")) {
throw new NoAuthorizationException(
"Not authorised to read datatable: " + datatable);
}
}
public Long getStaffId() {
Long staffId = null;
if (this.staff != null) {
staffId = this.staff.getId();
}
return staffId;
}
public String getStaffDisplayName() {
String staffDisplayName = null;
if (this.staff != null) {
staffDisplayName = this.staff.displayName();
}
return staffDisplayName;
}
}
@@ -21,11 +21,9 @@ public class Permission extends AbstractPersistable<Long> {
@Column(name = "code", nullable = false, length = 100)
private final String code;
@SuppressWarnings("unused")
@Column(name = "entity_name", nullable = true, length = 100)
private final String entityName;
@SuppressWarnings("unused")
@Column(name = "action_name", nullable = true, length = 100)
private final String actionName;
@@ -66,7 +64,7 @@ public class Permission extends AbstractPersistable<Long> {
}
public boolean enableMakerChecker(final boolean canMakerChecker) {
final boolean isUpdatedValueSame = (this.canMakerChecker == canMakerChecker);
final boolean isUpdatedValueSame = this.canMakerChecker == canMakerChecker;
this.canMakerChecker = canMakerChecker;
return !isUpdatedValueSame;