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;
}
}