final Loan loan = this.loanRepository.findOne(loanId);
if (loan == null) { throw new LoanNotFoundException(loanId); }
final CodeValue collateralType = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(
CollateralApiConstants.COLLATERAL_CODE_NAME, collateralCommand.getCollateralTypeId());
final LoanCollateral collateral = LoanCollateral.fromJson(loan, collateralType, command);
/**
* Collaterals may be added only when the loan associated with them
* are yet to be approved
**/
if (!loan.status().isSubmittedAndPendingApproval()) { throw new CollateralCannotBeCreatedException(
LOAN_COLLATERAL_CANNOT_BE_CREATED_REASON.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loan.getId()); }
this.collateralRepository.save(collateral);
return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) //
.withLoanId(loan.getId())//
.withEntityId(collateral.getId()) //
.build();
} catch (final DataIntegrityViolationException dve) {
handleCollateralDataIntegrityViolation(dve);
return CommandProcessingResult.empty();
}