svn commit: r701313 - in /ofbiz/trunk/applications/accounting: config/ script/org/ofbiz/accounting/invoice/ src/org/ofbiz/accounting/invoice/ src/org/ofbiz/accounting/payment/ webapp/accounting/WEB-INF/actions/invoice/

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

svn commit: r701313 - in /ofbiz/trunk/applications/accounting: config/ script/org/ofbiz/accounting/invoice/ src/org/ofbiz/accounting/invoice/ src/org/ofbiz/accounting/payment/ webapp/accounting/WEB-INF/actions/invoice/

hansbak-2
Author: hansbak
Date: Fri Oct  3 00:12:35 2008
New Revision: 701313

URL: http://svn.apache.org/viewvc?rev=701313&view=rev
Log:
correct some errors in the updpaymentappl service make the currency display properly in the messages, make the 'other currency' view of the invoice working again

Modified:
    ofbiz/trunk/applications/accounting/config/AccountingUiLabels.xml
    ofbiz/trunk/applications/accounting/script/org/ofbiz/accounting/invoice/InvoiceServices.xml
    ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java
    ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/payment/PaymentWorker.java
    ofbiz/trunk/applications/accounting/webapp/accounting/WEB-INF/actions/invoice/EditInvoice.groovy

Modified: ofbiz/trunk/applications/accounting/config/AccountingUiLabels.xml
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/config/AccountingUiLabels.xml?rev=701313&r1=701312&r2=701313&view=diff
==============================================================================
--- ofbiz/trunk/applications/accounting/config/AccountingUiLabels.xml (original)
+++ ofbiz/trunk/applications/accounting/config/AccountingUiLabels.xml Fri Oct  3 00:12:35 2008
@@ -4481,15 +4481,15 @@
         <value xml:lang="zh">已收到支付</value>
     </property>
     <property key="AccountingPaymentApplRemoved">
-        <value xml:lang="en">PaymentID [${paymentApplication.paymentId}] with amount ${paymentApplication.amountApplied?currency(${payment.currencyUomId})} removed from</value>
-        <value xml:lang="es">IdPago[${paymentApplication.paymentId}] con cantidad ${paymentApplication.amountApplied?currency(${payment.currencyUomId})} suprimido de</value>
-        <value xml:lang="fr">Le paiement [${paymentApplication.paymentId}] d'un montant de ${paymentApplication.amountApplied?currency(${payment.currencyUomId})} a été retiré de</value>
-        <value xml:lang="it">Codice Pagamento [${paymentApplication.paymentId}] con importo ${paymentApplication.amountApplied?currency(${payment.currencyUomId})} cancellato da</value>
-        <value xml:lang="nl">BetalingsNr [${paymentApplication.paymentId}] met het bedrag ${paymentApplication.amountApplied?currency(${payment.currencyUomId})} verwijdert van</value>
-        <value xml:lang="ro">Cod Plata [${paymentApplication.paymentId}] cu o valoare ${paymentApplication.amountApplied?currency(${payment.currencyUomId})} eliminata din</value>
-        <value xml:lang="ru">Платеж с кодом [${paymentApplication.paymentId}] на сумму ${paymentApplication.amountApplied?currency(${payment.currencyUomId})} удален из</value>
-        <value xml:lang="th">รหัสการชำระเงิน [${paymentApplication.paymentId}] ด้วยจำนวน ${paymentApplication.amountApplied?currency(${payment.currencyUomId})} ลบจาก</value>
-        <value xml:lang="zh">把支付编号为[${paymentApplication.paymentId}]、金额为${paymentApplication.amountApplied?currency(${payment.currencyUomId})}的支付删除出</value>
+        <value xml:lang="en">PaymentID [${paymentApplication.paymentId}] with amount ${paymentApplication.amountApplied?currency(${currencyUomId})} removed from</value>
+        <value xml:lang="es">IdPago[${paymentApplication.paymentId}] con cantidad ${paymentApplication.amountApplied?currency(${currencyUomId})} suprimido de</value>
+        <value xml:lang="fr">Le paiement [${paymentApplication.paymentId}] d'un montant de ${paymentApplication.amountApplied?currency(${currencyUomId})} a été retiré de</value>
+        <value xml:lang="it">Codice Pagamento [${paymentApplication.paymentId}] con importo ${paymentApplication.amountApplied?currency(${currencyUomId})} cancellato da</value>
+        <value xml:lang="nl">BetalingsNr [${paymentApplication.paymentId}] met het bedrag ${paymentApplication.amountApplied?currency(${currencyUomId})} verwijdert van</value>
+        <value xml:lang="ro">Cod Plata [${paymentApplication.paymentId}] cu o valoare ${paymentApplication.amountApplied?currency(${currencyUomId})} eliminata din</value>
+        <value xml:lang="ru">Платеж с кодом [${paymentApplication.paymentId}] на сумму ${paymentApplication.amountApplied?currency(${currencyUomId})} удален из</value>
+        <value xml:lang="th">รหัสการชำระเงิน [${paymentApplication.paymentId}] ด้วยจำนวน ${paymentApplication.amountApplied?currency(${currencyUomId})} ลบจาก</value>
+        <value xml:lang="zh">把支付编号为[${paymentApplication.paymentId}]、金额为${paymentApplication.amountApplied?currency(${currencyUomId})}的支付删除出</value>
     </property>
     <property key="AccountingPaymentApplToBillingAccount">
         <value xml:lang="en">Billing Account ID [${paymentApplication.billingAccountId}]</value>

Modified: ofbiz/trunk/applications/accounting/script/org/ofbiz/accounting/invoice/InvoiceServices.xml
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/script/org/ofbiz/accounting/invoice/InvoiceServices.xml?rev=701313&r1=701312&r2=701313&view=diff
==============================================================================
--- ofbiz/trunk/applications/accounting/script/org/ofbiz/accounting/invoice/InvoiceServices.xml (original)
+++ ofbiz/trunk/applications/accounting/script/org/ofbiz/accounting/invoice/InvoiceServices.xml Fri Oct  3 00:12:35 2008
@@ -147,7 +147,14 @@
             <set from-field="nowTimestamp" field="newEntity.invoiceDate"/>
         </if-empty>
         <if-empty field="parameters.currencyUomId">
-            <set from-field="partyAcctgPreference.baseCurrencyUomId" field="newEntity.currencyUomId"/>
+            <!-- if provided set the default currency to the receiving party -->
+            <entity-one entity-name="Party" value-name="party"/>
+            <if-not-empty field="party.preferredCurrencyUomId">
+                <set field="newEntity.currencyUomId" from-field="party.preferredCurrencyUomId"/>
+                <else>
+                    <set field="newEntity.currencyUomId" from-field="partyAcctgPreference.baseCurrencyUomId"/>
+                </else>
+            </if-not-empty>
         </if-empty>
 
         <create-value value-name="newEntity"/>
@@ -340,6 +347,7 @@
             <check-errors/>
         </if-empty>
         <!-- payment -->
+        <set field="currencyUomId" value=""/><!-- currency of the paymentApplication -->
         <if-not-empty field="paymentApplication.paymentId">
             <entity-one entity-name="Payment" value-name="payment">
                 <field-map field-name="paymentId" value="${paymentApplication.paymentId}"/>
@@ -351,8 +359,8 @@
                 <check-errors/>
             </if-not-empty>
             <field-to-result field-name="paymentApplication.paymentId" result-name="paymentId"/>
+            <set field="currencyUomId" from-field="paymentId.currencyUomId"/>
         </if-not-empty>
-        <property-to-field resource="AccountingUiLabels" property="AccountingPaymentApplRemoved" field-name="successMessage"/>
         <!-- check invoice -->
         <if-not-empty field="paymentApplication.invoiceId">
             <entity-one entity-name="Invoice" value-name="invoice">
@@ -363,6 +371,7 @@
                 <log level="info" message="Invoice not found, invoice Id: ${invoiceId}"/>
                 <check-errors/>
             </if-empty>
+            <set field="currencyUomId" from-field="invoice.currencyUomId"/>
             <!-- if the invoice is already PAID, then set it back to READY and clear out the paidDate -->
             <if-compare field="invoice.statusId" operator="equals" value="INVOICE_PAID">
                 <set field="invoiceStatusMap.invoiceId" value="${paymentApplication.invoiceId}" />
@@ -398,13 +407,18 @@
         <if-not-empty field="paymentApplication.billingAccountId">
             <field-to-result field-name="paymentApplication.billingAccountId" result-name="billingAccountId"/>
             <property-to-field resource="AccountingUiLabels" property="AccountingPaymentApplToBillingAccount" field-name="toMessage"/>
+            <entity-one entity-name="BillingAccount">
+                <field-map field-name="billingAccountId" env-name="paymentApplication.billingAccountId"/>
+            </entity-one>
+            <set field="currencyUomId" from-field="billingAccount.accountCurrencyUomId"/>
         </if-not-empty>
         <!-- tax authority -->
         <if-not-empty field="paymentApplication.taxAuthGeoId">
             <field-to-result field-name="paymentApplication.taxAuthGeoId" result-name="taxAuthGeoId"/>
             <property-to-field resource="AccountingUiLabels" property="AccountingPaymentApplToTaxAuth" field-name="toMessage"/>
         </if-not-empty>
-        <!-- finaly delete application -->
+        <!-- finally delete application -->
+        <property-to-field resource="AccountingUiLabels" property="AccountingPaymentApplRemoved" field-name="successMessage"/>
         <string-append field-name="successMessage" string=" ${toMessage}"/>
         <remove-value value-name="paymentApplication"/>
     </simple-method>

Modified: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java?rev=701313&r1=701312&r2=701313&view=diff
==============================================================================
--- ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java (original)
+++ ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java Fri Oct  3 00:12:35 2008
@@ -2341,51 +2341,38 @@
         // amount available on the payment reduced by the already applied amounts
         BigDecimal amountAppliedMax = ZERO;
         // the maximum that can be applied taking payment,invoice,invoiceitem,billing account in concideration
-        // if maxApplied is missing, this value can be used
+        // if maxApplied is missing, this value can be used,
+        // Payment this should be checked after the invoice checking because it is possible the currency is changed
         GenericValue payment = null;
+        String currencyUomId = null;
         if (paymentId == null || paymentId.equals("")) {
             errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentIdBlankNotSupplied",locale));
         } else {
-            try {
-                payment = delegator.findByPrimaryKey("Payment", UtilMisc.toMap("paymentId", paymentId));
-            } catch (GenericEntityException e) {
-                ServiceUtil.returnError(e.getMessage());
-            }
-            if (payment == null) {
-                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentRecordNotFound",UtilMisc.toMap("paymentId",paymentId),locale));
-            }
-            paymentApplyAvailable = payment.getBigDecimal("amount").subtract(PaymentWorker.getPaymentAppliedBd(payment)).setScale(decimals,rounding);
-
-            if (payment.getString("statusId").equals("PMNT_CANCELLED")) {
-                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentCancelled", UtilMisc.toMap("paymentId",paymentId), locale));
-            }
-            if (payment.getString("statusId").equals("PMNT_CONFIRMED")) {
-                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentConfirmed", UtilMisc.toMap("paymentId",paymentId), locale));
-            }
-
-            // if the amount to apply is 0 give it amount the payment still need
-            // to apply
-            if (amountApplied.signum() == 0) {
-                amountAppliedMax = paymentApplyAvailable;
-            }
-
-            if (paymentApplicationId == null) {
-                // only check for new application records, update on existing records is checked in the paymentApplication section
-                if (paymentApplyAvailable.signum() == 0) {
-                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentAlreadyApplied",UtilMisc.toMap("paymentId",paymentId), locale));
-                } else {
-                    // check here for too much application if a new record is
-                    // added (paymentApplicationId == null)
-                    if (amountApplied.compareTo(paymentApplyAvailable) > 0) {
-                        errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentLessRequested",
-                                UtilMisc.<String, Object>toMap("paymentId",paymentId,
-                                            "paymentApplyAvailable",paymentApplyAvailable,
-                                            "amountApplied",amountApplied,"isoCode",payment.getString("currencyUomId")),locale));
-                    }
-                }
-            }
+         try {
+         payment = delegator.findByPrimaryKey("Payment", UtilMisc.toMap("paymentId", paymentId));
+         } catch (GenericEntityException e) {
+         ServiceUtil.returnError(e.getMessage());
+         }
+         if (payment == null) {
+         errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentRecordNotFound",UtilMisc.toMap("paymentId",paymentId),locale));
+         }
+         paymentApplyAvailable = payment.getBigDecimal("amount").subtract(PaymentWorker.getPaymentAppliedBd(payment)).setScale(decimals,rounding);
+
+         if (payment.getString("statusId").equals("PMNT_CANCELLED")) {
+         errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentCancelled", UtilMisc.toMap("paymentId",paymentId), locale));
+         }
+         if (payment.getString("statusId").equals("PMNT_CONFIRMED")) {
+         errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentConfirmed", UtilMisc.toMap("paymentId",paymentId), locale));
+         }
+        
+         currencyUomId = payment.getString("currencyUomId");
+
+         // if the amount to apply is 0 give it amount the payment still need
+         // to apply
+         if (amountApplied.signum() == 0) {
+         amountAppliedMax = paymentApplyAvailable;
+         }
 
-            if (debug) Debug.logInfo("Payment info retrieved and checked...", module);
         }
 
         // the "TO" Payment.....
@@ -2425,7 +2412,7 @@
                             errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentLessRequested",
                                     UtilMisc.<String, Object>toMap("paymentId",toPaymentId,
                                                 "paymentApplyAvailable",toPaymentApplyAvailable,
-                                                "amountApplied",amountApplied,"isoCode",payment.getString("currencyUomId")),locale));
+                                                "amountApplied",amountApplied,"isoCode", currencyUomId),locale));
                     }
                 }
             }
@@ -2470,11 +2457,11 @@
                 errorMessageList.add(UtilProperties.getMessage(resource, "AccountingBillingAccountNotFound",UtilMisc.toMap("billingAccountId",billingAccountId), locale));
             }
             // check the currency
-            if (billingAccount.get("accountCurrencyUomId") != null && payment.get("currencyUomId") != null &&
-                    !billingAccount.getString("accountCurrencyUomId").equals(payment.getString("currencyUomId"))) {
+            if (billingAccount.get("accountCurrencyUomId") != null && currencyUomId != null &&
+                    !billingAccount.getString("accountCurrencyUomId").equals(currencyUomId)) {
                 errorMessageList.add(UtilProperties.getMessage(resource, "AccountingBillingAccountCurrencyProblem",
                         UtilMisc.toMap("billingAccountId",billingAccountId,"accountCurrencyUomId",billingAccount.getString("accountCurrencyUomId"),
-                                "paymentId",paymentId,"paymentCurrencyUomId", payment.getString("currencyUomId")),locale));
+                                "paymentId",paymentId,"paymentCurrencyUomId", currencyUomId),locale));
             }
 
             if (debug) Debug.logInfo("Billing Account info retrieved and checked...", module);
@@ -2503,8 +2490,8 @@
                 }
                 
                 // check the currency
-                if (payment.get("currencyUomId") != null && invoice.get("currencyUomId") != null &&
-                        !payment.getString("currencyUomId").equals(invoice.getString("currencyUomId"))) {
+                if (currencyUomId != null && invoice.get("currencyUomId") != null &&
+                        !currencyUomId.equals(invoice.getString("currencyUomId"))) {
                     Debug.logInfo(UtilProperties.getMessage(resource, "AccountingInvoicePaymentCurrencyProblem",
                             UtilMisc.toMap("invoiceCurrency", invoice.getString("currencyUomId"), "paymentCurrency", payment.getString("currencyUomId")),locale), module);
                     Debug.logInfo("will try to apply payment on the actualCurrency amount on payment", module);
@@ -2512,8 +2499,9 @@
                     if (payment.get("actualCurrencyAmount") == null || payment.get("actualCurrencyUomId") == null) {
                         errorMessageList.add("Actual amounts are required in the currency of the invoice to make this work....");
                     } else {
-                     if (!payment.get("actualCurrencyUomId").equals(invoice.get("currencyUomId"))) {
-                            errorMessageList.add("actual currency on payment not the same as original invoice currency");
+                     currencyUomId = payment.getString("actualCurrencyUomId");
+                     if (!currencyUomId.equals(invoice.getString("currencyUomId"))) {
+                            errorMessageList.add("actual currency on payment (" + currencyUomId + ") not the same as original invoice currency (" + invoice.getString("currencyUomId") + ")");
                      }
                     }
                     paymentApplyAvailable = payment.getBigDecimal("actualCurrencyAmount").subtract(PaymentWorker.getPaymentAppliedBd(payment)).setScale(decimals,rounding);
@@ -2569,8 +2557,8 @@
                 if (invoiceItem == null) {
                     errorMessageList.add(UtilProperties.getMessage(resource,"AccountingInvoiceItemNotFound",UtilMisc.toMap("invoiceId",invoiceId,"invoiceItemSeqId",invoiceItemSeqId),locale));
                 } else {
-                    if (invoice.get("currencyUomId") != null && payment.get("currencyUomId") != null && !invoice.getString("currencyUomId").equals(payment.getString("currencyUomId"))) {
-                        errorMessageList.add(UtilProperties.getMessage(resource,"AccountingInvoicePaymentCurrencyProblem",UtilMisc.toMap("paymentCurrencyId",payment.getString("currencyUomId"),"itemCurrency",invoice.getString("currencyUomId")) ,locale));
+                    if (invoice.get("currencyUomId") != null && currencyUomId != null && !invoice.getString("currencyUomId").equals(currencyUomId)) {
+                        errorMessageList.add(UtilProperties.getMessage(resource,"AccountingInvoicePaymentCurrencyProblem",UtilMisc.toMap("paymentCurrencyId", currencyUomId,"itemCurrency",invoice.getString("currencyUomId")) ,locale));
                     }
                     
                     // get the invoice item applied value
@@ -2597,6 +2585,24 @@
             }
         }
 
+        // check this at the end because the invoice can change the currency.......
+        if (paymentApplicationId == null) {
+            // only check for new application records, update on existing records is checked in the paymentApplication section
+            if (paymentApplyAvailable.signum() == 0) {
+                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentAlreadyApplied",UtilMisc.toMap("paymentId",paymentId), locale));
+            } else {
+                // check here for too much application if a new record is
+                // added (paymentApplicationId == null)
+                if (amountApplied.compareTo(paymentApplyAvailable) > 0) {
+                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentLessRequested",
+                            UtilMisc.<String, Object>toMap("paymentId",paymentId,
+                                        "paymentApplyAvailable",paymentApplyAvailable,
+                                        "amountApplied",amountApplied,"isoCode", currencyUomId),locale));
+                }
+            }
+        }
+
+
         // get the application record if the applicationId is supplied if not
         // create empty record.
         BigDecimal newInvoiceApplyAvailable = invoiceApplyAvailable;
@@ -2647,7 +2653,11 @@
 
                 // check if the payment for too much application if an existing
                 // application record is changed
-                newPaymentApplyAvailable = paymentApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(decimals, rounding);
+ if (paymentApplyAvailable.compareTo(ZERO) == 0) {
+ newPaymentApplyAvailable = paymentApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(decimals, rounding);
+ } else {
+ newPaymentApplyAvailable = paymentApplyAvailable.add(paymentApplyAvailable).subtract(amountApplied).setScale(decimals, rounding);
+ }
                 if (newPaymentApplyAvailable.compareTo(ZERO) < 0) {
                     errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentNotEnough", UtilMisc.<String, Object>toMap("paymentId",paymentId,"paymentApplyAvailable",paymentApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")),"amountApplied",amountApplied),locale));
                 }
@@ -2769,9 +2779,8 @@
         if (amountApplied.signum() == 0) {
             errorMessageList.add(UtilProperties.getMessage(resource, "AccountingNoAmount",locale));
         } else {
-            successMessage = UtilProperties.getMessage(resource, "AccountingApplicationSuccess",UtilMisc.<String, Object>toMap("amountApplied",amountApplied,"paymentId",paymentId,"isoCode", payment.getString("currencyUomId"),"toMessage",toMessage),locale);
+            successMessage = UtilProperties.getMessage(resource, "AccountingApplicationSuccess",UtilMisc.<String, Object>toMap("amountApplied",amountApplied,"paymentId",paymentId,"isoCode", currencyUomId, "toMessage", toMessage),locale);
         }
-        
         // report error messages if any
         if (errorMessageList.size() > 0) {
             return ServiceUtil.returnError(errorMessageList);
@@ -2878,8 +2887,8 @@
 
                         // create application payment record but check currency
                         // first if supplied
-                        if (invoice.get("currencyUomId") != null && payment.get("currencyUomId") != null && !invoice.getString("currencyUomId").equals( payment.getString("currencyUomId"))) {
-                            errorMessageList.add("Payment currency (" + payment.getString("currencyUomId") + ") and invoice currency(" + invoice.getString("currencyUomId") + ") not the same\n");
+                        if (invoice.get("currencyUomId") != null && currencyUomId != null && !invoice.getString("currencyUomId").equals(currencyUomId)) {
+                            errorMessageList.add("Payment currency (" + currencyUomId + ") and invoice currency(" + invoice.getString("currencyUomId") + ") not the same\n");
                         } else {
                             paymentApplication.set("paymentApplicationId", null);
                             // make sure we get a new record

Modified: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/payment/PaymentWorker.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/payment/PaymentWorker.java?rev=701313&r1=701312&r2=701313&view=diff
==============================================================================
--- ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/payment/PaymentWorker.java (original)
+++ ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/payment/PaymentWorker.java Fri Oct  3 00:12:35 2008
@@ -42,8 +42,6 @@
 import org.ofbiz.entity.util.EntityUtil;
 import org.ofbiz.entity.condition.EntityCondition;
 import org.ofbiz.entity.condition.EntityOperator;
-import org.ofbiz.entity.condition.EntityExpr;
-import org.ofbiz.entity.condition.EntityConditionList;
 
 
 /**

Modified: ofbiz/trunk/applications/accounting/webapp/accounting/WEB-INF/actions/invoice/EditInvoice.groovy
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/webapp/accounting/WEB-INF/actions/invoice/EditInvoice.groovy?rev=701313&r1=701312&r2=701313&view=diff
==============================================================================
--- ofbiz/trunk/applications/accounting/webapp/accounting/WEB-INF/actions/invoice/EditInvoice.groovy (original)
+++ ofbiz/trunk/applications/accounting/webapp/accounting/WEB-INF/actions/invoice/EditInvoice.groovy Fri Oct  3 00:12:35 2008
@@ -25,6 +25,7 @@
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.math.BigDecimal;
+import java.math.MathContext;
 import org.ofbiz.base.util.UtilNumber;
 import javolution.util.FastList;
 
@@ -34,32 +35,52 @@
 invoice = delegator.findByPrimaryKey("Invoice", [invoiceId : invoiceId]);
 context.invoice = invoice;
 
-other = parameters.other; // allow the display of the invoice in the currency of the other party. sales: partyId, purch: partyIdFrom using the convertUom service.
-conversionRate = BigDecimal.ONE;
+other = parameters.other;        // allow the display of the invoice in the currency of the other party. sales: partyId, purch: partyIdFrom using the convertUom service.
+conversionRate = null;
 ZERO = BigDecimal.ZERO;
 decimals = UtilNumber.getBigDecimalScale("invoice.decimals");
 rounding = UtilNumber.getBigDecimalRoundingMode("invoice.rounding");
 if ("Y".equalsIgnoreCase(other)) {
-  if ((invoice.getRelatedOne("InvoiceType")).parentTypeId.equals("SALES_INVOICE")) {
-    otherCurrency = invoice.getRelatedOne("Party").preferredCurrencyUomId;
-  } else {
-    otherCurrency = invoice.getRelatedOne("FromParty").preferredCurrencyUomId;
-  }
-  result = null;
-  if (otherCurrency && invoice.currencyUomId && !otherCurrency.equals(invoice.currencyUomId)) {
-    result = dispatcher.runSync("convertUom", [uomId : invoice.currencyUomId,
+    if (invoice.currencyUomId.equals(invoice.getRelatedOne("Party").preferredCurrencyUomId)) {
+        otherCurrency = invoice.getRelatedOne("FromParty").preferredCurrencyUomId;
+    } else {
+        otherCurrency = invoice.getRelatedOne("Party").preferredCurrencyUomId;
+    }
+    result = null;
+    if (otherCurrency && invoice.currencyUomId && !otherCurrency.equals(invoice.currencyUomId)) {
+        invoice.currencyUomId = otherCurrency;
+        // check if the transaction is created, take the conversion from there
+        acctgTransEntries = invoice.getRelated("AcctgTrans");
+        if (acctgTransEntries) {
+            acctgTransEntry = acctgTransEntries[0].getRelated("AcctgTransEntry")[0];
+            conversionRate = acctgTransEntry.getBigDecimal("amount").divided(acctgTransEntry.getBigDecimal("origAmount"), new MathContext(100));
+        }
+        // check if a payment is applied and use the currency conversion from there
+        if (!conversionRate) {
+            paymentAppls = invoice.getRelated("PaymentApplication");
+            paymentAppls.each { paymentAppl ->
+                payment = paymentAppl.getRelatedOne("Payment");
+                if (!conversionRate) {
+                    conversionRate = payment.getBigDecimal("amount").divide(payment.getBigDecimal("actualCurrencyAmount"),new MathContext(100));
+                } else {
+                    conversionRate = conversionRate.add(payment.getBigDecimal("amount").divide(payment.getBigDecimal("actualCurrencyAmount"),new MathContext(100))).divide(new BigDecimal("2"),new MathContext(100));
+                }
+            }
+        }
+        if (!conversionRate) {
+            result = dispatcher.runSync("convertUom", [uomId : invoice.currencyUomId,
                                                uomIdTo : otherCurrency,
                                                originalValue : new Double("1.00"),
                                                asOfDate : invoice.invoiceDate]);
     
-    if (result.convertedValue != null) {
-      conversionRate = new BigDecimal(result.convertedValue.doubleValue());
-      invoice.invoiceMessage = invoice.get("invoiceMessage") ?
+            if (result.convertedValue != null) {
+                conversionRate = new BigDecimal(result.convertedValue.doubleValue());
+                invoice.invoiceMessage = invoice.get("invoiceMessage") ?
                           invoice.invoiceMessage.concat(" Converted from " + invoice.currencyUomId + " Rate: " + conversionRate.setScale(6, rounding).toString()) :
                           "Converted from " + invoice.currencyUomId + " Rate: " + conversionRate.setScale(6, rounding).toString();
-      invoice.currencyUomId = otherCurrency;
-    }
-  }
+            }
+        }
+    }
 }
 
 if (invoice) {