public void reconcile(Resource resource, User consumer) {
//Write-off cycle
int consumersCount = 0;
User supplier = null;
Need consumerTender = null;
Supply supplierTender = null;
BigDecimal totalSuppliersPrice = BigDecimal.ZERO;
BigDecimal totalConsumerAmount = BigDecimal.ZERO;
for(Supply supply: resource.getSupplies()) {
if(supply.getAcceptDate() != null) {
//TODO: Consider coefficients depending on business regulators(
// reputation, demand/supply, etc...
totalSuppliersPrice = totalSuppliersPrice.add(supplierTender.getTotalPrice());
break;
}
}
for(Need need: resource.getNeeds()) {
if(need.getCompletionDate() == null) {
totalConsumerAmount = totalConsumerAmount.add(need.getAmount());
consumersCount++;
if(consumer.equals(need.getUser())) {
consumerTender = need;
}
}
}
if(consumerTender == null) {
throw new BusinessLogicException("The specified user #" + consumer.getId() + " is not consumer of the specified resource #" + resource.getId());
}
//Complete the tender
needManager.completeTender(consumerTender);
//Write-on cycle
BigDecimal writeOnAmount = totalSuppliersPrice.
divide(BigDecimal.valueOf(consumersCount), RoundingMode.HALF_UP);
moneyManager.performAutoMovement(Collections.singleton(
new PayerData(supplier, writeOnAmount, supplierTender.getCurrency())),
Collections.singleton(consumer));
}