List<GenericValue> acctgTransEntries = invoice.getRelated("AcctgTrans");
if (UtilValidate.isNotEmpty(acctgTransEntries)) {
GenericValue acctgTransEntry = (acctgTransEntries.get(0)).getRelated("AcctgTransEntry").get(0);
BigDecimal origAmount = acctgTransEntry.getBigDecimal("origAmount");
if (origAmount.compareTo(ZERO) == 1) {
conversionRate = acctgTransEntry.getBigDecimal("amount").divide(acctgTransEntry.getBigDecimal("origAmount"), new MathContext(100)).setScale(decimals,rounding);
}
}
// check if a payment is applied and use the currency conversion from there
if (UtilValidate.isEmpty(conversionRate)) {
List<GenericValue> paymentAppls = invoice.getRelated("PaymentApplication");
for (GenericValue paymentAppl : paymentAppls) {
GenericValue payment = paymentAppl.getRelatedOne("Payment");
if (UtilValidate.isNotEmpty(payment.getBigDecimal("actualCurrencyAmount"))) {
if (UtilValidate.isEmpty(conversionRate)) {
conversionRate = payment.getBigDecimal("amount").divide(payment.getBigDecimal("actualCurrencyAmount"),new MathContext(100)).setScale(decimals,rounding);
} else {
conversionRate = conversionRate.add(payment.getBigDecimal("amount").divide(payment.getBigDecimal("actualCurrencyAmount"),new MathContext(100))).divide(new BigDecimal("2"),new MathContext(100)).setScale(decimals,rounding);
}
}
}
}
// use the dated conversion entity
if (UtilValidate.isEmpty(conversionRate)) {
List<GenericValue> rates = EntityUtil.filterByDate(delegator.findByAnd("UomConversionDated", UtilMisc.toMap("uomIdTo", invoice.getString("currencyUomId"), "uomId", otherCurrencyUomId)), invoice.getTimestamp("invoiceDate"));
if (UtilValidate.isNotEmpty(rates)) {
conversionRate = (BigDecimal.ONE).divide((rates.get(0)).getBigDecimal("conversionFactor"), new MathContext(100)).setScale(decimals,rounding);
} else {
Debug.logError("Could not find conversionrate for invoice: " + invoice.getString("invoiceId"), module);
return new BigDecimal("1");
}
}