diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/GuarantorsApiResource.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/GuarantorsApiResource.java index 1e8a533a5..5e50693e8 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/GuarantorsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/GuarantorsApiResource.java @@ -35,84 +35,72 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class GuarantorsApiResource { - @Autowired - private GuarantorWritePlatformService guarantorWritePlatformService; + @Autowired + private GuarantorWritePlatformService guarantorWritePlatformService; - @Autowired - private GuarantorReadPlatformService guarantorReadPlatformService; + @Autowired + private GuarantorReadPlatformService guarantorReadPlatformService; - @Autowired - private PortfolioApiDataConversionService apiDataConversionService; + @Autowired + private PortfolioApiDataConversionService apiDataConversionService; - @Autowired - private PortfolioApiJsonSerializerService apiJsonSerializerService; + @Autowired + private PortfolioApiJsonSerializerService apiJsonSerializerService; - private static final Set typicalResponseParameters = new HashSet( - Arrays.asList("externalGuarantor", "existingClientId", "firstname", - "lastname", "addressLine1", "addressLine2", "city", - "state", "zip", "country", "mobileNumber", - "housePhoneNumber", "comment", "dob")); + private static final Set typicalResponseParameters = new HashSet(Arrays.asList("externalGuarantor", "existingClientId", + "firstname", "lastname", "addressLine1", "addressLine2", "city", "state", "zip", "country", "mobileNumber", "housePhoneNumber", + "comment", "dob")); - private final String SystemEntityType = "m_guarantor_external"; + private final String SystemEntityType = "m_guarantor_external"; - @Autowired - private PlatformSecurityContext context; + @Autowired + private PlatformSecurityContext context; - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveGuarantorDetails(@Context final UriInfo uriInfo, - @PathParam("loanId") final Long loanId) { - context.authenticatedUser().validateHasReadPermission(SystemEntityType); - Set responseParameters = ApiParameterHelper - .extractFieldsForResponseIfProvided(uriInfo - .getQueryParameters()); - if (responseParameters.isEmpty()) { - responseParameters.addAll(typicalResponseParameters); - } - boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo - .getQueryParameters()); + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveGuarantorDetails(@Context final UriInfo uriInfo, @PathParam("loanId") final Long loanId) { + context.authenticatedUser().validateHasReadPermission(SystemEntityType); + Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); + if (responseParameters.isEmpty()) { + responseParameters.addAll(typicalResponseParameters); + } + boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - GuarantorData guarantorData = guarantorReadPlatformService - .retrieveGuarantor(loanId); + GuarantorData guarantorData = guarantorReadPlatformService.retrieveGuarantor(loanId); - return this.apiJsonSerializerService.serializeGuarantorDataToJson( - prettyPrint, responseParameters, guarantorData); - } + return this.apiJsonSerializerService.serializeGuarantorDataToJson(prettyPrint, responseParameters, guarantorData); + } - @POST - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public Response createGuarantor(@PathParam("loanId") final Long loanId, - final String jsonRequestBody) { + @POST + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response createGuarantor(@PathParam("loanId") final Long loanId, final String jsonRequestBody) { - final GuarantorCommand command = this.apiDataConversionService - .convertJsonToGuarantorCommand(null, loanId, jsonRequestBody); + final GuarantorCommand command = this.apiDataConversionService.convertJsonToGuarantorCommand(null, loanId, jsonRequestBody); - this.guarantorWritePlatformService.createGuarantor(loanId, command); + this.guarantorWritePlatformService.createGuarantor(loanId, command); - // returns the loan Identifier for which the guarantor was associated - return Response.ok().entity(new EntityIdentifier(loanId)).build(); - } + // returns the loan Identifier for which the guarantor was associated + return Response.ok().entity(new EntityIdentifier(loanId)).build(); + } - @PUT - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public Response updateGuarantor(@PathParam("loanId") final Long loanId, - final String jsonRequestBody) { - final GuarantorCommand command = this.apiDataConversionService - .convertJsonToGuarantorCommand(null, loanId, jsonRequestBody); + @PUT + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response updateGuarantor(@PathParam("loanId") final Long loanId, final String jsonRequestBody) { + final GuarantorCommand command = this.apiDataConversionService.convertJsonToGuarantorCommand(null, loanId, jsonRequestBody); - this.guarantorWritePlatformService.updateGuarantor(loanId, command); + this.guarantorWritePlatformService.updateGuarantor(loanId, command); - return Response.ok().entity(new EntityIdentifier(loanId)).build(); - } + return Response.ok().entity(new EntityIdentifier(loanId)).build(); + } - @DELETE - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public Response deleteGuarantor(@PathParam("loanId") final Long loanId) { - this.guarantorWritePlatformService.removeGuarantor(loanId); - return Response.ok(new EntityIdentifier(loanId)).build(); - } + @DELETE + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response deleteGuarantor(@PathParam("loanId") final Long loanId) { + this.guarantorWritePlatformService.removeGuarantor(loanId); + return Response.ok(new EntityIdentifier(loanId)).build(); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/LoansApiResource.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/LoansApiResource.java index 528b06914..e499a9005 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/LoansApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/LoansApiResource.java @@ -70,442 +70,418 @@ import org.springframework.util.CollectionUtils; @Scope("singleton") public class LoansApiResource { - @Autowired - private LoanReadPlatformService loanReadPlatformService; + @Autowired + private LoanReadPlatformService loanReadPlatformService; - @Autowired - private LoanWritePlatformService loanWritePlatformService; - - @Autowired - private LoanProductReadPlatformService loanProductReadPlatformService; + @Autowired + private LoanWritePlatformService loanWritePlatformService; - @Autowired - private LoanDropdownReadPlatformService dropdownReadPlatformService; + @Autowired + private LoanProductReadPlatformService loanProductReadPlatformService; + + @Autowired + private LoanDropdownReadPlatformService dropdownReadPlatformService; + + @Autowired + private FundReadPlatformService fundReadPlatformService; - @Autowired - private FundReadPlatformService fundReadPlatformService; - @Autowired private ChargeReadPlatformService chargeReadPlatformService; - @Autowired - private CalculationPlatformService calculationPlatformService; + @Autowired + private CalculationPlatformService calculationPlatformService; - @Autowired - private PortfolioApiDataConversionService apiDataConversionService; - - @Autowired - private PortfolioApiJsonSerializerService apiJsonSerializerService; - - @Autowired - private StaffReadPlatformService staffReadPlatformService; + @Autowired + private PortfolioApiDataConversionService apiDataConversionService; + + @Autowired + private PortfolioApiJsonSerializerService apiJsonSerializerService; + + @Autowired + private StaffReadPlatformService staffReadPlatformService; @Autowired private PlatformSecurityContext context; - - @Autowired - private GuarantorReadPlatformService guarantorReadPlatformService; - - @GET - @Path("template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveDetailsForNewLoanApplicationStepOne( - @QueryParam("clientId") final Long clientId, - @QueryParam("groupId") final Long groupId, - @QueryParam("productId") final Long productId, - @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission("LOAN"); - - final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); - final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - - // tempate related - Collection productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup(); - Collection loanTermFrequencyTypeOptions = dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions(); - Collection repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions(); - Collection interestRateFrequencyTypeOptions = dropdownReadPlatformService.retrieveInterestRateFrequencyTypeOptions(); - - Collection amortizationTypeOptions = dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); - Collection interestTypeOptions = dropdownReadPlatformService.retrieveLoanInterestTypeOptions(); - Collection interestCalculationPeriodTypeOptions = dropdownReadPlatformService.retrieveLoanInterestRateCalculatedInPeriodOptions(); - - Collection fundOptions = this.fundReadPlatformService.retrieveAllFunds(); - Collection repaymentStrategyOptions = this.dropdownReadPlatformService.retreiveTransactionProcessingStrategies(); - - final boolean feeChargesOnly = false; - Collection chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly); - ChargeData chargeTemplate = this.chargeReadPlatformService.retrieveLoanChargeTemplate(); + @Autowired + private GuarantorReadPlatformService guarantorReadPlatformService; - LoanBasicDetailsData loanBasicDetails; - Long officeId; + @GET + @Path("template") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveDetailsForNewLoanApplicationStepOne(@QueryParam("clientId") final Long clientId, + @QueryParam("groupId") final Long groupId, @QueryParam("productId") final Long productId, @Context final UriInfo uriInfo) { - if ( clientId != null ){ - loanBasicDetails = this.loanReadPlatformService.retrieveClientAndProductDetails(clientId, productId); - officeId = loanBasicDetails.getClientOfficeId(); - } else { - loanBasicDetails = this.loanReadPlatformService.retrieveGroupAndProductDetails(groupId, productId); - officeId = loanBasicDetails.getGroupOfficeId(); + context.authenticatedUser().validateHasReadPermission("LOAN"); + + final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); + final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); + + // tempate related + Collection productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup(); + Collection loanTermFrequencyTypeOptions = dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions(); + Collection repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions(); + Collection interestRateFrequencyTypeOptions = dropdownReadPlatformService + .retrieveInterestRateFrequencyTypeOptions(); + + Collection amortizationTypeOptions = dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); + Collection interestTypeOptions = dropdownReadPlatformService.retrieveLoanInterestTypeOptions(); + Collection interestCalculationPeriodTypeOptions = dropdownReadPlatformService + .retrieveLoanInterestRateCalculatedInPeriodOptions(); + + Collection fundOptions = this.fundReadPlatformService.retrieveAllFunds(); + Collection repaymentStrategyOptions = this.dropdownReadPlatformService + .retreiveTransactionProcessingStrategies(); + + final boolean feeChargesOnly = false; + Collection chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly); + ChargeData chargeTemplate = this.chargeReadPlatformService.retrieveLoanChargeTemplate(); + + LoanBasicDetailsData loanBasicDetails; + Long officeId; + + if (clientId != null) { + loanBasicDetails = this.loanReadPlatformService.retrieveClientAndProductDetails(clientId, productId); + officeId = loanBasicDetails.getClientOfficeId(); + } else { + loanBasicDetails = this.loanReadPlatformService.retrieveGroupAndProductDetails(groupId, productId); + officeId = loanBasicDetails.getGroupOfficeId(); } - final boolean convenienceDataRequired = false; - Collection charges = loanBasicDetails.getCharges(); + final boolean convenienceDataRequired = false; + Collection charges = loanBasicDetails.getCharges(); - Collection allowedLoanOfficers = this.staffReadPlatformService.retrieveAllLoanOfficersByOffice(officeId); + Collection allowedLoanOfficers = this.staffReadPlatformService.retrieveAllLoanOfficersByOffice(officeId); - final LoanAccountData newLoanAccount = new LoanAccountData(loanBasicDetails, convenienceDataRequired, null, null, null, charges, - productOptions, loanTermFrequencyTypeOptions, repaymentFrequencyTypeOptions, - repaymentStrategyOptions, interestRateFrequencyTypeOptions, - amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, allowedLoanOfficers,null); + final LoanAccountData newLoanAccount = new LoanAccountData(loanBasicDetails, convenienceDataRequired, null, null, null, charges, + productOptions, loanTermFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentStrategyOptions, + interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, + fundOptions, chargeOptions, chargeTemplate, allowedLoanOfficers, null); - return this.apiJsonSerializerService.serializeLoanAccountDataToJson(prettyPrint, responseParameters, newLoanAccount); - } + return this.apiJsonSerializerService.serializeLoanAccountDataToJson(prettyPrint, responseParameters, newLoanAccount); + } - @GET - @Path("{loanId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveLoanAccountDetails( - @PathParam("loanId") final Long loanId, - @Context final UriInfo uriInfo) { + @GET + @Path("{loanId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveLoanAccountDetails(@PathParam("loanId") final Long loanId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission("LOAN"); - - final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); - final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - - final LoanBasicDetailsData loanBasicDetails = this.loanReadPlatformService.retrieveLoanAccountDetails(loanId); - - int loanRepaymentsCount = 0; - Collection loanRepayments = null; - LoanScheduleData repaymentSchedule = null; - LoanPermissionData permissions = null; + context.authenticatedUser().validateHasReadPermission("LOAN"); + + final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); + final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); + + final LoanBasicDetailsData loanBasicDetails = this.loanReadPlatformService.retrieveLoanAccountDetails(loanId); + + int loanRepaymentsCount = 0; + Collection loanRepayments = null; + LoanScheduleData repaymentSchedule = null; + LoanPermissionData permissions = null; Collection charges = null; GuarantorData guarantorData = null; boolean convenienceDataRequired = false; - final Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); - if (!associationParameters.isEmpty()) { - - if (associationParameters.contains("all")) { - associationParameters.addAll(Arrays.asList("repaymentSchedule", "transactions", "permissions", "convenienceData", "charges", "guarantor")); - } - - boolean existsGuarantor = false; - if (associationParameters.contains("guarantor")) { - if(guarantorReadPlatformService.existsGuarantor(loanId)){ - guarantorData = this.guarantorReadPlatformService.retrieveGuarantor(loanId); - existsGuarantor = true; - } - } - - if (associationParameters.contains("transactions")) { - final Collection currentLoanRepayments = this.loanReadPlatformService.retrieveLoanTransactions(loanId); - if (!CollectionUtils.isEmpty(currentLoanRepayments)) { - loanRepayments = currentLoanRepayments; - } - } - - if (associationParameters.contains("repaymentSchedule")) { - - DisbursementData singleDisbursement = loanBasicDetails.toDisburementData(); - repaymentSchedule = this.loanReadPlatformService.retrieveRepaymentSchedule(loanId, loanBasicDetails.getCurrency(), - singleDisbursement, loanBasicDetails.getTotalDisbursementCharges(), loanBasicDetails.getInArrearsTolerance()); - - // FIXME - KW - Waive feature was changed to waive interest at anytime so this permission checking is probably not needed - look into. - final MonetaryCurrency currency = new MonetaryCurrency(loanBasicDetails.getCurrency().getCode(), loanBasicDetails.getCurrency().getDecimalPlaces()); - final Money tolerance = Money.of(currency, loanBasicDetails.getInArrearsTolerance()); - final Money totalOutstandingMoney = Money.of(currency, repaymentSchedule.totalOutstanding()); - - boolean isWaiveAllowed = totalOutstandingMoney.isGreaterThanZero() && (tolerance.isGreaterThan(totalOutstandingMoney) || tolerance.isEqualTo(totalOutstandingMoney)); + final Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); + if (!associationParameters.isEmpty()) { - if (associationParameters.contains("permissions")) { - loanRepaymentsCount = retrieveNonDisbursementTransactions(loanRepayments); - permissions = this.loanReadPlatformService.retrieveLoanPermissions(loanBasicDetails, isWaiveAllowed, loanRepaymentsCount, existsGuarantor); - } - convenienceDataRequired = true; - } - - if (associationParameters.contains("charges")) { - charges = this.chargeReadPlatformService.retrieveLoanCharges(loanId); - if (CollectionUtils.isEmpty(charges)) { - charges = null; // set back to null so doesnt appear in JSON is no charges exist. - } - } - } + if (associationParameters.contains("all")) { + associationParameters.addAll(Arrays.asList("repaymentSchedule", "transactions", "permissions", "convenienceData", + "charges", "guarantor")); + } - Collection productOptions = null; - Collection loanTermFrequencyTypeOptions = null; - Collection repaymentFrequencyTypeOptions = null; - Collection repaymentStrategyOptions = null; - Collection interestRateFrequencyTypeOptions = null; - Collection amortizationTypeOptions = null; - Collection interestTypeOptions = null; - Collection interestCalculationPeriodTypeOptions = null; - Collection fundOptions = null; - Collection chargeOptions = null; - ChargeData chargeTemplate = null; - - final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters()); - if(template) { - productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup(); - loanTermFrequencyTypeOptions = dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions(); - repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions(); - interestRateFrequencyTypeOptions = dropdownReadPlatformService.retrieveInterestRateFrequencyTypeOptions(); - - amortizationTypeOptions = dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); - interestTypeOptions = dropdownReadPlatformService.retrieveLoanInterestTypeOptions(); - interestCalculationPeriodTypeOptions = dropdownReadPlatformService.retrieveLoanInterestRateCalculatedInPeriodOptions(); + boolean existsGuarantor = false; + if (associationParameters.contains("guarantor")) { + if (guarantorReadPlatformService.existsGuarantor(loanId)) { + guarantorData = this.guarantorReadPlatformService.retrieveGuarantor(loanId); + existsGuarantor = true; + } + } - fundOptions = this.fundReadPlatformService.retrieveAllFunds(); - repaymentStrategyOptions = this.dropdownReadPlatformService.retreiveTransactionProcessingStrategies(); - final boolean feeChargesOnly = false; - chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly); - chargeTemplate = this.chargeReadPlatformService.retrieveLoanChargeTemplate(); - } - - final LoanAccountData loanAccount = new LoanAccountData(loanBasicDetails, convenienceDataRequired, - repaymentSchedule, loanRepayments, permissions, charges, - productOptions, loanTermFrequencyTypeOptions, repaymentFrequencyTypeOptions, - repaymentStrategyOptions, interestRateFrequencyTypeOptions, - amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, - fundOptions, chargeOptions, chargeTemplate, null, guarantorData); - - return this.apiJsonSerializerService.serializeLoanAccountDataToJson(prettyPrint, responseParameters, loanAccount); - } + if (associationParameters.contains("transactions")) { + final Collection currentLoanRepayments = this.loanReadPlatformService.retrieveLoanTransactions(loanId); + if (!CollectionUtils.isEmpty(currentLoanRepayments)) { + loanRepayments = currentLoanRepayments; + } + } - private int retrieveNonDisbursementTransactions(final Collection loanRepayments) { - int loanRepaymentsCount = 0; - if (!CollectionUtils.isEmpty(loanRepayments)) { - for (LoanTransactionData transaction : loanRepayments) { - if (transaction.isNotDisbursement()) { - // use this to decide if undo disbural should permission should be set to true. - loanRepaymentsCount++; - } - } - } - return loanRepaymentsCount; - } + if (associationParameters.contains("repaymentSchedule")) { - @POST - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String calculateLoanScheduleOrSubmitLoanApplication( - @QueryParam("command") final String commandParam, - @Context final UriInfo uriInfo, - final String jsonRequestBody) { + DisbursementData singleDisbursement = loanBasicDetails.toDisburementData(); + repaymentSchedule = this.loanReadPlatformService.retrieveRepaymentSchedule(loanId, loanBasicDetails.getCurrency(), + singleDisbursement, loanBasicDetails.getTotalDisbursementCharges(), loanBasicDetails.getInArrearsTolerance()); - final LoanApplicationCommand command = this.apiDataConversionService.convertJsonToLoanApplicationCommand(null, jsonRequestBody); + // FIXME - KW - Waive feature was changed to waive interest at + // anytime so this permission checking is probably not needed - + // look into. + final MonetaryCurrency currency = new MonetaryCurrency(loanBasicDetails.getCurrency().getCode(), loanBasicDetails + .getCurrency().getDecimalPlaces()); + final Money tolerance = Money.of(currency, loanBasicDetails.getInArrearsTolerance()); + final Money totalOutstandingMoney = Money.of(currency, repaymentSchedule.totalOutstanding()); - if (is(commandParam, "calculateLoanSchedule")) { - CalculateLoanScheduleCommand calculateLoanScheduleCommand = command.toCalculateLoanScheduleCommand(); - return calculateLoanSchedule(uriInfo, calculateLoanScheduleCommand); - } + boolean isWaiveAllowed = totalOutstandingMoney.isGreaterThanZero() + && (tolerance.isGreaterThan(totalOutstandingMoney) || tolerance.isEqualTo(totalOutstandingMoney)); - final EntityIdentifier identifier = this.loanWritePlatformService.submitLoanApplication(command); + if (associationParameters.contains("permissions")) { + loanRepaymentsCount = retrieveNonDisbursementTransactions(loanRepayments); + permissions = this.loanReadPlatformService.retrieveLoanPermissions(loanBasicDetails, isWaiveAllowed, + loanRepaymentsCount, existsGuarantor); + } + convenienceDataRequired = true; + } - return this.apiJsonSerializerService.serializeEntityIdentifier(identifier); - } + if (associationParameters.contains("charges")) { + charges = this.chargeReadPlatformService.retrieveLoanCharges(loanId); + if (CollectionUtils.isEmpty(charges)) { + charges = null; // set back to null so doesnt appear in JSON + // is no charges exist. + } + } + } - private String calculateLoanSchedule(final UriInfo uriInfo, final CalculateLoanScheduleCommand command) { - - final LoanScheduleData loanSchedule = this.calculationPlatformService.calculateLoanSchedule(command); + Collection productOptions = null; + Collection loanTermFrequencyTypeOptions = null; + Collection repaymentFrequencyTypeOptions = null; + Collection repaymentStrategyOptions = null; + Collection interestRateFrequencyTypeOptions = null; + Collection amortizationTypeOptions = null; + Collection interestTypeOptions = null; + Collection interestCalculationPeriodTypeOptions = null; + Collection fundOptions = null; + Collection chargeOptions = null; + ChargeData chargeTemplate = null; - final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); - boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - - return this.apiJsonSerializerService.serializeLoanScheduleDataToJson(prettyPrint, responseParameters, loanSchedule); - } - - @PUT - @Path("{loanId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public String modifyLoanApplication( - @PathParam("loanId") final Long loanId, - final String jsonRequestBody) { + final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters()); + if (template) { + productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup(); + loanTermFrequencyTypeOptions = dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions(); + repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions(); + interestRateFrequencyTypeOptions = dropdownReadPlatformService.retrieveInterestRateFrequencyTypeOptions(); - final LoanApplicationCommand command = this.apiDataConversionService.convertJsonToLoanApplicationCommand(loanId, jsonRequestBody); + amortizationTypeOptions = dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); + interestTypeOptions = dropdownReadPlatformService.retrieveLoanInterestTypeOptions(); + interestCalculationPeriodTypeOptions = dropdownReadPlatformService.retrieveLoanInterestRateCalculatedInPeriodOptions(); - final EntityIdentifier identifier = this.loanWritePlatformService.modifyLoanApplication(command); + fundOptions = this.fundReadPlatformService.retrieveAllFunds(); + repaymentStrategyOptions = this.dropdownReadPlatformService.retreiveTransactionProcessingStrategies(); + final boolean feeChargesOnly = false; + chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly); + chargeTemplate = this.chargeReadPlatformService.retrieveLoanChargeTemplate(); + } - return this.apiJsonSerializerService.serializeEntityIdentifier(identifier); - } + final LoanAccountData loanAccount = new LoanAccountData(loanBasicDetails, convenienceDataRequired, repaymentSchedule, + loanRepayments, permissions, charges, productOptions, loanTermFrequencyTypeOptions, repaymentFrequencyTypeOptions, + repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, + interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, null, guarantorData); - @DELETE - @Path("{loanId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public Response deleteLoanApplication(@PathParam("loanId") final Long loanId) { + return this.apiJsonSerializerService.serializeLoanAccountDataToJson(prettyPrint, responseParameters, loanAccount); + } - EntityIdentifier identifier = this.loanWritePlatformService.deleteLoan(loanId); + private int retrieveNonDisbursementTransactions(final Collection loanRepayments) { + int loanRepaymentsCount = 0; + if (!CollectionUtils.isEmpty(loanRepayments)) { + for (LoanTransactionData transaction : loanRepayments) { + if (transaction.isNotDisbursement()) { + // use this to decide if undo disbural should permission + // should be set to true. + loanRepaymentsCount++; + } + } + } + return loanRepaymentsCount; + } - return Response.ok().entity(identifier).build(); - } + @POST + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String calculateLoanScheduleOrSubmitLoanApplication(@QueryParam("command") final String commandParam, + @Context final UriInfo uriInfo, final String jsonRequestBody) { - @POST - @Path("{loanId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public Response stateTransitions(@PathParam("loanId") final Long loanId, - @QueryParam("command") final String commandParam, - final String jsonRequestBody) { + final LoanApplicationCommand command = this.apiDataConversionService.convertJsonToLoanApplicationCommand(null, jsonRequestBody); - LoanStateTransitionCommand command = this.apiDataConversionService.convertJsonToLoanStateTransitionCommand(loanId, jsonRequestBody); + if (is(commandParam, "calculateLoanSchedule")) { + CalculateLoanScheduleCommand calculateLoanScheduleCommand = command.toCalculateLoanScheduleCommand(); + return calculateLoanSchedule(uriInfo, calculateLoanScheduleCommand); + } - Response response = null; + final EntityIdentifier identifier = this.loanWritePlatformService.submitLoanApplication(command); - if (is(commandParam, "reject")) { - EntityIdentifier identifier = this.loanWritePlatformService - .rejectLoan(command); - response = Response.ok().entity(identifier).build(); - } else if (is(commandParam, "withdrewbyclient")) { - EntityIdentifier identifier = this.loanWritePlatformService - .withdrawLoan(command); - response = Response.ok().entity(identifier).build(); - } else if (is(commandParam, "approve")) { - EntityIdentifier identifier = this.loanWritePlatformService - .approveLoanApplication(command); - response = Response.ok().entity(identifier).build(); - } else if (is(commandParam, "disburse")) { - EntityIdentifier identifier = this.loanWritePlatformService - .disburseLoan(command); - response = Response.ok().entity(identifier).build(); - } + return this.apiJsonSerializerService.serializeEntityIdentifier(identifier); + } - UndoStateTransitionCommand undoCommand = new UndoStateTransitionCommand( - loanId, command.getNote()); + private String calculateLoanSchedule(final UriInfo uriInfo, final CalculateLoanScheduleCommand command) { - if (is(commandParam, "undoapproval")) { - EntityIdentifier identifier = this.loanWritePlatformService - .undoLoanApproval(undoCommand); - response = Response.ok().entity(identifier).build(); - } else if (is(commandParam, "undodisbursal")) { - EntityIdentifier identifier = this.loanWritePlatformService - .undoLoanDisbursal(undoCommand); - response = Response.ok().entity(identifier).build(); - } + final LoanScheduleData loanSchedule = this.calculationPlatformService.calculateLoanSchedule(command); - if (response == null) { - throw new UnrecognizedQueryParamException("command", commandParam); - } + final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); + boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - return response; - } + return this.apiJsonSerializerService.serializeLoanScheduleDataToJson(prettyPrint, responseParameters, loanSchedule); + } - private boolean is(final String commandParam, final String commandValue) { - return StringUtils.isNotBlank(commandParam) - && commandParam.trim().equalsIgnoreCase(commandValue); - } + @PUT + @Path("{loanId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String modifyLoanApplication(@PathParam("loanId") final Long loanId, final String jsonRequestBody) { - @POST - @Path("{loanId}/transactions") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public Response executeLoanTransaction( - @PathParam("loanId") final Long loanId, - @QueryParam("command") final String commandParam, - final String jsonRequestBody) { + final LoanApplicationCommand command = this.apiDataConversionService.convertJsonToLoanApplicationCommand(loanId, jsonRequestBody); - final LoanTransactionCommand command = this.apiDataConversionService.convertJsonToLoanTransactionCommand(loanId, jsonRequestBody); + final EntityIdentifier identifier = this.loanWritePlatformService.modifyLoanApplication(command); - EntityIdentifier identifier = null; - if (is(commandParam, "repayment")) { - identifier = this.loanWritePlatformService.makeLoanRepayment(command); - } else if (is(commandParam, "waiveinterest")) { - identifier = this.loanWritePlatformService.waiveInterestOnLoan(command); - } else if (is(commandParam, "writeoff")) { - identifier = this.loanWritePlatformService.writeOff(command); - } else if (is(commandParam, "close-rescheduled")) { - identifier = this.loanWritePlatformService.closeAsRescheduled(command); - } else if (is(commandParam, "close")) { - identifier = this.loanWritePlatformService.closeLoan(command); - } + return this.apiJsonSerializerService.serializeEntityIdentifier(identifier); + } - if (identifier == null) { - throw new UnrecognizedQueryParamException("command", commandParam); - } + @DELETE + @Path("{loanId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response deleteLoanApplication(@PathParam("loanId") final Long loanId) { - return Response.ok().entity(identifier).build(); - } + EntityIdentifier identifier = this.loanWritePlatformService.deleteLoan(loanId); - @GET - @Path("{loanId}/transactions/template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveNewRepaymentDetails( - @PathParam("loanId") final Long loanId, - @QueryParam("command") final String commandParam, - @Context final UriInfo uriInfo) { + return Response.ok().entity(identifier).build(); + } - context.authenticatedUser().validateHasReadPermission("LOAN"); - - final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); - final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - - LoanTransactionData transactionData = null; - if (is(commandParam, "repayment")) { - transactionData = this.loanReadPlatformService.retrieveNewLoanRepaymentDetails(loanId); - } else if (is(commandParam, "waiveinterest")) { - transactionData = this.loanReadPlatformService.retrieveNewLoanWaiveInterestDetails(loanId); - } else if (is(commandParam, "writeoff")) { - transactionData = this.loanReadPlatformService.retrieveNewClosureDetails(); - } else if (is(commandParam, "close-rescheduled")) { - transactionData = this.loanReadPlatformService.retrieveNewClosureDetails(); - } else if (is(commandParam, "close")) { - transactionData = this.loanReadPlatformService.retrieveNewClosureDetails(); - } else { - throw new UnrecognizedQueryParamException("command", commandParam); - } - - return this.apiJsonSerializerService.serializeLoanTransactionDataToJson(prettyPrint, responseParameters, transactionData); - } + @POST + @Path("{loanId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response stateTransitions(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam, + final String jsonRequestBody) { - @GET - @Path("{loanId}/transactions/{transactionId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveTransaction(@PathParam("loanId") final Long loanId, - @PathParam("transactionId") final Long transactionId, - @Context final UriInfo uriInfo) { + LoanStateTransitionCommand command = this.apiDataConversionService.convertJsonToLoanStateTransitionCommand(loanId, jsonRequestBody); - context.authenticatedUser().validateHasReadPermission("LOAN"); - - final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); - final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - - final LoanTransactionData transactionData = this.loanReadPlatformService.retrieveLoanTransactionDetails(loanId, transactionId); + Response response = null; - return this.apiJsonSerializerService.serializeLoanTransactionDataToJson(prettyPrint, responseParameters, transactionData); - } + if (is(commandParam, "reject")) { + EntityIdentifier identifier = this.loanWritePlatformService.rejectLoan(command); + response = Response.ok().entity(identifier).build(); + } else if (is(commandParam, "withdrewbyclient")) { + EntityIdentifier identifier = this.loanWritePlatformService.withdrawLoan(command); + response = Response.ok().entity(identifier).build(); + } else if (is(commandParam, "approve")) { + EntityIdentifier identifier = this.loanWritePlatformService.approveLoanApplication(command); + response = Response.ok().entity(identifier).build(); + } else if (is(commandParam, "disburse")) { + EntityIdentifier identifier = this.loanWritePlatformService.disburseLoan(command); + response = Response.ok().entity(identifier).build(); + } - @POST - @Path("{loanId}/transactions/{transactionId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public Response adjustLoanTransaction( - @PathParam("loanId") final Long loanId, - @PathParam("transactionId") final Long transactionId, - final String jsonRequestBody) { + UndoStateTransitionCommand undoCommand = new UndoStateTransitionCommand(loanId, command.getNote()); - final AdjustLoanTransactionCommand command = this.apiDataConversionService - .convertJsonToAdjustLoanTransactionCommand(loanId, - transactionId, jsonRequestBody); + if (is(commandParam, "undoapproval")) { + EntityIdentifier identifier = this.loanWritePlatformService.undoLoanApproval(undoCommand); + response = Response.ok().entity(identifier).build(); + } else if (is(commandParam, "undodisbursal")) { + EntityIdentifier identifier = this.loanWritePlatformService.undoLoanDisbursal(undoCommand); + response = Response.ok().entity(identifier).build(); + } - EntityIdentifier identifier = this.loanWritePlatformService - .adjustLoanTransaction(command); + if (response == null) { throw new UnrecognizedQueryParamException("command", commandParam); } - return Response.ok().entity(identifier).build(); - } + return response; + } + + private boolean is(final String commandParam, final String commandValue) { + return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); + } + + @POST + @Path("{loanId}/transactions") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response executeLoanTransaction(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam, + final String jsonRequestBody) { + + final LoanTransactionCommand command = this.apiDataConversionService.convertJsonToLoanTransactionCommand(loanId, jsonRequestBody); + + EntityIdentifier identifier = null; + if (is(commandParam, "repayment")) { + identifier = this.loanWritePlatformService.makeLoanRepayment(command); + } else if (is(commandParam, "waiveinterest")) { + identifier = this.loanWritePlatformService.waiveInterestOnLoan(command); + } else if (is(commandParam, "writeoff")) { + identifier = this.loanWritePlatformService.writeOff(command); + } else if (is(commandParam, "close-rescheduled")) { + identifier = this.loanWritePlatformService.closeAsRescheduled(command); + } else if (is(commandParam, "close")) { + identifier = this.loanWritePlatformService.closeLoan(command); + } + + if (identifier == null) { throw new UnrecognizedQueryParamException("command", commandParam); } + + return Response.ok().entity(identifier).build(); + } + + @GET + @Path("{loanId}/transactions/template") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveNewRepaymentDetails(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam, + @Context final UriInfo uriInfo) { + + context.authenticatedUser().validateHasReadPermission("LOAN"); + + final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); + final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); + + LoanTransactionData transactionData = null; + if (is(commandParam, "repayment")) { + transactionData = this.loanReadPlatformService.retrieveNewLoanRepaymentDetails(loanId); + } else if (is(commandParam, "waiveinterest")) { + transactionData = this.loanReadPlatformService.retrieveNewLoanWaiveInterestDetails(loanId); + } else if (is(commandParam, "writeoff")) { + transactionData = this.loanReadPlatformService.retrieveNewClosureDetails(); + } else if (is(commandParam, "close-rescheduled")) { + transactionData = this.loanReadPlatformService.retrieveNewClosureDetails(); + } else if (is(commandParam, "close")) { + transactionData = this.loanReadPlatformService.retrieveNewClosureDetails(); + } else { + throw new UnrecognizedQueryParamException("command", commandParam); + } + + return this.apiJsonSerializerService.serializeLoanTransactionDataToJson(prettyPrint, responseParameters, transactionData); + } + + @GET + @Path("{loanId}/transactions/{transactionId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveTransaction(@PathParam("loanId") final Long loanId, @PathParam("transactionId") final Long transactionId, + @Context final UriInfo uriInfo) { + + context.authenticatedUser().validateHasReadPermission("LOAN"); + + final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); + final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); + + final LoanTransactionData transactionData = this.loanReadPlatformService.retrieveLoanTransactionDetails(loanId, transactionId); + + return this.apiJsonSerializerService.serializeLoanTransactionDataToJson(prettyPrint, responseParameters, transactionData); + } + + @POST + @Path("{loanId}/transactions/{transactionId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response adjustLoanTransaction(@PathParam("loanId") final Long loanId, @PathParam("transactionId") final Long transactionId, + final String jsonRequestBody) { + + final AdjustLoanTransactionCommand command = this.apiDataConversionService.convertJsonToAdjustLoanTransactionCommand(loanId, + transactionId, jsonRequestBody); + + EntityIdentifier identifier = this.loanWritePlatformService.adjustLoanTransaction(command); + + return Response.ok().entity(identifier).build(); + } @POST @Path("{loanId}/charges") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public Response addLoanCharge( - @PathParam("loanId") final Long loanId, - final String jsonRequestBody){ + public Response addLoanCharge(@PathParam("loanId") final Long loanId, final String jsonRequestBody) { final LoanChargeCommand command = this.apiDataConversionService.convertJsonToLoanChargeCommand(null, loanId, jsonRequestBody); @@ -516,14 +492,14 @@ public class LoansApiResource { @GET @Path("{loanId}/charges/template") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public String retrieveNewLoanChargeDetails(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission("LOAN"); - - final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); - final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); + context.authenticatedUser().validateHasReadPermission("LOAN"); + + final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); + final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean feeChargesOnly = false; final Collection chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly); @@ -534,57 +510,52 @@ public class LoansApiResource { @GET @Path("{loanId}/charges/{chargeId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public String retrieveLoanCharge( - @PathParam("loanId") final Long loanId, - @PathParam("chargeId") final Long loanChargeId, - @Context final UriInfo uriInfo){ + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId, + @Context final UriInfo uriInfo) { + + context.authenticatedUser().validateHasReadPermission("LOAN"); + + final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); + final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - context.authenticatedUser().validateHasReadPermission("LOAN"); - - final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); - final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - final LoanChargeData loanCharge = this.chargeReadPlatformService.retrieveLoanChargeDetails(loanChargeId, loanId); - + return this.apiJsonSerializerService.serializeLoanChargeDataToJson(prettyPrint, responseParameters, loanCharge); } - + @PUT @Path("{loanId}/charges/{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String updateLoanCharge( - @PathParam("loanId") final Long loanId, - @PathParam("chargeId") final Long loanChargeId, - final String jsonRequestBody){ + public String updateLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId, + final String jsonRequestBody) { - final LoanChargeCommand command = this.apiDataConversionService.convertJsonToLoanChargeCommand(loanChargeId, loanId, jsonRequestBody); + final LoanChargeCommand command = this.apiDataConversionService.convertJsonToLoanChargeCommand(loanChargeId, loanId, + jsonRequestBody); final EntityIdentifier identifier = this.loanWritePlatformService.updateLoanCharge(command); return this.apiJsonSerializerService.serializeEntityIdentifier(identifier); } - + @POST @Path("{loanId}/charges/{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String waiveLoanCharge( - @PathParam("loanId") final Long loanId, - @PathParam("chargeId") final Long loanChargeId, - @QueryParam("command") final String commandParam){ + public String waiveLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId, + @QueryParam("command") final String commandParam) { + + final LoanChargeCommand command = LoanChargeCommand.forWaiver(loanChargeId, loanId); - final LoanChargeCommand command = LoanChargeCommand.forWaiver(loanChargeId, loanId); - String json = ""; - if (is(commandParam, "waive")) { - final EntityIdentifier identifier = this.loanWritePlatformService.waiveLoanCharge(command); - json = this.apiJsonSerializerService.serializeEntityIdentifier(identifier); - } else { - throw new UnrecognizedQueryParamException("command", commandParam); - } + if (is(commandParam, "waive")) { + final EntityIdentifier identifier = this.loanWritePlatformService.waiveLoanCharge(command); + json = this.apiJsonSerializerService.serializeEntityIdentifier(identifier); + } else { + throw new UnrecognizedQueryParamException("command", commandParam); + } return json; } @@ -593,9 +564,7 @@ public class LoansApiResource { @Path("{loanId}/charges/{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String deleteLoanCharge( - @PathParam("loanId") final Long loanId, - @PathParam("chargeId") final Long loanChargeId){ + public String deleteLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId) { final EntityIdentifier identifier = this.loanWritePlatformService.deleteLoanCharge(loanId, loanChargeId); return this.apiJsonSerializerService.serializeEntityIdentifier(identifier); @@ -605,9 +574,7 @@ public class LoansApiResource { @Path("{loanId}/assign") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public Response assignLoanOfficer( - @PathParam("loanId") final Long loanId, - final String jsonRequestBody){ + public Response assignLoanOfficer(@PathParam("loanId") final Long loanId, final String jsonRequestBody) { final LoanReassignmentCommand command = this.apiDataConversionService.convertJsonToLoanReassignmentCommand(loanId, jsonRequestBody); @@ -620,19 +587,16 @@ public class LoansApiResource { @Path("{loanId}/assign/template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String assignLoanOfficerTemplate( - @PathParam("loanId") final Long loanId, - @Context final UriInfo uriInfo){ + public String assignLoanOfficerTemplate(@PathParam("loanId") final Long loanId, @Context final UriInfo uriInfo) { - final Set responseParameters = ApiParameterHelper - .extractFieldsForResponseIfProvided(uriInfo - .getQueryParameters()); + final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); LoanBasicDetailsData loanBasicDetails = this.loanReadPlatformService.retrieveLoanAccountDetails(loanId); - Collection allowedLoanOfficers = this.staffReadPlatformService.retrieveAllLoanOfficersByOffice(loanBasicDetails.getOfficeId()); + Collection allowedLoanOfficers = this.staffReadPlatformService.retrieveAllLoanOfficersByOffice(loanBasicDetails + .getOfficeId()); Long fromLoanOfficerId = loanBasicDetails.getLoanOfficerId(); LoanReassignmentData loanReassignmentData = LoanReassignmentData.template(fromLoanOfficerId, allowedLoanOfficers, new LocalDate()); diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/commands/GuarantorCommand.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/commands/GuarantorCommand.java index b5fe103b4..0ce078500 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/commands/GuarantorCommand.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/commands/GuarantorCommand.java @@ -7,135 +7,132 @@ import java.util.Set; */ public class GuarantorCommand { - private final boolean externalGuarantor; + private final boolean externalGuarantor; - /*** Fields for current customers serving as guarantors **/ - private final Long existingClientId; + /*** Fields for current customers serving as guarantors **/ + private final Long existingClientId; - /*** Fields for external persons serving as guarantors ***/ - private final String firstname; - private final String lastname; - private final String addressLine1; - private final String addressLine2; - private final String city; - private final String state; - private final String zip; - private final String country; - private final String mobileNumber; - private final String housePhoneNumber; - private final String comment; - private final String dob; - - /**Feilds for passing Locale info to generic data service api**/ - private String dateFormat; - private String locale; + /*** Fields for external persons serving as guarantors ***/ + // FIXME - kw - what the details for collecting guarantors change? we are using datatable approach but fixing here? + private final String firstname; + private final String lastname; + private final String addressLine1; + private final String addressLine2; + private final String city; + private final String state; + private final String zip; + private final String country; + private final String mobileNumber; + private final String housePhoneNumber; + private final String comment; + private final String dob; - private final Set modifiedParameters; + /** Feilds for passing Locale info to generic data service api **/ + private String dateFormat; + private String locale; - public GuarantorCommand(final Set modifiedParameters, - final Long existingClientId, final String firstname, - final String lastname, final Boolean externalGuarantor, - final String addressLine1, final String addressLine2, - final String city, final String state, final String zip, - final String country, final String mobileNumber, - final String housePhoneNumber, final String comment, - final String dob) { - this.modifiedParameters = modifiedParameters; + private final Set modifiedParameters; - this.externalGuarantor = externalGuarantor; + public GuarantorCommand(final Set modifiedParameters, final Long existingClientId, final String firstname, + final String lastname, final Boolean externalGuarantor, final String addressLine1, final String addressLine2, + final String city, final String state, final String zip, final String country, final String mobileNumber, + final String housePhoneNumber, final String comment, final String dob) { + this.modifiedParameters = modifiedParameters; - /*** Fields for current customers serving as guarantors **/ - this.existingClientId = existingClientId; + this.externalGuarantor = externalGuarantor; - /*** Fields for external persons serving as guarantors ***/ - this.firstname = firstname; - this.lastname = lastname; - this.addressLine1 = addressLine1; - this.addressLine2 = addressLine2; - this.city = city; - this.state = state; - this.zip = zip; - this.country = country; - this.mobileNumber = mobileNumber; - this.housePhoneNumber = housePhoneNumber; - this.comment = comment; - this.dob = dob; - } + /*** Fields for current customers serving as guarantors **/ + this.existingClientId = existingClientId; - public String getFirstname() { - return firstname; - } + /*** Fields for external persons serving as guarantors ***/ + this.firstname = firstname; + this.lastname = lastname; + this.addressLine1 = addressLine1; + this.addressLine2 = addressLine2; + this.city = city; + this.state = state; + this.zip = zip; + this.country = country; + this.mobileNumber = mobileNumber; + this.housePhoneNumber = housePhoneNumber; + this.comment = comment; + this.dob = dob; + } - public String getLastname() { - return lastname; - } + public String getFirstname() { + return firstname; + } - public Boolean isExternalGuarantor() { - return externalGuarantor; - } + public String getLastname() { + return lastname; + } - public Long getExistingClientId() { - return existingClientId; - } + public Boolean isExternalGuarantor() { + return externalGuarantor; + } - public String getAddressLine1() { - return addressLine1; - } + public Long getExistingClientId() { + return existingClientId; + } - public String getAddressLine2() { - return addressLine2; - } + public String getAddressLine1() { + return addressLine1; + } - public String getCity() { - return city; - } + public String getAddressLine2() { + return addressLine2; + } - public String getState() { - return state; - } + public String getCity() { + return city; + } - public String getZip() { - return zip; - } + public String getState() { + return state; + } - public String getCountry() { - return country; - } + public String getZip() { + return zip; + } - public String getMobileNumber() { - return mobileNumber; - } + public String getCountry() { + return country; + } - public String getHousePhoneNumber() { - return housePhoneNumber; - } + public String getMobileNumber() { + return mobileNumber; + } - public String getComment() { - return comment; - } + public String getHousePhoneNumber() { + return housePhoneNumber; + } - public Set getModifiedParameters() { - return modifiedParameters; - } + public String getComment() { + return comment; + } - public String getDob() { - return dob; - } + public Set getModifiedParameters() { + return modifiedParameters; + } - public String getDateFormat() { - return dateFormat; - } + public String getDob() { + return dob; + } - public void setDateFormat(String dateFormat) { - this.dateFormat = dateFormat; - } + public String getDateFormat() { + return dateFormat; + } - public String getLocale() { - return locale; - } + public void setDateFormat(String dateFormat) { + this.dateFormat = dateFormat; + } - public void setLocale(String locale) { - this.locale = locale; - } + public String getLocale() { + return locale; + } + + public void setLocale(String locale) { + this.locale = locale; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java index a449cce1c..63ec766eb 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java @@ -95,7 +95,7 @@ public interface PortfolioApiDataConversionService { CodeCommand convertJsonToCodeCommand(Long resourceIdentifier, String json); - SavingAccountCommand convertJsonToSavingAccountCommand(Long resourceIdentifier,String json); - - GuarantorCommand convertJsonToGuarantorCommand(Long resourceIdentifier, Long loanId, String json); + SavingAccountCommand convertJsonToSavingAccountCommand(Long resourceIdentifier, String json); + + GuarantorCommand convertJsonToGuarantorCommand(Long resourceIdentifier, Long loanId, String json); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java index a253b00fc..6cfe58550 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java @@ -1629,68 +1629,46 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo savingProductType, tenureType, frequency, interestType, minimumBalanceForWithdrawal, interestCalculationMethod, isLockinPeriodAllowed, isPartialDepositAllowed, lockinPeriod, lockinPeriodType); } - + @Override - public GuarantorCommand convertJsonToGuarantorCommand( - Long resourceIdentifier, Long loanId, String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public GuarantorCommand convertJsonToGuarantorCommand(Long resourceIdentifier, Long loanId, String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - Type typeOfMap = new TypeToken>() { - }.getType(); - Map requestMap = gsonConverter - .fromJson(json, typeOfMap); + Type typeOfMap = new TypeToken>() {}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); - Set supportedParams = new HashSet(Arrays.asList( - "externalGuarantor", "existingClientId", "firstname", - "lastname", "addressLine1", "addressLine2", "city", "state", - "zip", "country", "mobileNumber", "housePhoneNumber", - "comment", "dob", "locale", "dateFormat")); + Set supportedParams = new HashSet(Arrays.asList("externalGuarantor", "existingClientId", "firstname", "lastname", + "addressLine1", "addressLine2", "city", "state", "zip", "country", "mobileNumber", "housePhoneNumber", "comment", "dob", + "locale", "dateFormat")); - checkForUnsupportedParameters(requestMap, supportedParams); + checkForUnsupportedParameters(requestMap, supportedParams); - Set modifiedParameters = new HashSet(); + Set modifiedParameters = new HashSet(); - boolean externalGuarantor = extractBooleanParameter( - "externalGuarantor", requestMap, modifiedParameters); + boolean externalGuarantor = extractBooleanParameter("externalGuarantor", requestMap, modifiedParameters); - Long existingClientId = extractLongParameter("existingClientId", - requestMap, modifiedParameters); - String firstname = extractStringParameter("firstname", requestMap, - modifiedParameters); - String lastname = extractStringParameter("lastname", requestMap, - modifiedParameters); - String addressLine1 = extractStringParameter("addressLine1", - requestMap, modifiedParameters); - String addressLine2 = extractStringParameter("addressLine2", - requestMap, modifiedParameters); - String city = extractStringParameter("city", requestMap, - modifiedParameters); - String state = extractStringParameter("state", requestMap, - modifiedParameters); - String zip = extractStringParameter("zip", requestMap, - modifiedParameters); - String country = extractStringParameter("country", requestMap, - modifiedParameters); - String mobileNumber = extractStringParameter("mobileNumber", - requestMap, modifiedParameters); - String housePhoneNumber = extractStringParameter("housePhoneNumber", - requestMap, modifiedParameters); - String comment = extractStringParameter("comment", requestMap, - modifiedParameters); - String dob = extractStringParameter("dob", requestMap, - modifiedParameters); - // workaround for passing locale info to data table api - final String dateFormat = (String) requestMap.get("dateFormat"); - final String locale = (String) requestMap.get("locale"); + Long existingClientId = extractLongParameter("existingClientId", requestMap, modifiedParameters); + String firstname = extractStringParameter("firstname", requestMap, modifiedParameters); + String lastname = extractStringParameter("lastname", requestMap, modifiedParameters); + String addressLine1 = extractStringParameter("addressLine1", requestMap, modifiedParameters); + String addressLine2 = extractStringParameter("addressLine2", requestMap, modifiedParameters); + String city = extractStringParameter("city", requestMap, modifiedParameters); + String state = extractStringParameter("state", requestMap, modifiedParameters); + String zip = extractStringParameter("zip", requestMap, modifiedParameters); + String country = extractStringParameter("country", requestMap, modifiedParameters); + String mobileNumber = extractStringParameter("mobileNumber", requestMap, modifiedParameters); + String housePhoneNumber = extractStringParameter("housePhoneNumber", requestMap, modifiedParameters); + String comment = extractStringParameter("comment", requestMap, modifiedParameters); + String dob = extractStringParameter("dob", requestMap, modifiedParameters); + + // workaround for passing locale info to data table api + final String dateFormat = requestMap.get("dateFormat"); + final String locale = requestMap.get("locale"); - GuarantorCommand command = new GuarantorCommand(modifiedParameters, - existingClientId, firstname, lastname, externalGuarantor, - addressLine1, addressLine2, city, state, zip, country, - mobileNumber, housePhoneNumber, comment, dob); - command.setDateFormat(dateFormat); - command.setLocale(locale); - return command; - } + GuarantorCommand command = new GuarantorCommand(modifiedParameters, existingClientId, firstname, lastname, externalGuarantor, + addressLine1, addressLine2, city, state, zip, country, mobileNumber, housePhoneNumber, comment, dob); + command.setDateFormat(dateFormat); + command.setLocale(locale); + return command; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/guarantor/GuarantorReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/guarantor/GuarantorReadPlatformServiceImpl.java index 3deff67d1..b20f0a6cf 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/guarantor/GuarantorReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/guarantor/GuarantorReadPlatformServiceImpl.java @@ -12,111 +12,89 @@ import org.mifosng.platform.exceptions.LoanNotFoundException; import org.mifosng.platform.loan.domain.Loan; import org.mifosng.platform.loan.domain.LoanRepository; import org.mifosng.platform.noncore.ReadWriteNonCoreDataService; -import org.mifosng.platform.organisation.domain.OfficeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class GuarantorReadPlatformServiceImpl implements - GuarantorReadPlatformService { +public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformService { - private final LoanRepository loanRepository; - private final ReadWriteNonCoreDataService readWriteNonCoreDataService; - // Table for storing external Guarantor Details - public static final String EXTERNAL_GUARANTOR_TABLE_NAME = "m_guarantor_external"; + // Table for storing external Guarantor Details + public static final String EXTERNAL_GUARANTOR_TABLE_NAME = "m_guarantor_external"; + + private final LoanRepository loanRepository; + private final ReadWriteNonCoreDataService readWriteNonCoreDataService; - @Autowired - public GuarantorReadPlatformServiceImpl( - final LoanRepository loanRepository, - final ReadWriteNonCoreDataService readWriteNonCoreDataService, - final OfficeRepository officeRepository) { - this.loanRepository = loanRepository; - this.readWriteNonCoreDataService = readWriteNonCoreDataService; - } + @Autowired + public GuarantorReadPlatformServiceImpl(final LoanRepository loanRepository, + final ReadWriteNonCoreDataService readWriteNonCoreDataService) { + this.loanRepository = loanRepository; + this.readWriteNonCoreDataService = readWriteNonCoreDataService; + } - @Override - public boolean existsGuarantor(Long loanId) { - Loan loan = validateLoanExists(loanId); - // return if internal guarantor exists - if (loan.getGuarantor() != null) { - return true; - } - // return if an external guarantor exists - if (null != getExternalGuarantor(loanId)) { - return true; - } - // else no guarantor exists - return false; - } + @Override + public boolean existsGuarantor(Long loanId) { + Loan loan = retrieveLoanById(loanId); + // return if internal guarantor exists + if (loan.getGuarantor() != null) { return true; } + // return if an external guarantor exists + if (null != getExternalGuarantor(loanId)) { return true; } + // else no guarantor exists + return false; + } - @Override - public GuarantorData retrieveGuarantor(Long loanId) { - GuarantorData guarantorData = null; - Loan loan = validateLoanExists(loanId); - // does an internal guarantor exist - if (loan.getGuarantor() != null) { - Client guarantor = loan.getGuarantor(); - LocalDate localDate = new LocalDate(guarantor.getJoiningDate()); - guarantorData = new GuarantorData(guarantor.getId(), - guarantor.getFirstName(), guarantor.getLastName(), - guarantor.getExternalId(), guarantor.getOffice().getName(), - localDate); - } else { - guarantorData = getExternalGuarantor(loanId); - } - // throw error if guarantor does not exist - if (guarantorData == null) { - throw new GuarantorNotFoundException(loanId); - } - return guarantorData; - } + @Override + public GuarantorData retrieveGuarantor(Long loanId) { + GuarantorData guarantorData = null; + Loan loan = retrieveLoanById(loanId); + // does an internal guarantor exist + if (loan.getGuarantor() != null) { + Client guarantor = loan.getGuarantor(); + LocalDate localDate = new LocalDate(guarantor.getJoiningDate()); + guarantorData = new GuarantorData(guarantor.getId(), guarantor.getFirstName(), guarantor.getLastName(), + guarantor.getExternalId(), guarantor.getOffice().getName(), localDate); + } else { + guarantorData = getExternalGuarantor(loanId); + } + // throw error if guarantor does not exist + if (guarantorData == null) { throw new GuarantorNotFoundException(loanId); } + return guarantorData; + } - /** - * @param loanId - * @return - */ - private Loan validateLoanExists(Long loanId) { - Loan loan = loanRepository.findOne(loanId); - if (loan == null) { - throw new LoanNotFoundException(loanId); - } - return loan; - } + private Loan retrieveLoanById(final Long loanId) { + + // FIXME - KW - On the read side of services - we would prefer not to use the repository/ORM pattern + Loan loan = loanRepository.findOne(loanId); + if (loan == null) { throw new LoanNotFoundException(loanId); } + return loan; + } - /** - * @param loanId - * @return - */ - public GuarantorData getExternalGuarantor(Long loanId) { - GenericResultsetData genericResultDataSet = readWriteNonCoreDataService - .retrieveDataTableGenericResultSet( - EXTERNAL_GUARANTOR_TABLE_NAME, loanId, null, null); - if (genericResultDataSet.getData().size() == 1) { - List guarantorRow = genericResultDataSet.getData().get(0) - .getRow(); - String firstname = guarantorRow.get(1); - String lastname = guarantorRow.get(2); - - LocalDate dateOfBirth = null; - if (!StringUtils.isBlank(guarantorRow.get(3))) { - dateOfBirth = new LocalDate(guarantorRow.get(3)); - } - String addressLine1 = guarantorRow.get(4); - String addressLine2 = guarantorRow.get(5); - String city = guarantorRow.get(6); - String state = guarantorRow.get(7); - String country = guarantorRow.get(8); - String zip = guarantorRow.get(9); - String housePhoneNumber = guarantorRow.get(10); - String mobileNumber = guarantorRow.get(11); - String comment = guarantorRow.get(12); - GuarantorData guarantorData = new GuarantorData(firstname, - lastname, dateOfBirth, addressLine1, addressLine2, city, - state, zip, country, mobileNumber, housePhoneNumber, - comment); - return guarantorData; - } - return null; - } + @Override + public GuarantorData getExternalGuarantor(final Long loanId) { + + GenericResultsetData genericResultDataSet = readWriteNonCoreDataService.retrieveDataTableGenericResultSet( + EXTERNAL_GUARANTOR_TABLE_NAME, loanId, null, null); + if (genericResultDataSet.getData().size() == 1) { + List guarantorRow = genericResultDataSet.getData().get(0).getRow(); + String firstname = guarantorRow.get(1); + String lastname = guarantorRow.get(2); + LocalDate dateOfBirth = null; + if (!StringUtils.isBlank(guarantorRow.get(3))) { + dateOfBirth = new LocalDate(guarantorRow.get(3)); + } + String addressLine1 = guarantorRow.get(4); + String addressLine2 = guarantorRow.get(5); + String city = guarantorRow.get(6); + String state = guarantorRow.get(7); + String country = guarantorRow.get(8); + String zip = guarantorRow.get(9); + String housePhoneNumber = guarantorRow.get(10); + String mobileNumber = guarantorRow.get(11); + String comment = guarantorRow.get(12); + GuarantorData guarantorData = new GuarantorData(firstname, lastname, dateOfBirth, addressLine1, addressLine2, city, state, zip, + country, mobileNumber, housePhoneNumber, comment); + return guarantorData; + } + return null; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/guarantor/GuarantorWritePlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/guarantor/GuarantorWritePlatformServiceImpl.java index b8ce51614..a4d4d6e77 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/guarantor/GuarantorWritePlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/guarantor/GuarantorWritePlatformServiceImpl.java @@ -19,164 +19,126 @@ import org.mifosng.platform.exceptions.PlatformApiDataValidationException; import org.mifosng.platform.loan.domain.Loan; import org.mifosng.platform.loan.domain.LoanRepository; import org.mifosng.platform.noncore.ReadWriteNonCoreDataService; -import org.mifosng.platform.organisation.domain.OfficeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -public class GuarantorWritePlatformServiceImpl implements - GuarantorWritePlatformService { +public class GuarantorWritePlatformServiceImpl implements GuarantorWritePlatformService { - private final LoanRepository loanRepository; - private final ClientRepository clientRepository; - private final ReadWriteNonCoreDataService readWriteNonCoreDataService; - private final GuarantorReadPlatformService guarantorReadPlatformService; - // Table for storing external Guarantor Details - public static final String EXTERNAL_GUARANTOR_TABLE_NAME = "m_guarantor_external"; + // Table for storing external Guarantor Details + public static final String EXTERNAL_GUARANTOR_TABLE_NAME = "m_guarantor_external"; - @Autowired - public GuarantorWritePlatformServiceImpl( - final LoanRepository loanRepository, - final ReadWriteNonCoreDataService readWriteNonCoreDataService, - final OfficeRepository officeRepository, - final ClientRepository clientRepository, - final GuarantorReadPlatformService guarantorReadPlatformService) { - this.loanRepository = loanRepository; - this.readWriteNonCoreDataService = readWriteNonCoreDataService; - this.clientRepository = clientRepository; - this.guarantorReadPlatformService = guarantorReadPlatformService; - } + private final LoanRepository loanRepository; + private final ClientRepository clientRepository; + private final ReadWriteNonCoreDataService readWriteNonCoreDataService; + private final GuarantorReadPlatformService guarantorReadPlatformService; - @Override - @Transactional - public void createGuarantor(Long loanId, GuarantorCommand command) { - GuarantorCommandValidator validator = new GuarantorCommandValidator( - command); - validator.validateForCreate(); - saveOrUpdateGuarantor(loanId, command); - } + @Autowired + public GuarantorWritePlatformServiceImpl(final LoanRepository loanRepository, + final ReadWriteNonCoreDataService readWriteNonCoreDataService, final ClientRepository clientRepository, + final GuarantorReadPlatformService guarantorReadPlatformService) { + this.loanRepository = loanRepository; + this.readWriteNonCoreDataService = readWriteNonCoreDataService; + this.clientRepository = clientRepository; + this.guarantorReadPlatformService = guarantorReadPlatformService; + } - @Override - @Transactional - public void updateGuarantor(Long loanId, GuarantorCommand command) { - GuarantorCommandValidator validator = new GuarantorCommandValidator( - command); - validator.validateForUpdate(); - saveOrUpdateGuarantor(loanId, command); - } + @Override + @Transactional + public void createGuarantor(final Long loanId, final GuarantorCommand command) { + GuarantorCommandValidator validator = new GuarantorCommandValidator(command); + validator.validateForCreate(); + saveOrUpdateGuarantor(loanId, command); + } - @Override - @Transactional - public void removeGuarantor(Long loanId) { - Loan loan = validateLoanExists(loanId); - // remove internal guarantor, if any - if (loan.getGuarantor() != null) { - loan.setGuarantor(null); - loanRepository.saveAndFlush(loan); - } - // remove external guarantor, if any - readWriteNonCoreDataService.deleteDatatableEntries( - EXTERNAL_GUARANTOR_TABLE_NAME, loanId); - } + @Override + @Transactional + public void updateGuarantor(final Long loanId, final GuarantorCommand command) { + GuarantorCommandValidator validator = new GuarantorCommandValidator(command); + validator.validateForUpdate(); + saveOrUpdateGuarantor(loanId, command); + } - /** - * @param loanId - * @param command - */ - private void saveOrUpdateGuarantor(Long loanId, GuarantorCommand command) { - Loan loan = validateLoanExists(loanId); - // mark an existing client as a guarantor - if (command.isExternalGuarantor() == null - || !command.isExternalGuarantor()) { - // can't set client as a guarantor to himself - if (loan.getClient().getId().equals(command.getExistingClientId())) { - throw new InvalidGuarantorException( - command.getExistingClientId(), loanId); - } - Client guarantor = clientRepository.findOne(command - .getExistingClientId()); - if (guarantor == null) { - throw new ClientNotFoundException(command.getExistingClientId()); - } - loan.setGuarantor(guarantor); - this.loanRepository.saveAndFlush(loan); - // also delete any existing External Guarantors - readWriteNonCoreDataService.deleteDatatableEntries( - EXTERNAL_GUARANTOR_TABLE_NAME, loanId); - }// or create an external guarantor - else { - Set modifiedParameters = command.getModifiedParameters(); - Map modifiedParametersMap = new HashMap(); - /*** - * TODO Vishwas: Check with JW/KW if using reflection here is a good - * idea - **/ - Class guarantorCommandClass = command - .getClass(); - for (String modifiedParameter : modifiedParameters) { - Method method; - try { - if (modifiedParameter.equalsIgnoreCase("externalGuarantor") - || modifiedParameter - .equalsIgnoreCase("existingClientId")) { - continue; - } else { - method = guarantorCommandClass.getMethod("get" - + StringUtils.capitalize(modifiedParameter)); - } - String columnName = StringUtils.join(StringUtils - .splitByCharacterTypeCamelCase(modifiedParameter), - '_'); - modifiedParametersMap.put(columnName.toLowerCase(), method - .invoke(command).toString()); - } catch (Exception e) { - // TODO: This block would ideally never be reached, could - // use an - // empty catch block instead? - List dataValidationErrors = new ArrayList(); - ApiParameterError apiParameterError = ApiParameterError - .parameterError( - "validation.msg.validation.errors.exist", - "", modifiedParameter); - dataValidationErrors.add(apiParameterError); - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Invalid parameter passed for Creating updating Guarantor", - dataValidationErrors); - } + @Override + @Transactional + public void removeGuarantor(final Long loanId) { + Loan loan = retrieveLoanById(loanId); + // remove internal guarantor, if any + if (loan.getGuarantor() != null) { + loan.setGuarantor(null); + loanRepository.saveAndFlush(loan); + } + // remove external guarantor, if any + readWriteNonCoreDataService.deleteDatatableEntries(EXTERNAL_GUARANTOR_TABLE_NAME, loanId); + } - } + private void saveOrUpdateGuarantor(final Long loanId, final GuarantorCommand command) { + Loan loan = retrieveLoanById(loanId); + // mark an existing client as a guarantor + if (command.isExternalGuarantor() == null || !command.isExternalGuarantor()) { + // can't set client as a guarantor to himself + if (loan.getClient().getId().equals(command.getExistingClientId())) { throw new InvalidGuarantorException( + command.getExistingClientId(), loanId); } + Client guarantor = clientRepository.findOne(command.getExistingClientId()); + if (guarantor == null) { throw new ClientNotFoundException(command.getExistingClientId()); } + loan.setGuarantor(guarantor); + this.loanRepository.saveAndFlush(loan); + // also delete any existing External Guarantors + readWriteNonCoreDataService.deleteDatatableEntries(EXTERNAL_GUARANTOR_TABLE_NAME, loanId); + }// or create an external guarantor + else { + Set modifiedParameters = command.getModifiedParameters(); + Map modifiedParametersMap = new HashMap(); + + /*** + * TODO Vishwas: Check with JW/KW if using reflection here is a good + * idea + **/ + Class guarantorCommandClass = command.getClass(); + for (String modifiedParameter : modifiedParameters) { + Method method; + try { + if (modifiedParameter.equalsIgnoreCase("externalGuarantor") || modifiedParameter.equalsIgnoreCase("existingClientId")) { + continue; + } else { + method = guarantorCommandClass.getMethod("get" + StringUtils.capitalize(modifiedParameter)); + } + String columnName = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(modifiedParameter), '_'); + modifiedParametersMap.put(columnName.toLowerCase(), method.invoke(command).toString()); + } catch (Exception e) { + // TODO: This block would ideally never be reached, could + // use an + // empty catch block instead? + List dataValidationErrors = new ArrayList(); + ApiParameterError apiParameterError = ApiParameterError.parameterError("validation.msg.validation.errors.exist", "", + modifiedParameter); + dataValidationErrors.add(apiParameterError); + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", + "Invalid parameter passed for Creating updating Guarantor", dataValidationErrors); + } - /*** update or create a new external Guarantor entry ***/ - modifiedParametersMap.put("locale", command.getLocale()); - modifiedParametersMap.put("dateFormat", command.getDateFormat()); - if (guarantorReadPlatformService.getExternalGuarantor(loanId) != null) { - readWriteNonCoreDataService.updateDatatableEntryOnetoOne( - EXTERNAL_GUARANTOR_TABLE_NAME, loanId, - modifiedParametersMap); - } else { - readWriteNonCoreDataService.newDatatableEntry( - EXTERNAL_GUARANTOR_TABLE_NAME, loanId, - modifiedParametersMap); - } - // finally unset any existing internal guarantors - if (loan.getGuarantor() != null) { - loan.setGuarantor(null); - this.loanRepository.saveAndFlush(loan); - } - } - } + } - /** - * @param loanId - * @return - */ - private Loan validateLoanExists(Long loanId) { - Loan loan = loanRepository.findOne(loanId); - if (loan == null) { - throw new LoanNotFoundException(loanId); - } - return loan; - } + /*** update or create a new external Guarantor entry ***/ + modifiedParametersMap.put("locale", command.getLocale()); + modifiedParametersMap.put("dateFormat", command.getDateFormat()); + if (guarantorReadPlatformService.getExternalGuarantor(loanId) != null) { + readWriteNonCoreDataService.updateDatatableEntryOnetoOne(EXTERNAL_GUARANTOR_TABLE_NAME, loanId, modifiedParametersMap); + } else { + readWriteNonCoreDataService.newDatatableEntry(EXTERNAL_GUARANTOR_TABLE_NAME, loanId, modifiedParametersMap); + } + // finally unset any existing internal guarantors + if (loan.getGuarantor() != null) { + loan.setGuarantor(null); + this.loanRepository.saveAndFlush(loan); + } + } + } + + private Loan retrieveLoanById(final Long loanId) { + Loan loan = loanRepository.findOne(loanId); + if (loan == null) { throw new LoanNotFoundException(loanId); } + return loan; + } } \ No newline at end of file