MIFOSX-109: some formatting changes and removal of unused items.

This commit is contained in:
Keith Woodlock
2012-11-21 17:06:50 +00:00
parent e874efc3ac
commit 4101cfbcf5
7 changed files with 752 additions and 885 deletions
@@ -35,84 +35,72 @@ import org.springframework.stereotype.Component;
@Scope("singleton") @Scope("singleton")
public class GuarantorsApiResource { public class GuarantorsApiResource {
@Autowired @Autowired
private GuarantorWritePlatformService guarantorWritePlatformService; private GuarantorWritePlatformService guarantorWritePlatformService;
@Autowired @Autowired
private GuarantorReadPlatformService guarantorReadPlatformService; private GuarantorReadPlatformService guarantorReadPlatformService;
@Autowired @Autowired
private PortfolioApiDataConversionService apiDataConversionService; private PortfolioApiDataConversionService apiDataConversionService;
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
private static final Set<String> typicalResponseParameters = new HashSet<String>( private static final Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("externalGuarantor", "existingClientId",
Arrays.asList("externalGuarantor", "existingClientId", "firstname", "firstname", "lastname", "addressLine1", "addressLine2", "city", "state", "zip", "country", "mobileNumber", "housePhoneNumber",
"lastname", "addressLine1", "addressLine2", "city", "comment", "dob"));
"state", "zip", "country", "mobileNumber",
"housePhoneNumber", "comment", "dob"));
private final String SystemEntityType = "m_guarantor_external"; private final String SystemEntityType = "m_guarantor_external";
@Autowired @Autowired
private PlatformSecurityContext context; private PlatformSecurityContext context;
@GET @GET
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveGuarantorDetails(@Context final UriInfo uriInfo, public String retrieveGuarantorDetails(@Context final UriInfo uriInfo, @PathParam("loanId") final Long loanId) {
@PathParam("loanId") final Long loanId) { context.authenticatedUser().validateHasReadPermission(SystemEntityType);
context.authenticatedUser().validateHasReadPermission(SystemEntityType); Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
Set<String> responseParameters = ApiParameterHelper if (responseParameters.isEmpty()) {
.extractFieldsForResponseIfProvided(uriInfo responseParameters.addAll(typicalResponseParameters);
.getQueryParameters()); }
if (responseParameters.isEmpty()) { boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo
.getQueryParameters());
GuarantorData guarantorData = guarantorReadPlatformService GuarantorData guarantorData = guarantorReadPlatformService.retrieveGuarantor(loanId);
.retrieveGuarantor(loanId);
return this.apiJsonSerializerService.serializeGuarantorDataToJson( return this.apiJsonSerializerService.serializeGuarantorDataToJson(prettyPrint, responseParameters, guarantorData);
prettyPrint, responseParameters, guarantorData); }
}
@POST @POST
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public Response createGuarantor(@PathParam("loanId") final Long loanId, public Response createGuarantor(@PathParam("loanId") final Long loanId, final String jsonRequestBody) {
final String jsonRequestBody) {
final GuarantorCommand command = this.apiDataConversionService final GuarantorCommand command = this.apiDataConversionService.convertJsonToGuarantorCommand(null, loanId, jsonRequestBody);
.convertJsonToGuarantorCommand(null, loanId, jsonRequestBody);
this.guarantorWritePlatformService.createGuarantor(loanId, command); this.guarantorWritePlatformService.createGuarantor(loanId, command);
// returns the loan Identifier for which the guarantor was associated // returns the loan Identifier for which the guarantor was associated
return Response.ok().entity(new EntityIdentifier(loanId)).build(); return Response.ok().entity(new EntityIdentifier(loanId)).build();
} }
@PUT @PUT
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public Response updateGuarantor(@PathParam("loanId") final Long loanId, public Response updateGuarantor(@PathParam("loanId") final Long loanId, final String jsonRequestBody) {
final String jsonRequestBody) { final GuarantorCommand command = this.apiDataConversionService.convertJsonToGuarantorCommand(null, loanId, 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 @DELETE
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public Response deleteGuarantor(@PathParam("loanId") final Long loanId) { public Response deleteGuarantor(@PathParam("loanId") final Long loanId) {
this.guarantorWritePlatformService.removeGuarantor(loanId); this.guarantorWritePlatformService.removeGuarantor(loanId);
return Response.ok(new EntityIdentifier(loanId)).build(); return Response.ok(new EntityIdentifier(loanId)).build();
} }
} }
@@ -70,442 +70,418 @@ import org.springframework.util.CollectionUtils;
@Scope("singleton") @Scope("singleton")
public class LoansApiResource { public class LoansApiResource {
@Autowired @Autowired
private LoanReadPlatformService loanReadPlatformService; private LoanReadPlatformService loanReadPlatformService;
@Autowired @Autowired
private LoanWritePlatformService loanWritePlatformService; private LoanWritePlatformService loanWritePlatformService;
@Autowired
private LoanProductReadPlatformService loanProductReadPlatformService;
@Autowired @Autowired
private LoanDropdownReadPlatformService dropdownReadPlatformService; private LoanProductReadPlatformService loanProductReadPlatformService;
@Autowired
private LoanDropdownReadPlatformService dropdownReadPlatformService;
@Autowired
private FundReadPlatformService fundReadPlatformService;
@Autowired
private FundReadPlatformService fundReadPlatformService;
@Autowired @Autowired
private ChargeReadPlatformService chargeReadPlatformService; private ChargeReadPlatformService chargeReadPlatformService;
@Autowired @Autowired
private CalculationPlatformService calculationPlatformService; private CalculationPlatformService calculationPlatformService;
@Autowired @Autowired
private PortfolioApiDataConversionService apiDataConversionService; private PortfolioApiDataConversionService apiDataConversionService;
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
@Autowired @Autowired
private StaffReadPlatformService staffReadPlatformService; private StaffReadPlatformService staffReadPlatformService;
@Autowired @Autowired
private PlatformSecurityContext context; 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"); @Autowired
private GuarantorReadPlatformService guarantorReadPlatformService;
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
// tempate related
Collection<LoanProductData> productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup();
Collection<EnumOptionData> loanTermFrequencyTypeOptions = dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions();
Collection<EnumOptionData> repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions();
Collection<EnumOptionData> interestRateFrequencyTypeOptions = dropdownReadPlatformService.retrieveInterestRateFrequencyTypeOptions();
Collection<EnumOptionData> amortizationTypeOptions = dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions();
Collection<EnumOptionData> interestTypeOptions = dropdownReadPlatformService.retrieveLoanInterestTypeOptions();
Collection<EnumOptionData> interestCalculationPeriodTypeOptions = dropdownReadPlatformService.retrieveLoanInterestRateCalculatedInPeriodOptions();
Collection<FundData> fundOptions = this.fundReadPlatformService.retrieveAllFunds();
Collection<TransactionProcessingStrategyData> repaymentStrategyOptions = this.dropdownReadPlatformService.retreiveTransactionProcessingStrategies();
final boolean feeChargesOnly = false;
Collection<ChargeData> chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly);
ChargeData chargeTemplate = this.chargeReadPlatformService.retrieveLoanChargeTemplate();
LoanBasicDetailsData loanBasicDetails; @GET
Long officeId; @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 ){ context.authenticatedUser().validateHasReadPermission("LOAN");
loanBasicDetails = this.loanReadPlatformService.retrieveClientAndProductDetails(clientId, productId);
officeId = loanBasicDetails.getClientOfficeId(); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
} else { final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
loanBasicDetails = this.loanReadPlatformService.retrieveGroupAndProductDetails(groupId, productId);
officeId = loanBasicDetails.getGroupOfficeId(); // tempate related
Collection<LoanProductData> productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup();
Collection<EnumOptionData> loanTermFrequencyTypeOptions = dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions();
Collection<EnumOptionData> repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions();
Collection<EnumOptionData> interestRateFrequencyTypeOptions = dropdownReadPlatformService
.retrieveInterestRateFrequencyTypeOptions();
Collection<EnumOptionData> amortizationTypeOptions = dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions();
Collection<EnumOptionData> interestTypeOptions = dropdownReadPlatformService.retrieveLoanInterestTypeOptions();
Collection<EnumOptionData> interestCalculationPeriodTypeOptions = dropdownReadPlatformService
.retrieveLoanInterestRateCalculatedInPeriodOptions();
Collection<FundData> fundOptions = this.fundReadPlatformService.retrieveAllFunds();
Collection<TransactionProcessingStrategyData> repaymentStrategyOptions = this.dropdownReadPlatformService
.retreiveTransactionProcessingStrategies();
final boolean feeChargesOnly = false;
Collection<ChargeData> 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; final boolean convenienceDataRequired = false;
Collection<LoanChargeData> charges = loanBasicDetails.getCharges(); Collection<LoanChargeData> charges = loanBasicDetails.getCharges();
Collection<StaffData> allowedLoanOfficers = this.staffReadPlatformService.retrieveAllLoanOfficersByOffice(officeId); Collection<StaffData> allowedLoanOfficers = this.staffReadPlatformService.retrieveAllLoanOfficersByOffice(officeId);
final LoanAccountData newLoanAccount = new LoanAccountData(loanBasicDetails, convenienceDataRequired, null, null, null, charges, final LoanAccountData newLoanAccount = new LoanAccountData(loanBasicDetails, convenienceDataRequired, null, null, null, charges,
productOptions, loanTermFrequencyTypeOptions, repaymentFrequencyTypeOptions, productOptions, loanTermFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentStrategyOptions,
repaymentStrategyOptions, interestRateFrequencyTypeOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions,
amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, allowedLoanOfficers,null); fundOptions, chargeOptions, chargeTemplate, allowedLoanOfficers, null);
return this.apiJsonSerializerService.serializeLoanAccountDataToJson(prettyPrint, responseParameters, newLoanAccount); return this.apiJsonSerializerService.serializeLoanAccountDataToJson(prettyPrint, responseParameters, newLoanAccount);
} }
@GET @GET
@Path("{loanId}") @Path("{loanId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveLoanAccountDetails( public String retrieveLoanAccountDetails(@PathParam("loanId") final Long loanId, @Context final UriInfo uriInfo) {
@PathParam("loanId") final Long loanId,
@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission("LOAN"); context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final LoanBasicDetailsData loanBasicDetails = this.loanReadPlatformService.retrieveLoanAccountDetails(loanId); final LoanBasicDetailsData loanBasicDetails = this.loanReadPlatformService.retrieveLoanAccountDetails(loanId);
int loanRepaymentsCount = 0; int loanRepaymentsCount = 0;
Collection<LoanTransactionData> loanRepayments = null; Collection<LoanTransactionData> loanRepayments = null;
LoanScheduleData repaymentSchedule = null; LoanScheduleData repaymentSchedule = null;
LoanPermissionData permissions = null; LoanPermissionData permissions = null;
Collection<LoanChargeData> charges = null; Collection<LoanChargeData> charges = null;
GuarantorData guarantorData = null; GuarantorData guarantorData = null;
boolean convenienceDataRequired = false; boolean convenienceDataRequired = false;
final Set<String> associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters());
if (!associationParameters.isEmpty()) { 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<LoanTransactionData> 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));
if (associationParameters.contains("permissions")) { if (associationParameters.contains("all")) {
loanRepaymentsCount = retrieveNonDisbursementTransactions(loanRepayments); associationParameters.addAll(Arrays.asList("repaymentSchedule", "transactions", "permissions", "convenienceData",
permissions = this.loanReadPlatformService.retrieveLoanPermissions(loanBasicDetails, isWaiveAllowed, loanRepaymentsCount, existsGuarantor); "charges", "guarantor"));
} }
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.
}
}
}
Collection<LoanProductData> productOptions = null; boolean existsGuarantor = false;
Collection<EnumOptionData> loanTermFrequencyTypeOptions = null; if (associationParameters.contains("guarantor")) {
Collection<EnumOptionData> repaymentFrequencyTypeOptions = null; if (guarantorReadPlatformService.existsGuarantor(loanId)) {
Collection<TransactionProcessingStrategyData> repaymentStrategyOptions = null; guarantorData = this.guarantorReadPlatformService.retrieveGuarantor(loanId);
Collection<EnumOptionData> interestRateFrequencyTypeOptions = null; existsGuarantor = true;
Collection<EnumOptionData> amortizationTypeOptions = null; }
Collection<EnumOptionData> interestTypeOptions = null; }
Collection<EnumOptionData> interestCalculationPeriodTypeOptions = null;
Collection<FundData> fundOptions = null;
Collection<ChargeData> 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();
fundOptions = this.fundReadPlatformService.retrieveAllFunds(); if (associationParameters.contains("transactions")) {
repaymentStrategyOptions = this.dropdownReadPlatformService.retreiveTransactionProcessingStrategies(); final Collection<LoanTransactionData> currentLoanRepayments = this.loanReadPlatformService.retrieveLoanTransactions(loanId);
final boolean feeChargesOnly = false; if (!CollectionUtils.isEmpty(currentLoanRepayments)) {
chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly); loanRepayments = currentLoanRepayments;
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);
}
private int retrieveNonDisbursementTransactions(final Collection<LoanTransactionData> loanRepayments) { if (associationParameters.contains("repaymentSchedule")) {
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;
}
@POST DisbursementData singleDisbursement = loanBasicDetails.toDisburementData();
@Consumes({ MediaType.APPLICATION_JSON }) repaymentSchedule = this.loanReadPlatformService.retrieveRepaymentSchedule(loanId, loanBasicDetails.getCurrency(),
@Produces({ MediaType.APPLICATION_JSON }) singleDisbursement, loanBasicDetails.getTotalDisbursementCharges(), loanBasicDetails.getInArrearsTolerance());
public String calculateLoanScheduleOrSubmitLoanApplication(
@QueryParam("command") final String commandParam,
@Context final UriInfo uriInfo,
final String jsonRequestBody) {
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")) { boolean isWaiveAllowed = totalOutstandingMoney.isGreaterThanZero()
CalculateLoanScheduleCommand calculateLoanScheduleCommand = command.toCalculateLoanScheduleCommand(); && (tolerance.isGreaterThan(totalOutstandingMoney) || tolerance.isEqualTo(totalOutstandingMoney));
return calculateLoanSchedule(uriInfo, calculateLoanScheduleCommand);
}
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) { Collection<LoanProductData> productOptions = null;
Collection<EnumOptionData> loanTermFrequencyTypeOptions = null;
final LoanScheduleData loanSchedule = this.calculationPlatformService.calculateLoanSchedule(command); Collection<EnumOptionData> repaymentFrequencyTypeOptions = null;
Collection<TransactionProcessingStrategyData> repaymentStrategyOptions = null;
Collection<EnumOptionData> interestRateFrequencyTypeOptions = null;
Collection<EnumOptionData> amortizationTypeOptions = null;
Collection<EnumOptionData> interestTypeOptions = null;
Collection<EnumOptionData> interestCalculationPeriodTypeOptions = null;
Collection<FundData> fundOptions = null;
Collection<ChargeData> chargeOptions = null;
ChargeData chargeTemplate = null;
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); if (template) {
productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup();
return this.apiJsonSerializerService.serializeLoanScheduleDataToJson(prettyPrint, responseParameters, loanSchedule); loanTermFrequencyTypeOptions = dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions();
} repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions();
interestRateFrequencyTypeOptions = dropdownReadPlatformService.retrieveInterestRateFrequencyTypeOptions();
@PUT
@Path("{loanId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String modifyLoanApplication(
@PathParam("loanId") final Long loanId,
final String jsonRequestBody) {
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 return this.apiJsonSerializerService.serializeLoanAccountDataToJson(prettyPrint, responseParameters, loanAccount);
@Path("{loanId}") }
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response deleteLoanApplication(@PathParam("loanId") final Long loanId) {
EntityIdentifier identifier = this.loanWritePlatformService.deleteLoan(loanId); private int retrieveNonDisbursementTransactions(final Collection<LoanTransactionData> 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 final LoanApplicationCommand command = this.apiDataConversionService.convertJsonToLoanApplicationCommand(null, jsonRequestBody);
@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) {
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")) { return this.apiJsonSerializerService.serializeEntityIdentifier(identifier);
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();
}
UndoStateTransitionCommand undoCommand = new UndoStateTransitionCommand( private String calculateLoanSchedule(final UriInfo uriInfo, final CalculateLoanScheduleCommand command) {
loanId, command.getNote());
if (is(commandParam, "undoapproval")) { final LoanScheduleData loanSchedule = this.calculationPlatformService.calculateLoanSchedule(command);
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();
}
if (response == null) { final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
throw new UnrecognizedQueryParamException("command", commandParam); boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
}
return response; return this.apiJsonSerializerService.serializeLoanScheduleDataToJson(prettyPrint, responseParameters, loanSchedule);
} }
private boolean is(final String commandParam, final String commandValue) { @PUT
return StringUtils.isNotBlank(commandParam) @Path("{loanId}")
&& commandParam.trim().equalsIgnoreCase(commandValue); @Consumes({ MediaType.APPLICATION_JSON })
} @Produces({ MediaType.APPLICATION_JSON })
public String modifyLoanApplication(@PathParam("loanId") final Long loanId, final String jsonRequestBody) {
@POST final LoanApplicationCommand command = this.apiDataConversionService.convertJsonToLoanApplicationCommand(loanId, jsonRequestBody);
@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); final EntityIdentifier identifier = this.loanWritePlatformService.modifyLoanApplication(command);
EntityIdentifier identifier = null; return this.apiJsonSerializerService.serializeEntityIdentifier(identifier);
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) { @DELETE
throw new UnrecognizedQueryParamException("command", commandParam); @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 return Response.ok().entity(identifier).build();
@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"); @POST
@Path("{loanId}")
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); @Consumes({ MediaType.APPLICATION_JSON })
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); @Produces({ MediaType.APPLICATION_JSON })
public Response stateTransitions(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam,
LoanTransactionData transactionData = null; final String jsonRequestBody) {
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 LoanStateTransitionCommand command = this.apiDataConversionService.convertJsonToLoanStateTransitionCommand(loanId, jsonRequestBody);
@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"); Response response = null;
final Set<String> 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); 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 UndoStateTransitionCommand undoCommand = new UndoStateTransitionCommand(loanId, command.getNote());
@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 if (is(commandParam, "undoapproval")) {
.convertJsonToAdjustLoanTransactionCommand(loanId, EntityIdentifier identifier = this.loanWritePlatformService.undoLoanApproval(undoCommand);
transactionId, jsonRequestBody); 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 if (response == null) { throw new UnrecognizedQueryParamException("command", commandParam); }
.adjustLoanTransaction(command);
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<String> 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<String> 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 @POST
@Path("{loanId}/charges") @Path("{loanId}/charges")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public Response addLoanCharge( public Response addLoanCharge(@PathParam("loanId") final Long loanId, final String jsonRequestBody) {
@PathParam("loanId") final Long loanId,
final String jsonRequestBody){
final LoanChargeCommand command = this.apiDataConversionService.convertJsonToLoanChargeCommand(null, loanId, jsonRequestBody); final LoanChargeCommand command = this.apiDataConversionService.convertJsonToLoanChargeCommand(null, loanId, jsonRequestBody);
@@ -516,14 +492,14 @@ public class LoansApiResource {
@GET @GET
@Path("{loanId}/charges/template") @Path("{loanId}/charges/template")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveNewLoanChargeDetails(@Context final UriInfo uriInfo) { public String retrieveNewLoanChargeDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission("LOAN"); context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final boolean feeChargesOnly = false; final boolean feeChargesOnly = false;
final Collection<ChargeData> chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly); final Collection<ChargeData> chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly);
@@ -534,57 +510,52 @@ public class LoansApiResource {
@GET @GET
@Path("{loanId}/charges/{chargeId}") @Path("{loanId}/charges/{chargeId}")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveLoanCharge( public String retrieveLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId,
@PathParam("loanId") final Long loanId, @Context final UriInfo uriInfo) {
@PathParam("chargeId") final Long loanChargeId,
@Context final UriInfo uriInfo){ context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final LoanChargeData loanCharge = this.chargeReadPlatformService.retrieveLoanChargeDetails(loanChargeId, loanId); final LoanChargeData loanCharge = this.chargeReadPlatformService.retrieveLoanChargeDetails(loanChargeId, loanId);
return this.apiJsonSerializerService.serializeLoanChargeDataToJson(prettyPrint, responseParameters, loanCharge); return this.apiJsonSerializerService.serializeLoanChargeDataToJson(prettyPrint, responseParameters, loanCharge);
} }
@PUT @PUT
@Path("{loanId}/charges/{chargeId}") @Path("{loanId}/charges/{chargeId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String updateLoanCharge( public String updateLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId,
@PathParam("loanId") final Long loanId, final String jsonRequestBody) {
@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); final EntityIdentifier identifier = this.loanWritePlatformService.updateLoanCharge(command);
return this.apiJsonSerializerService.serializeEntityIdentifier(identifier); return this.apiJsonSerializerService.serializeEntityIdentifier(identifier);
} }
@POST @POST
@Path("{loanId}/charges/{chargeId}") @Path("{loanId}/charges/{chargeId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String waiveLoanCharge( public String waiveLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId,
@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam) {
@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 = ""; String json = "";
if (is(commandParam, "waive")) { if (is(commandParam, "waive")) {
final EntityIdentifier identifier = this.loanWritePlatformService.waiveLoanCharge(command); final EntityIdentifier identifier = this.loanWritePlatformService.waiveLoanCharge(command);
json = this.apiJsonSerializerService.serializeEntityIdentifier(identifier); json = this.apiJsonSerializerService.serializeEntityIdentifier(identifier);
} else { } else {
throw new UnrecognizedQueryParamException("command", commandParam); throw new UnrecognizedQueryParamException("command", commandParam);
} }
return json; return json;
} }
@@ -593,9 +564,7 @@ public class LoansApiResource {
@Path("{loanId}/charges/{chargeId}") @Path("{loanId}/charges/{chargeId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String deleteLoanCharge( public String deleteLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId) {
@PathParam("loanId") final Long loanId,
@PathParam("chargeId") final Long loanChargeId){
final EntityIdentifier identifier = this.loanWritePlatformService.deleteLoanCharge(loanId, loanChargeId); final EntityIdentifier identifier = this.loanWritePlatformService.deleteLoanCharge(loanId, loanChargeId);
return this.apiJsonSerializerService.serializeEntityIdentifier(identifier); return this.apiJsonSerializerService.serializeEntityIdentifier(identifier);
@@ -605,9 +574,7 @@ public class LoansApiResource {
@Path("{loanId}/assign") @Path("{loanId}/assign")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public Response assignLoanOfficer( public Response assignLoanOfficer(@PathParam("loanId") final Long loanId, final String jsonRequestBody) {
@PathParam("loanId") final Long loanId,
final String jsonRequestBody){
final LoanReassignmentCommand command = this.apiDataConversionService.convertJsonToLoanReassignmentCommand(loanId, jsonRequestBody); final LoanReassignmentCommand command = this.apiDataConversionService.convertJsonToLoanReassignmentCommand(loanId, jsonRequestBody);
@@ -620,19 +587,16 @@ public class LoansApiResource {
@Path("{loanId}/assign/template") @Path("{loanId}/assign/template")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String assignLoanOfficerTemplate( public String assignLoanOfficerTemplate(@PathParam("loanId") final Long loanId, @Context final UriInfo uriInfo) {
@PathParam("loanId") final Long loanId,
@Context final UriInfo uriInfo){
final Set<String> responseParameters = ApiParameterHelper final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
.extractFieldsForResponseIfProvided(uriInfo
.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
LoanBasicDetailsData loanBasicDetails = this.loanReadPlatformService.retrieveLoanAccountDetails(loanId); LoanBasicDetailsData loanBasicDetails = this.loanReadPlatformService.retrieveLoanAccountDetails(loanId);
Collection<StaffData> allowedLoanOfficers = this.staffReadPlatformService.retrieveAllLoanOfficersByOffice(loanBasicDetails.getOfficeId()); Collection<StaffData> allowedLoanOfficers = this.staffReadPlatformService.retrieveAllLoanOfficersByOffice(loanBasicDetails
.getOfficeId());
Long fromLoanOfficerId = loanBasicDetails.getLoanOfficerId(); Long fromLoanOfficerId = loanBasicDetails.getLoanOfficerId();
LoanReassignmentData loanReassignmentData = LoanReassignmentData.template(fromLoanOfficerId, allowedLoanOfficers, new LocalDate()); LoanReassignmentData loanReassignmentData = LoanReassignmentData.template(fromLoanOfficerId, allowedLoanOfficers, new LocalDate());
@@ -7,135 +7,132 @@ import java.util.Set;
*/ */
public class GuarantorCommand { public class GuarantorCommand {
private final boolean externalGuarantor; private final boolean externalGuarantor;
/*** Fields for current customers serving as guarantors **/ /*** Fields for current customers serving as guarantors **/
private final Long existingClientId; private final Long existingClientId;
/*** Fields for external persons serving as guarantors ***/ /*** Fields for external persons serving as guarantors ***/
private final String firstname; // FIXME - kw - what the details for collecting guarantors change? we are using datatable approach but fixing here?
private final String lastname; private final String firstname;
private final String addressLine1; private final String lastname;
private final String addressLine2; private final String addressLine1;
private final String city; private final String addressLine2;
private final String state; private final String city;
private final String zip; private final String state;
private final String country; private final String zip;
private final String mobileNumber; private final String country;
private final String housePhoneNumber; private final String mobileNumber;
private final String comment; private final String housePhoneNumber;
private final String dob; private final String comment;
private final String dob;
/**Feilds for passing Locale info to generic data service api**/
private String dateFormat;
private String locale;
private final Set<String> modifiedParameters; /** Feilds for passing Locale info to generic data service api **/
private String dateFormat;
private String locale;
public GuarantorCommand(final Set<String> modifiedParameters, private final Set<String> 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;
this.externalGuarantor = externalGuarantor; public GuarantorCommand(final Set<String> 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.externalGuarantor = externalGuarantor;
this.existingClientId = existingClientId;
/*** Fields for external persons serving as guarantors ***/ /*** Fields for current customers serving as guarantors **/
this.firstname = firstname; this.existingClientId = existingClientId;
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 getFirstname() { /*** Fields for external persons serving as guarantors ***/
return firstname; 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() { public String getFirstname() {
return lastname; return firstname;
} }
public Boolean isExternalGuarantor() { public String getLastname() {
return externalGuarantor; return lastname;
} }
public Long getExistingClientId() { public Boolean isExternalGuarantor() {
return existingClientId; return externalGuarantor;
} }
public String getAddressLine1() { public Long getExistingClientId() {
return addressLine1; return existingClientId;
} }
public String getAddressLine2() { public String getAddressLine1() {
return addressLine2; return addressLine1;
} }
public String getCity() { public String getAddressLine2() {
return city; return addressLine2;
} }
public String getState() { public String getCity() {
return state; return city;
} }
public String getZip() { public String getState() {
return zip; return state;
} }
public String getCountry() { public String getZip() {
return country; return zip;
} }
public String getMobileNumber() { public String getCountry() {
return mobileNumber; return country;
} }
public String getHousePhoneNumber() { public String getMobileNumber() {
return housePhoneNumber; return mobileNumber;
} }
public String getComment() { public String getHousePhoneNumber() {
return comment; return housePhoneNumber;
} }
public Set<String> getModifiedParameters() { public String getComment() {
return modifiedParameters; return comment;
} }
public String getDob() { public Set<String> getModifiedParameters() {
return dob; return modifiedParameters;
} }
public String getDateFormat() { public String getDob() {
return dateFormat; return dob;
} }
public void setDateFormat(String dateFormat) { public String getDateFormat() {
this.dateFormat = dateFormat; return dateFormat;
} }
public String getLocale() { public void setDateFormat(String dateFormat) {
return locale; this.dateFormat = dateFormat;
} }
public void setLocale(String locale) { public String getLocale() {
this.locale = locale; return locale;
} }
public void setLocale(String locale) {
this.locale = locale;
}
} }
@@ -95,7 +95,7 @@ public interface PortfolioApiDataConversionService {
CodeCommand convertJsonToCodeCommand(Long resourceIdentifier, String json); CodeCommand convertJsonToCodeCommand(Long resourceIdentifier, String json);
SavingAccountCommand convertJsonToSavingAccountCommand(Long resourceIdentifier,String json); SavingAccountCommand convertJsonToSavingAccountCommand(Long resourceIdentifier, String json);
GuarantorCommand convertJsonToGuarantorCommand(Long resourceIdentifier, Long loanId, String json); GuarantorCommand convertJsonToGuarantorCommand(Long resourceIdentifier, Long loanId, String json);
} }
@@ -1629,68 +1629,46 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo
savingProductType, tenureType, frequency, interestType, minimumBalanceForWithdrawal, interestCalculationMethod, savingProductType, tenureType, frequency, interestType, minimumBalanceForWithdrawal, interestCalculationMethod,
isLockinPeriodAllowed, isPartialDepositAllowed, lockinPeriod, lockinPeriodType); isLockinPeriodAllowed, isPartialDepositAllowed, lockinPeriod, lockinPeriodType);
} }
@Override @Override
public GuarantorCommand convertJsonToGuarantorCommand( public GuarantorCommand convertJsonToGuarantorCommand(Long resourceIdentifier, Long loanId, String json) {
Long resourceIdentifier, Long loanId, String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
if (StringUtils.isBlank(json)) {
throw new InvalidJsonException();
}
Type typeOfMap = new TypeToken<Map<String, String>>() { Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
}.getType(); Map<String, String> requestMap = gsonConverter.fromJson(json, typeOfMap);
Map<String, String> requestMap = gsonConverter
.fromJson(json, typeOfMap);
Set<String> supportedParams = new HashSet<String>(Arrays.asList( Set<String> supportedParams = new HashSet<String>(Arrays.asList("externalGuarantor", "existingClientId", "firstname", "lastname",
"externalGuarantor", "existingClientId", "firstname", "addressLine1", "addressLine2", "city", "state", "zip", "country", "mobileNumber", "housePhoneNumber", "comment", "dob",
"lastname", "addressLine1", "addressLine2", "city", "state", "locale", "dateFormat"));
"zip", "country", "mobileNumber", "housePhoneNumber",
"comment", "dob", "locale", "dateFormat"));
checkForUnsupportedParameters(requestMap, supportedParams); checkForUnsupportedParameters(requestMap, supportedParams);
Set<String> modifiedParameters = new HashSet<String>(); Set<String> modifiedParameters = new HashSet<String>();
boolean externalGuarantor = extractBooleanParameter( boolean externalGuarantor = extractBooleanParameter("externalGuarantor", requestMap, modifiedParameters);
"externalGuarantor", requestMap, modifiedParameters);
Long existingClientId = extractLongParameter("existingClientId", Long existingClientId = extractLongParameter("existingClientId", requestMap, modifiedParameters);
requestMap, modifiedParameters); String firstname = extractStringParameter("firstname", requestMap, modifiedParameters);
String firstname = extractStringParameter("firstname", requestMap, String lastname = extractStringParameter("lastname", requestMap, modifiedParameters);
modifiedParameters); String addressLine1 = extractStringParameter("addressLine1", requestMap, modifiedParameters);
String lastname = extractStringParameter("lastname", requestMap, String addressLine2 = extractStringParameter("addressLine2", requestMap, modifiedParameters);
modifiedParameters); String city = extractStringParameter("city", requestMap, modifiedParameters);
String addressLine1 = extractStringParameter("addressLine1", String state = extractStringParameter("state", requestMap, modifiedParameters);
requestMap, modifiedParameters); String zip = extractStringParameter("zip", requestMap, modifiedParameters);
String addressLine2 = extractStringParameter("addressLine2", String country = extractStringParameter("country", requestMap, modifiedParameters);
requestMap, modifiedParameters); String mobileNumber = extractStringParameter("mobileNumber", requestMap, modifiedParameters);
String city = extractStringParameter("city", requestMap, String housePhoneNumber = extractStringParameter("housePhoneNumber", requestMap, modifiedParameters);
modifiedParameters); String comment = extractStringParameter("comment", requestMap, modifiedParameters);
String state = extractStringParameter("state", requestMap, String dob = extractStringParameter("dob", requestMap, modifiedParameters);
modifiedParameters);
String zip = extractStringParameter("zip", requestMap, // workaround for passing locale info to data table api
modifiedParameters); final String dateFormat = requestMap.get("dateFormat");
String country = extractStringParameter("country", requestMap, final String locale = requestMap.get("locale");
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");
GuarantorCommand command = new GuarantorCommand(modifiedParameters, GuarantorCommand command = new GuarantorCommand(modifiedParameters, existingClientId, firstname, lastname, externalGuarantor,
existingClientId, firstname, lastname, externalGuarantor, addressLine1, addressLine2, city, state, zip, country, mobileNumber, housePhoneNumber, comment, dob);
addressLine1, addressLine2, city, state, zip, country, command.setDateFormat(dateFormat);
mobileNumber, housePhoneNumber, comment, dob); command.setLocale(locale);
command.setDateFormat(dateFormat); return command;
command.setLocale(locale); }
return command;
}
} }
@@ -12,111 +12,89 @@ import org.mifosng.platform.exceptions.LoanNotFoundException;
import org.mifosng.platform.loan.domain.Loan; import org.mifosng.platform.loan.domain.Loan;
import org.mifosng.platform.loan.domain.LoanRepository; import org.mifosng.platform.loan.domain.LoanRepository;
import org.mifosng.platform.noncore.ReadWriteNonCoreDataService; import org.mifosng.platform.noncore.ReadWriteNonCoreDataService;
import org.mifosng.platform.organisation.domain.OfficeRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class GuarantorReadPlatformServiceImpl implements public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformService {
GuarantorReadPlatformService {
private final LoanRepository loanRepository; // Table for storing external Guarantor Details
private final ReadWriteNonCoreDataService readWriteNonCoreDataService; 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 @Autowired
public GuarantorReadPlatformServiceImpl( public GuarantorReadPlatformServiceImpl(final LoanRepository loanRepository,
final LoanRepository loanRepository, final ReadWriteNonCoreDataService readWriteNonCoreDataService) {
final ReadWriteNonCoreDataService readWriteNonCoreDataService, this.loanRepository = loanRepository;
final OfficeRepository officeRepository) { this.readWriteNonCoreDataService = readWriteNonCoreDataService;
this.loanRepository = loanRepository; }
this.readWriteNonCoreDataService = readWriteNonCoreDataService;
}
@Override @Override
public boolean existsGuarantor(Long loanId) { public boolean existsGuarantor(Long loanId) {
Loan loan = validateLoanExists(loanId); Loan loan = retrieveLoanById(loanId);
// return if internal guarantor exists // return if internal guarantor exists
if (loan.getGuarantor() != null) { if (loan.getGuarantor() != null) { return true; }
return true; // return if an external guarantor exists
} if (null != getExternalGuarantor(loanId)) { return true; }
// return if an external guarantor exists // else no guarantor exists
if (null != getExternalGuarantor(loanId)) { return false;
return true; }
}
// else no guarantor exists
return false;
}
@Override @Override
public GuarantorData retrieveGuarantor(Long loanId) { public GuarantorData retrieveGuarantor(Long loanId) {
GuarantorData guarantorData = null; GuarantorData guarantorData = null;
Loan loan = validateLoanExists(loanId); Loan loan = retrieveLoanById(loanId);
// does an internal guarantor exist // does an internal guarantor exist
if (loan.getGuarantor() != null) { if (loan.getGuarantor() != null) {
Client guarantor = loan.getGuarantor(); Client guarantor = loan.getGuarantor();
LocalDate localDate = new LocalDate(guarantor.getJoiningDate()); LocalDate localDate = new LocalDate(guarantor.getJoiningDate());
guarantorData = new GuarantorData(guarantor.getId(), guarantorData = new GuarantorData(guarantor.getId(), guarantor.getFirstName(), guarantor.getLastName(),
guarantor.getFirstName(), guarantor.getLastName(), guarantor.getExternalId(), guarantor.getOffice().getName(), localDate);
guarantor.getExternalId(), guarantor.getOffice().getName(), } else {
localDate); guarantorData = getExternalGuarantor(loanId);
} else { }
guarantorData = getExternalGuarantor(loanId); // throw error if guarantor does not exist
} if (guarantorData == null) { throw new GuarantorNotFoundException(loanId); }
// throw error if guarantor does not exist return guarantorData;
if (guarantorData == null) { }
throw new GuarantorNotFoundException(loanId);
}
return guarantorData;
}
/** private Loan retrieveLoanById(final Long loanId) {
* @param loanId
* @return // FIXME - KW - On the read side of services - we would prefer not to use the repository/ORM pattern
*/ Loan loan = loanRepository.findOne(loanId);
private Loan validateLoanExists(Long loanId) { if (loan == null) { throw new LoanNotFoundException(loanId); }
Loan loan = loanRepository.findOne(loanId); return loan;
if (loan == null) { }
throw new LoanNotFoundException(loanId);
}
return loan;
}
/** @Override
* @param loanId public GuarantorData getExternalGuarantor(final Long loanId) {
* @return
*/ GenericResultsetData genericResultDataSet = readWriteNonCoreDataService.retrieveDataTableGenericResultSet(
public GuarantorData getExternalGuarantor(Long loanId) { EXTERNAL_GUARANTOR_TABLE_NAME, loanId, null, null);
GenericResultsetData genericResultDataSet = readWriteNonCoreDataService if (genericResultDataSet.getData().size() == 1) {
.retrieveDataTableGenericResultSet( List<String> guarantorRow = genericResultDataSet.getData().get(0).getRow();
EXTERNAL_GUARANTOR_TABLE_NAME, loanId, null, null); String firstname = guarantorRow.get(1);
if (genericResultDataSet.getData().size() == 1) { String lastname = guarantorRow.get(2);
List<String> 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;
}
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;
}
} }
@@ -19,164 +19,126 @@ import org.mifosng.platform.exceptions.PlatformApiDataValidationException;
import org.mifosng.platform.loan.domain.Loan; import org.mifosng.platform.loan.domain.Loan;
import org.mifosng.platform.loan.domain.LoanRepository; import org.mifosng.platform.loan.domain.LoanRepository;
import org.mifosng.platform.noncore.ReadWriteNonCoreDataService; import org.mifosng.platform.noncore.ReadWriteNonCoreDataService;
import org.mifosng.platform.organisation.domain.OfficeRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@Service @Service
public class GuarantorWritePlatformServiceImpl implements public class GuarantorWritePlatformServiceImpl implements GuarantorWritePlatformService {
GuarantorWritePlatformService {
private final LoanRepository loanRepository; // Table for storing external Guarantor Details
private final ClientRepository clientRepository; public static final String EXTERNAL_GUARANTOR_TABLE_NAME = "m_guarantor_external";
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";
@Autowired private final LoanRepository loanRepository;
public GuarantorWritePlatformServiceImpl( private final ClientRepository clientRepository;
final LoanRepository loanRepository, private final ReadWriteNonCoreDataService readWriteNonCoreDataService;
final ReadWriteNonCoreDataService readWriteNonCoreDataService, private final GuarantorReadPlatformService guarantorReadPlatformService;
final OfficeRepository officeRepository,
final ClientRepository clientRepository,
final GuarantorReadPlatformService guarantorReadPlatformService) {
this.loanRepository = loanRepository;
this.readWriteNonCoreDataService = readWriteNonCoreDataService;
this.clientRepository = clientRepository;
this.guarantorReadPlatformService = guarantorReadPlatformService;
}
@Override @Autowired
@Transactional public GuarantorWritePlatformServiceImpl(final LoanRepository loanRepository,
public void createGuarantor(Long loanId, GuarantorCommand command) { final ReadWriteNonCoreDataService readWriteNonCoreDataService, final ClientRepository clientRepository,
GuarantorCommandValidator validator = new GuarantorCommandValidator( final GuarantorReadPlatformService guarantorReadPlatformService) {
command); this.loanRepository = loanRepository;
validator.validateForCreate(); this.readWriteNonCoreDataService = readWriteNonCoreDataService;
saveOrUpdateGuarantor(loanId, command); this.clientRepository = clientRepository;
} this.guarantorReadPlatformService = guarantorReadPlatformService;
}
@Override @Override
@Transactional @Transactional
public void updateGuarantor(Long loanId, GuarantorCommand command) { public void createGuarantor(final Long loanId, final GuarantorCommand command) {
GuarantorCommandValidator validator = new GuarantorCommandValidator( GuarantorCommandValidator validator = new GuarantorCommandValidator(command);
command); validator.validateForCreate();
validator.validateForUpdate(); saveOrUpdateGuarantor(loanId, command);
saveOrUpdateGuarantor(loanId, command); }
}
@Override @Override
@Transactional @Transactional
public void removeGuarantor(Long loanId) { public void updateGuarantor(final Long loanId, final GuarantorCommand command) {
Loan loan = validateLoanExists(loanId); GuarantorCommandValidator validator = new GuarantorCommandValidator(command);
// remove internal guarantor, if any validator.validateForUpdate();
if (loan.getGuarantor() != null) { saveOrUpdateGuarantor(loanId, command);
loan.setGuarantor(null); }
loanRepository.saveAndFlush(loan);
}
// remove external guarantor, if any
readWriteNonCoreDataService.deleteDatatableEntries(
EXTERNAL_GUARANTOR_TABLE_NAME, loanId);
}
/** @Override
* @param loanId @Transactional
* @param command public void removeGuarantor(final Long loanId) {
*/ Loan loan = retrieveLoanById(loanId);
private void saveOrUpdateGuarantor(Long loanId, GuarantorCommand command) { // remove internal guarantor, if any
Loan loan = validateLoanExists(loanId); if (loan.getGuarantor() != null) {
// mark an existing client as a guarantor loan.setGuarantor(null);
if (command.isExternalGuarantor() == null loanRepository.saveAndFlush(loan);
|| !command.isExternalGuarantor()) { }
// can't set client as a guarantor to himself // remove external guarantor, if any
if (loan.getClient().getId().equals(command.getExistingClientId())) { readWriteNonCoreDataService.deleteDatatableEntries(EXTERNAL_GUARANTOR_TABLE_NAME, loanId);
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<String> modifiedParameters = command.getModifiedParameters();
Map<String, String> modifiedParametersMap = new HashMap<String, String>();
/***
* TODO Vishwas: Check with JW/KW if using reflection here is a good
* idea
**/
Class<? extends GuarantorCommand> 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<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
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);
}
} 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<String> modifiedParameters = command.getModifiedParameters();
Map<String, String> modifiedParametersMap = new HashMap<String, String>();
/***
* TODO Vishwas: Check with JW/KW if using reflection here is a good
* idea
**/
Class<? extends GuarantorCommand> 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<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
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);
}
}
}
/** /*** update or create a new external Guarantor entry ***/
* @param loanId modifiedParametersMap.put("locale", command.getLocale());
* @return modifiedParametersMap.put("dateFormat", command.getDateFormat());
*/ if (guarantorReadPlatformService.getExternalGuarantor(loanId) != null) {
private Loan validateLoanExists(Long loanId) { readWriteNonCoreDataService.updateDatatableEntryOnetoOne(EXTERNAL_GUARANTOR_TABLE_NAME, loanId, modifiedParametersMap);
Loan loan = loanRepository.findOne(loanId); } else {
if (loan == null) { readWriteNonCoreDataService.newDatatableEntry(EXTERNAL_GUARANTOR_TABLE_NAME, loanId, modifiedParametersMap);
throw new LoanNotFoundException(loanId); }
} // finally unset any existing internal guarantors
return loan; 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;
}
} }