@Override
@Transactional
public CommandProcessingResult updateGuarantor(final Long loanId, final Long guarantorId, final JsonCommand command) {
try {
final GuarantorCommand guarantorCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json());
guarantorCommand.validateForUpdate();
final Loan loan = this.loanRepositoryWrapper.findOneWithNotFoundDetection(loanId);
final Guarantor guarantorForUpdate = this.guarantorRepository.findByLoanAndId(loan, guarantorId);
if (guarantorForUpdate == null) { throw new GuarantorNotFoundException(loanId, guarantorId); }
final Map<String, Object> changesOnly = guarantorForUpdate.update(command);
if (changesOnly.containsKey(GUARANTOR_JSON_INPUT_PARAMS.CLIENT_RELATIONSHIP_TYPE_ID.getValue())) {
final Long clientRelationshipId = guarantorCommand.getClientRelationshipTypeId();
CodeValue clientRelationshipType = null;
if (clientRelationshipId != null) {
clientRelationshipType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection(
GuarantorConstants.GUARANTOR_RELATIONSHIP_CODE_NAME, clientRelationshipId);
}
guarantorForUpdate.updateClientRelationshipType(clientRelationshipType);
}
final List<Guarantor> existGuarantorList = this.guarantorRepository.findByLoan(loan);
final Integer guarantorTypeId = guarantorCommand.getGuarantorTypeId();
final GuarantorType guarantorType = GuarantorType.fromInt(guarantorTypeId);
if (guarantorType.isCustomer() || guarantorType.isStaff()) {
final Long entityId = guarantorCommand.getEntityId();
for (final Guarantor guarantor : existGuarantorList) {
if (guarantor.getLoanId() == loanId && guarantor.getEntityId() == entityId
&& guarantor.getGurantorType() == guarantorTypeId && !guarantorForUpdate.getId().equals(guarantor.getId())) {
String defaultUserMessage = this.clientRepositoryWrapper.findOneWithNotFoundDetection(entityId).getDisplayName();
defaultUserMessage = defaultUserMessage + " is already exist as a guarantor for this loan";