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")
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<String> typicalResponseParameters = new HashSet<String>(
Arrays.asList("externalGuarantor", "existingClientId", "firstname",
"lastname", "addressLine1", "addressLine2", "city",
"state", "zip", "country", "mobileNumber",
"housePhoneNumber", "comment", "dob"));
private static final Set<String> typicalResponseParameters = new HashSet<String>(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<String> 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<String> 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();
}
}
@@ -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 LoanWritePlatformService loanWritePlatformService;
@Autowired
private LoanProductReadPlatformService loanProductReadPlatformService;
@Autowired
private LoanProductReadPlatformService loanProductReadPlatformService;
@Autowired
private LoanDropdownReadPlatformService dropdownReadPlatformService;
@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 PortfolioApiDataConversionService apiDataConversionService;
@Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService;
@Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService;
@Autowired
private StaffReadPlatformService staffReadPlatformService;
@Autowired
private StaffReadPlatformService staffReadPlatformService;
@Autowired
private PlatformSecurityContext context;
@Autowired
private GuarantorReadPlatformService guarantorReadPlatformService;
@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) {
@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");
context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
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();
// 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<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();
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();
final boolean feeChargesOnly = false;
Collection<ChargeData> chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly);
ChargeData chargeTemplate = this.chargeReadPlatformService.retrieveLoanChargeTemplate();
LoanBasicDetailsData loanBasicDetails;
Long officeId;
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();
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<LoanChargeData> charges = loanBasicDetails.getCharges();
final boolean convenienceDataRequired = false;
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,
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");
context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(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;
Collection<LoanTransactionData> loanRepayments = null;
LoanScheduleData repaymentSchedule = null;
LoanPermissionData permissions = null;
int loanRepaymentsCount = 0;
Collection<LoanTransactionData> loanRepayments = null;
LoanScheduleData repaymentSchedule = null;
LoanPermissionData permissions = null;
Collection<LoanChargeData> charges = null;
GuarantorData guarantorData = null;
boolean convenienceDataRequired = false;
final Set<String> associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters());
if (!associationParameters.isEmpty()) {
final Set<String> associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters());
if (!associationParameters.isEmpty()) {
if (associationParameters.contains("all")) {
associationParameters.addAll(Arrays.asList("repaymentSchedule", "transactions", "permissions", "convenienceData", "charges", "guarantor"));
}
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;
}
}
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("transactions")) {
final Collection<LoanTransactionData> currentLoanRepayments = this.loanReadPlatformService.retrieveLoanTransactions(loanId);
if (!CollectionUtils.isEmpty(currentLoanRepayments)) {
loanRepayments = currentLoanRepayments;
}
}
if (associationParameters.contains("repaymentSchedule")) {
if (associationParameters.contains("repaymentSchedule")) {
DisbursementData singleDisbursement = loanBasicDetails.toDisburementData();
repaymentSchedule = this.loanReadPlatformService.retrieveRepaymentSchedule(loanId, loanBasicDetails.getCurrency(),
singleDisbursement, loanBasicDetails.getTotalDisbursementCharges(), loanBasicDetails.getInArrearsTolerance());
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());
// 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));
boolean isWaiveAllowed = totalOutstandingMoney.isGreaterThanZero()
&& (tolerance.isGreaterThan(totalOutstandingMoney) || tolerance.isEqualTo(totalOutstandingMoney));
if (associationParameters.contains("permissions")) {
loanRepaymentsCount = retrieveNonDisbursementTransactions(loanRepayments);
permissions = this.loanReadPlatformService.retrieveLoanPermissions(loanBasicDetails, isWaiveAllowed, loanRepaymentsCount, existsGuarantor);
}
convenienceDataRequired = true;
}
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("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;
Collection<EnumOptionData> loanTermFrequencyTypeOptions = null;
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;
Collection<LoanProductData> productOptions = null;
Collection<EnumOptionData> loanTermFrequencyTypeOptions = null;
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 boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
if(template) {
productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup();
loanTermFrequencyTypeOptions = dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions();
repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions();
interestRateFrequencyTypeOptions = dropdownReadPlatformService.retrieveInterestRateFrequencyTypeOptions();
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();
amortizationTypeOptions = dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions();
interestTypeOptions = dropdownReadPlatformService.retrieveLoanInterestTypeOptions();
interestCalculationPeriodTypeOptions = dropdownReadPlatformService.retrieveLoanInterestRateCalculatedInPeriodOptions();
fundOptions = this.fundReadPlatformService.retrieveAllFunds();
repaymentStrategyOptions = this.dropdownReadPlatformService.retreiveTransactionProcessingStrategies();
final boolean feeChargesOnly = false;
chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly);
chargeTemplate = this.chargeReadPlatformService.retrieveLoanChargeTemplate();
}
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);
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);
}
return this.apiJsonSerializerService.serializeLoanAccountDataToJson(prettyPrint, responseParameters, loanAccount);
}
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;
}
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;
}
@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
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String calculateLoanScheduleOrSubmitLoanApplication(@QueryParam("command") final String commandParam,
@Context final UriInfo uriInfo, final String jsonRequestBody) {
final LoanApplicationCommand command = this.apiDataConversionService.convertJsonToLoanApplicationCommand(null, jsonRequestBody);
final LoanApplicationCommand command = this.apiDataConversionService.convertJsonToLoanApplicationCommand(null, jsonRequestBody);
if (is(commandParam, "calculateLoanSchedule")) {
CalculateLoanScheduleCommand calculateLoanScheduleCommand = command.toCalculateLoanScheduleCommand();
return calculateLoanSchedule(uriInfo, calculateLoanScheduleCommand);
}
if (is(commandParam, "calculateLoanSchedule")) {
CalculateLoanScheduleCommand calculateLoanScheduleCommand = command.toCalculateLoanScheduleCommand();
return calculateLoanSchedule(uriInfo, calculateLoanScheduleCommand);
}
final EntityIdentifier identifier = this.loanWritePlatformService.submitLoanApplication(command);
final EntityIdentifier identifier = this.loanWritePlatformService.submitLoanApplication(command);
return this.apiJsonSerializerService.serializeEntityIdentifier(identifier);
}
return this.apiJsonSerializerService.serializeEntityIdentifier(identifier);
}
private String calculateLoanSchedule(final UriInfo uriInfo, final CalculateLoanScheduleCommand command) {
private String calculateLoanSchedule(final UriInfo uriInfo, final CalculateLoanScheduleCommand command) {
final LoanScheduleData loanSchedule = this.calculationPlatformService.calculateLoanSchedule(command);
final LoanScheduleData loanSchedule = this.calculationPlatformService.calculateLoanSchedule(command);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
return this.apiJsonSerializerService.serializeLoanScheduleDataToJson(prettyPrint, responseParameters, loanSchedule);
}
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) {
@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);
final LoanApplicationCommand command = this.apiDataConversionService.convertJsonToLoanApplicationCommand(loanId, jsonRequestBody);
final EntityIdentifier identifier = this.loanWritePlatformService.modifyLoanApplication(command);
final EntityIdentifier identifier = this.loanWritePlatformService.modifyLoanApplication(command);
return this.apiJsonSerializerService.serializeEntityIdentifier(identifier);
}
return this.apiJsonSerializerService.serializeEntityIdentifier(identifier);
}
@DELETE
@Path("{loanId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response deleteLoanApplication(@PathParam("loanId") final Long loanId) {
@DELETE
@Path("{loanId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response deleteLoanApplication(@PathParam("loanId") final Long loanId) {
EntityIdentifier identifier = this.loanWritePlatformService.deleteLoan(loanId);
EntityIdentifier identifier = this.loanWritePlatformService.deleteLoan(loanId);
return Response.ok().entity(identifier).build();
}
return Response.ok().entity(identifier).build();
}
@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) {
@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) {
LoanStateTransitionCommand command = this.apiDataConversionService.convertJsonToLoanStateTransitionCommand(loanId, jsonRequestBody);
LoanStateTransitionCommand command = this.apiDataConversionService.convertJsonToLoanStateTransitionCommand(loanId, jsonRequestBody);
Response response = null;
Response response = null;
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();
}
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();
}
UndoStateTransitionCommand undoCommand = new UndoStateTransitionCommand(
loanId, command.getNote());
UndoStateTransitionCommand undoCommand = new UndoStateTransitionCommand(loanId, command.getNote());
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();
}
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();
}
if (response == null) {
throw new UnrecognizedQueryParamException("command", commandParam);
}
if (response == null) { throw new UnrecognizedQueryParamException("command", commandParam); }
return response;
}
return response;
}
private boolean is(final String commandParam, final String commandValue) {
return StringUtils.isNotBlank(commandParam)
&& commandParam.trim().equalsIgnoreCase(commandValue);
}
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) {
@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);
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);
}
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);
}
if (identifier == null) { throw new UnrecognizedQueryParamException("command", commandParam); }
return Response.ok().entity(identifier).build();
}
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) {
@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");
context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
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);
}
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);
}
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) {
@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");
context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final LoanTransactionData transactionData = this.loanReadPlatformService.retrieveLoanTransactionDetails(loanId, transactionId);
final LoanTransactionData transactionData = this.loanReadPlatformService.retrieveLoanTransactionDetails(loanId, transactionId);
return this.apiJsonSerializerService.serializeLoanTransactionDataToJson(prettyPrint, responseParameters, transactionData);
}
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) {
@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);
final AdjustLoanTransactionCommand command = this.apiDataConversionService.convertJsonToAdjustLoanTransactionCommand(loanId,
transactionId, jsonRequestBody);
EntityIdentifier identifier = this.loanWritePlatformService
.adjustLoanTransaction(command);
EntityIdentifier identifier = this.loanWritePlatformService.adjustLoanTransaction(command);
return Response.ok().entity(identifier).build();
}
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");
context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final boolean feeChargesOnly = false;
final Collection<ChargeData> chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly);
@@ -534,17 +510,15 @@ 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");
context.authenticatedUser().validateHasReadPermission("LOAN");
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final LoanChargeData loanCharge = this.chargeReadPlatformService.retrieveLoanChargeDetails(loanChargeId, loanId);
@@ -555,12 +529,11 @@ public class LoansApiResource {
@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);
@@ -571,20 +544,18 @@ public class LoansApiResource {
@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<String> responseParameters = ApiParameterHelper
.extractFieldsForResponseIfProvided(uriInfo
.getQueryParameters());
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
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();
LoanReassignmentData loanReassignmentData = LoanReassignmentData.template(fromLoanOfficerId, allowedLoanOfficers, new LocalDate());
@@ -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;
/*** 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;
/**Feilds for passing Locale info to generic data service api**/
private String dateFormat;
private String locale;
/** Feilds for passing Locale info to generic data service api **/
private String dateFormat;
private String locale;
private final Set<String> modifiedParameters;
private final Set<String> modifiedParameters;
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;
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;
this.externalGuarantor = externalGuarantor;
this.externalGuarantor = externalGuarantor;
/*** Fields for current customers serving as guarantors **/
this.existingClientId = existingClientId;
/*** Fields for current customers serving as guarantors **/
this.existingClientId = existingClientId;
/*** 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 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 getFirstname() {
return firstname;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public String getLastname() {
return lastname;
}
public Boolean isExternalGuarantor() {
return externalGuarantor;
}
public Boolean isExternalGuarantor() {
return externalGuarantor;
}
public Long getExistingClientId() {
return existingClientId;
}
public Long getExistingClientId() {
return existingClientId;
}
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getAddressLine2() {
return addressLine2;
}
public String getCity() {
return city;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public String getState() {
return state;
}
public String getZip() {
return zip;
}
public String getZip() {
return zip;
}
public String getCountry() {
return country;
}
public String getCountry() {
return country;
}
public String getMobileNumber() {
return mobileNumber;
}
public String getMobileNumber() {
return mobileNumber;
}
public String getHousePhoneNumber() {
return housePhoneNumber;
}
public String getHousePhoneNumber() {
return housePhoneNumber;
}
public String getComment() {
return comment;
}
public String getComment() {
return comment;
}
public Set<String> getModifiedParameters() {
return modifiedParameters;
}
public Set<String> getModifiedParameters() {
return modifiedParameters;
}
public String getDob() {
return dob;
}
public String getDob() {
return dob;
}
public String getDateFormat() {
return dateFormat;
}
public String getDateFormat() {
return dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public String getLocale() {
return locale;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
}
@@ -95,7 +95,7 @@ public interface PortfolioApiDataConversionService {
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);
}
@@ -1631,66 +1631,44 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo
}
@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<Map<String, String>>() {
}.getType();
Map<String, String> requestMap = gsonConverter
.fromJson(json, typeOfMap);
Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> requestMap = gsonConverter.fromJson(json, typeOfMap);
Set<String> supportedParams = new HashSet<String>(Arrays.asList(
"externalGuarantor", "existingClientId", "firstname",
"lastname", "addressLine1", "addressLine2", "city", "state",
"zip", "country", "mobileNumber", "housePhoneNumber",
"comment", "dob", "locale", "dateFormat"));
Set<String> supportedParams = new HashSet<String>(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<String> modifiedParameters = new HashSet<String>();
Set<String> modifiedParameters = new HashSet<String>();
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);
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;
}
// 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;
}
}
@@ -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";
@Autowired
public GuarantorReadPlatformServiceImpl(
final LoanRepository loanRepository,
final ReadWriteNonCoreDataService readWriteNonCoreDataService,
final OfficeRepository officeRepository) {
this.loanRepository = loanRepository;
this.readWriteNonCoreDataService = readWriteNonCoreDataService;
}
private final LoanRepository loanRepository;
private final 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;
}
@Autowired
public GuarantorReadPlatformServiceImpl(final LoanRepository loanRepository,
final ReadWriteNonCoreDataService readWriteNonCoreDataService) {
this.loanRepository = loanRepository;
this.readWriteNonCoreDataService = readWriteNonCoreDataService;
}
@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 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;
}
/**
* @param loanId
* @return
*/
private Loan validateLoanExists(Long loanId) {
Loan loan = loanRepository.findOne(loanId);
if (loan == null) {
throw new LoanNotFoundException(loanId);
}
return loan;
}
@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
*/
public GuarantorData getExternalGuarantor(Long loanId) {
GenericResultsetData genericResultDataSet = readWriteNonCoreDataService
.retrieveDataTableGenericResultSet(
EXTERNAL_GUARANTOR_TABLE_NAME, loanId, null, null);
if (genericResultDataSet.getData().size() == 1) {
List<String> guarantorRow = genericResultDataSet.getData().get(0)
.getRow();
String firstname = guarantorRow.get(1);
String lastname = guarantorRow.get(2);
private Loan retrieveLoanById(final Long loanId) {
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;
}
// 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;
}
@Override
public GuarantorData getExternalGuarantor(final Long loanId) {
GenericResultsetData genericResultDataSet = readWriteNonCoreDataService.retrieveDataTableGenericResultSet(
EXTERNAL_GUARANTOR_TABLE_NAME, loanId, null, null);
if (genericResultDataSet.getData().size() == 1) {
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;
}
}
@@ -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<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);
}
@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<String> modifiedParameters = command.getModifiedParameters();
Map<String, String> modifiedParametersMap = new HashMap<String, String>();
/*** 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);
}
}
}
/***
* 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);
}
/**
* @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;
}
}