if(BigDecimal.ZERO.compareTo(amount) > 0) {
//Free reserved amount
creditStatusDAO.freeAmount(amount.negate(), consumer.getId());
}
CHECreditStatus status = creditStatusDAO.getOrCreateByUserId(consumer.getId());
BigDecimal debt = status.getDebt();
if(amount.compareTo(BigDecimal.ZERO) > 0) {
//amount > 0
if(debt.compareTo(amount) > 0) {
status.setDebt(debt.subtract(amount));
} else {
status.setDebt(BigDecimal.ZERO);
amount = amount.subtract(debt);
CHEPayment newPayment = new CHEPayment();
newPayment.setCreditStatus(status);
newPayment.setValue(amount);
newPayment.setPaymentDate(new Date());
status.getPayments().add(newPayment);
}
} else {
//amount <= 0
//'Eat' payments first
Collection<CHEPayment> payments = status.getPayments();
for(Iterator<CHEPayment> paymentIt = payments.iterator(); paymentIt.hasNext();) {
CHEPayment payment = paymentIt.next();
BigDecimal paymentValue = payment.getValue();
if(paymentValue.compareTo(amount.negate()) < 0) {
//paymentValue < -amount
amount = amount.add(paymentValue);//amount <= 0,paymentValue >= 0
paymentIt.remove();
} else {
//paymentValue >= -amount
payment.setValue(paymentValue.add(amount)); //amount <= 0
amount = BigDecimal.ZERO;
break;
}
}
//Update debt if no more payments exists
status.setDebt(debt.subtract(amount));//NOTE: amount <= 0, debt >= 0
}
creditStatusDAO.save(status);//Commit status changes
}