001package io.konik.calculation;
002
003import static io.konik.validation.AmountCalculator.recalculate;
004
005import java.util.List;
006
007import javax.validation.constraints.NotNull;
008
009import org.slf4j.Logger;
010import org.slf4j.LoggerFactory;
011
012import io.konik.validation.AmountCalculator.RecalculationResult;
013import io.konik.validation.AmountCalculator.TaxAggregator;
014import io.konik.zugferd.Invoice;
015import io.konik.zugferd.entity.trade.MonetarySummation;
016import io.konik.zugferd.entity.trade.TradeTax;
017
018/**
019 * Recalculates invoice settlement {@link MonetarySummation} and replaces it in the {@link Invoice} object.
020 */
021public final class InvoiceMonetarySummationAndTradeTaxCompleter implements Correction<Invoice> {
022
023   protected static Logger log = LoggerFactory.getLogger(InvoiceMonetarySummationAndTradeTaxCompleter.class);
024
025   @Override
026   public Invoice correct(@NotNull final Invoice invoice) {
027
028      log.debug("Running InvoiceMonetarySummationCompleter...");
029
030      if (invoice.getTrade() != null && invoice.getTrade().getSettlement() != null) {
031         RecalculationResult result = recalculate(invoice);
032         MonetarySummation monetarySummation = result.getMonetarySummation();
033         invoice.getTrade().getSettlement().setMonetarySummation(monetarySummation);
034
035         TaxAggregator taxAggregator = result.getTaxAggregator();
036         List<TradeTax> taxes = taxAggregator.generateTradeTaxList(invoice.getTrade().getSettlement().getCurrency(),
037               invoice.getTrade().getSettlement().getTradeTax());
038
039         invoice.getTrade().getSettlement().getTradeTax().clear();
040
041         for (TradeTax tradeTax : taxes) {
042            invoice.getTrade().getSettlement().addTradeTax(tradeTax);
043         }
044
045      }
046      return invoice;
047   }
048}