code cleanup and renaming entry date in journal entries

This commit is contained in:
Vishwas Babu AJ
2013-02-18 20:32:07 +05:30
parent bf2bdde478
commit 4030608442
45 changed files with 454 additions and 439 deletions
+8 -8
View File
@@ -5293,13 +5293,13 @@ GET https://DomainName/api/v1/loanproducts/{productId}
<div class="method-description"> <div class="method-description">
<h4>Create a Loan Product</h4> <h4>Create a Loan Product</h4>
<p>Depending of the Accounting Rule (accountingRule) selected, <p>Depending of the Accounting Rule (accountingRule) selected,
additional fields with details with the appropriate Ledger Account additional fields with details of the appropriate Ledger Account
identifiers would need to be passed in. identifiers would need to be passed in.
</p> </p>
</p>Refer <a href="https://mifosforge.jira.com/wiki/display/MIFOSX/A+Possible+accounting+Spec"> </p>Refer <a href="https://mifosforge.jira.com/wiki/display/MIFOSX/A+Possible+accounting+Spec">
MifosX Accounting Specs Draft</a> for more details regarding the MifosX Accounting Specs Draft</a> for more details regarding the
significance of the selected accounting Rule significance of the selected accounting rule
</p> </p>
<table class=matrixHeading> <table class=matrixHeading>
@@ -9665,7 +9665,7 @@ No Request Body:
</td> </td>
</tr> </tr>
<tr class=alt> <tr class=alt>
<td>entryDate</td> <td>transactionDate</td>
</tr> </tr>
<tr> <tr>
<td class=fielddesc>The target date for which this <td class=fielddesc>The target date for which this
@@ -9798,7 +9798,7 @@ GET https://DomainName/api/v1/journalentries?transactionId=PB37X8Y21EQUY4S
"code": "accountType.equity", "code": "accountType.equity",
"value": "EQUITY" "value": "EQUITY"
}, },
"entryDate": [ "transactionDate": [
2012, 2012,
12, 12,
12 12
@@ -9832,7 +9832,7 @@ GET https://DomainName/api/v1/journalentries?transactionId=PB37X8Y21EQUY4S
"code": "accountType.equity", "code": "accountType.equity",
"value": "EQUITY" "value": "EQUITY"
}, },
"entryDate": [ "transactionDate": [
2012, 2012,
12, 12,
12 12
@@ -9877,7 +9877,7 @@ GET https://DomainName/api/v1/journalentries?transactionId=PB37X8Y21EQUY4S
<td><div class="mifosXHeading2">Mandatory Fields</div></td> <td><div class="mifosXHeading2">Mandatory Fields</div></td>
</tr> </tr>
<tr class=alt> <tr class=alt>
<td>officeId, entryDate <td>officeId, transactionDate
</td> </td>
</tr> </tr>
<tr> <tr>
@@ -9927,7 +9927,7 @@ Content-Type: application/json
Request Body: Request Body:
{ {
"officeId": 1, "officeId": 1,
"entryDate": "06 December 2012", "transactionDate": "06 December 2012",
"comments": "Gifts for staff", "comments": "Gifts for staff",
"locale": "en" , "locale": "en" ,
"dateFormat": "dd MMMM yyyy", "dateFormat": "dd MMMM yyyy",
@@ -9981,7 +9981,7 @@ GET https://DomainName/api/v1/journalentries/{entryId}
"code": "accountType.income", "code": "accountType.income",
"value": "INCOME" "value": "INCOME"
}, },
"entryDate": [ "transactionDate": [
2012, 2012,
11, 11,
2 2
@@ -17,7 +17,7 @@ public enum GLClosureJsonInputParams {
private static final Set<String> values = new HashSet<String>(); private static final Set<String> values = new HashSet<String>();
static { static {
for (GLClosureJsonInputParams type : GLClosureJsonInputParams.values()) { for (final GLClosureJsonInputParams type : GLClosureJsonInputParams.values()) {
values.add(type.value); values.add(type.value);
} }
} }
@@ -51,8 +51,8 @@ public class GLClosuresApiResource {
private final String resourceNameForPermission = "GLCLOSURE"; private final String resourceNameForPermission = "GLCLOSURE";
private GLClosureReadPlatformService glClosureReadPlatformService; private final GLClosureReadPlatformService glClosureReadPlatformService;
private OfficeReadPlatformService officeReadPlatformService; private final OfficeReadPlatformService officeReadPlatformService;
private final DefaultToApiJsonSerializer<GLClosureData> apiJsonSerializerService; private final DefaultToApiJsonSerializer<GLClosureData> apiJsonSerializerService;
private final ApiRequestParameterHelper apiRequestParameterHelper; private final ApiRequestParameterHelper apiRequestParameterHelper;
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
@@ -76,10 +76,10 @@ public class GLClosuresApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveAllClosures(@Context final UriInfo uriInfo, @QueryParam("officeId") final Long officeId) { public String retrieveAllClosures(@Context final UriInfo uriInfo, @QueryParam("officeId") final Long officeId) {
context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
final List<GLClosureData> glClosureDatas = this.glClosureReadPlatformService.retrieveAllGLClosures(officeId); final List<GLClosureData> glClosureDatas = this.glClosureReadPlatformService.retrieveAllGLClosures(officeId);
final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.apiJsonSerializerService.serialize(settings, glClosureDatas, RESPONSE_DATA_PARAMETERS); return this.apiJsonSerializerService.serialize(settings, glClosureDatas, RESPONSE_DATA_PARAMETERS);
} }
@@ -89,13 +89,13 @@ public class GLClosuresApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String retreiveClosure(@PathParam("glClosureId") final Long glClosureId, @Context final UriInfo uriInfo) { public String retreiveClosure(@PathParam("glClosureId") final Long glClosureId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
final GLClosureData glClosureData = this.glClosureReadPlatformService.retrieveGLClosureById(glClosureId); final GLClosureData glClosureData = this.glClosureReadPlatformService.retrieveGLClosureById(glClosureId);
if (settings.isTemplate()) { if (settings.isTemplate()) {
glClosureData.setAllowedOffices(new ArrayList<OfficeLookup>(officeReadPlatformService.retrieveAllOfficesForLookup())); glClosureData.setAllowedOffices(new ArrayList<OfficeLookup>(this.officeReadPlatformService.retrieveAllOfficesForLookup()));
} }
return this.apiJsonSerializerService.serialize(settings, glClosureData, RESPONSE_DATA_PARAMETERS); return this.apiJsonSerializerService.serialize(settings, glClosureData, RESPONSE_DATA_PARAMETERS);
@@ -34,9 +34,9 @@ public class GLClosureCommand {
public void validateForCreate() { public void validateForCreate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLClosure"); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLClosure");
baseDataValidator.reset().parameter(GLClosureJsonInputParams.CLOSING_DATE.getValue()).value(this.closingDate).notBlank(); baseDataValidator.reset().parameter(GLClosureJsonInputParams.CLOSING_DATE.getValue()).value(this.closingDate).notBlank();
baseDataValidator.reset().parameter(GLClosureJsonInputParams.OFFICE_ID.getValue()).value(this.officeId).notNull() baseDataValidator.reset().parameter(GLClosureJsonInputParams.OFFICE_ID.getValue()).value(this.officeId).notNull()
@@ -49,9 +49,9 @@ public class GLClosureCommand {
} }
public void validateForUpdate() { public void validateForUpdate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLClosure"); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLClosure");
baseDataValidator.reset().parameter(GLClosureJsonInputParams.COMMENTS.getValue()).value(this.comments).ignoreIfNull() baseDataValidator.reset().parameter(GLClosureJsonInputParams.COMMENTS.getValue()).value(this.comments).ignoreIfNull()
.notExceedingLengthOf(500); .notExceedingLengthOf(500);
@@ -46,9 +46,9 @@ public class GLClosureData {
private List<OfficeLookup> allowedOffices = new ArrayList<OfficeLookup>(); private List<OfficeLookup> allowedOffices = new ArrayList<OfficeLookup>();
public GLClosureData(Long id, Long officeId, String officeName, LocalDate closingDate, boolean deleted, LocalDate createdDate, public GLClosureData(final Long id, final Long officeId, final String officeName, final LocalDate closingDate, final boolean deleted,
LocalDate lastUpdatedDate, Long createdByUserId, String createdByUsername, Long lastUpdatedByUserId, final LocalDate createdDate, final LocalDate lastUpdatedDate, final Long createdByUserId, final String createdByUsername,
String lastUpdatedByUsername, String comments) { final Long lastUpdatedByUserId, final String lastUpdatedByUsername, final String comments) {
this.id = id; this.id = id;
this.officeId = officeId; this.officeId = officeId;
this.officeName = officeName; this.officeName = officeName;
@@ -68,7 +68,7 @@ public class GLClosureData {
return this.allowedOffices; return this.allowedOffices;
} }
public void setAllowedOffices(List<OfficeLookup> allowedOffices) { public void setAllowedOffices(final List<OfficeLookup> allowedOffices) {
this.allowedOffices = allowedOffices; this.allowedOffices = allowedOffices;
} }
@@ -44,7 +44,7 @@ public class GLClosure extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "comments", nullable = true, length = 500) @Column(name = "comments", nullable = true, length = 500)
private String comments; private String comments;
public static GLClosure createNew(Office office, Date closingDate, String comments) { public static GLClosure createNew(final Office office, final Date closingDate, final String comments) {
return new GLClosure(office, closingDate, comments); return new GLClosure(office, closingDate, comments);
} }
@@ -52,7 +52,7 @@ public class GLClosure extends AbstractAuditableCustom<AppUser, Long> {
// //
} }
public GLClosure(Office office, Date closingDate, String comments) { public GLClosure(final Office office, final Date closingDate, final String comments) {
this.office = office; this.office = office;
this.deleted = false; this.deleted = false;
this.closingDate = closingDate; this.closingDate = closingDate;
@@ -62,9 +62,9 @@ public class GLClosure extends AbstractAuditableCustom<AppUser, Long> {
} }
} }
public static GLClosure fromJson(Office office, final JsonCommand command) { public static GLClosure fromJson(final Office office, final JsonCommand command) {
Date closingDate = command.DateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue()); final Date closingDate = command.DateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue());
String comments = command.stringValueOfParameterNamed(GLClosureJsonInputParams.COMMENTS.getValue()); final String comments = command.stringValueOfParameterNamed(GLClosureJsonInputParams.COMMENTS.getValue());
return new GLClosure(office, closingDate, comments); return new GLClosure(office, closingDate, comments);
} }
@@ -75,7 +75,7 @@ public class GLClosure extends AbstractAuditableCustom<AppUser, Long> {
} }
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName, private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
String propertyToBeUpdated) { final String propertyToBeUpdated) {
if (command.isChangeInStringParameterNamed(paramName, propertyToBeUpdated)) { if (command.isChangeInStringParameterNamed(paramName, propertyToBeUpdated)) {
final String newValue = command.stringValueOfParameterNamed(paramName); final String newValue = command.stringValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
@@ -15,7 +15,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul
public class GLClosureInvalidDeleteException extends AbstractPlatformDomainRuleException { public class GLClosureInvalidDeleteException extends AbstractPlatformDomainRuleException {
public GLClosureInvalidDeleteException(final Long officeId, final String officeName, final Date latestclosureDate) { public GLClosureInvalidDeleteException(final Long officeId, final String officeName, final Date latestclosureDate) {
super("error.msg.glclosure.invalid.delete", "The latest closure for office with Id " + officeId + " and name " + officeName + " is on " super("error.msg.glclosure.invalid.delete", "The latest closure for office with Id " + officeId + " and name " + officeName
+ latestclosureDate.toString() + ", please delete this closure first", latestclosureDate); + " is on " + latestclosureDate.toString() + ", please delete this closure first", latestclosureDate);
} }
} }
@@ -39,20 +39,20 @@ public final class GLClosureCommandFromApiJsonDeserializer extends AbstractFromA
} }
@Override @Override
public GLClosureCommand commandFromApiJson(String json) { public GLClosureCommand commandFromApiJson(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType(); final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
Set<String> supportedParameters = GLClosureJsonInputParams.getAllValues(); final Set<String> supportedParameters = GLClosureJsonInputParams.getAllValues();
fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters);
final JsonElement element = fromApiJsonHelper.parse(json); final JsonElement element = this.fromApiJsonHelper.parse(json);
final Long id = fromApiJsonHelper.extractLongNamed(GLClosureJsonInputParams.ID.getValue(), element); final Long id = this.fromApiJsonHelper.extractLongNamed(GLClosureJsonInputParams.ID.getValue(), element);
final Long officeId = fromApiJsonHelper.extractLongNamed(GLClosureJsonInputParams.OFFICE_ID.getValue(), element); final Long officeId = this.fromApiJsonHelper.extractLongNamed(GLClosureJsonInputParams.OFFICE_ID.getValue(), element);
final String comments = fromApiJsonHelper.extractStringNamed(GLClosureJsonInputParams.COMMENTS.getValue(), element); final String comments = this.fromApiJsonHelper.extractStringNamed(GLClosureJsonInputParams.COMMENTS.getValue(), element);
final LocalDate closingDate = fromApiJsonHelper final LocalDate closingDate = this.fromApiJsonHelper.extractLocalDateNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue(),
.extractLocalDateNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue(), element); element);
return new GLClosureCommand(id, officeId, closingDate, comments); return new GLClosureCommand(id, officeId, closingDate, comments);
} }
@@ -46,18 +46,18 @@ public class GLClosureReadPlatformServiceImpl implements GLClosureReadPlatformSe
@Override @Override
public GLClosureData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { public GLClosureData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = rs.getLong("id"); final Long id = rs.getLong("id");
Long officeId = rs.getLong("officeId"); final Long officeId = rs.getLong("officeId");
String officeName = rs.getString("officeName"); final String officeName = rs.getString("officeName");
LocalDate closingDate = JdbcSupport.getLocalDate(rs, "closingDate"); final LocalDate closingDate = JdbcSupport.getLocalDate(rs, "closingDate");
Boolean deleted = rs.getBoolean("isDeleted"); final Boolean deleted = rs.getBoolean("isDeleted");
LocalDate createdDate = JdbcSupport.getLocalDate(rs, "createdDate"); final LocalDate createdDate = JdbcSupport.getLocalDate(rs, "createdDate");
LocalDate lastUpdatedDate = JdbcSupport.getLocalDate(rs, "updatedDate"); final LocalDate lastUpdatedDate = JdbcSupport.getLocalDate(rs, "updatedDate");
Long creatingByUserId = rs.getLong("creatingUserId"); final Long creatingByUserId = rs.getLong("creatingUserId");
String createdByUserName = rs.getString("creatingUserName"); final String createdByUserName = rs.getString("creatingUserName");
Long lastUpdatedByUserId = rs.getLong("updatingUserId"); final Long lastUpdatedByUserId = rs.getLong("updatingUserId");
String lastUpdatedByUserName = rs.getString("updatingUserName"); final String lastUpdatedByUserName = rs.getString("updatingUserName");
String comments = rs.getString("comments"); final String comments = rs.getString("comments");
return new GLClosureData(id, officeId, officeName, closingDate, deleted, createdDate, lastUpdatedDate, creatingByUserId, return new GLClosureData(id, officeId, officeName, closingDate, deleted, createdDate, lastUpdatedDate, creatingByUserId,
createdByUserName, lastUpdatedByUserId, lastUpdatedByUserName, comments); createdByUserName, lastUpdatedByUserId, lastUpdatedByUserName, comments);
@@ -65,11 +65,11 @@ public class GLClosureReadPlatformServiceImpl implements GLClosureReadPlatformSe
} }
@Override @Override
public List<GLClosureData> retrieveAllGLClosures(Long officeId) { public List<GLClosureData> retrieveAllGLClosures(final Long officeId) {
GLClosureMapper rm = new GLClosureMapper(); final GLClosureMapper rm = new GLClosureMapper();
String sql = "select " + rm.schema() + " and glClosure.is_deleted = 0"; String sql = "select " + rm.schema() + " and glClosure.is_deleted = 0";
Object[] objectArray = new Object[1]; final Object[] objectArray = new Object[1];
int arrayPos = 0; int arrayPos = 0;
if (officeId != null && officeId != 0) { if (officeId != null && officeId != 0) {
sql += " and glClosure.office_id = ?"; sql += " and glClosure.office_id = ?";
@@ -79,21 +79,21 @@ public class GLClosureReadPlatformServiceImpl implements GLClosureReadPlatformSe
sql = sql + " order by glClosure.closing_date desc"; sql = sql + " order by glClosure.closing_date desc";
Object[] finalObjectArray = Arrays.copyOf(objectArray, arrayPos); final Object[] finalObjectArray = Arrays.copyOf(objectArray, arrayPos);
return this.jdbcTemplate.query(sql, rm, finalObjectArray); return this.jdbcTemplate.query(sql, rm, finalObjectArray);
} }
@Override @Override
public GLClosureData retrieveGLClosureById(long glClosureId) { public GLClosureData retrieveGLClosureById(final long glClosureId) {
try { try {
GLClosureMapper rm = new GLClosureMapper(); final GLClosureMapper rm = new GLClosureMapper();
String sql = "select " + rm.schema() + " and glClosure.id = ?"; final String sql = "select " + rm.schema() + " and glClosure.id = ?";
GLClosureData glAccountData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { glClosureId }); final GLClosureData glAccountData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { glClosureId });
return glAccountData; return glAccountData;
} catch (EmptyResultDataAccessException e) { } catch (final EmptyResultDataAccessException e) {
throw new GLClosureNotFoundException(glClosureId); throw new GLClosureNotFoundException(glClosureId);
} }
} }
@@ -44,7 +44,7 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure
@Autowired @Autowired
public GLClosureWritePlatformServiceJpaRepositoryImpl(final GLClosureRepository glClosureRepository, public GLClosureWritePlatformServiceJpaRepositoryImpl(final GLClosureRepository glClosureRepository,
final OfficeRepository officeRepository, GLClosureCommandFromApiJsonDeserializer fromApiJsonDeserializer) { final OfficeRepository officeRepository, final GLClosureCommandFromApiJsonDeserializer fromApiJsonDeserializer) {
this.glClosureRepository = glClosureRepository; this.glClosureRepository = glClosureRepository;
this.officeRepository = officeRepository; this.officeRepository = officeRepository;
this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.fromApiJsonDeserializer = fromApiJsonDeserializer;
@@ -52,7 +52,7 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure
@Transactional @Transactional
@Override @Override
public CommandProcessingResult createGLClosure(JsonCommand command) { public CommandProcessingResult createGLClosure(final JsonCommand command) {
try { try {
final GLClosureCommand closureCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json()); final GLClosureCommand closureCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json());
closureCommand.validateForCreate(); closureCommand.validateForCreate();
@@ -64,22 +64,22 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure
// TODO: Get Tenant specific date // TODO: Get Tenant specific date
// ensure closure date is not in the future // ensure closure date is not in the future
Date todaysDate = new Date(); final Date todaysDate = new Date();
Date closureDate = command.DateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue()); final Date closureDate = command.DateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue());
if (closureDate.after(todaysDate)) { throw new GLClosureInvalidException(GL_CLOSURE_INVALID_REASON.FUTURE_DATE, closureDate); } if (closureDate.after(todaysDate)) { throw new GLClosureInvalidException(GL_CLOSURE_INVALID_REASON.FUTURE_DATE, closureDate); }
// shouldn't be before an existing accounting closure // shouldn't be before an existing accounting closure
GLClosure latestGLClosure = glClosureRepository.getLatestGLClosureByBranch(officeId); final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(officeId);
if (latestGLClosure != null) { if (latestGLClosure != null) {
if (latestGLClosure.getClosingDate().after(closureDate)) { throw new GLClosureInvalidException( if (latestGLClosure.getClosingDate().after(closureDate)) { throw new GLClosureInvalidException(
GL_CLOSURE_INVALID_REASON.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate()); } GL_CLOSURE_INVALID_REASON.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate()); }
} }
GLClosure glClosure = GLClosure.fromJson(office, command); final GLClosure glClosure = GLClosure.fromJson(office, command);
this.glClosureRepository.saveAndFlush(glClosure); this.glClosureRepository.saveAndFlush(glClosure);
return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(officeId) return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(officeId)
.withEntityId(glClosure.getId()).build(); .withEntityId(glClosure.getId()).build();
} catch (DataIntegrityViolationException dve) { } catch (final DataIntegrityViolationException dve) {
handleGLClosureIntegrityIssues(command, dve); handleGLClosureIntegrityIssues(command, dve);
return CommandProcessingResult.empty(); return CommandProcessingResult.empty();
} }
@@ -87,12 +87,12 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure
@Transactional @Transactional
@Override @Override
public CommandProcessingResult updateGLClosure(Long glClosureId, JsonCommand command) { public CommandProcessingResult updateGLClosure(final Long glClosureId, final JsonCommand command) {
final GLClosureCommand closureCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json()); final GLClosureCommand closureCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json());
closureCommand.validateForUpdate(); closureCommand.validateForUpdate();
// is the glClosure valid // is the glClosure valid
GLClosure glClosure = glClosureRepository.findOne(glClosureId); final GLClosure glClosure = this.glClosureRepository.findOne(glClosureId);
if (glClosure == null) { throw new GLClosureNotFoundException(glClosureId); } if (glClosure == null) { throw new GLClosureNotFoundException(glClosureId); }
final Map<String, Object> changesOnly = glClosure.update(command); final Map<String, Object> changesOnly = glClosure.update(command);
@@ -107,7 +107,7 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure
@Transactional @Transactional
@Override @Override
public CommandProcessingResult deleteGLClosure(Long glClosureId) { public CommandProcessingResult deleteGLClosure(final Long glClosureId) {
final GLClosure glClosure = this.glClosureRepository.findOne(glClosureId); final GLClosure glClosure = this.glClosureRepository.findOne(glClosureId);
if (glClosure == null) { throw new GLClosureNotFoundException(glClosureId); } if (glClosure == null) { throw new GLClosureNotFoundException(glClosureId); }
@@ -116,8 +116,8 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure
* check if any closures are present for this branch at a later date * check if any closures are present for this branch at a later date
* than this closure date * than this closure date
**/ **/
Date closureDate = glClosure.getClosingDate(); final Date closureDate = glClosure.getClosingDate();
GLClosure latestGLClosure = glClosureRepository.getLatestGLClosureByBranch(glClosure.getOffice().getId()); final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(glClosure.getOffice().getId());
if (latestGLClosure.getClosingDate().after(closureDate)) { throw new GLClosureInvalidDeleteException(latestGLClosure.getOffice() if (latestGLClosure.getClosingDate().after(closureDate)) { throw new GLClosureInvalidDeleteException(latestGLClosure.getOffice()
.getId(), latestGLClosure.getOffice().getName(), latestGLClosure.getClosingDate()); } .getId(), latestGLClosure.getOffice().getName(), latestGLClosure.getClosingDate()); }
@@ -130,8 +130,8 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure
* @param command * @param command
* @param dve * @param dve
*/ */
private void handleGLClosureIntegrityIssues(final JsonCommand command, DataIntegrityViolationException dve) { private void handleGLClosureIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause(); final Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("office_id_closing_date")) { throw new GLClosureDuplicateException( if (realCause.getMessage().contains("office_id_closing_date")) { throw new GLClosureDuplicateException(
command.longValueOfParameterNamed(GLClosureJsonInputParams.OFFICE_ID.getValue()), new LocalDate( command.longValueOfParameterNamed(GLClosureJsonInputParams.OFFICE_ID.getValue()), new LocalDate(
command.DateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue()))); } command.DateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue()))); }
@@ -31,13 +31,13 @@ public class AccountingConstants {
private static final Map<Integer, CASH_ACCOUNTS_FOR_LOAN> intToEnumMap = new HashMap<Integer, CASH_ACCOUNTS_FOR_LOAN>(); private static final Map<Integer, CASH_ACCOUNTS_FOR_LOAN> intToEnumMap = new HashMap<Integer, CASH_ACCOUNTS_FOR_LOAN>();
static { static {
for (CASH_ACCOUNTS_FOR_LOAN type : CASH_ACCOUNTS_FOR_LOAN.values()) { for (final CASH_ACCOUNTS_FOR_LOAN type : CASH_ACCOUNTS_FOR_LOAN.values()) {
intToEnumMap.put(type.value, type); intToEnumMap.put(type.value, type);
} }
} }
public static CASH_ACCOUNTS_FOR_LOAN fromInt(int i) { public static CASH_ACCOUNTS_FOR_LOAN fromInt(final int i) {
CASH_ACCOUNTS_FOR_LOAN type = intToEnumMap.get(Integer.valueOf(i)); final CASH_ACCOUNTS_FOR_LOAN type = intToEnumMap.get(Integer.valueOf(i));
return type; return type;
} }
} }
@@ -64,13 +64,13 @@ public class AccountingConstants {
private static final Map<Integer, ACCRUAL_ACCOUNTS_FOR_LOAN> intToEnumMap = new HashMap<Integer, ACCRUAL_ACCOUNTS_FOR_LOAN>(); private static final Map<Integer, ACCRUAL_ACCOUNTS_FOR_LOAN> intToEnumMap = new HashMap<Integer, ACCRUAL_ACCOUNTS_FOR_LOAN>();
static { static {
for (ACCRUAL_ACCOUNTS_FOR_LOAN type : ACCRUAL_ACCOUNTS_FOR_LOAN.values()) { for (final ACCRUAL_ACCOUNTS_FOR_LOAN type : ACCRUAL_ACCOUNTS_FOR_LOAN.values()) {
intToEnumMap.put(type.value, type); intToEnumMap.put(type.value, type);
} }
} }
public static ACCRUAL_ACCOUNTS_FOR_LOAN fromInt(int i) { public static ACCRUAL_ACCOUNTS_FOR_LOAN fromInt(final int i) {
ACCRUAL_ACCOUNTS_FOR_LOAN type = intToEnumMap.get(Integer.valueOf(i)); final ACCRUAL_ACCOUNTS_FOR_LOAN type = intToEnumMap.get(Integer.valueOf(i));
return type; return type;
} }
@@ -21,13 +21,14 @@ public class AccountingEnumerations {
} }
public static EnumOptionData gLAccountType(final GLAccountType accountType) { public static EnumOptionData gLAccountType(final GLAccountType accountType) {
EnumOptionData optionData = new EnumOptionData(accountType.getValue().longValue(), accountType.getCode(), accountType.toString()); final EnumOptionData optionData = new EnumOptionData(accountType.getValue().longValue(), accountType.getCode(),
accountType.toString());
return optionData; return optionData;
} }
public static List<EnumOptionData> gLAccountType(GLAccountType[] accountTypes) { public static List<EnumOptionData> gLAccountType(final GLAccountType[] accountTypes) {
List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>(); final List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>();
for (GLAccountType accountType : accountTypes) { for (final GLAccountType accountType : accountTypes) {
optionDatas.add(gLAccountType(accountType)); optionDatas.add(gLAccountType(accountType));
} }
return optionDatas; return optionDatas;
@@ -38,13 +39,14 @@ public class AccountingEnumerations {
} }
public static EnumOptionData gLAccountUsage(final GLAccountUsage accountUsage) { public static EnumOptionData gLAccountUsage(final GLAccountUsage accountUsage) {
EnumOptionData optionData = new EnumOptionData(accountUsage.getValue().longValue(), accountUsage.getCode(), accountUsage.toString()); final EnumOptionData optionData = new EnumOptionData(accountUsage.getValue().longValue(), accountUsage.getCode(),
accountUsage.toString());
return optionData; return optionData;
} }
public static List<EnumOptionData> gLAccountUsage(GLAccountUsage[] accountUsages) { public static List<EnumOptionData> gLAccountUsage(final GLAccountUsage[] accountUsages) {
List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>(); final List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>();
for (GLAccountUsage accountUsage : accountUsages) { for (final GLAccountUsage accountUsage : accountUsages) {
optionDatas.add(gLAccountUsage(accountUsage)); optionDatas.add(gLAccountUsage(accountUsage));
} }
return optionDatas; return optionDatas;
@@ -55,14 +57,14 @@ public class AccountingEnumerations {
} }
public static EnumOptionData journalEntryType(final JournalEntryType journalEntryType) { public static EnumOptionData journalEntryType(final JournalEntryType journalEntryType) {
EnumOptionData optionData = new EnumOptionData(journalEntryType.getValue().longValue(), journalEntryType.getCode(), final EnumOptionData optionData = new EnumOptionData(journalEntryType.getValue().longValue(), journalEntryType.getCode(),
journalEntryType.toString()); journalEntryType.toString());
return optionData; return optionData;
} }
public static List<EnumOptionData> journalEntryTypes(JournalEntryType[] journalEntryTypes) { public static List<EnumOptionData> journalEntryTypes(final JournalEntryType[] journalEntryTypes) {
List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>(); final List<EnumOptionData> optionDatas = new ArrayList<EnumOptionData>();
for (JournalEntryType journalEntryType : journalEntryTypes) { for (final JournalEntryType journalEntryType : journalEntryTypes) {
optionDatas.add(journalEntryType(journalEntryType)); optionDatas.add(journalEntryType(journalEntryType));
} }
return optionDatas; return optionDatas;
@@ -73,7 +75,7 @@ public class AccountingEnumerations {
} }
public static EnumOptionData portfolioProductType(final PortfolioProductType portfolioProductType) { public static EnumOptionData portfolioProductType(final PortfolioProductType portfolioProductType) {
EnumOptionData optionData = new EnumOptionData(portfolioProductType.getValue().longValue(), portfolioProductType.getCode(), final EnumOptionData optionData = new EnumOptionData(portfolioProductType.getValue().longValue(), portfolioProductType.getCode(),
portfolioProductType.toString()); portfolioProductType.toString());
return optionData; return optionData;
} }
@@ -7,8 +7,8 @@ import java.util.Set;
* Enum of all parameters passed in while creating/updating a loan product * Enum of all parameters passed in while creating/updating a loan product
***/ ***/
public enum GLAccountJsonInputParams { public enum GLAccountJsonInputParams {
ID("id"), NAME("name"), PARENT_ID("parentId"), GL_CODE("glCode"), DISABLED("disabled"), MANUAL_ENTRIES_ALLOWED( ID("id"), NAME("name"), PARENT_ID("parentId"), GL_CODE("glCode"), DISABLED("disabled"), MANUAL_ENTRIES_ALLOWED("manualEntriesAllowed"), TYPE(
"manualEntriesAllowed"), TYPE("type"), USAGE("usage"), DESCRIPTION("description"); "type"), USAGE("usage"), DESCRIPTION("description");
private final String value; private final String value;
@@ -18,7 +18,7 @@ public enum GLAccountJsonInputParams {
private static final Set<String> values = new HashSet<String>(); private static final Set<String> values = new HashSet<String>();
static { static {
for (GLAccountJsonInputParams type : GLAccountJsonInputParams.values()) { for (final GLAccountJsonInputParams type : GLAccountJsonInputParams.values()) {
values.add(type.value); values.add(type.value);
} }
} }
@@ -49,8 +49,8 @@ public class GLAccountsApiResource {
private final String resourceNameForPermission = "GLACCOUNT"; private final String resourceNameForPermission = "GLACCOUNT";
private GLAccountReadPlatformService glAccountReadPlatformService; private final GLAccountReadPlatformService glAccountReadPlatformService;
private AccountingDropdownReadPlatformService dropdownReadPlatformService; private final AccountingDropdownReadPlatformService dropdownReadPlatformService;
private final DefaultToApiJsonSerializer<GLAccountData> apiJsonSerializerService; private final DefaultToApiJsonSerializer<GLAccountData> apiJsonSerializerService;
private final ApiRequestParameterHelper apiRequestParameterHelper; private final ApiRequestParameterHelper apiRequestParameterHelper;
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
@@ -75,12 +75,12 @@ public class GLAccountsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveNewAccountDetails(@Context final UriInfo uriInfo) { public String retrieveNewAccountDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
GLAccountData glAccountData = this.glAccountReadPlatformService.retrieveNewGLAccountDetails(); GLAccountData glAccountData = this.glAccountReadPlatformService.retrieveNewGLAccountDetails();
glAccountData = handleTemplate(glAccountData); glAccountData = handleTemplate(glAccountData);
final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.apiJsonSerializerService.serialize(settings, glAccountData, RESPONSE_DATA_PARAMETERS); return this.apiJsonSerializerService.serialize(settings, glAccountData, RESPONSE_DATA_PARAMETERS);
} }
@@ -91,11 +91,11 @@ public class GLAccountsApiResource {
@QueryParam("searchParam") final String searchParam, @QueryParam("usage") final Integer usage, @QueryParam("searchParam") final String searchParam, @QueryParam("usage") final Integer usage,
@QueryParam("manualEntriesAllowed") final Boolean manualEntriesAllowed, @QueryParam("disabled") final Boolean disabled) { @QueryParam("manualEntriesAllowed") final Boolean manualEntriesAllowed, @QueryParam("disabled") final Boolean disabled) {
context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
final List<GLAccountData> glAccountDatas = this.glAccountReadPlatformService.retrieveAllGLAccounts(type, searchParam, usage, final List<GLAccountData> glAccountDatas = this.glAccountReadPlatformService.retrieveAllGLAccounts(type, searchParam, usage,
manualEntriesAllowed, disabled); manualEntriesAllowed, disabled);
final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.apiJsonSerializerService.serialize(settings, glAccountDatas, RESPONSE_DATA_PARAMETERS); return this.apiJsonSerializerService.serialize(settings, glAccountDatas, RESPONSE_DATA_PARAMETERS);
} }
@@ -105,9 +105,9 @@ public class GLAccountsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String retreiveAccount(@PathParam("glAccountId") final Long glAccountId, @Context final UriInfo uriInfo) { public String retreiveAccount(@PathParam("glAccountId") final Long glAccountId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
GLAccountData glAccountData = this.glAccountReadPlatformService.retrieveGLAccountById(glAccountId); GLAccountData glAccountData = this.glAccountReadPlatformService.retrieveGLAccountById(glAccountId);
if (settings.isTemplate()) { if (settings.isTemplate()) {
@@ -155,9 +155,9 @@ public class GLAccountsApiResource {
return this.apiJsonSerializerService.serialize(result); return this.apiJsonSerializerService.serialize(result);
} }
private GLAccountData handleTemplate(GLAccountData glAccountData) { private GLAccountData handleTemplate(final GLAccountData glAccountData) {
List<EnumOptionData> accountTypeOptions = dropdownReadPlatformService.retrieveGLAccountTypeOptions(); final List<EnumOptionData> accountTypeOptions = this.dropdownReadPlatformService.retrieveGLAccountTypeOptions();
List<EnumOptionData> usageOptions = dropdownReadPlatformService.retrieveGLAccountUsageOptions(); final List<EnumOptionData> usageOptions = this.dropdownReadPlatformService.retrieveGLAccountUsageOptions();
return new GLAccountData(glAccountData, accountTypeOptions, usageOptions); return new GLAccountData(glAccountData, accountTypeOptions, usageOptions);
} }
} }
@@ -46,12 +46,11 @@ public class GLAccountCommand {
public void validateForCreate() { public void validateForCreate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLAccount"); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLAccount");
baseDataValidator.reset().parameter(GLAccountJsonInputParams.NAME.getValue()).value(this.name).notBlank() baseDataValidator.reset().parameter(GLAccountJsonInputParams.NAME.getValue()).value(this.name).notBlank().notExceedingLengthOf(45);
.notExceedingLengthOf(45);
baseDataValidator.reset().parameter(GLAccountJsonInputParams.GL_CODE.getValue()).value(this.glCode).notBlank() baseDataValidator.reset().parameter(GLAccountJsonInputParams.GL_CODE.getValue()).value(this.glCode).notBlank()
.notExceedingLengthOf(45); .notExceedingLengthOf(45);
@@ -68,17 +67,17 @@ public class GLAccountCommand {
baseDataValidator.reset().parameter(GLAccountJsonInputParams.DESCRIPTION.getValue()).value(this.description).ignoreIfNull() baseDataValidator.reset().parameter(GLAccountJsonInputParams.DESCRIPTION.getValue()).value(this.description).ignoreIfNull()
.notExceedingLengthOf(500); .notExceedingLengthOf(500);
baseDataValidator.reset().parameter(GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED.getValue()) baseDataValidator.reset().parameter(GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED.getValue()).value(this.manualEntriesAllowed)
.value(this.manualEntriesAllowed).notBlank(); .notBlank();
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors); } "Validation errors exist.", dataValidationErrors); }
} }
public void validateForUpdate() { public void validateForUpdate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLAccount"); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLAccount");
baseDataValidator.reset().parameter(GLAccountJsonInputParams.NAME.getValue()).value(this.name).ignoreIfNull().notBlank() baseDataValidator.reset().parameter(GLAccountJsonInputParams.NAME.getValue()).value(this.name).ignoreIfNull().notBlank()
.notExceedingLengthOf(45); .notExceedingLengthOf(45);
@@ -49,7 +49,8 @@ public class GLAccountData {
this.usageOptions = null; this.usageOptions = null;
} }
public GLAccountData(GLAccountData accountData, List<EnumOptionData> accountTypeOptions, List<EnumOptionData> usageOptions) { public GLAccountData(final GLAccountData accountData, final List<EnumOptionData> accountTypeOptions,
final List<EnumOptionData> usageOptions) {
this.id = accountData.id; this.id = accountData.id;
this.name = accountData.name; this.name = accountData.name;
this.parentId = accountData.parentId; this.parentId = accountData.parentId;
@@ -27,9 +27,9 @@ public class LoanTransactionDTO {
private boolean contra; private boolean contra;
private boolean writeOff; private boolean writeOff;
public LoanTransactionDTO(String transactionId, Date transactionDate, BigDecimal amount, BigDecimal principal, BigDecimal interest, public LoanTransactionDTO(final String transactionId, final Date transactionDate, final BigDecimal amount, final BigDecimal principal,
BigDecimal fees, BigDecimal penalties, boolean disbursement, boolean repayment, boolean repaymentAtDisbursement, final BigDecimal interest, final BigDecimal fees, final BigDecimal penalties, final boolean disbursement,
boolean contra, boolean writeOff) { final boolean repayment, final boolean repaymentAtDisbursement, final boolean contra, final boolean writeOff) {
this.transactionId = transactionId; this.transactionId = transactionId;
this.transactionDate = transactionDate; this.transactionDate = transactionDate;
this.amount = amount; this.amount = amount;
@@ -48,7 +48,7 @@ public class LoanTransactionDTO {
return this.transactionDate; return this.transactionDate;
} }
public void setTransactionDate(Date transactionDate) { public void setTransactionDate(final Date transactionDate) {
this.transactionDate = transactionDate; this.transactionDate = transactionDate;
} }
@@ -56,7 +56,7 @@ public class LoanTransactionDTO {
return this.transactionId; return this.transactionId;
} }
public void setTransactionId(String transactionId) { public void setTransactionId(final String transactionId) {
this.transactionId = transactionId; this.transactionId = transactionId;
} }
@@ -64,7 +64,7 @@ public class LoanTransactionDTO {
return this.amount; return this.amount;
} }
public void setAmount(BigDecimal amount) { public void setAmount(final BigDecimal amount) {
this.amount = amount; this.amount = amount;
} }
@@ -72,7 +72,7 @@ public class LoanTransactionDTO {
return this.principal; return this.principal;
} }
public void setPrincipal(BigDecimal principal) { public void setPrincipal(final BigDecimal principal) {
this.principal = principal; this.principal = principal;
} }
@@ -80,7 +80,7 @@ public class LoanTransactionDTO {
return this.interest; return this.interest;
} }
public void setInterest(BigDecimal interest) { public void setInterest(final BigDecimal interest) {
this.interest = interest; this.interest = interest;
} }
@@ -88,7 +88,7 @@ public class LoanTransactionDTO {
return this.fees; return this.fees;
} }
public void setFees(BigDecimal fees) { public void setFees(final BigDecimal fees) {
this.fees = fees; this.fees = fees;
} }
@@ -96,7 +96,7 @@ public class LoanTransactionDTO {
return this.penalties; return this.penalties;
} }
public void setPenalties(BigDecimal penalties) { public void setPenalties(final BigDecimal penalties) {
this.penalties = penalties; this.penalties = penalties;
} }
@@ -104,7 +104,7 @@ public class LoanTransactionDTO {
return this.disbursement; return this.disbursement;
} }
public void setDisbursement(boolean disbursement) { public void setDisbursement(final boolean disbursement) {
this.disbursement = disbursement; this.disbursement = disbursement;
} }
@@ -112,7 +112,7 @@ public class LoanTransactionDTO {
return this.repayment; return this.repayment;
} }
public void setRepayment(boolean repayment) { public void setRepayment(final boolean repayment) {
this.repayment = repayment; this.repayment = repayment;
} }
@@ -120,7 +120,7 @@ public class LoanTransactionDTO {
return this.contra; return this.contra;
} }
public void setContra(boolean contra) { public void setContra(final boolean contra) {
this.contra = contra; this.contra = contra;
} }
@@ -128,7 +128,7 @@ public class LoanTransactionDTO {
return this.writeOff; return this.writeOff;
} }
public void setWriteOff(boolean writeOff) { public void setWriteOff(final boolean writeOff) {
this.writeOff = writeOff; this.writeOff = writeOff;
} }
@@ -136,7 +136,7 @@ public class LoanTransactionDTO {
return this.repaymentAtDisbursement; return this.repaymentAtDisbursement;
} }
public void setRepaymentAtDisbursement(boolean repaymentAtDisbursement) { public void setRepaymentAtDisbursement(final boolean repaymentAtDisbursement) {
this.repaymentAtDisbursement = repaymentAtDisbursement; this.repaymentAtDisbursement = repaymentAtDisbursement;
} }
@@ -36,7 +36,7 @@ public class GLAccount extends AbstractPersistable<Long> {
@OneToMany(fetch = FetchType.LAZY) @OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id") @JoinColumn(name = "parent_id")
private List<GLAccount> children = new LinkedList<GLAccount>(); private final List<GLAccount> children = new LinkedList<GLAccount>();
@Column(name = "name", nullable = false, length = 45) @Column(name = "name", nullable = false, length = 45)
private String name; private String name;
@@ -80,15 +80,15 @@ public class GLAccount extends AbstractPersistable<Long> {
this.parent = parent; this.parent = parent;
} }
public static GLAccount fromJson(GLAccount parent, final JsonCommand command) { public static GLAccount fromJson(final GLAccount parent, final JsonCommand command) {
String name = command.stringValueOfParameterNamed(GLAccountJsonInputParams.NAME.getValue()); final String name = command.stringValueOfParameterNamed(GLAccountJsonInputParams.NAME.getValue());
String glCode = command.stringValueOfParameterNamed(GLAccountJsonInputParams.GL_CODE.getValue()); final String glCode = command.stringValueOfParameterNamed(GLAccountJsonInputParams.GL_CODE.getValue());
boolean disabled = command.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.DISABLED.getValue()); final boolean disabled = command.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.DISABLED.getValue());
boolean manualEntriesAllowed = command.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED final boolean manualEntriesAllowed = command.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED
.getValue()); .getValue());
Integer usage = command.integerValueSansLocaleOfParameterNamed(GLAccountJsonInputParams.USAGE.getValue()); final Integer usage = command.integerValueSansLocaleOfParameterNamed(GLAccountJsonInputParams.USAGE.getValue());
Integer type = command.integerValueSansLocaleOfParameterNamed(GLAccountJsonInputParams.TYPE.getValue()); final Integer type = command.integerValueSansLocaleOfParameterNamed(GLAccountJsonInputParams.TYPE.getValue());
String description = command.stringValueOfParameterNamed(GLAccountJsonInputParams.DESCRIPTION.getValue()); final String description = command.stringValueOfParameterNamed(GLAccountJsonInputParams.DESCRIPTION.getValue());
return new GLAccount(parent, name, glCode, disabled, manualEntriesAllowed, type, usage, description); return new GLAccount(parent, name, glCode, disabled, manualEntriesAllowed, type, usage, description);
} }
@@ -106,7 +106,7 @@ public class GLAccount extends AbstractPersistable<Long> {
} }
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName, private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
Integer propertyToBeUpdated, boolean sansLocale) { final Integer propertyToBeUpdated, final boolean sansLocale) {
boolean changeDetected = false; boolean changeDetected = false;
if (sansLocale) { if (sansLocale) {
changeDetected = command.isChangeInIntegerSansLocaleParameterNamed(paramName, propertyToBeUpdated); changeDetected = command.isChangeInIntegerSansLocaleParameterNamed(paramName, propertyToBeUpdated);
@@ -131,7 +131,7 @@ public class GLAccount extends AbstractPersistable<Long> {
} }
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName, private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
String propertyToBeUpdated) { final String propertyToBeUpdated) {
if (command.isChangeInStringParameterNamed(paramName, propertyToBeUpdated)) { if (command.isChangeInStringParameterNamed(paramName, propertyToBeUpdated)) {
final String newValue = command.stringValueOfParameterNamed(paramName); final String newValue = command.stringValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
@@ -147,7 +147,7 @@ public class GLAccount extends AbstractPersistable<Long> {
} }
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName, private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
Long propertyToBeUpdated) { final Long propertyToBeUpdated) {
if (command.isChangeInLongParameterNamed(paramName, propertyToBeUpdated)) { if (command.isChangeInLongParameterNamed(paramName, propertyToBeUpdated)) {
final Long newValue = command.longValueOfParameterNamed(paramName); final Long newValue = command.longValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
@@ -159,7 +159,7 @@ public class GLAccount extends AbstractPersistable<Long> {
} }
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName, private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
boolean propertyToBeUpdated) { final boolean propertyToBeUpdated) {
if (command.isChangeInBooleanParameterNamed(paramName, propertyToBeUpdated)) { if (command.isChangeInBooleanParameterNamed(paramName, propertyToBeUpdated)) {
final Boolean newValue = command.booleanObjectValueOfParameterNamed(paramName); final Boolean newValue = command.booleanObjectValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
@@ -25,7 +25,7 @@ public enum GLAccountType {
} }
public String getCode() { public String getCode() {
return code; return this.code;
} }
private static final Map<Integer, GLAccountType> intToEnumMap = new HashMap<Integer, GLAccountType>(); private static final Map<Integer, GLAccountType> intToEnumMap = new HashMap<Integer, GLAccountType>();
@@ -33,7 +33,7 @@ public enum GLAccountType {
private static int maxValue; private static int maxValue;
static { static {
int i = 0; int i = 0;
for (GLAccountType type : GLAccountType.values()) { for (final GLAccountType type : GLAccountType.values()) {
if (i == 0) { if (i == 0) {
minValue = type.value; minValue = type.value;
} }
@@ -48,8 +48,8 @@ public enum GLAccountType {
} }
} }
public static GLAccountType fromInt(int i) { public static GLAccountType fromInt(final int i) {
GLAccountType type = intToEnumMap.get(Integer.valueOf(i)); final GLAccountType type = intToEnumMap.get(Integer.valueOf(i));
return type; return type;
} }
@@ -25,7 +25,7 @@ public enum GLAccountUsage {
} }
public String getCode() { public String getCode() {
return code; return this.code;
} }
private static final Map<Integer, GLAccountUsage> intToEnumMap = new HashMap<Integer, GLAccountUsage>(); private static final Map<Integer, GLAccountUsage> intToEnumMap = new HashMap<Integer, GLAccountUsage>();
@@ -33,7 +33,7 @@ public enum GLAccountUsage {
private static int maxValue; private static int maxValue;
static { static {
int i = 0; int i = 0;
for (GLAccountUsage type : GLAccountUsage.values()) { for (final GLAccountUsage type : GLAccountUsage.values()) {
if (i == 0) { if (i == 0) {
minValue = type.value; minValue = type.value;
} }
@@ -48,8 +48,8 @@ public enum GLAccountUsage {
} }
} }
public static GLAccountUsage fromInt(int i) { public static GLAccountUsage fromInt(final int i) {
GLAccountUsage type = intToEnumMap.get(Integer.valueOf(i)); final GLAccountUsage type = intToEnumMap.get(Integer.valueOf(i));
return type; return type;
} }
@@ -13,7 +13,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul
*/ */
public class GLAccountInvalidParentException extends AbstractPlatformDomainRuleException { public class GLAccountInvalidParentException extends AbstractPlatformDomainRuleException {
public GLAccountInvalidParentException(long glAccountId) { public GLAccountInvalidParentException(final long glAccountId) {
super("error.msg.glaccount.parent.invalid", "The account with id " + glAccountId super("error.msg.glaccount.parent.invalid", "The account with id " + glAccountId
+ " is a 'Detail' account and cannot be used as a parent", glAccountId); + " is a 'Detail' account and cannot be used as a parent", glAccountId);
} }
@@ -38,25 +38,25 @@ public final class GLAccountCommandFromApiJsonDeserializer extends AbstractFromA
} }
@Override @Override
public GLAccountCommand commandFromApiJson(String json) { public GLAccountCommand commandFromApiJson(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType(); final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
Set<String> supportedParameters = GLAccountJsonInputParams.getAllValues(); final Set<String> supportedParameters = GLAccountJsonInputParams.getAllValues();
fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters);
final JsonElement element = fromApiJsonHelper.parse(json); final JsonElement element = this.fromApiJsonHelper.parse(json);
final Long id = fromApiJsonHelper.extractLongNamed(GLAccountJsonInputParams.ID.getValue(), element); final Long id = this.fromApiJsonHelper.extractLongNamed(GLAccountJsonInputParams.ID.getValue(), element);
final String name = fromApiJsonHelper.extractStringNamed(GLAccountJsonInputParams.NAME.getValue(), element); final String name = this.fromApiJsonHelper.extractStringNamed(GLAccountJsonInputParams.NAME.getValue(), element);
final Long parentId = fromApiJsonHelper.extractLongNamed(GLAccountJsonInputParams.PARENT_ID.getValue(), element); final Long parentId = this.fromApiJsonHelper.extractLongNamed(GLAccountJsonInputParams.PARENT_ID.getValue(), element);
final String glCode = fromApiJsonHelper.extractStringNamed(GLAccountJsonInputParams.GL_CODE.getValue(), element); final String glCode = this.fromApiJsonHelper.extractStringNamed(GLAccountJsonInputParams.GL_CODE.getValue(), element);
final Boolean disabled = fromApiJsonHelper.extractBooleanNamed(GLAccountJsonInputParams.DISABLED.getValue(), element); final Boolean disabled = this.fromApiJsonHelper.extractBooleanNamed(GLAccountJsonInputParams.DISABLED.getValue(), element);
final Boolean manualEntriesAllowed = fromApiJsonHelper.extractBooleanNamed( final Boolean manualEntriesAllowed = this.fromApiJsonHelper.extractBooleanNamed(
GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED.getValue(), element); GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED.getValue(), element);
final Integer type = fromApiJsonHelper.extractIntegerSansLocaleNamed(GLAccountJsonInputParams.TYPE.getValue(), element); final Integer type = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(GLAccountJsonInputParams.TYPE.getValue(), element);
final Integer usage = fromApiJsonHelper.extractIntegerSansLocaleNamed(GLAccountJsonInputParams.USAGE.getValue(), element); final Integer usage = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(GLAccountJsonInputParams.USAGE.getValue(), element);
final String description = fromApiJsonHelper.extractStringNamed(GLAccountJsonInputParams.DESCRIPTION.getValue(), element); final String description = this.fromApiJsonHelper.extractStringNamed(GLAccountJsonInputParams.DESCRIPTION.getValue(), element);
return new GLAccountCommand(id, name, parentId, glCode, disabled, manualEntriesAllowed, type, usage, description); return new GLAccountCommand(id, name, parentId, glCode, disabled, manualEntriesAllowed, type, usage, description);
} }
@@ -47,25 +47,25 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe
@Override @Override
public GLAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { public GLAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = rs.getLong("id"); final Long id = rs.getLong("id");
String name = rs.getString("name"); final String name = rs.getString("name");
Long parentId = JdbcSupport.getLong(rs,"parentId"); final Long parentId = JdbcSupport.getLong(rs, "parentId");
String glCode = rs.getString("glCode"); final String glCode = rs.getString("glCode");
boolean disabled = rs.getBoolean("disabled"); final boolean disabled = rs.getBoolean("disabled");
boolean manualEntriesAllowed = rs.getBoolean("manualEntriesAllowed"); final boolean manualEntriesAllowed = rs.getBoolean("manualEntriesAllowed");
final int accountTypeId = JdbcSupport.getInteger(rs, "classification"); final int accountTypeId = JdbcSupport.getInteger(rs, "classification");
final EnumOptionData accountType = AccountingEnumerations.gLAccountType(accountTypeId); final EnumOptionData accountType = AccountingEnumerations.gLAccountType(accountTypeId);
final int usageId = JdbcSupport.getInteger(rs, "accountUsage"); final int usageId = JdbcSupport.getInteger(rs, "accountUsage");
final EnumOptionData usage = AccountingEnumerations.gLAccountUsage(usageId); final EnumOptionData usage = AccountingEnumerations.gLAccountUsage(usageId);
String description = rs.getString("description"); final String description = rs.getString("description");
return new GLAccountData(id, name, parentId, glCode, disabled, manualEntriesAllowed, accountType, usage, description); return new GLAccountData(id, name, parentId, glCode, disabled, manualEntriesAllowed, accountType, usage, description);
} }
} }
@Override @Override
public List<GLAccountData> retrieveAllGLAccounts(Integer accountClassification, String searchParam, Integer usage, public List<GLAccountData> retrieveAllGLAccounts(final Integer accountClassification, final String searchParam, final Integer usage,
Boolean manualTransactionsAllowed, Boolean disabled) { final Boolean manualTransactionsAllowed, final Boolean disabled) {
if (accountClassification != null) { if (accountClassification != null) {
if (!checkValidGLAccountType(accountClassification)) { throw new GLAccountInvalidClassificationException(accountClassification); } if (!checkValidGLAccountType(accountClassification)) { throw new GLAccountInvalidClassificationException(accountClassification); }
} }
@@ -74,9 +74,9 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe
if (!checkValidGLAccountUsage(usage)) { throw new GLAccountInvalidClassificationException(accountClassification); } if (!checkValidGLAccountUsage(usage)) { throw new GLAccountInvalidClassificationException(accountClassification); }
} }
GLAccountMapper rm = new GLAccountMapper(); final GLAccountMapper rm = new GLAccountMapper();
String sql = "select " + rm.schema(); String sql = "select " + rm.schema();
Object[] paramaterArray = new Object[3]; final Object[] paramaterArray = new Object[3];
int arrayPos = 0; int arrayPos = 0;
boolean filtersPresent = false; boolean filtersPresent = false;
if ((accountClassification != null) || StringUtils.isNotBlank(searchParam) || (usage != null) if ((accountClassification != null) || StringUtils.isNotBlank(searchParam) || (usage != null)
@@ -142,39 +142,39 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe
} }
sql = sql + " order by glCode"; sql = sql + " order by glCode";
Object[] finalObjectArray = Arrays.copyOf(paramaterArray, arrayPos); final Object[] finalObjectArray = Arrays.copyOf(paramaterArray, arrayPos);
return this.jdbcTemplate.query(sql, rm, finalObjectArray); return this.jdbcTemplate.query(sql, rm, finalObjectArray);
} }
@Override @Override
public GLAccountData retrieveGLAccountById(long glAccountId) { public GLAccountData retrieveGLAccountById(final long glAccountId) {
try { try {
GLAccountMapper rm = new GLAccountMapper(); final GLAccountMapper rm = new GLAccountMapper();
String sql = "select " + rm.schema() + " where id = ?"; final String sql = "select " + rm.schema() + " where id = ?";
GLAccountData glAccountData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { glAccountId }); final GLAccountData glAccountData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { glAccountId });
return glAccountData; return glAccountData;
} catch (EmptyResultDataAccessException e) { } catch (final EmptyResultDataAccessException e) {
throw new GLAccountNotFoundException(glAccountId); throw new GLAccountNotFoundException(glAccountId);
} }
} }
@Override @Override
public List<GLAccountData> retrieveAllEnabledDetailGLAccounts(GLAccountType accountType) { public List<GLAccountData> retrieveAllEnabledDetailGLAccounts(final GLAccountType accountType) {
return retrieveAllGLAccounts(accountType.getValue(), null, GLAccountUsage.DETAIL.getValue(), null, false); return retrieveAllGLAccounts(accountType.getValue(), null, GLAccountUsage.DETAIL.getValue(), null, false);
} }
private static boolean checkValidGLAccountType(final int type) { private static boolean checkValidGLAccountType(final int type) {
for (GLAccountType accountType : GLAccountType.values()) { for (final GLAccountType accountType : GLAccountType.values()) {
if (accountType.getValue().equals(type)) { return true; } if (accountType.getValue().equals(type)) { return true; }
} }
return false; return false;
} }
private static boolean checkValidGLAccountUsage(final int type) { private static boolean checkValidGLAccountUsage(final int type) {
for (GLAccountUsage accountUsage : GLAccountUsage.values()) { for (final GLAccountUsage accountUsage : GLAccountUsage.values()) {
if (accountUsage.getValue().equals(type)) { return true; } if (accountUsage.getValue().equals(type)) { return true; }
} }
return false; return false;
@@ -58,17 +58,17 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
accountCommand.validateForCreate(); accountCommand.validateForCreate();
// check parent is valid // check parent is valid
Long parentId = command.longValueOfParameterNamed(GLAccountJsonInputParams.PARENT_ID.getValue()); final Long parentId = command.longValueOfParameterNamed(GLAccountJsonInputParams.PARENT_ID.getValue());
GLAccount parentGLAccount = null; GLAccount parentGLAccount = null;
if (parentId != null) { if (parentId != null) {
parentGLAccount = validateParentGLAccount(parentId); parentGLAccount = validateParentGLAccount(parentId);
} }
GLAccount glAccount = GLAccount.fromJson(parentGLAccount, command); final GLAccount glAccount = GLAccount.fromJson(parentGLAccount, command);
this.glAccountRepository.saveAndFlush(glAccount); this.glAccountRepository.saveAndFlush(glAccount);
return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(glAccount.getId()).build(); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(glAccount.getId()).build();
} catch (DataIntegrityViolationException dve) { } catch (final DataIntegrityViolationException dve) {
handleGLAccountDataIntegrityIssues(command, dve); handleGLAccountDataIntegrityIssues(command, dve);
return CommandProcessingResult.empty(); return CommandProcessingResult.empty();
} }
@@ -82,14 +82,14 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
accountCommand.validateForUpdate(); accountCommand.validateForUpdate();
// is the glAccount valid // is the glAccount valid
GLAccount glAccount = glAccountRepository.findOne(glAccountId); final GLAccount glAccount = this.glAccountRepository.findOne(glAccountId);
if (glAccount == null) { throw new GLAccountNotFoundException(glAccountId); } if (glAccount == null) { throw new GLAccountNotFoundException(glAccountId); }
final Map<String, Object> changesOnly = glAccount.update(command); final Map<String, Object> changesOnly = glAccount.update(command);
// is the new parent valid // is the new parent valid
if (changesOnly.containsKey(GLAccountJsonInputParams.PARENT_ID.getValue())) { if (changesOnly.containsKey(GLAccountJsonInputParams.PARENT_ID.getValue())) {
Long parentId = command.longValueOfParameterNamed(GLAccountJsonInputParams.PARENT_ID.getValue()); final Long parentId = command.longValueOfParameterNamed(GLAccountJsonInputParams.PARENT_ID.getValue());
validateParentGLAccount(parentId); validateParentGLAccount(parentId);
} }
@@ -99,7 +99,8 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
**/ **/
if (changesOnly.containsKey(GLAccountJsonInputParams.USAGE.getValue())) { if (changesOnly.containsKey(GLAccountJsonInputParams.USAGE.getValue())) {
if (glAccount.isHeaderAccount()) { if (glAccount.isHeaderAccount()) {
List<JournalEntry> journalEntriesForAccount = glJournalEntryRepository.findFirstJournalEntryForAccount(glAccountId); final List<JournalEntry> journalEntriesForAccount = this.glJournalEntryRepository
.findFirstJournalEntryForAccount(glAccountId);
if (journalEntriesForAccount.size() > 0) { throw new GLAccountInvalidUpdateException( if (journalEntriesForAccount.size() > 0) { throw new GLAccountInvalidUpdateException(
GL_ACCOUNT_INVALID_UPDATE_REASON.TRANSANCTIONS_LOGGED, glAccountId); } GL_ACCOUNT_INVALID_UPDATE_REASON.TRANSANCTIONS_LOGGED, glAccountId); }
} }
@@ -111,7 +112,7 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(glAccount.getId()) return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(glAccount.getId())
.with(changesOnly).build(); .with(changesOnly).build();
} catch (DataIntegrityViolationException dve) { } catch (final DataIntegrityViolationException dve) {
handleGLAccountDataIntegrityIssues(command, dve); handleGLAccountDataIntegrityIssues(command, dve);
return CommandProcessingResult.empty(); return CommandProcessingResult.empty();
} }
@@ -129,7 +130,7 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
GL_ACCOUNT_INVALID_DELETE_REASON.HAS_CHILDREN, glAccountId); } GL_ACCOUNT_INVALID_DELETE_REASON.HAS_CHILDREN, glAccountId); }
// does this account have transactions logged against it // does this account have transactions logged against it
List<JournalEntry> journalEntriesForAccount = glJournalEntryRepository.findFirstJournalEntryForAccount(glAccountId); final List<JournalEntry> journalEntriesForAccount = this.glJournalEntryRepository.findFirstJournalEntryForAccount(glAccountId);
if (journalEntriesForAccount.size() > 0) { throw new GLAccountInvalidDeleteException( if (journalEntriesForAccount.size() > 0) { throw new GLAccountInvalidDeleteException(
GL_ACCOUNT_INVALID_DELETE_REASON.TRANSANCTIONS_LOGGED, glAccountId); } GL_ACCOUNT_INVALID_DELETE_REASON.TRANSANCTIONS_LOGGED, glAccountId); }
this.glAccountRepository.delete(glAccount); this.glAccountRepository.delete(glAccount);
@@ -141,9 +142,9 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
* @param command * @param command
* @return * @return
*/ */
private GLAccount validateParentGLAccount(Long parentAccountId) { private GLAccount validateParentGLAccount(final Long parentAccountId) {
GLAccount parentGLAccount; GLAccount parentGLAccount;
parentGLAccount = glAccountRepository.findOne(parentAccountId); parentGLAccount = this.glAccountRepository.findOne(parentAccountId);
if (parentGLAccount == null) { throw new GLAccountNotFoundException(parentAccountId); } if (parentGLAccount == null) { throw new GLAccountNotFoundException(parentAccountId); }
// ensure parent is not a detail account // ensure parent is not a detail account
if (parentGLAccount.isHeaderAccount()) { throw new GLAccountInvalidParentException(parentAccountId); } if (parentGLAccount.isHeaderAccount()) { throw new GLAccountInvalidParentException(parentAccountId); }
@@ -154,10 +155,10 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
* @param command * @param command
* @param dve * @param dve
*/ */
private void handleGLAccountDataIntegrityIssues(final JsonCommand command, DataIntegrityViolationException dve) { private void handleGLAccountDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause(); final Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("acc_gl_code")) { if (realCause.getMessage().contains("acc_gl_code")) {
String glCode = command.stringValueOfParameterNamed(GLAccountJsonInputParams.GL_CODE.getValue()); final String glCode = command.stringValueOfParameterNamed(GLAccountJsonInputParams.GL_CODE.getValue());
throw new GLAccountDuplicateException(glCode); throw new GLAccountDuplicateException(glCode);
} }
@@ -28,7 +28,7 @@ public class DateParam {
private final Date date; private final Date date;
public DateParam(String dateStr) throws WebApplicationException { public DateParam(final String dateStr) throws WebApplicationException {
if (StringUtils.isEmpty(dateStr)) { if (StringUtils.isEmpty(dateStr)) {
this.date = null; this.date = null;
return; return;
@@ -36,13 +36,13 @@ public class DateParam {
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try { try {
this.date = dateFormat.parse(dateStr); this.date = dateFormat.parse(dateStr);
} catch (ParseException e) { } catch (final ParseException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST) throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
.entity("Couldn't parse date string: Expected format yyyy-mm-dd " + e.getMessage()).build()); .entity("Couldn't parse date string: Expected format yyyy-mm-dd " + e.getMessage()).build());
} }
} }
public Date getDate() { public Date getDate() {
return date; return this.date;
} }
} }
@@ -44,12 +44,12 @@ import org.springframework.stereotype.Component;
public class JournalEntriesApiResource { public class JournalEntriesApiResource {
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<String>(Arrays.asList("id", "officeId", "officeName", private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<String>(Arrays.asList("id", "officeId", "officeName",
"glAccountName", "glAccountId", "glAccountCode", "glAccountType", "entryDate", "entryType", "amount", "transactionId", "glAccountName", "glAccountId", "glAccountCode", "glAccountType", "transactionDate", "entryType", "amount", "transactionId",
"portfolioGenerated", "entityType", "entityId", "createdByUserId", "createdDate", "createdByUserName", "comments", "reversed")); "portfolioGenerated", "entityType", "entityId", "createdByUserId", "createdDate", "createdByUserName", "comments", "reversed"));
private final String resourceNameForPermission = "JOURNALENTRY"; private final String resourceNameForPermission = "JOURNALENTRY";
private JournalEntryReadPlatformService journalEntryReadPlatformService; private final JournalEntryReadPlatformService journalEntryReadPlatformService;
private final DefaultToApiJsonSerializer<JournalEntryData> apiJsonSerializerService; private final DefaultToApiJsonSerializer<JournalEntryData> apiJsonSerializerService;
private final ApiRequestParameterHelper apiRequestParameterHelper; private final ApiRequestParameterHelper apiRequestParameterHelper;
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
@@ -74,9 +74,9 @@ public class JournalEntriesApiResource {
public String retrieveAllJournalEntries(@Context final UriInfo uriInfo, @QueryParam("officeId") final Long officeId, public String retrieveAllJournalEntries(@Context final UriInfo uriInfo, @QueryParam("officeId") final Long officeId,
@QueryParam("glAccountId") final Long glAccountId, @QueryParam("portfolioGenerated") final Boolean portfolioGenerated, @QueryParam("glAccountId") final Long glAccountId, @QueryParam("portfolioGenerated") final Boolean portfolioGenerated,
@QueryParam("fromDate") final DateParam fromDateParam, @QueryParam("toDate") final DateParam toDateParam, @QueryParam("fromDate") final DateParam fromDateParam, @QueryParam("toDate") final DateParam toDateParam,
@QueryParam("transactionId") String transactionId) { @QueryParam("transactionId") final String transactionId) {
context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
List<JournalEntryData> glJournalEntryDatas = null; List<JournalEntryData> glJournalEntryDatas = null;
// get dates from date params // get dates from date params
@@ -95,7 +95,7 @@ public class JournalEntriesApiResource {
glJournalEntryDatas = this.journalEntryReadPlatformService.retrieveRelatedJournalEntries(transactionId); glJournalEntryDatas = this.journalEntryReadPlatformService.retrieveRelatedJournalEntries(transactionId);
} }
final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.apiJsonSerializerService.serialize(settings, glJournalEntryDatas, RESPONSE_DATA_PARAMETERS); return this.apiJsonSerializerService.serialize(settings, glJournalEntryDatas, RESPONSE_DATA_PARAMETERS);
} }
@@ -105,10 +105,10 @@ public class JournalEntriesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String retreiveJournalEntryById(@PathParam("journalEntryId") final Long journalEntryId, @Context final UriInfo uriInfo) { public String retreiveJournalEntryById(@PathParam("journalEntryId") final Long journalEntryId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
final JournalEntryData glJournalEntryData = this.journalEntryReadPlatformService.retrieveGLJournalEntryById(journalEntryId); final JournalEntryData glJournalEntryData = this.journalEntryReadPlatformService.retrieveGLJournalEntryById(journalEntryId);
final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.apiJsonSerializerService.serialize(settings, glJournalEntryData, RESPONSE_DATA_PARAMETERS); return this.apiJsonSerializerService.serialize(settings, glJournalEntryData, RESPONSE_DATA_PARAMETERS);
} }
@@ -7,7 +7,7 @@ import java.util.Set;
* Enum of all parameters passed in while creating/updating a journal Entry * Enum of all parameters passed in while creating/updating a journal Entry
***/ ***/
public enum JournalEntryJsonInputParams { public enum JournalEntryJsonInputParams {
OFFICE_ID("officeId"), ENTRY_DATE("entryDate"), COMMENTS("comments"), CREDITS("credits"), DEBITS("debits"), LOCALE("locale"), DATE_FORMAT( OFFICE_ID("officeId"), TRANSACTION_DATE("transactionDate"), COMMENTS("comments"), CREDITS("credits"), DEBITS("debits"), LOCALE("locale"), DATE_FORMAT(
"dateFormat"); "dateFormat");
private final String value; private final String value;
@@ -18,7 +18,7 @@ public enum JournalEntryJsonInputParams {
private static final Set<String> values = new HashSet<String>(); private static final Set<String> values = new HashSet<String>();
static { static {
for (JournalEntryJsonInputParams type : JournalEntryJsonInputParams.values()) { for (final JournalEntryJsonInputParams type : JournalEntryJsonInputParams.values()) {
values.add(type.value); values.add(type.value);
} }
} }
@@ -19,16 +19,16 @@ import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidation
public class JournalEntryCommand { public class JournalEntryCommand {
private final Long officeId; private final Long officeId;
private final LocalDate entryDate; private final LocalDate transactionDate;
private final String comments; private final String comments;
private final SingleDebitOrCreditEntryCommand[] credits; private final SingleDebitOrCreditEntryCommand[] credits;
private final SingleDebitOrCreditEntryCommand[] debits; private final SingleDebitOrCreditEntryCommand[] debits;
public JournalEntryCommand(Long officeId, LocalDate entryDate, String comments, SingleDebitOrCreditEntryCommand[] credits, public JournalEntryCommand(final Long officeId, final LocalDate transactionDate, final String comments,
SingleDebitOrCreditEntryCommand[] debits) { final SingleDebitOrCreditEntryCommand[] credits, final SingleDebitOrCreditEntryCommand[] debits) {
this.officeId = officeId; this.officeId = officeId;
this.entryDate = entryDate; this.transactionDate = transactionDate;
this.comments = comments; this.comments = comments;
this.credits = credits; this.credits = credits;
this.debits = debits; this.debits = debits;
@@ -36,11 +36,11 @@ public class JournalEntryCommand {
public void validateForCreate() { public void validateForCreate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLJournalEntry"); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("GLJournalEntry");
baseDataValidator.reset().parameter("entryDate").value(this.entryDate).notBlank(); baseDataValidator.reset().parameter("transactionDate").value(this.transactionDate).notBlank();
baseDataValidator.reset().parameter("officeId").value(this.officeId).notNull().integerGreaterThanZero(); baseDataValidator.reset().parameter("officeId").value(this.officeId).notNull().integerGreaterThanZero();
@@ -56,7 +56,7 @@ public class JournalEntryCommand {
validateSingleDebitOrCredit(baseDataValidator, "credits", 0, new SingleDebitOrCreditEntryCommand(null, null, null, null)); validateSingleDebitOrCredit(baseDataValidator, "credits", 0, new SingleDebitOrCreditEntryCommand(null, null, null, null));
} else { } else {
int i = 0; int i = 0;
for (SingleDebitOrCreditEntryCommand credit : this.credits) { for (final SingleDebitOrCreditEntryCommand credit : this.credits) {
validateSingleDebitOrCredit(baseDataValidator, "credits", i, credit); validateSingleDebitOrCredit(baseDataValidator, "credits", i, credit);
i++; i++;
} }
@@ -69,7 +69,7 @@ public class JournalEntryCommand {
validateSingleDebitOrCredit(baseDataValidator, "credits", 0, new SingleDebitOrCreditEntryCommand(null, null, null, null)); validateSingleDebitOrCredit(baseDataValidator, "credits", 0, new SingleDebitOrCreditEntryCommand(null, null, null, null));
} else { } else {
int i = 0; int i = 0;
for (SingleDebitOrCreditEntryCommand debit : this.debits) { for (final SingleDebitOrCreditEntryCommand debit : this.debits) {
validateSingleDebitOrCredit(baseDataValidator, "debits", i, debit); validateSingleDebitOrCredit(baseDataValidator, "debits", i, debit);
i++; i++;
} }
@@ -85,8 +85,8 @@ public class JournalEntryCommand {
* @param i * @param i
* @param credit * @param credit
*/ */
private void validateSingleDebitOrCredit(DataValidatorBuilder baseDataValidator, String paramSuffix, int arrayPos, private void validateSingleDebitOrCredit(final DataValidatorBuilder baseDataValidator, final String paramSuffix, final int arrayPos,
SingleDebitOrCreditEntryCommand credit) { final SingleDebitOrCreditEntryCommand credit) {
baseDataValidator.reset().parameter(paramSuffix + "[" + arrayPos + "].glAccountId").value(credit.getGlAccountId()).notNull() baseDataValidator.reset().parameter(paramSuffix + "[" + arrayPos + "].glAccountId").value(credit.getGlAccountId()).notNull()
.integerGreaterThanZero(); .integerGreaterThanZero();
baseDataValidator.reset().parameter(paramSuffix + "[" + arrayPos + "].amount").value(credit.getAmount()).notNull() baseDataValidator.reset().parameter(paramSuffix + "[" + arrayPos + "].amount").value(credit.getAmount()).notNull()
@@ -97,8 +97,8 @@ public class JournalEntryCommand {
return this.officeId; return this.officeId;
} }
public LocalDate getEntryDate() { public LocalDate getTransactionDate() {
return this.entryDate; return this.transactionDate;
} }
public String getComments() { public String getComments() {
@@ -19,7 +19,8 @@ public class SingleDebitOrCreditEntryCommand {
private final Set<String> parametersPassedInRequest; private final Set<String> parametersPassedInRequest;
public SingleDebitOrCreditEntryCommand(Set<String> parametersPassedInRequest, Long glAccountId, BigDecimal amount, String comments) { public SingleDebitOrCreditEntryCommand(final Set<String> parametersPassedInRequest, final Long glAccountId, final BigDecimal amount,
final String comments) {
this.parametersPassedInRequest = parametersPassedInRequest; this.parametersPassedInRequest = parametersPassedInRequest;
this.glAccountId = glAccountId; this.glAccountId = glAccountId;
this.amount = amount; this.amount = amount;
@@ -33,7 +33,7 @@ public class JournalEntryData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final EnumOptionData glAccountType; private final EnumOptionData glAccountType;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final LocalDate entryDate; private final LocalDate transactionDate;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final EnumOptionData entryType; private final EnumOptionData entryType;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@@ -57,10 +57,11 @@ public class JournalEntryData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Boolean reversed; private final Boolean reversed;
public JournalEntryData(Long id, Long officeId, String officeName, String glAccountName, Long glAccountId, String glAccountCode, public JournalEntryData(final Long id, final Long officeId, final String officeName, final String glAccountName,
EnumOptionData glAccountClassification, LocalDate entryDate, EnumOptionData entryType, BigDecimal amount, String transactionId, final Long glAccountId, final String glAccountCode, final EnumOptionData glAccountClassification,
Boolean portfolioGenerated, String entityType, Long entityId, Long createdByUserId, LocalDate createdDate, final LocalDate transactionDate, final EnumOptionData entryType, final BigDecimal amount, final String transactionId,
String createdByUserName, String comments, Boolean reversed) { final Boolean portfolioGenerated, final String entityType, final Long entityId, final Long createdByUserId,
final LocalDate createdDate, final String createdByUserName, final String comments, final Boolean reversed) {
this.id = id; this.id = id;
this.officeId = officeId; this.officeId = officeId;
this.officeName = officeName; this.officeName = officeName;
@@ -68,7 +69,7 @@ public class JournalEntryData {
this.glAccountId = glAccountId; this.glAccountId = glAccountId;
this.glAccountCode = glAccountCode; this.glAccountCode = glAccountCode;
this.glAccountType = glAccountClassification; this.glAccountType = glAccountClassification;
this.entryDate = entryDate; this.transactionDate = transactionDate;
this.entryType = entryType; this.entryType = entryType;
this.amount = amount; this.amount = amount;
this.transactionId = transactionId; this.transactionId = transactionId;
@@ -54,7 +54,7 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "entry_date") @Column(name = "entry_date")
@Temporal(TemporalType.DATE) @Temporal(TemporalType.DATE)
private Date entryDate; private Date transactionDate;
@Column(name = "type_enum", nullable = false, length = 50) @Column(name = "type_enum", nullable = false, length = 50)
private Integer type; private Integer type;
@@ -74,9 +74,10 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "entity_id") @Column(name = "entity_id")
private Long entityId; private Long entityId;
public static JournalEntry createNew(Office office, GLAccount glAccount, String transactionId, boolean portfolioGenerated, public static JournalEntry createNew(final Office office, final GLAccount glAccount, final String transactionId,
Date entryDate, JournalEntryType journalEntryType, BigDecimal amount, String description, String entityType, Long entityId) { final boolean portfolioGenerated, final Date transactionDate, final JournalEntryType journalEntryType, final BigDecimal amount,
return new JournalEntry(office, glAccount, transactionId, portfolioGenerated, entryDate, journalEntryType.getValue(), amount, final String description, final String entityType, final Long entityId) {
return new JournalEntry(office, glAccount, transactionId, portfolioGenerated, transactionDate, journalEntryType.getValue(), amount,
description, entityType, entityId); description, entityType, entityId);
} }
@@ -84,15 +85,16 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
// //
} }
public JournalEntry(Office office, GLAccount glAccount, String transactionId, boolean portfolioGenerated, Date entryDate, public JournalEntry(final Office office, final GLAccount glAccount, final String transactionId, final boolean portfolioGenerated,
Integer type, BigDecimal amount, String description, String entityType, Long entityId) { final Date transactionDate, final Integer type, final BigDecimal amount, final String description, final String entityType,
final Long entityId) {
this.office = office; this.office = office;
this.glAccount = glAccount; this.glAccount = glAccount;
this.reversalJournalEntry = null; this.reversalJournalEntry = null;
this.transactionId = transactionId; this.transactionId = transactionId;
this.reversed = false; this.reversed = false;
this.portfolioGenerated = portfolioGenerated; this.portfolioGenerated = portfolioGenerated;
this.entryDate = entryDate; this.transactionDate = transactionDate;
this.type = type; this.type = type;
this.amount = amount; this.amount = amount;
this.description = StringUtils.defaultIfEmpty(description, null); this.description = StringUtils.defaultIfEmpty(description, null);
@@ -101,7 +103,7 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
} }
public boolean isDebitEntry() { public boolean isDebitEntry() {
return JournalEntryType.DEBIT.getValue().equals(type); return JournalEntryType.DEBIT.getValue().equals(this.type);
} }
public Integer getType() { public Integer getType() {
@@ -116,19 +118,19 @@ public class JournalEntry extends AbstractAuditableCustom<AppUser, Long> {
return this.glAccount; return this.glAccount;
} }
public Date getEntryDate() { public Date getTransactionDate() {
return this.entryDate; return this.transactionDate;
} }
public BigDecimal getAmount() { public BigDecimal getAmount() {
return this.amount; return this.amount;
} }
public void setReversalJournalEntry(JournalEntry reversalJournalEntry) { public void setReversalJournalEntry(final JournalEntry reversalJournalEntry) {
this.reversalJournalEntry = reversalJournalEntry; this.reversalJournalEntry = reversalJournalEntry;
} }
public void setReversed(boolean reversed) { public void setReversed(final boolean reversed) {
this.reversed = reversed; this.reversed = reversed;
} }
@@ -7,7 +7,6 @@ package org.mifosplatform.accounting.journalentry.domain;
import java.util.List; import java.util.List;
public interface JournalEntryRepositoryCustom { public interface JournalEntryRepositoryCustom {
List<JournalEntry> findFirstJournalEntryForAccount(long glAccountId); List<JournalEntry> findFirstJournalEntryForAccount(long glAccountId);
@@ -20,8 +20,8 @@ public class JournalEntryRepositoryImpl implements JournalEntryRepositoryCustom
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<JournalEntry> findFirstJournalEntryForAccount(long glAccountId) { public List<JournalEntry> findFirstJournalEntryForAccount(final long glAccountId) {
List<JournalEntry> journalEntries = entityManager final List<JournalEntry> journalEntries = this.entityManager
.createQuery("SELECT journalEntry FROM JournalEntry journalEntry where journalEntry.glAccount.id= :glAccountId") .createQuery("SELECT journalEntry FROM JournalEntry journalEntry where journalEntry.glAccount.id= :glAccountId")
.setParameter("glAccountId", glAccountId).setFirstResult(0).setMaxResults(1).getResultList(); .setParameter("glAccountId", glAccountId).setFirstResult(0).setMaxResults(1).getResultList();
return journalEntries; return journalEntries;
@@ -8,7 +8,6 @@ package org.mifosplatform.accounting.journalentry.domain;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public enum JournalEntryType { public enum JournalEntryType {
CREDIT(1, "journalEntryType.credit"), DEBIT(2, "journalEntrytType.debit"); CREDIT(1, "journalEntryType.credit"), DEBIT(2, "journalEntrytType.debit");
@@ -26,18 +25,18 @@ public enum JournalEntryType {
} }
public String getCode() { public String getCode() {
return code; return this.code;
} }
private static final Map<Integer, JournalEntryType> intToEnumMap = new HashMap<Integer, JournalEntryType>(); private static final Map<Integer, JournalEntryType> intToEnumMap = new HashMap<Integer, JournalEntryType>();
static { static {
for (JournalEntryType type : JournalEntryType.values()) { for (final JournalEntryType type : JournalEntryType.values()) {
intToEnumMap.put(type.value, type); intToEnumMap.put(type.value, type);
} }
} }
public static JournalEntryType fromInt(int i) { public static JournalEntryType fromInt(final int i) {
JournalEntryType type = intToEnumMap.get(Integer.valueOf(i)); final JournalEntryType type = intToEnumMap.get(Integer.valueOf(i));
return type; return type;
} }
@@ -44,37 +44,36 @@ public final class JournalEntryCommandFromApiJsonDeserializer extends AbstractFr
} }
@Override @Override
public JournalEntryCommand commandFromApiJson(String json) { public JournalEntryCommand commandFromApiJson(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType(); final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
Set<String> supportedParameters = JournalEntryJsonInputParams.getAllValues(); final Set<String> supportedParameters = JournalEntryJsonInputParams.getAllValues();
fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters);
final JsonElement element = fromApiJsonHelper.parse(json); final JsonElement element = this.fromApiJsonHelper.parse(json);
final Long officeId = fromApiJsonHelper.extractLongNamed(JournalEntryJsonInputParams.OFFICE_ID.getValue(), element); final Long officeId = this.fromApiJsonHelper.extractLongNamed(JournalEntryJsonInputParams.OFFICE_ID.getValue(), element);
final String comments = fromApiJsonHelper.extractStringNamed(JournalEntryJsonInputParams.COMMENTS.getValue(), element); final String comments = this.fromApiJsonHelper.extractStringNamed(JournalEntryJsonInputParams.COMMENTS.getValue(), element);
final LocalDate entryDate = fromApiJsonHelper.extractLocalDateNamed(JournalEntryJsonInputParams.ENTRY_DATE.getValue(), element); final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(
JournalEntryJsonInputParams.TRANSACTION_DATE.getValue(), element);
final JsonObject topLevelJsonElement = element.getAsJsonObject(); final JsonObject topLevelJsonElement = element.getAsJsonObject();
Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
SingleDebitOrCreditEntryCommand[] credits = null; SingleDebitOrCreditEntryCommand[] credits = null;
SingleDebitOrCreditEntryCommand[] debits = null; SingleDebitOrCreditEntryCommand[] debits = null;
if (element.isJsonObject()) { if (element.isJsonObject()) {
if (topLevelJsonElement.has(JournalEntryJsonInputParams.CREDITS.getValue()) if (topLevelJsonElement.has(JournalEntryJsonInputParams.CREDITS.getValue())
&& topLevelJsonElement.get(JournalEntryJsonInputParams.CREDITS.getValue()).isJsonArray()) { && topLevelJsonElement.get(JournalEntryJsonInputParams.CREDITS.getValue()).isJsonArray()) {
credits = populateCreditsOrDebitsArray(topLevelJsonElement, locale, credits, credits = populateCreditsOrDebitsArray(topLevelJsonElement, locale, credits, JournalEntryJsonInputParams.CREDITS.getValue());
JournalEntryJsonInputParams.CREDITS.getValue());
} }
if (topLevelJsonElement.has(JournalEntryJsonInputParams.DEBITS.getValue()) if (topLevelJsonElement.has(JournalEntryJsonInputParams.DEBITS.getValue())
&& topLevelJsonElement.get(JournalEntryJsonInputParams.DEBITS.getValue()).isJsonArray()) { && topLevelJsonElement.get(JournalEntryJsonInputParams.DEBITS.getValue()).isJsonArray()) {
debits = populateCreditsOrDebitsArray(topLevelJsonElement, locale, debits, debits = populateCreditsOrDebitsArray(topLevelJsonElement, locale, debits, JournalEntryJsonInputParams.DEBITS.getValue());
JournalEntryJsonInputParams.DEBITS.getValue());
} }
} }
return new JournalEntryCommand(officeId, entryDate, comments, credits, debits); return new JournalEntryCommand(officeId, transactionDate, comments, credits, debits);
} }
/** /**
@@ -83,7 +82,7 @@ public final class JournalEntryCommandFromApiJsonDeserializer extends AbstractFr
* @param locale * @param locale
*/ */
private SingleDebitOrCreditEntryCommand[] populateCreditsOrDebitsArray(final JsonObject topLevelJsonElement, final Locale locale, private SingleDebitOrCreditEntryCommand[] populateCreditsOrDebitsArray(final JsonObject topLevelJsonElement, final Locale locale,
SingleDebitOrCreditEntryCommand[] debitOrCredits, String paramName) { SingleDebitOrCreditEntryCommand[] debitOrCredits, final String paramName) {
final JsonArray array = topLevelJsonElement.get(paramName).getAsJsonArray(); final JsonArray array = topLevelJsonElement.get(paramName).getAsJsonArray();
debitOrCredits = new SingleDebitOrCreditEntryCommand[array.size()]; debitOrCredits = new SingleDebitOrCreditEntryCommand[array.size()];
for (int i = 0; i < array.size(); i++) { for (int i = 0; i < array.size(); i++) {
@@ -91,9 +90,9 @@ public final class JournalEntryCommandFromApiJsonDeserializer extends AbstractFr
final JsonObject creditElement = array.get(i).getAsJsonObject(); final JsonObject creditElement = array.get(i).getAsJsonObject();
final Set<String> parametersPassedInForCreditsCommand = new HashSet<String>(); final Set<String> parametersPassedInForCreditsCommand = new HashSet<String>();
final Long glAccountId = fromApiJsonHelper.extractLongNamed("glAccountId", creditElement); final Long glAccountId = this.fromApiJsonHelper.extractLongNamed("glAccountId", creditElement);
final String comments = fromApiJsonHelper.extractStringNamed("comments", creditElement); final String comments = this.fromApiJsonHelper.extractStringNamed("comments", creditElement);
final BigDecimal amount = fromApiJsonHelper.extractBigDecimalNamed("amount", creditElement, locale); final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount", creditElement, locale);
debitOrCredits[i] = new SingleDebitOrCreditEntryCommand(parametersPassedInForCreditsCommand, glAccountId, amount, comments); debitOrCredits[i] = new SingleDebitOrCreditEntryCommand(parametersPassedInForCreditsCommand, glAccountId, amount, comments);
} }
@@ -43,7 +43,7 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat
return " journalEntry.id as journalEntryId, glAccount.classification_enum as classification ," return " journalEntry.id as journalEntryId, glAccount.classification_enum as classification ,"
+ " glAccount.name as glAccountName, glAccount.gl_code as glCode, journalEntry.account_id as glAccountId," + " glAccount.name as glAccountName, glAccount.gl_code as glCode, journalEntry.account_id as glAccountId,"
+ " journalEntry.office_id as officeId, office.name as officeName, " + " journalEntry.office_id as officeId, office.name as officeName, "
+ " journalEntry.portfolio_generated as portfolioGenerated,journalEntry.entry_date as entryDate, " + " journalEntry.portfolio_generated as portfolioGenerated,journalEntry.entry_date as transactionDate, "
+ " journalEntry.type_enum as entryType,journalEntry.amount as amount, journalEntry.transaction_id as transactionId," + " journalEntry.type_enum as entryType,journalEntry.amount as amount, journalEntry.transaction_id as transactionId,"
+ " journalEntry.entity_type as entityType, journalEntry.entity_id as entityId, creatingUser.id as createdByUserId, " + " journalEntry.entity_type as entityType, journalEntry.entity_id as entityId, creatingUser.id as createdByUserId, "
+ " creatingUser.username as createdByUserName, journalEntry.description as comments, " + " creatingUser.username as createdByUserName, journalEntry.description as comments, "
@@ -56,41 +56,41 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat
@Override @Override
public JournalEntryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { public JournalEntryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long journalEntryId = rs.getLong("journalEntryId"); final Long journalEntryId = rs.getLong("journalEntryId");
Long officeId = rs.getLong("officeId"); final Long officeId = rs.getLong("officeId");
String officeName = rs.getString("officeName"); final String officeName = rs.getString("officeName");
String glCode = rs.getString("glCode"); final String glCode = rs.getString("glCode");
String glAccountName = rs.getString("glAccountName"); final String glAccountName = rs.getString("glAccountName");
Long glAccountId = rs.getLong("glAccountId"); final Long glAccountId = rs.getLong("glAccountId");
final int accountTypeId = JdbcSupport.getInteger(rs, "classification"); final int accountTypeId = JdbcSupport.getInteger(rs, "classification");
final EnumOptionData accountType = AccountingEnumerations.gLAccountType(accountTypeId); final EnumOptionData accountType = AccountingEnumerations.gLAccountType(accountTypeId);
LocalDate entryDate = JdbcSupport.getLocalDate(rs, "entryDate"); final LocalDate transactionDate = JdbcSupport.getLocalDate(rs, "transactionDate");
Boolean portfolioGenerated = rs.getBoolean("portfolioGenerated"); final Boolean portfolioGenerated = rs.getBoolean("portfolioGenerated");
BigDecimal amount = rs.getBigDecimal("amount"); final BigDecimal amount = rs.getBigDecimal("amount");
int entryTypeId = JdbcSupport.getInteger(rs, "entryType"); final int entryTypeId = JdbcSupport.getInteger(rs, "entryType");
final EnumOptionData entryType = AccountingEnumerations.journalEntryType(entryTypeId); final EnumOptionData entryType = AccountingEnumerations.journalEntryType(entryTypeId);
String transactionId = rs.getString("transactionId"); final String transactionId = rs.getString("transactionId");
String entityType = rs.getString("entityType"); final String entityType = rs.getString("entityType");
Long entityId = JdbcSupport.getLong(rs, "entityId"); final Long entityId = JdbcSupport.getLong(rs, "entityId");
Long createdByUserId = rs.getLong("createdByUserId"); final Long createdByUserId = rs.getLong("createdByUserId");
LocalDate createdDate = JdbcSupport.getLocalDate(rs, "createdDate"); final LocalDate createdDate = JdbcSupport.getLocalDate(rs, "createdDate");
String createdByUserName = rs.getString("createdByUserName"); final String createdByUserName = rs.getString("createdByUserName");
String comments = rs.getString("comments"); final String comments = rs.getString("comments");
Boolean reversed = rs.getBoolean("reversed"); final Boolean reversed = rs.getBoolean("reversed");
return new JournalEntryData(journalEntryId, officeId, officeName, glAccountName, glAccountId, glCode, accountType, entryDate, return new JournalEntryData(journalEntryId, officeId, officeName, glAccountName, glAccountId, glCode, accountType,
entryType, amount, transactionId, portfolioGenerated, entityType, entityId, createdByUserId, createdDate, transactionDate, entryType, amount, transactionId, portfolioGenerated, entityType, entityId, createdByUserId,
createdByUserName, comments, reversed); createdDate, createdByUserName, comments, reversed);
} }
} }
@Override @Override
public List<JournalEntryData> retrieveAllGLJournalEntries(Long officeId, Long glAccountId, Boolean portfolioGenerated, Date fromDate, public List<JournalEntryData> retrieveAllGLJournalEntries(final Long officeId, final Long glAccountId,
Date toDate) { final Boolean portfolioGenerated, final Date fromDate, final Date toDate) {
GLJournalEntryMapper rm = new GLJournalEntryMapper(); final GLJournalEntryMapper rm = new GLJournalEntryMapper();
String sql = "select " + rm.schema(); String sql = "select " + rm.schema();
Object[] objectArray = new Object[4]; final Object[] objectArray = new Object[4];
int arrayPos = 0; int arrayPos = 0;
if (officeId != null && officeId != 0) { if (officeId != null && officeId != 0) {
@@ -106,7 +106,7 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat
} }
if (fromDate != null || toDate != null) { if (fromDate != null || toDate != null) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String fromDateString = null; String fromDateString = null;
String toDateString = null; String toDateString = null;
if (fromDate != null && toDate != null) { if (fromDate != null && toDate != null) {
@@ -140,36 +140,36 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat
sql += " order by journalEntry.entry_date desc,journalEntry.transaction_id"; sql += " order by journalEntry.entry_date desc,journalEntry.transaction_id";
Object[] finalObjectArray = Arrays.copyOf(objectArray, arrayPos); final Object[] finalObjectArray = Arrays.copyOf(objectArray, arrayPos);
return this.jdbcTemplate.query(sql, rm, finalObjectArray); return this.jdbcTemplate.query(sql, rm, finalObjectArray);
} }
@Override @Override
public JournalEntryData retrieveGLJournalEntryById(long glJournalEntryId) { public JournalEntryData retrieveGLJournalEntryById(final long glJournalEntryId) {
try { try {
GLJournalEntryMapper rm = new GLJournalEntryMapper(); final GLJournalEntryMapper rm = new GLJournalEntryMapper();
String sql = "select " + rm.schema() + " and journalEntry.id = ?"; final String sql = "select " + rm.schema() + " and journalEntry.id = ?";
JournalEntryData glJournalEntryData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { glJournalEntryId }); final JournalEntryData glJournalEntryData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { glJournalEntryId });
return glJournalEntryData; return glJournalEntryData;
} catch (EmptyResultDataAccessException e) { } catch (final EmptyResultDataAccessException e) {
throw new JournalEntriesNotFoundException(glJournalEntryId); throw new JournalEntriesNotFoundException(glJournalEntryId);
} }
} }
@Override @Override
public List<JournalEntryData> retrieveRelatedJournalEntries(String transactionId) { public List<JournalEntryData> retrieveRelatedJournalEntries(final String transactionId) {
try { try {
GLJournalEntryMapper rm = new GLJournalEntryMapper(); final GLJournalEntryMapper rm = new GLJournalEntryMapper();
String sql = "select " + rm.schema() + " and journalEntry.transaction_id = ?"; final String sql = "select " + rm.schema() + " and journalEntry.transaction_id = ?";
List<JournalEntryData> journalEntryDatas = this.jdbcTemplate.query(sql, rm, new Object[] { transactionId }); final List<JournalEntryData> journalEntryDatas = this.jdbcTemplate.query(sql, rm, new Object[] { transactionId });
return journalEntryDatas; return journalEntryDatas;
} catch (EmptyResultDataAccessException e) { } catch (final EmptyResultDataAccessException e) {
throw new JournalEntriesNotFoundException(transactionId); throw new JournalEntriesNotFoundException(transactionId);
} }
} }
@@ -18,7 +18,7 @@ public interface JournalEntryWritePlatformService {
CommandProcessingResult revertJournalEntry(JsonCommand command); CommandProcessingResult revertJournalEntry(JsonCommand command);
void createJournalEntriesForLoan(Map<String, Object> accountingBridgeData); void createJournalEntriesForLoan(Map<String, Object> accountingBridgeData);
void createJournalEntriesForLoan(LoanDTO loanDTO); void createJournalEntriesForLoan(LoanDTO loanDTO);
} }
@@ -76,31 +76,31 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
@Transactional @Transactional
@Override @Override
public CommandProcessingResult createJournalEntry(JsonCommand command) { public CommandProcessingResult createJournalEntry(final JsonCommand command) {
try { try {
final JournalEntryCommand journalEntryCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json()); final JournalEntryCommand journalEntryCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json());
journalEntryCommand.validateForCreate(); journalEntryCommand.validateForCreate();
// check office is valid // check office is valid
Long officeId = command.longValueOfParameterNamed(JournalEntryJsonInputParams.OFFICE_ID.getValue()); final Long officeId = command.longValueOfParameterNamed(JournalEntryJsonInputParams.OFFICE_ID.getValue());
final Office office = this.officeRepository.findOne(officeId); final Office office = this.officeRepository.findOne(officeId);
if (office == null) { throw new OfficeNotFoundException(officeId); } if (office == null) { throw new OfficeNotFoundException(officeId); }
validateBusinessRulesForJournalEntries(journalEntryCommand); validateBusinessRulesForJournalEntries(journalEntryCommand);
/** Set a transaction Id and save these Journal entries **/ /** Set a transaction Id and save these Journal entries **/
Date entryDate = command.DateValueOfParameterNamed(JournalEntryJsonInputParams.ENTRY_DATE.getValue()); final Date transactionDate = command.DateValueOfParameterNamed(JournalEntryJsonInputParams.TRANSACTION_DATE.getValue());
String transactionId = generateTransactionId(); final String transactionId = generateTransactionId();
saveAllDebitOrCreditEntries(journalEntryCommand, office, entryDate, journalEntryCommand.getDebits(), transactionId, saveAllDebitOrCreditEntries(journalEntryCommand, office, transactionDate, journalEntryCommand.getDebits(), transactionId,
JournalEntryType.DEBIT); JournalEntryType.DEBIT);
saveAllDebitOrCreditEntries(journalEntryCommand, office, entryDate, journalEntryCommand.getCredits(), transactionId, saveAllDebitOrCreditEntries(journalEntryCommand, office, transactionDate, journalEntryCommand.getCredits(), transactionId,
JournalEntryType.CREDIT); JournalEntryType.CREDIT);
return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(officeId) return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(officeId)
.withTransactionId(transactionId).build(); .withTransactionId(transactionId).build();
} catch (DataIntegrityViolationException dve) { } catch (final DataIntegrityViolationException dve) {
handleJournalEntryDataIntegrityIssues(dve); handleJournalEntryDataIntegrityIssues(dve);
return null; return null;
} }
@@ -108,25 +108,27 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
@Transactional @Transactional
@Override @Override
public CommandProcessingResult revertJournalEntry(JsonCommand command) { public CommandProcessingResult revertJournalEntry(final JsonCommand command) {
// is the transaction Id valid // is the transaction Id valid
List<JournalEntry> journalEntries = glJournalEntryRepository.findUnReversedManualJournalEntriesByTransactionId(command final List<JournalEntry> journalEntries = this.glJournalEntryRepository.findUnReversedManualJournalEntriesByTransactionId(command
.getTransactionId()); .getTransactionId());
if (journalEntries.size() <= 1) { throw new JournalEntriesNotFoundException(command.getTransactionId()); } if (journalEntries.size() <= 1) { throw new JournalEntriesNotFoundException(command.getTransactionId()); }
String reversalTransactionId = generateTransactionId(); final String reversalTransactionId = generateTransactionId();
for (JournalEntry journalEntry : journalEntries) { for (final JournalEntry journalEntry : journalEntries) {
JournalEntry reversalJournalEntry; JournalEntry reversalJournalEntry;
String reversalComment = "Reversal entry for Journal Entry with Entry Id :" + journalEntry.getId() + " and transaction Id " final String reversalComment = "Reversal entry for Journal Entry with Entry Id :" + journalEntry.getId()
+ command.getTransactionId(); + " and transaction Id " + command.getTransactionId();
if (journalEntry.isDebitEntry()) { if (journalEntry.isDebitEntry()) {
reversalJournalEntry = JournalEntry.createNew(journalEntry.getOffice(), journalEntry.getGlAccount(), reversalTransactionId, reversalJournalEntry = JournalEntry.createNew(journalEntry.getOffice(), journalEntry.getGlAccount(), reversalTransactionId,
false, journalEntry.getEntryDate(), JournalEntryType.CREDIT, journalEntry.getAmount(), reversalComment, null, null); false, journalEntry.getTransactionDate(), JournalEntryType.CREDIT, journalEntry.getAmount(), reversalComment, null,
null);
} else { } else {
reversalJournalEntry = JournalEntry.createNew(journalEntry.getOffice(), journalEntry.getGlAccount(), reversalTransactionId, reversalJournalEntry = JournalEntry.createNew(journalEntry.getOffice(), journalEntry.getGlAccount(), reversalTransactionId,
false, journalEntry.getEntryDate(), JournalEntryType.DEBIT, journalEntry.getAmount(), reversalComment, null, null); false, journalEntry.getTransactionDate(), JournalEntryType.DEBIT, journalEntry.getAmount(), reversalComment, null,
null);
} }
// save the reversal entry // save the reversal entry
this.glJournalEntryRepository.saveAndFlush(reversalJournalEntry); this.glJournalEntryRepository.saveAndFlush(reversalJournalEntry);
@@ -176,19 +178,19 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final List<Map<String, Object>> newTransactionsMap = (List<Map<String, Object>>) accountingBridgeData.get("newLoanTransactions"); final List<Map<String, Object>> newTransactionsMap = (List<Map<String, Object>>) accountingBridgeData.get("newLoanTransactions");
for (Map<String, Object> map : newTransactionsMap) { for (final Map<String, Object> map : newTransactionsMap) {
String transactionId = ((Long) map.get("id")).toString(); final String transactionId = ((Long) map.get("id")).toString();
Date transactionDate = ((LocalDate) map.get("date")).toDate(); final Date transactionDate = ((LocalDate) map.get("date")).toDate();
BigDecimal amount = (BigDecimal) map.get("amount"); final BigDecimal amount = (BigDecimal) map.get("amount");
BigDecimal principal = (BigDecimal) map.get("principalPortion"); final BigDecimal principal = (BigDecimal) map.get("principalPortion");
BigDecimal interest = (BigDecimal) map.get("interestPortion"); final BigDecimal interest = (BigDecimal) map.get("interestPortion");
BigDecimal fees = (BigDecimal) map.get("feeChargesPortion"); final BigDecimal fees = (BigDecimal) map.get("feeChargesPortion");
BigDecimal penalties = (BigDecimal) map.get("penaltyChargesPortion"); final BigDecimal penalties = (BigDecimal) map.get("penaltyChargesPortion");
boolean disbursement = (Boolean) map.get("disbursement"); final boolean disbursement = (Boolean) map.get("disbursement");
boolean repayment = (Boolean) map.get("repayment"); final boolean repayment = (Boolean) map.get("repayment");
boolean repaymentAtDisbursement = (Boolean) map.get("repaymentAtDisbursement"); final boolean repaymentAtDisbursement = (Boolean) map.get("repaymentAtDisbursement");
boolean contra = (Boolean) map.get("contra"); final boolean contra = (Boolean) map.get("contra");
boolean writeOff = (Boolean) map.get("writeOff"); final boolean writeOff = (Boolean) map.get("writeOff");
final LoanTransactionDTO transaction = new LoanTransactionDTO(transactionId, transactionDate, amount, principal, interest, final LoanTransactionDTO transaction = new LoanTransactionDTO(transactionId, transactionDate, amount, principal, interest,
fees, penalties, disbursement, repayment, repaymentAtDisbursement, contra, writeOff); fees, penalties, disbursement, repayment, repaymentAtDisbursement, contra, writeOff);
@@ -201,48 +203,52 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
} }
private void createJournalEntriesUsingCashRules(final LoanDTO loanDTO) { private void createJournalEntriesUsingCashRules(final LoanDTO loanDTO) {
GLClosure latestGLClosure = glClosureRepository.getLatestGLClosureByBranch(loanDTO.getOfficeId()); final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(loanDTO.getOfficeId());
Office office = officeRepository.findOne(loanDTO.getOfficeId()); final Office office = this.officeRepository.findOne(loanDTO.getOfficeId());
Long loanProductId = loanDTO.getLoanProductId(); final Long loanProductId = loanDTO.getLoanProductId();
// TODO: Check for accounting type // TODO: Check for accounting type
for (LoanTransactionDTO loanTransactionDTO : loanDTO.getNewLoanTransactions()) { for (final LoanTransactionDTO loanTransactionDTO : loanDTO.getNewLoanTransactions()) {
Date entryDate = loanTransactionDTO.getTransactionDate(); final Date transactionDate = loanTransactionDTO.getTransactionDate();
String transactionId = loanTransactionDTO.getTransactionId(); final String transactionId = loanTransactionDTO.getTransactionId();
Long loanId = loanDTO.getLoanId(); final Long loanId = loanDTO.getLoanId();
/** /**
* check if an accounting closure has happened for this branch after * check if an accounting closure has happened for this branch after
* the transaction Date * the transaction Date
**/ **/
if (latestGLClosure != null) { if (latestGLClosure != null) {
if (latestGLClosure.getClosingDate().after(entryDate) || latestGLClosure.getClosingDate().equals(entryDate)) { throw new JournalEntryInvalidException( if (latestGLClosure.getClosingDate().after(transactionDate) || latestGLClosure.getClosingDate().equals(transactionDate)) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), null, null); } GL_JOURNAL_ENTRY_INVALID_REASON.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), null, null); }
} }
/*** Debit loan Portfolio and credit Fund source for Disbursal **/ /*** Debit loan Portfolio and credit Fund source for Disbursal **/
if (loanTransactionDTO.isDisbursement()) { if (loanTransactionDTO.isDisbursement()) {
GLAccount loanPortfolioAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO); final GLAccount loanPortfolioAccount = getLinkedFinAccountForLoanProduct(loanProductId,
GLAccount fundSourceAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE); CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO);
final GLAccount fundSourceAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE);
BigDecimal disbursalAmount = loanTransactionDTO.getAmount(); final BigDecimal disbursalAmount = loanTransactionDTO.getAmount();
createDebitJournalEntryForLoanProduct(office, loanPortfolioAccount, loanId, transactionId, entryDate, disbursalAmount); createDebitJournalEntryForLoanProduct(office, loanPortfolioAccount, loanId, transactionId, transactionDate, disbursalAmount);
createCreditJournalEntryForLoanProduct(office, fundSourceAccount, loanId, transactionId, entryDate, disbursalAmount); createCreditJournalEntryForLoanProduct(office, fundSourceAccount, loanId, transactionId, transactionDate, disbursalAmount);
} else if (loanTransactionDTO.isRepayment() || loanTransactionDTO.isRepaymentAtDisbursement() || loanTransactionDTO.isContra()) { } else if (loanTransactionDTO.isRepayment() || loanTransactionDTO.isRepaymentAtDisbursement() || loanTransactionDTO.isContra()) {
createJournalEntriesForRepaymentOrContraUsingCashRules(office, loanProductId, loanTransactionDTO, entryDate, transactionId, createJournalEntriesForRepaymentOrContraUsingCashRules(office, loanProductId, loanTransactionDTO, transactionDate,
loanId); transactionId, loanId);
}/*** }/***
* Only principal write off affects cash based accounting (interest * Only principal write off affects cash based accounting (interest
* and fee write off need not be considered). Debit losses written * and fee write off need not be considered). Debit losses written
* off and credit Loan Portfolio * off and credit Loan Portfolio
**/ **/
else if (loanTransactionDTO.isWriteOff()) { else if (loanTransactionDTO.isWriteOff()) {
BigDecimal principalAmount = loanTransactionDTO.getPrincipal(); final BigDecimal principalAmount = loanTransactionDTO.getPrincipal();
GLAccount lossesWrittenOffAccount = getLinkedFinAccountForLoanProduct(loanProductId, final GLAccount lossesWrittenOffAccount = getLinkedFinAccountForLoanProduct(loanProductId,
CASH_ACCOUNTS_FOR_LOAN.LOSSES_WRITTEN_OFF); CASH_ACCOUNTS_FOR_LOAN.LOSSES_WRITTEN_OFF);
createDebitJournalEntryForLoanProduct(office, lossesWrittenOffAccount, loanId, transactionId, entryDate, principalAmount); createDebitJournalEntryForLoanProduct(office, lossesWrittenOffAccount, loanId, transactionId, transactionDate,
principalAmount);
GLAccount loanPortfolioAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO); final GLAccount loanPortfolioAccount = getLinkedFinAccountForLoanProduct(loanProductId,
createCreditJournalEntryForLoanProduct(office, loanPortfolioAccount, loanId, transactionId, entryDate, principalAmount); CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO);
createCreditJournalEntryForLoanProduct(office, loanPortfolioAccount, loanId, transactionId, transactionDate,
principalAmount);
} }
} }
} }
@@ -257,12 +263,12 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
* credits and vice versa * credits and vice versa
*/ */
private void createJournalEntriesForRepaymentOrContraUsingCashRules(final Office office, final Long loanProductId, private void createJournalEntriesForRepaymentOrContraUsingCashRules(final Office office, final Long loanProductId,
final LoanTransactionDTO loanTransactionDTO, final Date entryDate, String transactionId, final Long loanId) { final LoanTransactionDTO loanTransactionDTO, final Date transactionDate, String transactionId, final Long loanId) {
BigDecimal principalAmount = loanTransactionDTO.getPrincipal(); final BigDecimal principalAmount = loanTransactionDTO.getPrincipal();
BigDecimal interestAmount = loanTransactionDTO.getInterest(); final BigDecimal interestAmount = loanTransactionDTO.getInterest();
BigDecimal feesAmount = loanTransactionDTO.getFees(); final BigDecimal feesAmount = loanTransactionDTO.getFees();
BigDecimal penaltiesAmount = loanTransactionDTO.getPenalties(); final BigDecimal penaltiesAmount = loanTransactionDTO.getPenalties();
boolean isContraTransaction = loanTransactionDTO.isContra(); final boolean isContraTransaction = loanTransactionDTO.isContra();
BigDecimal totalDebitAmount = new BigDecimal(0); BigDecimal totalDebitAmount = new BigDecimal(0);
@@ -273,90 +279,94 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
if (principalAmount != null && !(principalAmount.compareTo(BigDecimal.ZERO) == 0)) { if (principalAmount != null && !(principalAmount.compareTo(BigDecimal.ZERO) == 0)) {
totalDebitAmount = totalDebitAmount.add(principalAmount); totalDebitAmount = totalDebitAmount.add(principalAmount);
GLAccount loanPortfolioAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO); final GLAccount loanPortfolioAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO);
if (isContraTransaction) { if (isContraTransaction) {
createDebitJournalEntryForLoanProduct(office, loanPortfolioAccount, loanId, transactionId, entryDate, principalAmount); createDebitJournalEntryForLoanProduct(office, loanPortfolioAccount, loanId, transactionId, transactionDate, principalAmount);
} else { } else {
createCreditJournalEntryForLoanProduct(office, loanPortfolioAccount, loanId, transactionId, entryDate, principalAmount); createCreditJournalEntryForLoanProduct(office, loanPortfolioAccount, loanId, transactionId, transactionDate,
principalAmount);
} }
} }
if (interestAmount != null && !(interestAmount.compareTo(BigDecimal.ZERO) == 0)) { if (interestAmount != null && !(interestAmount.compareTo(BigDecimal.ZERO) == 0)) {
totalDebitAmount = totalDebitAmount.add(interestAmount); totalDebitAmount = totalDebitAmount.add(interestAmount);
GLAccount interestAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.INTEREST_ON_LOANS); final GLAccount interestAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.INTEREST_ON_LOANS);
if (isContraTransaction) { if (isContraTransaction) {
createDebitJournalEntryForLoanProduct(office, interestAccount, loanId, transactionId, entryDate, interestAmount); createDebitJournalEntryForLoanProduct(office, interestAccount, loanId, transactionId, transactionDate, interestAmount);
} else { } else {
createCreditJournalEntryForLoanProduct(office, interestAccount, loanId, transactionId, entryDate, interestAmount); createCreditJournalEntryForLoanProduct(office, interestAccount, loanId, transactionId, transactionDate, interestAmount);
} }
} }
if (feesAmount != null && !(feesAmount.compareTo(BigDecimal.ZERO) == 0)) { if (feesAmount != null && !(feesAmount.compareTo(BigDecimal.ZERO) == 0)) {
totalDebitAmount = totalDebitAmount.add(feesAmount); totalDebitAmount = totalDebitAmount.add(feesAmount);
GLAccount incomeFromFeesAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES); final GLAccount incomeFromFeesAccount = getLinkedFinAccountForLoanProduct(loanProductId,
CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES);
if (isContraTransaction) { if (isContraTransaction) {
createDebitJournalEntryForLoanProduct(office, incomeFromFeesAccount, loanId, transactionId, entryDate, feesAmount); createDebitJournalEntryForLoanProduct(office, incomeFromFeesAccount, loanId, transactionId, transactionDate, feesAmount);
} else { } else {
createCreditJournalEntryForLoanProduct(office, incomeFromFeesAccount, loanId, transactionId, entryDate, feesAmount); createCreditJournalEntryForLoanProduct(office, incomeFromFeesAccount, loanId, transactionId, transactionDate, feesAmount);
} }
} }
if (penaltiesAmount != null && !(penaltiesAmount.compareTo(BigDecimal.ZERO) == 0)) { if (penaltiesAmount != null && !(penaltiesAmount.compareTo(BigDecimal.ZERO) == 0)) {
totalDebitAmount = totalDebitAmount.add(penaltiesAmount); totalDebitAmount = totalDebitAmount.add(penaltiesAmount);
GLAccount incomeFromPenaltiesAccount = getLinkedFinAccountForLoanProduct(loanProductId, final GLAccount incomeFromPenaltiesAccount = getLinkedFinAccountForLoanProduct(loanProductId,
CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_PENALTIES); CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_PENALTIES);
if (isContraTransaction) { if (isContraTransaction) {
createDebitJournalEntryForLoanProduct(office, incomeFromPenaltiesAccount, loanId, transactionId, entryDate, penaltiesAmount); createDebitJournalEntryForLoanProduct(office, incomeFromPenaltiesAccount, loanId, transactionId, transactionDate,
penaltiesAmount);
} else { } else {
createCreditJournalEntryForLoanProduct(office, incomeFromPenaltiesAccount, loanId, transactionId, entryDate, createCreditJournalEntryForLoanProduct(office, incomeFromPenaltiesAccount, loanId, transactionId, transactionDate,
penaltiesAmount); penaltiesAmount);
} }
} }
GLAccount fundSourceAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE); final GLAccount fundSourceAccount = getLinkedFinAccountForLoanProduct(loanProductId, CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE);
if (isContraTransaction) { if (isContraTransaction) {
createCreditJournalEntryForLoanProduct(office, fundSourceAccount, loanId, transactionId, entryDate, totalDebitAmount); createCreditJournalEntryForLoanProduct(office, fundSourceAccount, loanId, transactionId, transactionDate, totalDebitAmount);
} else { } else {
createDebitJournalEntryForLoanProduct(office, fundSourceAccount, loanId, transactionId, entryDate, totalDebitAmount); createDebitJournalEntryForLoanProduct(office, fundSourceAccount, loanId, transactionId, transactionDate, totalDebitAmount);
} }
} }
private GLAccount getLinkedFinAccountForLoanProduct(final Long loanProductId, final CASH_ACCOUNTS_FOR_LOAN finAccountType) { private GLAccount getLinkedFinAccountForLoanProduct(final Long loanProductId, final CASH_ACCOUNTS_FOR_LOAN finAccountType) {
ProductToGLAccountMapping accountMapping = accountMappingRepository.findByProductIdAndProductTypeAndFinancialAccountType( final ProductToGLAccountMapping accountMapping = this.accountMappingRepository
loanProductId, PortfolioProductType.LOAN.getValue(), finAccountType.getValue()); .findByProductIdAndProductTypeAndFinancialAccountType(loanProductId, PortfolioProductType.LOAN.getValue(),
finAccountType.getValue());
return accountMapping.getGlAccount(); return accountMapping.getGlAccount();
} }
private void createCreditJournalEntryForLoanProduct(Office office, GLAccount account, Long loanId, String transactionId, private void createCreditJournalEntryForLoanProduct(final Office office, final GLAccount account, final Long loanId,
Date entryDate, BigDecimal amount) { final String transactionId, final Date transactionDate, final BigDecimal amount) {
JournalEntry journalEntry = JournalEntry.createNew(office, account, transactionId, true, entryDate, JournalEntryType.CREDIT, final JournalEntry journalEntry = JournalEntry.createNew(office, account, transactionId, true, transactionDate,
amount, null, PortfolioProductType.LOAN.toString(), loanId); JournalEntryType.CREDIT, amount, null, PortfolioProductType.LOAN.toString(), loanId);
glJournalEntryRepository.saveAndFlush(journalEntry); this.glJournalEntryRepository.saveAndFlush(journalEntry);
} }
private void createDebitJournalEntryForLoanProduct(Office office, GLAccount account, Long loanId, String transactionId, Date entryDate, private void createDebitJournalEntryForLoanProduct(final Office office, final GLAccount account, final Long loanId,
BigDecimal amount) { final String transactionId, final Date transactionDate, final BigDecimal amount) {
JournalEntry journalEntry = JournalEntry.createNew(office, account, transactionId, true, entryDate, JournalEntryType.DEBIT, amount, final JournalEntry journalEntry = JournalEntry.createNew(office, account, transactionId, true, transactionDate,
null, PortfolioProductType.LOAN.toString(), loanId); JournalEntryType.DEBIT, amount, null, PortfolioProductType.LOAN.toString(), loanId);
glJournalEntryRepository.saveAndFlush(journalEntry); this.glJournalEntryRepository.saveAndFlush(journalEntry);
} }
private void validateBusinessRulesForJournalEntries(JournalEntryCommand command) { private void validateBusinessRulesForJournalEntries(final JournalEntryCommand command) {
/** check if date of Journal entry is valid ***/ /** check if date of Journal entry is valid ***/
final LocalDate entryLocalDate = command.getEntryDate(); final LocalDate entryLocalDate = command.getTransactionDate();
Date entryDate = entryLocalDate.toDateMidnight().toDate(); final Date transactionDate = entryLocalDate.toDateMidnight().toDate();
// shouldn't be in the future // shouldn't be in the future
Date todaysDate = new Date(); final Date todaysDate = new Date();
if (entryDate.after(todaysDate)) { throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.FUTURE_DATE, entryDate, if (transactionDate.after(todaysDate)) { throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.FUTURE_DATE,
null, null); } transactionDate, null, null); }
// shouldn't be before an accounting closure // shouldn't be before an accounting closure
GLClosure latestGLClosure = glClosureRepository.getLatestGLClosureByBranch(command.getOfficeId()); final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(command.getOfficeId());
if (latestGLClosure != null) { if (latestGLClosure != null) {
if (latestGLClosure.getClosingDate().after(entryDate) || latestGLClosure.getClosingDate().equals(entryDate)) { throw new JournalEntryInvalidException( if (latestGLClosure.getClosingDate().after(transactionDate) || latestGLClosure.getClosingDate().equals(transactionDate)) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), null, null); } GL_JOURNAL_ENTRY_INVALID_REASON.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), null, null); }
} }
/*** check if credits and debits are valid **/ /*** check if credits and debits are valid **/
SingleDebitOrCreditEntryCommand[] credits = command.getCredits(); final SingleDebitOrCreditEntryCommand[] credits = command.getCredits();
SingleDebitOrCreditEntryCommand[] debits = command.getDebits(); final SingleDebitOrCreditEntryCommand[] debits = command.getDebits();
// atleast one debit or credit must be present // atleast one debit or credit must be present
if ((credits == null || credits.length <= 0) || (debits == null || debits.length <= 0)) { throw new JournalEntryInvalidException( if ((credits == null || credits.length <= 0) || (debits == null || debits.length <= 0)) { throw new JournalEntryInvalidException(
@@ -365,12 +375,12 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
// sum of all debits must be = sum of all credits // sum of all debits must be = sum of all credits
BigDecimal creditsSum = BigDecimal.ZERO; BigDecimal creditsSum = BigDecimal.ZERO;
BigDecimal debitsSum = BigDecimal.ZERO; BigDecimal debitsSum = BigDecimal.ZERO;
for (SingleDebitOrCreditEntryCommand creditEntryCommand : credits) { for (final SingleDebitOrCreditEntryCommand creditEntryCommand : credits) {
if (creditEntryCommand.getAmount() == null || creditEntryCommand.getGlAccountId() == null) { throw new JournalEntryInvalidException( if (creditEntryCommand.getAmount() == null || creditEntryCommand.getGlAccountId() == null) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); } GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); }
creditsSum = creditsSum.add(creditEntryCommand.getAmount()); creditsSum = creditsSum.add(creditEntryCommand.getAmount());
} }
for (SingleDebitOrCreditEntryCommand debitEntryCommand : debits) { for (final SingleDebitOrCreditEntryCommand debitEntryCommand : debits) {
if (debitEntryCommand.getAmount() == null || debitEntryCommand.getGlAccountId() == null) { throw new JournalEntryInvalidException( if (debitEntryCommand.getAmount() == null || debitEntryCommand.getGlAccountId() == null) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); } GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); }
debitsSum = debitsSum.add(debitEntryCommand.getAmount()); debitsSum = debitsSum.add(debitEntryCommand.getAmount());
@@ -379,11 +389,11 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_SUM_MISMATCH, null, null, null); } GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_SUM_MISMATCH, null, null, null); }
} }
private void saveAllDebitOrCreditEntries(final JournalEntryCommand command, final Office office, final Date entryDate, private void saveAllDebitOrCreditEntries(final JournalEntryCommand command, final Office office, final Date transactionDate,
final SingleDebitOrCreditEntryCommand[] singleDebitOrCreditEntryCommands, final String transactionId, final SingleDebitOrCreditEntryCommand[] singleDebitOrCreditEntryCommands, final String transactionId,
final JournalEntryType type) { final JournalEntryType type) {
for (SingleDebitOrCreditEntryCommand singleDebitOrCreditEntryCommand : singleDebitOrCreditEntryCommands) { for (final SingleDebitOrCreditEntryCommand singleDebitOrCreditEntryCommand : singleDebitOrCreditEntryCommands) {
GLAccount glAccount = glAccountRepository.findOne(singleDebitOrCreditEntryCommand.getGlAccountId()); final GLAccount glAccount = this.glAccountRepository.findOne(singleDebitOrCreditEntryCommand.getGlAccountId());
if (glAccount == null) { throw new GLAccountNotFoundException(singleDebitOrCreditEntryCommand.getGlAccountId()); } if (glAccount == null) { throw new GLAccountNotFoundException(singleDebitOrCreditEntryCommand.getGlAccountId()); }
/*** /***
@@ -401,14 +411,14 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
if (!StringUtils.isBlank(singleDebitOrCreditEntryCommand.getComments())) { if (!StringUtils.isBlank(singleDebitOrCreditEntryCommand.getComments())) {
comments = singleDebitOrCreditEntryCommand.getComments(); comments = singleDebitOrCreditEntryCommand.getComments();
} }
JournalEntry glJournalEntry = JournalEntry.createNew(office, glAccount, transactionId, false, entryDate, type, final JournalEntry glJournalEntry = JournalEntry.createNew(office, glAccount, transactionId, false, transactionDate, type,
singleDebitOrCreditEntryCommand.getAmount(), comments, null, null); singleDebitOrCreditEntryCommand.getAmount(), comments, null, null);
glJournalEntryRepository.saveAndFlush(glJournalEntry); this.glJournalEntryRepository.saveAndFlush(glJournalEntry);
} }
} }
private void handleJournalEntryDataIntegrityIssues(final DataIntegrityViolationException dve) { private void handleJournalEntryDataIntegrityIssues(final DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause(); final Throwable realCause = dve.getMostSpecificCause();
logger.error(dve.getMessage(), dve); logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.glJournalEntry.unknown.data.integrity.issue", throw new PlatformDataIntegrityException("error.msg.glJournalEntry.unknown.data.integrity.issue",
"Unknown data integrity issue with resource Journal Entry: " + realCause.getMessage()); "Unknown data integrity issue with resource Journal Entry: " + realCause.getMessage());
@@ -29,18 +29,18 @@ public enum PortfolioProductType {
} }
public String getCode() { public String getCode() {
return code; return this.code;
} }
private static final Map<Integer, PortfolioProductType> intToEnumMap = new HashMap<Integer, PortfolioProductType>(); private static final Map<Integer, PortfolioProductType> intToEnumMap = new HashMap<Integer, PortfolioProductType>();
static { static {
for (PortfolioProductType type : PortfolioProductType.values()) { for (final PortfolioProductType type : PortfolioProductType.values()) {
intToEnumMap.put(type.value, type); intToEnumMap.put(type.value, type);
} }
} }
public static PortfolioProductType fromInt(int i) { public static PortfolioProductType fromInt(final int i) {
PortfolioProductType type = intToEnumMap.get(Integer.valueOf(i)); final PortfolioProductType type = intToEnumMap.get(Integer.valueOf(i));
return type; return type;
} }
@@ -43,7 +43,7 @@ public class ProductToGLAccountMapping extends AbstractPersistable<Long> {
// //
} }
public ProductToGLAccountMapping(GLAccount glAccount, Long productId, int productType, int financialAccountType) { public ProductToGLAccountMapping(final GLAccount glAccount, final Long productId, final int productType, final int financialAccountType) {
this.glAccount = glAccount; this.glAccount = glAccount;
this.productId = productId; this.productId = productId;
this.productType = productType; this.productType = productType;
@@ -54,7 +54,7 @@ public class ProductToGLAccountMapping extends AbstractPersistable<Long> {
return this.glAccount; return this.glAccount;
} }
public void setGlAccount(GLAccount glAccount) { public void setGlAccount(final GLAccount glAccount) {
this.glAccount = glAccount; this.glAccount = glAccount;
} }
@@ -62,7 +62,7 @@ public class ProductToGLAccountMapping extends AbstractPersistable<Long> {
return this.productId; return this.productId;
} }
public void setProductId(Long productId) { public void setProductId(final Long productId) {
this.productId = productId; this.productId = productId;
} }
@@ -70,7 +70,7 @@ public class ProductToGLAccountMapping extends AbstractPersistable<Long> {
return this.productType; return this.productType;
} }
public void setProductType(int productType) { public void setProductType(final int productType) {
this.productType = productType; this.productType = productType;
} }
@@ -78,7 +78,7 @@ public class ProductToGLAccountMapping extends AbstractPersistable<Long> {
return this.financialAccountType; return this.financialAccountType;
} }
public void setFinancialAccountType(int financialAccountType) { public void setFinancialAccountType(final int financialAccountType) {
this.financialAccountType = financialAccountType; this.financialAccountType = financialAccountType;
} }
@@ -13,8 +13,8 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul
*/ */
public class ProductToGLAccountMappingInvalidException extends AbstractPlatformDomainRuleException { public class ProductToGLAccountMappingInvalidException extends AbstractPlatformDomainRuleException {
public ProductToGLAccountMappingInvalidException(final String paramName, String accountName, Long accountId, public ProductToGLAccountMappingInvalidException(final String paramName, final String accountName, final Long accountId,
String actualAccountCategory, String expectedAccountCategory) { final String actualAccountCategory, final String expectedAccountCategory) {
super("error.msg." + paramName + ".invalid.account.type", "Passed in GLAccount " + paramName + " with Id " + accountId super("error.msg." + paramName + ".invalid.account.type", "Passed in GLAccount " + paramName + " with Id " + accountId
+ "maps to the account " + accountName + " of type " + actualAccountCategory + ", the expected account type was " + "maps to the account " + accountName + " of type " + actualAccountCategory + ", the expected account type was "
+ expectedAccountCategory, paramName, accountId, accountName, actualAccountCategory, expectedAccountCategory); + expectedAccountCategory, paramName, accountId, accountName, actualAccountCategory, expectedAccountCategory);
@@ -14,7 +14,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN
*/ */
public class ProductToGLAccountMappingNotFoundException extends AbstractPlatformResourceNotFoundException { public class ProductToGLAccountMappingNotFoundException extends AbstractPlatformResourceNotFoundException {
public ProductToGLAccountMappingNotFoundException(final PortfolioProductType type, final Long productId, String accountType) { public ProductToGLAccountMappingNotFoundException(final PortfolioProductType type, final Long productId, final String accountType) {
super("error.msg.productTyAccountMapping.not.found", "Mapping for product of type" + type.toString() + " with Id " + productId super("error.msg.productTyAccountMapping.not.found", "Mapping for product of type" + type.toString() + " with Id " + productId
+ " does not exist for an account of type " + accountType, type.toString(), productId, accountType); + " does not exist for an account of type " + accountType, type.toString(), productId, accountType);
} }
@@ -65,40 +65,41 @@ public final class ProductToGLAccountMappingFromApiJsonDeserializer {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanproduct"); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanproduct");
final JsonElement element = fromApiJsonHelper.parse(json); final JsonElement element = this.fromApiJsonHelper.parse(json);
// accounting related data validation // accounting related data validation
final Integer accountingRuleType = fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault()); final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault());
baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).notNull().inMinMaxRange(1, 3); baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).notNull().inMinMaxRange(1, 3);
if (isCashBasedAccounting(accountingRuleType) || isAccrualBasedAccounting(accountingRuleType)) { if (isCashBasedAccounting(accountingRuleType) || isAccrualBasedAccounting(accountingRuleType)) {
final Long fundAccountId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), element); final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(),
element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).value(fundAccountId).notNull() baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).value(fundAccountId).notNull()
.integerGreaterThanZero(); .integerGreaterThanZero();
final Long loanPortfolioAccountId = fromApiJsonHelper.extractLongNamed( final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element); LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue()).value(loanPortfolioAccountId) baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue()).value(loanPortfolioAccountId)
.notNull().integerGreaterThanZero(); .notNull().integerGreaterThanZero();
final Long incomeFromInterestId = fromApiJsonHelper.extractLongNamed( final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element); LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue()).value(incomeFromInterestId) baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue()).value(incomeFromInterestId)
.notNull().integerGreaterThanZero(); .notNull().integerGreaterThanZero();
final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(
element); LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId)
.notNull().integerGreaterThanZero(); .notNull().integerGreaterThanZero();
final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId)
.notNull().integerGreaterThanZero(); .notNull().integerGreaterThanZero();
final Long writeOffAccountId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed(
element); LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue()).value(writeOffAccountId) baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue()).value(writeOffAccountId)
.notNull().integerGreaterThanZero(); .notNull().integerGreaterThanZero();
@@ -106,17 +107,17 @@ public final class ProductToGLAccountMappingFromApiJsonDeserializer {
if (isAccrualBasedAccounting(accountingRuleType)) { if (isAccrualBasedAccounting(accountingRuleType)) {
final Long receivableInterestAccountId = fromApiJsonHelper.extractLongNamed( final Long receivableInterestAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element); LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue()) baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue())
.value(receivableInterestAccountId).notNull().integerGreaterThanZero(); .value(receivableInterestAccountId).notNull().integerGreaterThanZero();
final Long receivableFeeAccountId = fromApiJsonHelper.extractLongNamed( final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element); LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue()).value(receivableFeeAccountId) baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue()).value(receivableFeeAccountId)
.notNull().integerGreaterThanZero(); .notNull().integerGreaterThanZero();
final Long receivablePenaltyAccountId = fromApiJsonHelper.extractLongNamed( final Long receivablePenaltyAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element); LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue()) baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue())
.value(receivablePenaltyAccountId).notNull().integerGreaterThanZero(); .value(receivablePenaltyAccountId).notNull().integerGreaterThanZero();
@@ -70,10 +70,10 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product
if (AccountingRuleType.CASH_BASED.getValue().equals(accountingType)) { if (AccountingRuleType.CASH_BASED.getValue().equals(accountingType)) {
for (Map<String, Object> productToGLAccountMap : listOfProductToGLAccountMaps) { for (final Map<String, Object> productToGLAccountMap : listOfProductToGLAccountMaps) {
final Integer financialAccountType = (Integer) productToGLAccountMap.get("financialAccountType"); final Integer financialAccountType = (Integer) productToGLAccountMap.get("financialAccountType");
CASH_ACCOUNTS_FOR_LOAN glAccountForLoan = CASH_ACCOUNTS_FOR_LOAN.fromInt(financialAccountType); final CASH_ACCOUNTS_FOR_LOAN glAccountForLoan = CASH_ACCOUNTS_FOR_LOAN.fromInt(financialAccountType);
final Long glAccountId = (Long) productToGLAccountMap.get("glAccountId"); final Long glAccountId = (Long) productToGLAccountMap.get("glAccountId");
@@ -93,9 +93,9 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product
} }
} else if (AccountingRuleType.ACCRUAL_BASED.getValue().equals(accountingType)) { } else if (AccountingRuleType.ACCRUAL_BASED.getValue().equals(accountingType)) {
for (Map<String, Object> productToGLAccountMap : listOfProductToGLAccountMaps) { for (final Map<String, Object> productToGLAccountMap : listOfProductToGLAccountMaps) {
final Integer financialAccountType = (Integer) productToGLAccountMap.get("financialAccountType"); final Integer financialAccountType = (Integer) productToGLAccountMap.get("financialAccountType");
ACCRUAL_ACCOUNTS_FOR_LOAN glAccountForLoan = ACCRUAL_ACCOUNTS_FOR_LOAN.fromInt(financialAccountType); final ACCRUAL_ACCOUNTS_FOR_LOAN glAccountForLoan = ACCRUAL_ACCOUNTS_FOR_LOAN.fromInt(financialAccountType);
final Long glAccountId = (Long) productToGLAccountMap.get("glAccountId"); final Long glAccountId = (Long) productToGLAccountMap.get("glAccountId");
@@ -111,7 +111,7 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc
@Override @Override
@Transactional @Transactional
public Map<String, Object> updateLoanProductToGLAccountMapping(final Long loanProductId, final JsonCommand command, public Map<String, Object> updateLoanProductToGLAccountMapping(final Long loanProductId, final JsonCommand command,
final boolean accountingRuleChanged, int accountingRuleTypeId) { final boolean accountingRuleChanged, final int accountingRuleTypeId) {
/*** /***
* Variable tracks all accounting mapping properties that have been * Variable tracks all accounting mapping properties that have been
* updated * updated
@@ -125,7 +125,7 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc
* for the product and recreate a new set of mappings * for the product and recreate a new set of mappings
***/ ***/
if (accountingRuleChanged) { if (accountingRuleChanged) {
deserializer.validateForCreate(command.json()); this.deserializer.validateForCreate(command.json());
handleChangesToAccountingRuleType(loanProductId, command, changes, element, accountingRuleType); handleChangesToAccountingRuleType(loanProductId, command, changes, element, accountingRuleType);
}/*** else examine and update individual changes ***/ }/*** else examine and update individual changes ***/
else { else {