[ChangePassword] Merge with pi
authorJonathan Bueno <jonathan.bueno@openbravo.com>
Mon, 15 Feb 2016 12:28:37 +0100
changeset 28675 1cf700dfd92e
parent 28674 5970284b4e82 (current diff)
parent 28601 5543dcdb0d5f (diff)
child 28676 0d920474c5da
[ChangePassword] Merge with pi
lib/runtime/fop.jar
src-db/database/sourcedata/AD_COLUMN.xml
--- a/legal/Licensing.txt	Mon Feb 15 12:11:46 2016 +0100
+++ b/legal/Licensing.txt	Mon Feb 15 12:28:37 2016 +0100
@@ -111,7 +111,7 @@
 # commons-lang-2.6.jar
 # commons-logging-1.1.1.jar
 # commons-pool-1.5.6.jar
-# fop.jar
+# fop-1.1.jar
 # jakarta-oro-2.0.8.jar
 # jettison-1.3.jar
 # log4j-1.2.16.jar
Binary file lib/runtime/fop-1.1.jar has changed
Binary file lib/runtime/fop.jar has changed
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_GEN_PAYMENTSCHEDULE_INV.xml	Mon Feb 15 12:11:46 2016 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_GEN_PAYMENTSCHEDULE_INV.xml	Mon Feb 15 12:28:37 2016 +0100
@@ -1070,6 +1070,20 @@
       IF (v_count <> 0) THEN
         RAISE_APPLICATION_ERROR(-20000, '@APRM_InvoiceWithPayments@' || ' ' || v_documentno);
       END IF;
+
+      SELECT count(*)
+      INTO v_count
+      FROM DUAL
+      WHERE EXISTS (SELECT 1
+                    FROM C_InvoiceTax_CashVAT itcv
+                    INNER JOIN C_InvoiceTax it on (it.C_InvoiceTax_ID = itcv.C_InvoiceTax_ID)
+                    WHERE it.C_Invoice_ID = p_record_id
+                    AND itcv.IsManualSettlement = 'Y'
+                    );
+      IF (v_count > 0) THEN
+        RAISE_APPLICATION_ERROR(-20000, '@APRM_InvoiceWithManualCashVATSettlement@');
+      END IF;
+
       SELECT count(*), max(p.documentno)
         INTO v_count, v_documentno
       FROM fin_payment_schedule ps, fin_payment_scheduledetail psd, fin_payment_prop_detail pd, fin_payment_proposal p
@@ -1121,6 +1135,20 @@
       UPDATE C_BPARTNER
          SET SO_CREDITUSED = COALESCE(SO_CREDITUSED,0) - v_convertedAmount
       WHERE C_BPARTNER_ID = v_BPartner_ID;
+
+      -- Delete C_InvoiceTax_CashVAT records for this invoice
+      --  this only happens for prepayments, which are bypassed by the previous check
+      DELETE FROM C_InvoiceTax_CashVAT itcv
+      WHERE EXISTS (SELECT 1
+                    FROM C_InvoiceTax it
+                    WHERE it.C_InvoiceTax_ID = itcv.C_InvoiceTax_ID
+                    AND it.C_Invoice_ID = p_record_id
+                    )
+      AND EXISTS (SELECT 1
+                  FROM FIN_Payment_Detail fpd
+                  WHERE fpd.FIN_Payment_Detail_ID = itcv.FIN_Payment_Detail_ID
+                  AND fpd.IsPrepayment = 'Y')
+      AND itcv.IsManualSettlement = 'N';
     END;
 
   ELSIF (p_docaction = 'RC') THEN
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_COLUMN.xml	Mon Feb 15 12:11:46 2016 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_COLUMN.xml	Mon Feb 15 12:28:37 2016 +0100
@@ -287,8 +287,8 @@
 <!--07DD87B8F3BE41C18546260D616E1404-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--07DD87B8F3BE41C18546260D616E1404-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--07DD87B8F3BE41C18546260D616E1404-->  <SQLLOGIC><![CDATA[(SELECT count(*) FROM fin_bankstatementline bl, fin_bankstatement b, fin_reconciliation r WHERE (bl.fin_finacc_transaction_id IS NULL OR (EXISTS ( SELECT 1 FROM fin_finacc_transaction t, fin_reconciliation rec WHERE t.fin_reconciliation_id  = rec.fin_reconciliation_id AND bl.fin_finacc_transaction_id  = t.fin_finacc_transaction_id  AND t.fin_financial_account_id  = b.fin_financial_account_id  AND rec.created > r.created))) AND bl.datetrx <= r.dateto AND b.fin_bankstatement_id  = bl.fin_bankstatement_id AND b.fin_financial_account_id  = r.fin_financial_account_id and r.fin_reconciliation_id = fin_reconciliation_id)]]></SQLLOGIC>
-<!--07DD87B8F3BE41C18546260D616E1404-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--07DD87B8F3BE41C18546260D616E1404-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--07DD87B8F3BE41C18546260D616E1404-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--07DD87B8F3BE41C18546260D616E1404-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--07DD87B8F3BE41C18546260D616E1404--></AD_COLUMN>
 
 <!--09A1C598D8134CAC92CB30E476A213B0--><AD_COLUMN>
@@ -2272,8 +2272,8 @@
 <!--3FE18B378FA24031A2E24B058414729F-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--3FE18B378FA24031A2E24B058414729F-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--3FE18B378FA24031A2E24B058414729F-->  <SQLLOGIC><![CDATA[(SELECT COALESCE(sum(t.depositamt), 0) FROM fin_finacc_transaction t,  fin_reconciliation rec WHERE (t.fin_reconciliation_id IS NULL OR (EXISTS ( SELECT 1 FROM fin_reconciliation r WHERE r.dateto > rec.dateto AND t.fin_reconciliation_id  = r.fin_reconciliation_id ))) AND t.statementdate <= rec.dateto AND t.depositamt <> 0 AND t.fin_financial_account_id  = rec.fin_financial_account_id AND rec.fin_reconciliation_id = fin_reconciliation_id)]]></SQLLOGIC>
-<!--3FE18B378FA24031A2E24B058414729F-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--3FE18B378FA24031A2E24B058414729F-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--3FE18B378FA24031A2E24B058414729F-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--3FE18B378FA24031A2E24B058414729F-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--3FE18B378FA24031A2E24B058414729F--></AD_COLUMN>
 
 <!--40405759C1E1456E99B537D36A06F987--><AD_COLUMN>
@@ -3090,8 +3090,8 @@
 <!--590088D9DDB34C1FB99E97CF50022B62-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--590088D9DDB34C1FB99E97CF50022B62-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--590088D9DDB34C1FB99E97CF50022B62-->  <SQLLOGIC><![CDATA[( SELECT count(*) FROM fin_finacc_transaction WHERE fin_finacc_transaction.fin_reconciliation_id = fin_reconciliation_id)]]></SQLLOGIC>
-<!--590088D9DDB34C1FB99E97CF50022B62-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--590088D9DDB34C1FB99E97CF50022B62-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--590088D9DDB34C1FB99E97CF50022B62-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--590088D9DDB34C1FB99E97CF50022B62-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--590088D9DDB34C1FB99E97CF50022B62--></AD_COLUMN>
 
 <!--5961F18CC4934FCCA8AB18B2B3AFC960--><AD_COLUMN>
@@ -4208,8 +4208,8 @@
 <!--7791426B8C214F0EB68C13D99A577229-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--7791426B8C214F0EB68C13D99A577229-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--7791426B8C214F0EB68C13D99A577229-->  <SQLLOGIC><![CDATA[(SELECT COALESCE(sum(fin_finacc_transaction.depositamt - fin_finacc_transaction.paymentamt), 0) FROM fin_finacc_transaction WHERE fin_finacc_transaction.fin_reconciliation_id = fin_reconciliation_id)]]></SQLLOGIC>
-<!--7791426B8C214F0EB68C13D99A577229-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--7791426B8C214F0EB68C13D99A577229-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--7791426B8C214F0EB68C13D99A577229-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--7791426B8C214F0EB68C13D99A577229-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--7791426B8C214F0EB68C13D99A577229--></AD_COLUMN>
 
 <!--78A3367822B35459E040007F01012510--><AD_COLUMN>
@@ -4612,8 +4612,8 @@
 <!--81822D492C88480C8830E5059387A771-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--81822D492C88480C8830E5059387A771-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--81822D492C88480C8830E5059387A771-->  <SQLLOGIC><![CDATA[(SELECT count(*) FROM fin_finacc_transaction t,  fin_reconciliation rec WHERE (t.fin_reconciliation_id IS NULL OR (EXISTS ( SELECT 1 FROM fin_reconciliation r WHERE r.dateto > rec.dateto AND t.fin_reconciliation_id  = r.fin_reconciliation_id ))) AND t.statementdate <= rec.dateto AND t.depositamt <> 0 AND t.fin_financial_account_id  = rec.fin_financial_account_id AND rec.fin_reconciliation_id = fin_reconciliation_id) ]]></SQLLOGIC>
-<!--81822D492C88480C8830E5059387A771-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--81822D492C88480C8830E5059387A771-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--81822D492C88480C8830E5059387A771-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--81822D492C88480C8830E5059387A771-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--81822D492C88480C8830E5059387A771--></AD_COLUMN>
 
 <!--82EFB8E4043C19C9E040007F01003778--><AD_COLUMN>
@@ -6792,8 +6792,8 @@
 <!--91BC2133F04647938F702192A5156C25-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--91BC2133F04647938F702192A5156C25-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--91BC2133F04647938F702192A5156C25-->  <SQLLOGIC><![CDATA[(SELECT count(*) FROM fin_finacc_transaction t,  fin_reconciliation rec WHERE (t.fin_reconciliation_id IS NULL OR (EXISTS ( SELECT 1 FROM fin_reconciliation r WHERE r.dateto > rec.dateto AND t.fin_reconciliation_id  = r.fin_reconciliation_id ))) AND t.statementdate <= rec.dateto AND t.paymentamt <> 0 AND t.fin_financial_account_id  = rec.fin_financial_account_id AND rec.fin_reconciliation_id = fin_reconciliation_id) ]]></SQLLOGIC>
-<!--91BC2133F04647938F702192A5156C25-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--91BC2133F04647938F702192A5156C25-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--91BC2133F04647938F702192A5156C25-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--91BC2133F04647938F702192A5156C25-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--91BC2133F04647938F702192A5156C25--></AD_COLUMN>
 
 <!--923F5B228E5F4D2D96C00C206D47BC63--><AD_COLUMN>
@@ -10230,8 +10230,8 @@
 <!--BBE47252ECEF4B5BA7116E0E23CA5D8D-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--BBE47252ECEF4B5BA7116E0E23CA5D8D-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--BBE47252ECEF4B5BA7116E0E23CA5D8D-->  <SQLLOGIC><![CDATA[(SELECT COALESCE(sum(t.paymentamt), 0) FROM fin_finacc_transaction t,  fin_reconciliation rec WHERE (t.fin_reconciliation_id IS NULL OR (EXISTS ( SELECT 1 FROM fin_reconciliation r WHERE r.dateto > rec.dateto AND t.fin_reconciliation_id  = r.fin_reconciliation_id ))) AND t.statementdate <= rec.dateto AND t.paymentamt <> 0 AND t.fin_financial_account_id  = rec.fin_financial_account_id AND rec.fin_reconciliation_id = fin_reconciliation_id)]]></SQLLOGIC>
-<!--BBE47252ECEF4B5BA7116E0E23CA5D8D-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--BBE47252ECEF4B5BA7116E0E23CA5D8D-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--BBE47252ECEF4B5BA7116E0E23CA5D8D-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--BBE47252ECEF4B5BA7116E0E23CA5D8D-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--BBE47252ECEF4B5BA7116E0E23CA5D8D--></AD_COLUMN>
 
 <!--BC78354AB2F7403FA9725CDF267C0A70--><AD_COLUMN>
@@ -10674,8 +10674,8 @@
 <!--C72EC790B2EF4BEEA2A843D30770B85D-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--C72EC790B2EF4BEEA2A843D30770B85D-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--C72EC790B2EF4BEEA2A843D30770B85D-->  <SQLLOGIC><![CDATA[(SELECT COALESCE(sum(bl.cramount - bl.dramount), 0) FROM fin_bankstatementline bl, fin_bankstatement b, fin_reconciliation r WHERE (bl.fin_finacc_transaction_id IS NULL OR (EXISTS ( SELECT 1 FROM fin_finacc_transaction t, fin_reconciliation rec WHERE t.fin_reconciliation_id  = rec.fin_reconciliation_id AND bl.fin_finacc_transaction_id  = t.fin_finacc_transaction_id  AND t.fin_financial_account_id  = b.fin_financial_account_id  AND rec.created > r.created))) AND bl.datetrx <= r.dateto AND b.fin_bankstatement_id  = bl.fin_bankstatement_id AND b.fin_financial_account_id  = r.fin_financial_account_id and r.fin_reconciliation_id = fin_reconciliation_id)]]></SQLLOGIC>
-<!--C72EC790B2EF4BEEA2A843D30770B85D-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--C72EC790B2EF4BEEA2A843D30770B85D-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--C72EC790B2EF4BEEA2A843D30770B85D-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--C72EC790B2EF4BEEA2A843D30770B85D-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--C72EC790B2EF4BEEA2A843D30770B85D--></AD_COLUMN>
 
 <!--C9FD369BECE545828033CC49CAB85D9D--><AD_COLUMN>
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_MESSAGE.xml	Mon Feb 15 12:11:46 2016 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_MESSAGE.xml	Mon Feb 15 12:28:37 2016 +0100
@@ -1309,6 +1309,18 @@
 <!--D0F129E2F69F4D199DAE68813D2327A2-->  <ISINCLUDEINI18N><![CDATA[N]]></ISINCLUDEINI18N>
 <!--D0F129E2F69F4D199DAE68813D2327A2--></AD_MESSAGE>
 
+<!--D1CF6692476E409DBACAC1809BBC1788--><AD_MESSAGE>
+<!--D1CF6692476E409DBACAC1809BBC1788-->  <AD_MESSAGE_ID><![CDATA[D1CF6692476E409DBACAC1809BBC1788]]></AD_MESSAGE_ID>
+<!--D1CF6692476E409DBACAC1809BBC1788-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--D1CF6692476E409DBACAC1809BBC1788-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--D1CF6692476E409DBACAC1809BBC1788-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--D1CF6692476E409DBACAC1809BBC1788-->  <VALUE><![CDATA[APRM_InvoiceWithManualCashVATSettlement]]></VALUE>
+<!--D1CF6692476E409DBACAC1809BBC1788-->  <MSGTEXT><![CDATA[The invoice is already included into a Manual Cash VAT Settlement]]></MSGTEXT>
+<!--D1CF6692476E409DBACAC1809BBC1788-->  <MSGTYPE><![CDATA[E]]></MSGTYPE>
+<!--D1CF6692476E409DBACAC1809BBC1788-->  <AD_MODULE_ID><![CDATA[A918E3331C404B889D69AA9BFAFB23AC]]></AD_MODULE_ID>
+<!--D1CF6692476E409DBACAC1809BBC1788-->  <ISINCLUDEINI18N><![CDATA[N]]></ISINCLUDEINI18N>
+<!--D1CF6692476E409DBACAC1809BBC1788--></AD_MESSAGE>
+
 <!--D2585EEAC94945C7B3CF79C209FD7650--><AD_MESSAGE>
 <!--D2585EEAC94945C7B3CF79C209FD7650-->  <AD_MESSAGE_ID><![CDATA[D2585EEAC94945C7B3CF79C209FD7650]]></AD_MESSAGE_ID>
 <!--D2585EEAC94945C7B3CF79C209FD7650-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/form/formitem/ob-formitem-number.js	Mon Feb 15 12:11:46 2016 +0100
+++ b/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/form/formitem/ob-formitem-number.js	Mon Feb 15 12:28:37 2016 +0100
@@ -41,11 +41,8 @@
     return this.Super('init', arguments);
   },
 
-  // after a change also store the textual value in the form
-  // for precision, the textual value is sent to the server
-  // which can be transferred to a bigdecimal there
   changed: function (form, item, value) {
-    if (item && item.setValue) {
+    if (this.form.className === 'OBViewForm' && item && item.setValue) {
       item.setValue(this.getEnteredValue());
     }
     this.Super('changed', arguments);
--- a/src-core/.classpath	Mon Feb 15 12:11:46 2016 +0100
+++ b/src-core/.classpath	Mon Feb 15 12:28:37 2016 +0100
@@ -4,7 +4,7 @@
 	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
 	<classpathentry kind="lib" path="/openbravo/lib/runtime/commons-dbcp-1.4.jar"/>
 	<classpathentry kind="lib" path="/openbravo/lib/runtime/commons-pool-1.5.6.jar"/>
-	<classpathentry kind="lib" path="/openbravo/lib/runtime/fop.jar"/>
+	<classpathentry kind="lib" path="/openbravo/lib/runtime/fop-1.1.jar"/>
 	<classpathentry kind="lib" path="/openbravo/lib/runtime/renderFoRmi.jar"/>
 	<classpathentry kind="lib" path="/openbravo/lib/runtime/avalon-framework-4.1.5.jar"/>
 	<classpathentry kind="lib" path="/openbravo/lib/runtime/commons-fileupload-1.2.2.jar"/>
--- a/src-db/database/model/functions/M_INOUT_POST.xml	Mon Feb 15 12:11:46 2016 +0100
+++ b/src-db/database/model/functions/M_INOUT_POST.xml	Mon Feb 15 12:28:37 2016 +0100
@@ -102,6 +102,7 @@
     v_isSoTrx CHAR(1);
     v_ProductName M_Product.name%TYPE;
     v_reservation_id    VARCHAR2(32);
+    v_reservationstock_id    VARCHAR2(32);
     v_M_Warehouse_ID    VARCHAR2(32);
     v_voidmovementdate M_Inout.MovementDate%TYPE;
     v_voiddate_acct M_Inout.DateAcct%TYPE;
@@ -119,8 +120,11 @@
     v_IsQtyVariable M_Product.IsQuantityVariable%TYPE;
     v_IsReversedDoc CHAR(1);
 
-    v_uuid VARCHAR2(32);
-    v_qtyordered NUMBER;
+    v_countRS NUMBER:=0;
+    v_R_Quantity NUMBER;
+    v_R_Reservedqty NUMBER;
+    v_RS_Quantity NUMBER;
+    v_RS_Releasedqty NUMBER;
 
   BEGIN
   
@@ -557,38 +561,15 @@
                   M_RESERVATION_CONSUMPTION(v_reservation_id, cur_inoutline.m_locator_id, cur_inoutline.m_attributesetinstance_id, cur_inoutline.movementqty, v_user, v_result, v_message);
                 END IF;
               ELSIF (cur_inout.issotrx = 'Y' AND cur_inoutline.c_orderline_id IS NOT NULL AND v_qty > 0 AND cur_inoutline.canceled_inoutline_id IS NOT NULL) THEN
-                -- Undo reservation
-                DECLARE
-                  cur_released_stock RECORD;
-                  v_qtyaux NUMBER;
-                  v_undoqty NUMBER;
-                BEGIN
-                  SELECT count(*), max(m_reservation_id)
-                    INTO v_aux, v_reservation_id
-                  FROM m_reservation
-                  WHERE c_orderline_id = cur_inoutline.c_orderline_id
-                  AND res_status NOT IN ('DR', 'CL');
-                  IF (v_aux > 1) THEN
-                    RAISE_APPLICATION_ERROR(-20000, '@SOLineWithMoreThanOneOpenReservation@');
-                  ELSIF (v_aux = 1) THEN
-                    v_qtyaux := v_qty;
-                    FOR cur_released_stock IN (
-                        SELECT m_reservation_stock_id, quantity, releasedqty
-                        FROM m_reservation_stock
-                        WHERE m_locator_id = cur_inoutline.m_locator_id
-                          AND COALESCE(m_attributesetinstance_id, '0') = COALESCE(cur_inoutline.m_attributesetinstance_id, '0')
-                          AND m_reservation_id = v_reservation_id
-                          AND COALESCE(releasedqty, 0) > 0
-                        ORDER BY CASE isallocated WHEN 'N' THEN 0 ELSE 1 END
-                    ) LOOP
-                      v_undoqty := LEAST(v_qtyaux, cur_released_stock.releasedqty);
-                      UPDATE m_reservation_stock
-                      SET releasedqty = releasedqty - v_undoqty
-                      WHERE m_reservation_stock_id = cur_released_stock.m_reservation_stock_id;
-                      v_qtyaux := v_qtyaux - v_undoqty;
-                    END LOOP;
-                  END IF;
-                END;
+                -- Undo reservation is done when voiding shipment
+                SELECT count(*), max(m_reservation_id)
+                INTO v_aux, v_reservation_id
+                FROM m_reservation
+                WHERE c_orderline_id = cur_inoutline.c_orderline_id
+                AND res_status NOT IN ('DR', 'CL');
+                IF (v_aux > 1) THEN
+                  RAISE_APPLICATION_ERROR(-20000, '@SOLineWithMoreThanOneOpenReservation@');
+                END IF;
               ELSIF (cur_inout.issotrx = 'N' AND cur_inoutline.canceled_inoutline_id IS NULL) THEN
                 -- Manage pre-reserves
                 DECLARE
@@ -1168,62 +1149,8 @@
               Updated=now(),
               UpdatedBy=v_User
             WHERE M_INOUTLINE.M_INOUTLINE_ID=Cur_InOutLine.M_INOUTLINE_ID;
+          END LOOP;
 
-	    -- Create new reservation to replace the closed related one
-	    FOR Cur_Reservation IN
-              (SELECT *
-              FROM M_RESERVATION
-              WHERE M_RESERVATION.C_OrderLine_ID=Cur_InOutLine.C_OrderLine_ID
-              AND IsActive='Y')
-	    LOOP
-	      IF (Cur_Reservation.Res_Status = 'CL') THEN
-
-		v_uuid := get_uuid();
-
-		-- Get the ordered quantity from the order line
-	        SELECT qtyordered
-	        INTO v_qtyordered
-	        FROM C_ORDERLINE
-	        WHERE C_OrderLine_ID=Cur_Reservation.C_OrderLine_ID;
-
-	        -- Create a new reservation with the ordered quantity
-	        INSERT INTO M_RESERVATION (
-		  m_reservation_id, ad_client_id, ad_org_id, isactive,
-		  created, createdby, updated, updatedby,
-		  m_product_id, quantity, c_uom_id, c_orderline_id,
-		  ad_user_id, c_bpartner_id, m_warehouse_id, m_attributesetinstance_id, m_locator_id,
-		  res_status, res_process, managereservation_pe, reservedgoodmnt_pe
-	        ) VALUES (
-		  v_uuid, Cur_Reservation.ad_client_id, Cur_Reservation.ad_org_id, 'Y',
-		  now(), v_user, now(), v_user,
-		  Cur_Reservation.m_product_id, v_qtyordered, Cur_Reservation.c_uom_id, Cur_Reservation.c_orderline_id,
-		  Cur_Reservation.ad_user_id, Cur_Reservation.c_bpartner_id, Cur_Reservation.m_warehouse_id,
-		  Cur_Reservation.m_attributesetinstance_id, Cur_Reservation.m_locator_id, 'DR', 'PR',
-		  Cur_Reservation.managereservation_pe, Cur_Reservation.reservedgoodmnt_pe
-	        );
-
-		-- Add a reservation stock with the ordered quantity
-		INSERT INTO M_RESERVATION_STOCK (
-		  m_reservation_stock_id, ad_client_id, ad_org_id, isactive,
-   	          created, createdby, updated, updatedby,
-		  m_reservation_id, c_orderline_id, quantity, isallocated,
-		  m_locator_id, m_attributesetinstance_id )
-		SELECT get_uuid(), ad_client_id, ad_org_id, 'Y',
-		  now(), v_user, now(), v_user,
-		  v_uuid, c_orderline_id, v_qtyordered, isallocated,
-		  m_locator_id, m_attributesetinstance_id
-		FROM M_RESERVATION_STOCK
-		WHERE M_RESERVATION_STOCK.M_Reservation_ID=Cur_Reservation.M_Reservation_ID
-		AND IsActive='Y';
-
-	        -- Process the reservation
-	        M_RESERVATION_POST(null, v_uuid, 'PR', v_user);
-
-	      END IF;
-	    END LOOP;
-
-          END LOOP;
-          
           -- Post Reversal
           v_ResultStr:='PostReversal';
           -- Update reversal goods dates
@@ -1234,6 +1161,144 @@
             UPDATE M_INOUT SET DateAcct = v_voiddate_acct WHERE M_INOUT_ID = v_RInOut_ID;
           END IF;
           M_INOUT_POST(NULL, v_RInOut_ID) ;
+
+          -- Undo reservation by updating completed existing one or
+          -- by creating new reservation to replace closed existing one
+          IF (Cur_InOut.issotrx = 'Y') THEN
+            FOR Cur_Reservation IN (
+              SELECT r.m_reservation_id, r.ad_client_id, r.ad_org_id,
+              r.m_product_id, r.quantity, r.c_uom_id, r.c_orderline_id, r.ad_user_id,
+              r.c_bpartner_id, r.m_warehouse_id, r.m_attributesetinstance_id, r.m_locator_id,
+              r.reservedqty, r.res_status, r.managereservation_pe, r.reservedgoodmnt_pe,
+              ol.qtyordered, sum(iol.movementqty) as movementqty
+              FROM M_RESERVATION r
+              JOIN C_ORDERLINE ol
+              ON r.c_orderline_id = ol.c_orderline_id
+              JOIN M_INOUTLINE iol
+              ON ol.c_orderline_id = iol.c_orderline_id
+              AND ol.m_product_id = iol.m_product_id
+              WHERE iol.m_inout_id = Cur_InOut.m_inout_id
+              AND r.res_status <> 'DR'
+              AND iol.movementqty > 0
+              AND iol.canceled_inoutline_id IS NULL
+              AND r.created = (
+                SELECT max(created)
+                FROM M_RESERVATION
+                WHERE c_orderline_id = r.c_orderline_id
+                AND res_status <> 'DR'
+              )
+              GROUP BY r.m_reservation_id, r.ad_client_id, r.ad_org_id,
+              r.m_product_id, r.quantity, r.c_uom_id, r.c_orderline_id, r.ad_user_id,
+              r.c_bpartner_id, r.m_warehouse_id, r.m_attributesetinstance_id, r.m_locator_id,
+              r.reservedqty, r.res_status, r.managereservation_pe, r.reservedgoodmnt_pe, ol.qtyordered
+            )
+            LOOP
+
+              -- Get the least quantity between ordered quantity and movement quantity
+              v_R_Quantity := LEAST(Cur_Reservation.qtyordered, Cur_Reservation.movementqty);
+
+              -- If completed reservation exists already update it,
+              -- otherwise create a new one with this quantity
+              IF (Cur_Reservation.res_status <> 'CL') THEN
+                v_reservation_id := Cur_Reservation.m_reservation_id;
+                v_R_Reservedqty := Cur_Reservation.reservedqty;
+              ELSE
+                v_reservation_id := get_uuid();
+                v_R_Reservedqty := 0;
+                INSERT INTO M_RESERVATION (
+                  m_reservation_id, ad_client_id, ad_org_id, isactive,
+                  created, createdby, updated, updatedby,
+                  m_product_id, quantity, c_uom_id, c_orderline_id,
+                  ad_user_id, c_bpartner_id, m_warehouse_id, m_attributesetinstance_id, m_locator_id,
+                  res_status, res_process, managereservation_pe, reservedgoodmnt_pe
+                ) VALUES (
+                  v_reservation_id, Cur_Reservation.ad_client_id, Cur_Reservation.ad_org_id, 'Y',
+                  now(), v_user, now(), v_user,
+                  Cur_Reservation.m_product_id, Cur_Reservation.qtyordered, Cur_Reservation.c_uom_id, Cur_Reservation.c_orderline_id,
+                  Cur_Reservation.ad_user_id, Cur_Reservation.c_bpartner_id, Cur_Reservation.m_warehouse_id,
+                  Cur_Reservation.m_attributesetinstance_id, Cur_Reservation.m_locator_id,
+                  'DR', 'PR', Cur_Reservation.managereservation_pe, Cur_Reservation.reservedgoodmnt_pe
+                );
+                -- To avoid create a reservation with all available stock,
+                -- process new reservation before creating new stock reservations
+                -- and delete stock reservation created by m_reserve_stock_manual
+                M_RESERVATION_POST(null, v_reservation_id, 'PR', v_user);
+                UPDATE M_RESERVATION_STOCK SET releasedqty = 0 WHERE m_reservation_id = v_reservation_id;
+                DELETE FROM M_RESERVATION_STOCK WHERE m_reservation_id = v_reservation_id;
+              END IF;
+
+              -- Add a reservation stock fo each related inout line
+              FOR Cur_InOutLine IN (
+                SELECT iol.m_locator_id, COALESCE(iol.m_attributesetinstance_id, '0') as m_attributesetinstance_id,
+                sum(iol.movementqty) as movementqty
+                FROM M_INOUTLINE iol
+                WHERE iol.m_inout_id = Cur_InOut.m_inout_id
+                AND iol.c_orderline_id = Cur_Reservation.c_orderline_id
+                AND iol.m_product_id = Cur_Reservation.m_product_id
+                AND iol.movementqty > 0
+                AND iol.canceled_inoutline_id IS NULL
+                GROUP BY iol.m_locator_id, COALESCE(iol.m_attributesetinstance_id, '0')
+              )
+              LOOP
+
+                -- Check if movement quantity is less or equals than ordered quantity,
+                -- if so insert a new reservation stock with movement quantity,
+                -- otherwise insert a new reservation stock with pending ordered quantity
+                IF (Cur_InOutLine.movementqty <= v_R_Quantity) THEN
+                  v_RS_Quantity := Cur_InOutLine.movementqty;
+                ELSE
+                  v_RS_Quantity := v_R_Quantity;
+                END IF;
+                v_R_Quantity := v_R_Quantity - v_RS_Quantity;
+
+                -- If completed reservation stock exists already update it
+                -- by decreasing its releasedqty or by increasing its quantity,
+                -- otherwise create a new one with this quantity
+                SELECT count(*), max(rs.m_reservation_stock_id), max(rs.releasedqty)
+                INTO v_countRS, v_reservationstock_id, v_RS_Releasedqty
+                FROM M_RESERVATION_STOCK rs
+                WHERE rs.m_reservation_id = v_reservation_id
+                AND rs.m_locator_id = Cur_InOutLine.m_locator_id
+                AND COALESCE(rs.m_attributesetinstance_id, '0') = Cur_InOutLine.m_attributesetinstance_id;
+
+                IF (v_countRS > 0) THEN
+                  IF (v_RS_Releasedqty > 0) THEN
+                    v_RS_Releasedqty := LEAST(v_RS_Releasedqty, v_RS_Quantity);
+                    UPDATE M_RESERVATION_STOCK
+                    SET releasedqty = releasedqty - v_RS_Releasedqty
+                    WHERE m_reservation_stock_id = v_reservationstock_id;
+                    v_RS_Quantity := v_RS_Quantity - v_RS_Releasedqty;
+                  END IF;
+                  IF (v_RS_Quantity > 0 AND Cur_Reservation.quantity >= v_R_Reservedqty + v_RS_Quantity) THEN
+                    UPDATE M_RESERVATION_STOCK
+                    SET quantity = quantity + v_RS_Quantity
+                    WHERE m_reservation_stock_id = v_reservationstock_id;
+                    v_R_Reservedqty := v_R_Reservedqty + v_RS_Quantity;
+                  END IF;
+                ELSE
+                  INSERT INTO M_RESERVATION_STOCK (
+                    m_reservation_stock_id, ad_client_id, ad_org_id, isactive,
+                    created, createdby, updated, updatedby,
+                    m_reservation_id, quantity, isallocated,
+                    m_locator_id, m_attributesetinstance_id
+                  ) VALUES (
+                    get_uuid(), Cur_Reservation.ad_client_id, Cur_Reservation.ad_org_id, 'Y',
+                    now(), v_user, now(), v_user,
+                    v_reservation_id, v_RS_Quantity, 'N',
+                    Cur_InOutLine.m_locator_id, Cur_InOutLine.m_attributesetinstance_id
+                  );
+                  v_R_Reservedqty := v_R_Reservedqty + v_RS_Quantity;
+                END IF;
+
+                -- Exit if we have reserved all pending ordered quantity
+                IF (v_R_Quantity <= 0) THEN
+                  EXIT;
+                END IF;
+
+              END LOOP;
+            END LOOP;
+          END IF;
+
           -- Indicate as Reversal Transaction
           v_ResultStr:='IndicateReversal';
           UPDATE M_INOUT
--- a/src-db/database/model/functions/M_RESERVE_STOCK_AUTO.xml	Mon Feb 15 12:11:46 2016 +0100
+++ b/src-db/database/model/functions/M_RESERVE_STOCK_AUTO.xml	Mon Feb 15 12:28:37 2016 +0100
@@ -22,7 +22,7 @@
 * under the License.
 * The Original Code is Openbravo ERP.
 * The Initial Developer of the Original Code is Openbravo SLU
-* All portions are Copyright (C) 2012-2015 Openbravo SLU
+* All portions are Copyright (C) 2012-2016 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -93,6 +93,7 @@
         JOIN m_locator l ON sd.m_locator_id = l.m_locator_id
         JOIN m_warehouse w ON l.m_warehouse_id = w.m_warehouse_id
     WHERE sp.ad_pinstance_id = v_pinstance_id
+    AND sd.m_product_uom_id IS NULL
     ORDER BY sp.priority
   ) LOOP
     v_qty := LEAST(cur_stock.quantity, v_pendingqty);
--- a/src-db/database/model/triggers/M_TRANSACTION_TRG.xml	Mon Feb 15 12:11:46 2016 +0100
+++ b/src-db/database/model/triggers/M_TRANSACTION_TRG.xml	Mon Feb 15 12:28:37 2016 +0100
@@ -18,7 +18,7 @@
 * under the License.
 * The Original Code is Openbravo ERP.
 * The Initial Developer of the Original Code is Openbravo SLU
-* All portions are Copyright (C) 2001-2012 Openbravo SLU
+* All portions are Copyright (C) 2001-2016 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -38,6 +38,7 @@
   v_doIncrease BOOLEAN:= FALSE;
   v_doDecrease BOOLEAN:= FALSE;
   v_stockdiff NUMBER:= 0;
+  v_checkuom NUMBER:= 0;
 BEGIN
     
     IF AD_isTriggerEnabled()='N' THEN RETURN;
@@ -92,7 +93,11 @@
 		IF INSERTING THEN
 			IF(COALESCE(v_UOM_ID, '0') <> COALESCE(:NEW.C_UOM_ID, '0')) THEN
         IF (:new.M_InventoryLine_ID IS NOT NULL) THEN
-	  SELECT line INTO v_DocumentLineNo FROM M_InventoryLine WHERE M_InventoryLine_ID = :new.M_InventoryLine_ID;
+	  SELECT il.line, CASE WHEN i.inventory_type = 'O' OR i.inventory_type = 'C' THEN 1 ELSE 0 END
+	  INTO v_DocumentLineNo, v_checkuom
+	  FROM M_Inventory i JOIN M_InventoryLine il
+	  ON i.m_inventory_id = il.m_inventory_id
+	  WHERE il.m_inventoryline_id = :new.M_InventoryLine_ID;
 	END IF;
 	IF (:new.M_MovementLine_ID IS NOT NULL) THEN
 	  SELECT line INTO v_DocumentLineNo FROM M_MovementLine WHERE M_MovementLine_ID = :new.M_MovementLine_ID;
@@ -106,8 +111,10 @@
 	IF (:new.M_Internal_ConsumptionLine_ID IS NOT NULL) THEN
 	  SELECT line INTO v_DocumentLineNo FROM M_Internal_ConsumptionLine WHERE M_Internal_ConsumptionLine_ID = :new.M_Internal_ConsumptionLine_ID;
 	END IF;
-	  
-	RAISE_APPLICATION_ERROR(-20000, '@DocUOMMismatch@' || ' ' || COALESCE(v_DocumentLineNo, 0));
+
+	IF (v_checkuom = 0) THEN
+	  RAISE_APPLICATION_ERROR(-20000, '@DocUOMMismatch@' || ' ' || COALESCE(v_DocumentLineNo, 0));
+	END IF;
      	END IF;
       IF(v_attributeset_id IS NOT NULL AND (v_AttrSetValueType IS NULL OR v_AttrSetValueType <> 'F') AND v_IsOneAtSetValReq = 'Y' AND COALESCE(:NEW.M_ATTRIBUTESETINSTANCE_ID, '0') = '0') THEN
        	RAISE_APPLICATION_ERROR(-20000, '@20112@' || ' - ' || v_Name) ;
@@ -127,7 +134,29 @@
   END IF;
   
   -- Updating inventory
-  IF UPDATING OR DELETING THEN
+  IF DELETING OR (UPDATING AND (
+    (COALESCE(:OLD.M_TRANSACTION_ID, '0') <> COALESCE(:NEW.M_TRANSACTION_ID, '0')) OR
+    (COALESCE(:OLD.AD_CLIENT_ID, '0') <> COALESCE(:NEW.AD_CLIENT_ID, '0')) OR
+    (COALESCE(:OLD.AD_ORG_ID, '0') <> COALESCE(:NEW.AD_ORG_ID, '0')) OR
+    (COALESCE(:OLD.ISACTIVE, 'Y') <> COALESCE(:NEW.ISACTIVE, 'Y')) OR
+    (COALESCE(:OLD.MOVEMENTTYPE, '.') <> COALESCE(:NEW.MOVEMENTTYPE, '.')) OR
+    (COALESCE(:OLD.M_LOCATOR_ID, '0') <> COALESCE(:NEW.M_LOCATOR_ID, '0')) OR
+    (COALESCE(:OLD.M_PRODUCT_ID, '0') <> COALESCE(:NEW.M_PRODUCT_ID, '0')) OR
+    (COALESCE(:OLD.MOVEMENTDATE, v_DateNull) <> COALESCE(:NEW.MOVEMENTDATE, v_DateNull)) OR
+    (COALESCE(:OLD.MOVEMENTQTY, '0') <> COALESCE(:NEW.MOVEMENTQTY, '0')) OR
+    (COALESCE(:OLD.M_INVENTORYLINE_ID, '0') <> COALESCE(:NEW.M_INVENTORYLINE_ID, '0')) OR
+    (COALESCE(:OLD.M_MOVEMENTLINE_ID, '0') <> COALESCE(:NEW.M_MOVEMENTLINE_ID, '0')) OR
+    (COALESCE(:OLD.M_INOUTLINE_ID, '0') <> COALESCE(:NEW.M_INOUTLINE_ID, '0')) OR
+    (COALESCE(:OLD.M_PRODUCTIONLINE_ID, '0') <> COALESCE(:NEW.M_PRODUCTIONLINE_ID, '0')) OR
+    (COALESCE(:OLD.C_PROJECTISSUE_ID, '0') <> COALESCE(:NEW.C_PROJECTISSUE_ID, '0')) OR
+    (COALESCE(:OLD.M_ATTRIBUTESETINSTANCE_ID, '0') <> COALESCE(:NEW.M_ATTRIBUTESETINSTANCE_ID, '0')) OR
+    (COALESCE(:OLD.M_PRODUCT_UOM_ID, '0') <> COALESCE(:NEW.M_PRODUCT_UOM_ID, '0')) OR
+    (COALESCE(:OLD.QUANTITYORDER, '0') <> COALESCE(:NEW.QUANTITYORDER, '0')) OR
+    (COALESCE(:OLD.C_UOM_ID, '0') <> COALESCE(:NEW.C_UOM_ID, '0')) OR
+    (COALESCE(:OLD.M_INTERNAL_CONSUMPTIONLINE_ID, '0') <> COALESCE(:NEW.M_INTERNAL_CONSUMPTIONLINE_ID, '0')) OR
+    (COALESCE(:OLD.TRXPROCESSDATE, v_DateNull) <> COALESCE(:NEW.TRXPROCESSDATE, v_DateNull)) OR
+    (COALESCE(:OLD.CHECKRESERVEDQTY, 'Y') <> COALESCE(:NEW.CHECKRESERVEDQTY, 'Y'))
+  )) THEN
     M_UPDATE_INVENTORY(:OLD.AD_CLIENT_ID, :OLD.AD_ORG_ID, :OLD.UPDATEDBY, :OLD.M_PRODUCT_ID, :OLD.M_LOCATOR_ID, :OLD.M_ATTRIBUTESETINSTANCE_ID, :OLD.C_UOM_ID, :OLD.M_PRODUCT_UOM_ID, -:OLD.MOVEMENTQTY, -:OLD.QUANTITYORDER, NULL, :OLD.MOVEMENTQTY, :OLD.QUANTITYORDER) ;
     -- FIXME: this shall be removed/reviewed when new warehouse management is implemented
     IF (:OLD.M_PRODUCTIONLINE_ID IS NOT NULL) THEN     
@@ -140,7 +169,29 @@
     END IF;
     -- END FIXME
   END IF;
-  IF INSERTING OR UPDATING THEN
+  IF INSERTING OR (UPDATING AND (
+    (COALESCE(:OLD.M_TRANSACTION_ID, '0') <> COALESCE(:NEW.M_TRANSACTION_ID, '0')) OR
+    (COALESCE(:OLD.AD_CLIENT_ID, '0') <> COALESCE(:NEW.AD_CLIENT_ID, '0')) OR
+    (COALESCE(:OLD.AD_ORG_ID, '0') <> COALESCE(:NEW.AD_ORG_ID, '0')) OR
+    (COALESCE(:OLD.ISACTIVE, 'Y') <> COALESCE(:NEW.ISACTIVE, 'Y')) OR
+    (COALESCE(:OLD.MOVEMENTTYPE, '.') <> COALESCE(:NEW.MOVEMENTTYPE, '.')) OR
+    (COALESCE(:OLD.M_LOCATOR_ID, '0') <> COALESCE(:NEW.M_LOCATOR_ID, '0')) OR
+    (COALESCE(:OLD.M_PRODUCT_ID, '0') <> COALESCE(:NEW.M_PRODUCT_ID, '0')) OR
+    (COALESCE(:OLD.MOVEMENTDATE, v_DateNull) <> COALESCE(:NEW.MOVEMENTDATE, v_DateNull)) OR
+    (COALESCE(:OLD.MOVEMENTQTY, '0') <> COALESCE(:NEW.MOVEMENTQTY, '0')) OR
+    (COALESCE(:OLD.M_INVENTORYLINE_ID, '0') <> COALESCE(:NEW.M_INVENTORYLINE_ID, '0')) OR
+    (COALESCE(:OLD.M_MOVEMENTLINE_ID, '0') <> COALESCE(:NEW.M_MOVEMENTLINE_ID, '0')) OR
+    (COALESCE(:OLD.M_INOUTLINE_ID, '0') <> COALESCE(:NEW.M_INOUTLINE_ID, '0')) OR
+    (COALESCE(:OLD.M_PRODUCTIONLINE_ID, '0') <> COALESCE(:NEW.M_PRODUCTIONLINE_ID, '0')) OR
+    (COALESCE(:OLD.C_PROJECTISSUE_ID, '0') <> COALESCE(:NEW.C_PROJECTISSUE_ID, '0')) OR
+    (COALESCE(:OLD.M_ATTRIBUTESETINSTANCE_ID, '0') <> COALESCE(:NEW.M_ATTRIBUTESETINSTANCE_ID, '0')) OR
+    (COALESCE(:OLD.M_PRODUCT_UOM_ID, '0') <> COALESCE(:NEW.M_PRODUCT_UOM_ID, '0')) OR
+    (COALESCE(:OLD.QUANTITYORDER, '0') <> COALESCE(:NEW.QUANTITYORDER, '0')) OR
+    (COALESCE(:OLD.C_UOM_ID, '0') <> COALESCE(:NEW.C_UOM_ID, '0')) OR
+    (COALESCE(:OLD.M_INTERNAL_CONSUMPTIONLINE_ID, '0') <> COALESCE(:NEW.M_INTERNAL_CONSUMPTIONLINE_ID, '0')) OR
+    (COALESCE(:OLD.TRXPROCESSDATE, v_DateNull) <> COALESCE(:NEW.TRXPROCESSDATE, v_DateNull)) OR
+    (COALESCE(:OLD.CHECKRESERVEDQTY, 'Y') <> COALESCE(:NEW.CHECKRESERVEDQTY, 'Y'))
+  )) THEN
     SELECT MAX(MOVEMENTDATE)
       INTO v_DATEINVENTORY
     FROM M_INVENTORY I,
--- a/src-db/database/sourcedata/AD_COLUMN.xml	Mon Feb 15 12:11:46 2016 +0100
+++ b/src-db/database/sourcedata/AD_COLUMN.xml	Mon Feb 15 12:28:37 2016 +0100
@@ -238428,8 +238428,8 @@
 <!--062D7EC34B074DC4BF2BB6A1E973D171-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--062D7EC34B074DC4BF2BB6A1E973D171-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--062D7EC34B074DC4BF2BB6A1E973D171-->  <SQLLOGIC><![CDATA[(select ps.duedate from FIN_Payment_ScheduleDetail psd, FIN_Payment_Schedule ps where ps.FIN_Payment_Schedule_ID = coalesce(psd.fin_payment_schedule_invoice, psd.fin_payment_schedule_order) and psd.FIN_Payment_ScheduleDetail_ID = fin_payment_scheduledetail_id)]]></SQLLOGIC>
-<!--062D7EC34B074DC4BF2BB6A1E973D171-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--062D7EC34B074DC4BF2BB6A1E973D171-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--062D7EC34B074DC4BF2BB6A1E973D171-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--062D7EC34B074DC4BF2BB6A1E973D171-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--062D7EC34B074DC4BF2BB6A1E973D171--></AD_COLUMN>
 
 <!--0665AD61112844B18C999D519EDB12A0--><AD_COLUMN>
@@ -239766,8 +239766,8 @@
 <!--0C6CC9768B5144EBB4827B9B98976816-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--0C6CC9768B5144EBB4827B9B98976816-->  <SQLLOGIC><![CDATA[(select ff.writeofflimit  from fin_financial_account ff where ff.fin_financial_account_id=fin_financial_account_id)
 ]]></SQLLOGIC>
-<!--0C6CC9768B5144EBB4827B9B98976816-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--0C6CC9768B5144EBB4827B9B98976816-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--0C6CC9768B5144EBB4827B9B98976816-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--0C6CC9768B5144EBB4827B9B98976816-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--0C6CC9768B5144EBB4827B9B98976816--></AD_COLUMN>
 
 <!--0C9CABC3B4CE4F5993D1A08CF5EEF302--><AD_COLUMN>
@@ -241678,8 +241678,8 @@
 <!--13A5B506645546CA8054A88CFD263DF0-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--13A5B506645546CA8054A88CFD263DF0-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--13A5B506645546CA8054A88CFD263DF0-->  <SQLLOGIC><![CDATA[SELECT coalesce(sum(psd.doubtfuldebt_amount),0) FROM fin_payment_scheduledetail psd left join fin_payment_detail pd on psd.fin_payment_detail_id = pd.fin_payment_detail_id left join fin_payment p on pd.fin_payment_id = p.fin_payment_id WHERE psd.fin_payment_schedule_invoice = fin_payment_schedule_id and psd.isinvoicepaid = 'N']]></SQLLOGIC>
-<!--13A5B506645546CA8054A88CFD263DF0-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--13A5B506645546CA8054A88CFD263DF0-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--13A5B506645546CA8054A88CFD263DF0-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--13A5B506645546CA8054A88CFD263DF0-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--13A5B506645546CA8054A88CFD263DF0--></AD_COLUMN>
 
 <!--13AB438B6900462FB3B92343175BFDD2--><AD_COLUMN>
@@ -242508,8 +242508,8 @@
 <!--16AF14EF22134D3FB1D700EA0EE3D16C-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--16AF14EF22134D3FB1D700EA0EE3D16C-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--16AF14EF22134D3FB1D700EA0EE3D16C-->  <SQLLOGIC><![CDATA[(SELECT count(distinct pd.fin_payment_id) FROM fin_payment_detail pd, fin_payment_scheduledetail psd, fin_payment_schedule ps WHERE pd.fin_payment_detail_id = psd.fin_payment_detail_id AND psd.fin_payment_schedule_invoice = ps.fin_payment_schedule_id AND ps.c_invoice_id IS NOT NULL  AND ps.fin_payment_schedule_id = fin_payment_schedule_id)]]></SQLLOGIC>
-<!--16AF14EF22134D3FB1D700EA0EE3D16C-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--16AF14EF22134D3FB1D700EA0EE3D16C-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--16AF14EF22134D3FB1D700EA0EE3D16C-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--16AF14EF22134D3FB1D700EA0EE3D16C-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--16AF14EF22134D3FB1D700EA0EE3D16C--></AD_COLUMN>
 
 <!--16C389B66EE04CE7B2A6A15CC7739A76--><AD_COLUMN>
@@ -249707,8 +249707,8 @@
 <!--2D56F14A0C524D8F95282389F1A45878-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--2D56F14A0C524D8F95282389F1A45878-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--2D56F14A0C524D8F95282389F1A45878-->  <SQLLOGIC><![CDATA[SELECT coalesce(sum(psd.doubtfuldebt_amount),0) FROM fin_payment_scheduledetail psd left join fin_payment_detail pd on psd.fin_payment_detail_id = pd.fin_payment_detail_id left join fin_payment p on pd.fin_payment_id = p.fin_payment_id WHERE psd.fin_payment_schedule_invoice = fin_payment_schedule_id and psd.isinvoicepaid = 'N']]></SQLLOGIC>
-<!--2D56F14A0C524D8F95282389F1A45878-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--2D56F14A0C524D8F95282389F1A45878-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--2D56F14A0C524D8F95282389F1A45878-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--2D56F14A0C524D8F95282389F1A45878-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--2D56F14A0C524D8F95282389F1A45878--></AD_COLUMN>
 
 <!--2D64DA0BA824432DB229752F8B22A487--><AD_COLUMN>
@@ -308150,8 +308150,8 @@
 <!--831F84E0E0904C22B9E00AD729DDECAE-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--831F84E0E0904C22B9E00AD729DDECAE-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--831F84E0E0904C22B9E00AD729DDECAE-->  <SQLLOGIC><![CDATA[(select coalesce(c_invoice.grandtotal, c_order.grandtotal) from FIN_Payment_ScheduleDetail psd, FIN_Payment_Schedule ps left join c_invoice on c_invoice.c_invoice_id = ps.c_invoice_id left join c_order on c_order.c_order_id = ps.c_order_id where ps.FIN_Payment_Schedule_ID = coalesce(psd.fin_payment_schedule_invoice, psd.fin_payment_schedule_order) and psd.FIN_Payment_ScheduleDetail_ID = fin_payment_scheduledetail_id)]]></SQLLOGIC>
-<!--831F84E0E0904C22B9E00AD729DDECAE-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--831F84E0E0904C22B9E00AD729DDECAE-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--831F84E0E0904C22B9E00AD729DDECAE-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--831F84E0E0904C22B9E00AD729DDECAE-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--831F84E0E0904C22B9E00AD729DDECAE--></AD_COLUMN>
 
 <!--833CD522133546A994DFE6AECC8B1F77--><AD_COLUMN>
@@ -309328,8 +309328,8 @@
 <!--8638D66DE4474084BC8F44BEEF3C9F22-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--8638D66DE4474084BC8F44BEEF3C9F22-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--8638D66DE4474084BC8F44BEEF3C9F22-->  <SQLLOGIC><![CDATA[(select ps.amount from FIN_Payment_ScheduleDetail psd, FIN_Payment_Schedule ps where ps.FIN_Payment_Schedule_ID = coalesce(psd.fin_payment_schedule_invoice, psd.fin_payment_schedule_order) and psd.FIN_Payment_ScheduleDetail_ID = fin_payment_scheduledetail_id)]]></SQLLOGIC>
-<!--8638D66DE4474084BC8F44BEEF3C9F22-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--8638D66DE4474084BC8F44BEEF3C9F22-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--8638D66DE4474084BC8F44BEEF3C9F22-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--8638D66DE4474084BC8F44BEEF3C9F22-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--8638D66DE4474084BC8F44BEEF3C9F22--></AD_COLUMN>
 
 <!--86486D2A475A452DB3A739D1FA2F5F4E--><AD_COLUMN>
@@ -313004,8 +313004,8 @@
 <!--87EA9943323E40E38DBCF9863880E8E1-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--87EA9943323E40E38DBCF9863880E8E1-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--87EA9943323E40E38DBCF9863880E8E1-->  <SQLLOGIC><![CDATA[SELECT sum(tc.cost) FROM m_transaction_cost tc WHERE tc.m_transaction_id = m_transaction_id]]></SQLLOGIC>
-<!--87EA9943323E40E38DBCF9863880E8E1-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--87EA9943323E40E38DBCF9863880E8E1-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--87EA9943323E40E38DBCF9863880E8E1-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--87EA9943323E40E38DBCF9863880E8E1-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--87EA9943323E40E38DBCF9863880E8E1--></AD_COLUMN>
 
 <!--87EABF329C5211DD9C0C001D09C4A2FE--><AD_COLUMN>
@@ -322304,8 +322304,8 @@
 <!--9AFE960A44A147ECAADB875D96399AA2-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--9AFE960A44A147ECAADB875D96399AA2-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--9AFE960A44A147ECAADB875D96399AA2-->  <SQLLOGIC><![CDATA[(select C_GETINVOICESTATUSFROMSHIPMENT(m_inout_id) from dual)]]></SQLLOGIC>
-<!--9AFE960A44A147ECAADB875D96399AA2-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--9AFE960A44A147ECAADB875D96399AA2-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--9AFE960A44A147ECAADB875D96399AA2-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--9AFE960A44A147ECAADB875D96399AA2-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--9AFE960A44A147ECAADB875D96399AA2--></AD_COLUMN>
 
 <!--9B52F391EFDF42798A630FE55E6AC709--><AD_COLUMN>
@@ -324314,8 +324314,8 @@
 round(coalesce(sum(abs(ol.qtydelivered)), 0)/sum(abs(ol.qtyordered)) * 100, 0)  end 
  from c_orderline ol where ol.c_order_id=c_order_id and ol.c_order_discount_id is null
  ),0))]]></SQLLOGIC>
-<!--9E82E728716246B393C40D2CDCA0133A-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--9E82E728716246B393C40D2CDCA0133A-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--9E82E728716246B393C40D2CDCA0133A-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--9E82E728716246B393C40D2CDCA0133A-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--9E82E728716246B393C40D2CDCA0133A--></AD_COLUMN>
 
 <!--9E96300C46ED4928E040007F01006BD5--><AD_COLUMN>
@@ -324584,8 +324584,8 @@
  when sum(fps.amount) = 0 then 0
  else round(sum(fps.paidamt)/sum(fps.amount) * 100, 0) end
 from FIN_Payment_Schedule fps where fps.c_order_id=c_order_id),0))]]></SQLLOGIC>
-<!--9F1044EB393B4D60895532DB5D568BEE-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--9F1044EB393B4D60895532DB5D568BEE-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--9F1044EB393B4D60895532DB5D568BEE-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--9F1044EB393B4D60895532DB5D568BEE-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--9F1044EB393B4D60895532DB5D568BEE--></AD_COLUMN>
 
 <!--9F3ADE0CE0734BE2BD059AAEFCF1D51C--><AD_COLUMN>
@@ -326366,8 +326366,8 @@
 <!--A3D348CF2D9346D4BEDF3952226927B5-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--A3D348CF2D9346D4BEDF3952226927B5-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--A3D348CF2D9346D4BEDF3952226927B5-->  <SQLLOGIC><![CDATA[SELECT sum(tc.cost) FROM m_transaction_cost tc WHERE tc.m_transaction_id = m_transaction_id and tc.isunitcost = 'Y']]></SQLLOGIC>
-<!--A3D348CF2D9346D4BEDF3952226927B5-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--A3D348CF2D9346D4BEDF3952226927B5-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--A3D348CF2D9346D4BEDF3952226927B5-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--A3D348CF2D9346D4BEDF3952226927B5-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--A3D348CF2D9346D4BEDF3952226927B5--></AD_COLUMN>
 
 <!--A3E2CADB797A491688CC2FB0DBED5F78--><AD_COLUMN>
@@ -330019,8 +330019,8 @@
 <!--AECA45F025F14E6DBA669E12DDA55D17-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--AECA45F025F14E6DBA669E12DDA55D17-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--AECA45F025F14E6DBA669E12DDA55D17-->  <SQLLOGIC><![CDATA[SELECT max(p.paymentdate) FROM fin_payment p, fin_payment_detail pd, fin_payment_scheduledetail psd, fin_payment_schedule ps WHERE p.fin_payment_id = pd.fin_payment_id AND   pd.fin_payment_detail_id = psd.fin_payment_detail_id AND   psd.fin_payment_schedule_invoice = ps.fin_payment_schedule_id AND   ps.c_invoice_id IS NOT NULL AND   ps.fin_payment_schedule_id = fin_payment_schedule_id]]></SQLLOGIC>
-<!--AECA45F025F14E6DBA669E12DDA55D17-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--AECA45F025F14E6DBA669E12DDA55D17-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--AECA45F025F14E6DBA669E12DDA55D17-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--AECA45F025F14E6DBA669E12DDA55D17-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--AECA45F025F14E6DBA669E12DDA55D17--></AD_COLUMN>
 
 <!--AF03184D0C395E0CE040A8C091661ED6--><AD_COLUMN>
@@ -334980,8 +334980,8 @@
 <!--B5B203AE8D674B8DABC6669419815CA7-->  <SQLLOGIC><![CDATA[(coalesce((select case when sum(abs(ol.qtyordered)) = 0 then 0 else 
 round(coalesce(sum(abs(ol.qtyinvoiced)), 0)/sum(abs(ol.qtyordered)) * 100, 0)  end 
 from c_orderline ol   where ol.c_order_id=c_order_id and  ol.c_order_discount_id is null), 0))]]></SQLLOGIC>
-<!--B5B203AE8D674B8DABC6669419815CA7-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--B5B203AE8D674B8DABC6669419815CA7-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--B5B203AE8D674B8DABC6669419815CA7-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--B5B203AE8D674B8DABC6669419815CA7-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--B5B203AE8D674B8DABC6669419815CA7--></AD_COLUMN>
 
 <!--B5B4E54AEAC82679E040007F01004CAA--><AD_COLUMN>
@@ -363007,8 +363007,8 @@
 <!--F02817A43E904DF394E07DE81E98C767-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--F02817A43E904DF394E07DE81E98C767-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--F02817A43E904DF394E07DE81E98C767-->  <SQLLOGIC><![CDATA[(SELECT CASE WHEN to_number(trunc((case when max(ps.outstandingamt) = 0 then max(p.paymentdate) else now() end)) -trunc(min(ps.expecteddate))) > 0 THEN to_number(trunc((case when max(ps.outstandingamt) = 0 then max(p.paymentdate) else now() end)) -trunc(min(ps.expecteddate)))ELSE 0 END AS "case" FROM fin_payment_schedule ps LEFT JOIN fin_payment_scheduledetail psd ON ps.fin_payment_schedule_id =  psd.fin_payment_schedule_invoice LEFT JOIN fin_payment_detail pd ON pd.fin_payment_detail_id = psd.fin_payment_detail_id LEFT JOIN fin_payment p ON p.fin_payment_id = pd.fin_payment_id WHERE ps.fin_payment_schedule_id = fin_payment_schedule_id)]]></SQLLOGIC>
-<!--F02817A43E904DF394E07DE81E98C767-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
-<!--F02817A43E904DF394E07DE81E98C767-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--F02817A43E904DF394E07DE81E98C767-->  <ALLOWSORTING><![CDATA[N]]></ALLOWSORTING>
+<!--F02817A43E904DF394E07DE81E98C767-->  <ALLOWFILTERING><![CDATA[N]]></ALLOWFILTERING>
 <!--F02817A43E904DF394E07DE81E98C767--></AD_COLUMN>
 
 <!--F038FDD2AAEC47AAA752573384DF5DCB--><AD_COLUMN>
--- a/src-db/database/sourcedata/AD_TEXTINTERFACES.xml	Mon Feb 15 12:11:46 2016 +0100
+++ b/src-db/database/sourcedata/AD_TEXTINTERFACES.xml	Mon Feb 15 12:28:37 2016 +0100
@@ -72,17 +72,6 @@
 <!--800114-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
 <!--800114--></AD_TEXTINTERFACES>
 
-<!--800116--><AD_TEXTINTERFACES>
-<!--800116-->  <AD_TEXTINTERFACES_ID><![CDATA[800116]]></AD_TEXTINTERFACES_ID>
-<!--800116-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
-<!--800116-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
-<!--800116-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
-<!--800116-->  <TEXT><![CDATA[New address entrance]]></TEXT>
-<!--800116-->  <FILENAME><![CDATA[/org/openbravo/erpCommon/info/Location_F1.html]]></FILENAME>
-<!--800116-->  <ISUSED><![CDATA[Y]]></ISUSED>
-<!--800116-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
-<!--800116--></AD_TEXTINTERFACES>
-
 <!--800117--><AD_TEXTINTERFACES>
 <!--800117-->  <AD_TEXTINTERFACES_ID><![CDATA[800117]]></AD_TEXTINTERFACES_ID>
 <!--800117-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/src-test/src/org/openbravo/test/costing/TestCosting.java	Mon Feb 15 12:11:46 2016 +0100
+++ b/src-test/src/org/openbravo/test/costing/TestCosting.java	Mon Feb 15 12:28:37 2016 +0100
@@ -13094,11 +13094,17 @@
           rate = BigDecimal.ONE;
         }
 
-        else if ((document.getEntityName().equals(ShipmentInOut.ENTITY_NAME) || document
-            .getEntityName().equals(CostAdjustment.ENTITY_NAME))
+        else if ((document.getEntityName().equals(ShipmentInOut.ENTITY_NAME)
+            || document.getEntityName().equals(CostAdjustment.ENTITY_NAME) || (document
+            .getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME) && (line.getEntityName()
+            .equals(ShipmentInOutLine.ENTITY_NAME) || (line.getEntityName().equals(
+            InvoiceLine.ENTITY_NAME) && ((InvoiceLine) line).getInvoice().getCurrency()
+            .equals(CURRENCY2_ID)))))
             && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency() != null
             && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency().getId()
-                .equals(CURRENCY2_ID)) {
+                .equals(CURRENCY2_ID)
+            && !accountingFact.getCurrency().getId()
+                .equals(accountingFact.getAccountingSchema().getCurrency().getId())) {
           Calendar calendar = Calendar.getInstance();
           calendar.set(9999, 0, 1);
           OBCriteria<ConversionRate> criteria = OBDal.getInstance().createCriteria(
@@ -13113,6 +13119,15 @@
           rate = criteria.list().get(0).getMultipleRateBy();
         }
 
+        else if (document.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)
+            && line.getEntityName().equals(InvoiceLine.ENTITY_NAME)
+            && !((InvoiceLine) line).getInvoice().getCurrencyConversionRateDocList().isEmpty()
+            && BigDecimal.ZERO.compareTo(((InvoiceLine) line).getInvoice()
+                .getCurrencyConversionRateDocList().get(0).getRate()) != 0) {
+          rate = BigDecimal.ONE.divide(((InvoiceLine) line).getInvoice()
+              .getCurrencyConversionRateDocList().get(0).getRate());
+        }
+
         assertEquals(
             accountingFact.getForeignCurrencyDebit().setScale(2, BigDecimal.ROUND_HALF_UP),
             documentPostAssert
@@ -13243,6 +13258,9 @@
         if ((productId != null && productId.equals(LANDEDCOSTTYPE3_ID))
             || (document.getEntityName().equals(Invoice.ENTITY_NAME) && ((Invoice) document)
                 .getCurrency().getId().equals(CURRENCY2_ID))
+            || (document.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)
+                && line.getEntityName().equals(InvoiceLine.ENTITY_NAME) && ((InvoiceLine) line)
+                .getInvoice().getCurrency().getId().equals(CURRENCY2_ID))
             || (document.getEntityName().equals(LandedCost.ENTITY_NAME) && ((LCReceiptLineAmt) line)
                 .getLandedCostCost()
                 .getLandedCostType()
@@ -13253,10 +13271,12 @@
                 && ((LCMatched) line).getInvoiceLine().getProduct() != null && ((LCMatched) line)
                 .getInvoiceLine().getProduct().getId().equals(LANDEDCOSTTYPE3_ID))
             || (!document.getEntityName().equals(Invoice.ENTITY_NAME)
-                && !document.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)
-                && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency() != null && OBDal
-                .getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency().getId()
-                .equals(CURRENCY2_ID))) {
+                && !(document.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME) && line
+                    .getEntityName().equals(InvoiceLine.ENTITY_NAME))
+                && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency() != null
+                && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency()
+                    .getId().equals(CURRENCY2_ID) && !accountingFact.getCurrency().getId()
+                .equals(accountingFact.getAccountingSchema().getCurrency().getId()))) {
           assertEquals(accountingFact.getCurrency(),
               OBDal.getInstance().get(Currency.class, CURRENCY2_ID));
         } else {
--- a/src/org/openbravo/common/datasource/ReturnToFromCustomerVendorHQLTransformer.java	Mon Feb 15 12:11:46 2016 +0100
+++ b/src/org/openbravo/common/datasource/ReturnToFromCustomerVendorHQLTransformer.java	Mon Feb 15 12:28:37 2016 +0100
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2014 Openbravo SLU
+ * All portions are Copyright (C) 2014-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -32,12 +32,13 @@
   private static final String returnToVendorTabId = "5A5CCFC8359B4D79BA705DC487FE8173";
 
   private static final String rtv_unitPriceLeftClause = "(case when (select e.salesOrderLine.salesOrder.priceList.priceIncludesTax from ProcurementPOInvoiceMatch as e where e.goodsShipmentLine = iol) = true then  coalesce((select ol.unitPrice from OrderLine as ol where ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine = iol), (select e.salesOrderLine.grossUnitPrice from ProcurementPOInvoiceMatch as e where e.goodsShipmentLine = iol)) else   coalesce((select ol.unitPrice from OrderLine as ol where ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine = iol), (select e.salesOrderLine.unitPrice from ProcurementPOInvoiceMatch as e where e.goodsShipmentLine = iol)) end)";
-  private static final String rtv_orderNoLeftClause = " coalesce ((select e.salesOrderLine.salesOrder.documentNo from ProcurementPOInvoiceMatch as e where e.goodsShipmentLine = iol), '0')";
-  private static final String rfc_unitPriceLeftClause = "(case when (iol.salesOrderLine.salesOrder.priceList.priceIncludesTax) = true then  coalesce((select ol.unitPrice from OrderLine as ol where ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine = iol), (iol.salesOrderLine.grossUnitPrice)) else   coalesce((select ol.unitPrice from OrderLine as ol where ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine = iol), (coalesce(iol.salesOrderLine.unitPrice,''))) end)";
-  private static final String rfc_orderNoLeftClause = " (select e.salesOrderLine.salesOrder.documentNo from MaterialMgmtShipmentInOutLine as e where e.id = iol)";
+  private static final String rtv_orderNoLeftClause = " coalesce ((select e.salesOrderLine.salesOrder.documentNo from ProcurementPOInvoiceMatch as e where e.goodsShipmentLine = iol), '')";
+  private static final String rfc_unitPriceLeftClause = "(case when (iol.salesOrderLine.salesOrder.priceList.priceIncludesTax) = true then  coalesce((select ol.unitPrice from OrderLine as ol where ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine = iol), (iol.salesOrderLine.grossUnitPrice)) else   coalesce((select ol.unitPrice from OrderLine as ol where ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine = iol), (coalesce(iol.salesOrderLine.unitPrice,0))) end)";
+  private static final String rfc_orderNoLeftClause = " coalesce((select e.salesOrderLine.salesOrder.documentNo from MaterialMgmtShipmentInOutLine as e where e.id = iol), '')";
   private static final String returnedLeftClause = " coalesce((select ol.orderedQuantity from OrderLine as ol where ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine = iol),0)";
   private static final String returnedOthersLeftClause = " coalesce((select sum(ol.orderedQuantity) from OrderLine as ol left join ol.salesOrder as o where ol.goodsShipmentLine = iol and o.processed = true and o.documentStatus <> 'VO'), 0)";
   private static final String returnReasonLeftClause = " coalesce((select ol.returnReason.id from OrderLine as ol where ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine = iol), '')";
+  private static final String returnReasonLeftClause2 = " coalesce((select ol.returnReason.name from OrderLine as ol where ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine = iol), '')";
   private static final String returnReasonCountQuery = " select count(distinct e.name) from ReturnReason as e where exists (select distinct ol.returnReason from OrderLine as ol where ol.returnReason = e and ol.salesOrder.id = :salesOrderId  and ol.goodsShipmentLine is not null) ";
   private static final String returnReasonDataQuery = " select distinct e, e.name from ReturnReason as e where exists (select distinct ol.returnReason from OrderLine as ol where ol.returnReason = e and ol.salesOrder.id = :salesOrderId and ol.goodsShipmentLine is not null) ";
   private static final String unitPriceProperty = "unitPrice";
@@ -118,6 +119,8 @@
     } else {
       transformedHqlQuery = transformedHqlQuery.replace("@returnReasonLeftClause@.id",
           returnReasonLeftClause);
+      transformedHqlQuery = transformedHqlQuery.replace("@returnReasonLeftClause@.name",
+          returnReasonLeftClause2);
     }
     return transformedHqlQuery;
   }
@@ -148,6 +151,8 @@
     } else {
       transformedHqlQuery = transformedHqlQuery.replace("@returnReasonLeftClause@.id",
           returnReasonLeftClause);
+      transformedHqlQuery = transformedHqlQuery.replace("@returnReasonLeftClause@.name",
+          returnReasonLeftClause2);
     }
     return transformedHqlQuery;
   }
--- a/src/org/openbravo/costing/CostingMigrationProcess.java	Mon Feb 15 12:11:46 2016 +0100
+++ b/src/org/openbravo/costing/CostingMigrationProcess.java	Mon Feb 15 12:28:37 2016 +0100
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2012-2015 Openbravo SLU
+ * All portions are Copyright (C) 2012-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -495,7 +495,6 @@
 
     int costPrecision = cur.getCostingPrecision().intValue();
     int stdPrecision = cur.getStandardPrecision().intValue();
-    CostingRuleProcess crp = new CostingRuleProcess();
     // Update cost of inventories and process starting physical inventories.
     ScrollableResults icls = getCloseInventoryLines(orgs);
     String productId = "";
@@ -512,7 +511,7 @@
           totalStock = stock.get("stock");
         }
 
-        MaterialTransaction trx = crp.getInventoryLineTransaction(icl);
+        MaterialTransaction trx = icl.getMaterialMgmtMaterialTransactionList().get(0);
         trx.setTransactionProcessDate(DateUtils.addSeconds(trx.getTransactionProcessDate(), -1));
         trx.setCurrency(OBDal.getInstance().get(Currency.class, curId));
 
--- a/src/org/openbravo/costing/CostingRuleProcess.java	Mon Feb 15 12:11:46 2016 +0100
+++ b/src/org/openbravo/costing/CostingRuleProcess.java	Mon Feb 15 12:28:37 2016 +0100
@@ -20,6 +20,7 @@
 
 import java.math.BigDecimal;
 import java.math.RoundingMode;
+import java.sql.SQLException;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.HashMap;
@@ -58,6 +59,8 @@
 import org.openbravo.model.materialmgmt.transaction.InventoryCount;
 import org.openbravo.model.materialmgmt.transaction.InventoryCountLine;
 import org.openbravo.model.materialmgmt.transaction.MaterialTransaction;
+import org.openbravo.model.materialmgmt.transaction.ShipmentInOut;
+import org.openbravo.model.materialmgmt.transaction.ShipmentInOutLine;
 import org.openbravo.scheduling.Process;
 import org.openbravo.scheduling.ProcessBundle;
 import org.openbravo.scheduling.ProcessLogger;
@@ -200,7 +203,8 @@
     pQry.setFilterOnReadableOrganization(false);
     pQry.setNamedParameter("porgs", naturalOrgs);
     pQry.setNamedParameter("childOrgs", childOrgs);
-    return pQry.count() > 0;
+    pQry.setMaxResult(1);
+    return pQry.uniqueResult() != null;
   }
 
   private void checkAllTrxCalculated(Set<String> naturalOrgs, Set<String> childOrgs) {
@@ -219,7 +223,8 @@
     pQry.setFilterOnReadableOrganization(false);
     pQry.setNamedParameter("porgs", naturalOrgs);
     pQry.setNamedParameter("childOrgs", childOrgs);
-    if (pQry.count() > 0) {
+    pQry.setMaxResult(1);
+    if (pQry.uniqueResult() != null) {
       throw new OBException("@TrxWithCostNoCalculated@");
     }
   }
@@ -240,57 +245,83 @@
     pQry.setFilterOnReadableOrganization(false);
     pQry.setNamedParameter("porgs", naturalOrgs);
     pQry.setNamedParameter("childOrgs", childOrgs);
-    if (pQry.count() > 0) {
+    pQry.setMaxResult(1);
+    if (pQry.uniqueResult() != null) {
       throw new OBException("@ProductsWithTrxCalculated@");
     }
   }
 
-  private void initializeOldTrx(Set<String> childOrgs, Date date) {
-    StringBuffer where = new StringBuffer();
-    where.append(" where " + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
-    where.append("   and " + MaterialTransaction.PROPERTY_MOVEMENTDATE + " < :date");
-    OBQuery<MaterialTransaction> trxQry = OBDal.getInstance().createQuery(
-        MaterialTransaction.class, where.toString());
-    trxQry.setFilterOnReadableOrganization(false);
-    trxQry.setNamedParameter("orgs", childOrgs);
-    trxQry.setNamedParameter("date", date);
-    trxQry.setFetchSize(1000);
-    ScrollableResults trxs = trxQry.scroll(ScrollMode.FORWARD_ONLY);
-    int i = 1;
-    try {
-      while (trxs.next()) {
-        MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
+  private void initializeOldTrx(Set<String> childOrgs, Date date) throws SQLException {
+    Client client = OBDal.getInstance().get(Client.class,
+        OBContext.getOBContext().getCurrentClient().getId());
 
-        TransactionCost transactionCost = OBProvider.getInstance().get(TransactionCost.class);
-        transactionCost.setInventoryTransaction(trx);
-        transactionCost.setCostDate(trx.getTransactionProcessDate());
-        transactionCost.setClient(trx.getClient());
-        transactionCost.setOrganization(trx.getOrganization());
-        transactionCost.setCost(BigDecimal.ZERO);
-        transactionCost.setCurrency(trx.getClient().getCurrency());
-        transactionCost.setAccountingDate(trx.getGoodsShipmentLine() != null ? trx
-            .getGoodsShipmentLine().getShipmentReceipt().getAccountingDate() : trx
-            .getMovementDate());
-        List<TransactionCost> trxCosts = trx.getTransactionCostList();
-        trxCosts.add(transactionCost);
-        trx.setTransactionCostList(trxCosts);
+    StringBuffer insert = new StringBuffer();
+    insert.append(" insert into " + TransactionCost.ENTITY_NAME);
+    insert.append(" (" + TransactionCost.PROPERTY_ID);
+    insert.append(", " + TransactionCost.PROPERTY_CLIENT);
+    insert.append(", " + TransactionCost.PROPERTY_ORGANIZATION);
+    insert.append(", " + TransactionCost.PROPERTY_CREATIONDATE);
+    insert.append(", " + TransactionCost.PROPERTY_CREATEDBY);
+    insert.append(", " + TransactionCost.PROPERTY_UPDATED);
+    insert.append(", " + TransactionCost.PROPERTY_UPDATEDBY);
+    insert.append(", " + TransactionCost.PROPERTY_ACTIVE);
+    insert.append(", " + TransactionCost.PROPERTY_INVENTORYTRANSACTION);
+    insert.append(", " + TransactionCost.PROPERTY_COST);
+    insert.append(", " + TransactionCost.PROPERTY_COSTDATE);
+    insert.append(", " + TransactionCost.PROPERTY_CURRENCY);
+    insert.append(", " + TransactionCost.PROPERTY_ACCOUNTINGDATE);
+    insert.append(")");
+    insert.append(" select get_uuid()");
+    insert.append(", t." + MaterialTransaction.PROPERTY_CLIENT);
+    insert.append(", t." + MaterialTransaction.PROPERTY_ORGANIZATION);
+    insert.append(", now()");
+    insert.append(", t." + MaterialTransaction.PROPERTY_CREATEDBY);
+    insert.append(", now()");
+    insert.append(", t." + MaterialTransaction.PROPERTY_UPDATEDBY);
+    insert.append(", t." + MaterialTransaction.PROPERTY_ACTIVE);
+    insert.append(", t");
+    insert.append(", cast(0 as big_decimal)");
+    insert.append(", t." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE);
+    insert.append(", t." + MaterialTransaction.PROPERTY_CLIENT + "." + Client.PROPERTY_CURRENCY);
+    insert.append(", coalesce(io." + ShipmentInOut.PROPERTY_ACCOUNTINGDATE + ", t."
+        + MaterialTransaction.PROPERTY_MOVEMENTDATE + ")");
+    insert.append(" from " + MaterialTransaction.ENTITY_NAME + " as t");
+    insert.append(" left join t." + MaterialTransaction.PROPERTY_GOODSSHIPMENTLINE + " as iol");
+    insert.append(" left join iol." + ShipmentInOutLine.PROPERTY_SHIPMENTRECEIPT + " as io");
+    insert.append(" where t." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
+    insert.append(" and t." + MaterialTransaction.PROPERTY_MOVEMENTDATE + " < :date");
+    insert.append(" and t." + MaterialTransaction.PROPERTY_ISPROCESSED + " = false");
+    insert.append(" and t." + MaterialTransaction.PROPERTY_ACTIVE + " = true");
+    insert.append(" and t." + MaterialTransaction.PROPERTY_CLIENT + ".id = :client");
 
-        trx.setCostCalculated(true);
-        trx.setCostingStatus("CC");
-        trx.setTransactionCost(BigDecimal.ZERO);
-        trx.setCurrency(trx.getClient().getCurrency());
-        trx.setProcessed(true);
-        OBDal.getInstance().save(trx);
+    Query queryInsert = OBDal.getInstance().getSession().createQuery(insert.toString());
+    queryInsert.setParameterList("orgs", childOrgs);
+    queryInsert.setDate("date", date);
+    queryInsert.setString("client", client.getId());
+    queryInsert.executeUpdate();
 
-        if ((i % 100) == 0) {
-          OBDal.getInstance().flush();
-          OBDal.getInstance().getSession().clear();
-        }
-        i++;
-      }
-    } finally {
-      trxs.close();
-    }
+    StringBuffer update = new StringBuffer();
+    update.append(" update " + MaterialTransaction.ENTITY_NAME);
+    update.append(" set " + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + " = true");
+    update.append(", " + MaterialTransaction.PROPERTY_COSTINGSTATUS + " = 'CC'");
+    update.append(", " + MaterialTransaction.PROPERTY_TRANSACTIONCOST + " = " + BigDecimal.ZERO);
+    update.append(", " + MaterialTransaction.PROPERTY_CURRENCY + " = :currency");
+    update.append(", " + MaterialTransaction.PROPERTY_ISPROCESSED + " = true");
+    update.append(" where " + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
+    update.append(" and " + MaterialTransaction.PROPERTY_MOVEMENTDATE + " < :date");
+    update.append(" and " + MaterialTransaction.PROPERTY_ISPROCESSED + " = false");
+    update.append(" and " + MaterialTransaction.PROPERTY_ACTIVE + " = true");
+    update.append(" and " + MaterialTransaction.PROPERTY_CLIENT + ".id = :client");
+
+    Query queryUpdate = OBDal.getInstance().getSession().createQuery(update.toString());
+    queryUpdate.setParameter("currency", client.getCurrency());
+    queryUpdate.setParameterList("orgs", childOrgs);
+    queryUpdate.setDate("date", date);
+    queryUpdate.setString("client", client.getId());
+    queryUpdate.executeUpdate();
+
+    OBDal.getInstance().getSession().flush();
+    OBDal.getInstance().getSession().clear();
   }
 
   @Deprecated
@@ -366,6 +397,7 @@
       stockLines.close();
     }
     // Process closing physical inventories.
+    rule = OBDal.getInstance().get(CostingRule.class, ruleId);
     for (CostingRuleInit cri : rule.getCostingRuleInitList()) {
       new InventoryCountProcess().processInventory(cri.getCloseInventory(), false);
     }
@@ -496,52 +528,67 @@
       boolean existsPreviousRule) {
     CostingRule rule = OBDal.getInstance().get(CostingRule.class, ruleId);
     for (CostingRuleInit cri : rule.getCostingRuleInitList()) {
-      for (InventoryCountLine icl : cri.getCloseInventory().getMaterialMgmtInventoryCountLineList()) {
-        MaterialTransaction trx = getInventoryLineTransaction(icl);
-        // Remove 1 second from transaction date to ensure that cost is calculated with previous
-        // costing rule.
-        trx.setTransactionProcessDate(DateUtils.addSeconds(startingDate, -1));
-        BigDecimal trxCost = BigDecimal.ZERO;
-        BigDecimal cost = null;
-        Currency cur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
-        if (existsPreviousRule) {
-          trxCost = CostingUtils.getTransactionCost(trx, startingDate, true, cur);
-          if (trx.getMovementQuantity().compareTo(BigDecimal.ZERO) != 0) {
-            cost = trxCost.divide(trx.getMovementQuantity().abs(), cur.getCostingPrecision()
-                .intValue(), RoundingMode.HALF_UP);
-            trx = OBDal.getInstance().get(MaterialTransaction.class, trx.getId());
+      ScrollableResults trxs = getInventoryLineTransactions(cri.getCloseInventory());
+      int i = 1;
+      try {
+        while (trxs.next()) {
+          MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
+          // Remove 1 second from transaction date to ensure that cost is calculated with previous
+          // costing rule.
+          trx.setTransactionProcessDate(DateUtils.addSeconds(startingDate, -1));
+          BigDecimal trxCost = BigDecimal.ZERO;
+          BigDecimal cost = null;
+          Currency cur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
+          if (existsPreviousRule) {
+            trxCost = CostingUtils.getTransactionCost(trx, startingDate, true, cur);
+            if (trx.getMovementQuantity().compareTo(BigDecimal.ZERO) != 0) {
+              cost = trxCost.divide(trx.getMovementQuantity().abs(), cur.getCostingPrecision()
+                  .intValue(), RoundingMode.HALF_UP);
+              trx = OBDal.getInstance().get(MaterialTransaction.class, trx.getId());
+            }
+          } else {
+            // Insert transaction cost record big ZERO cost.
+            cur = trx.getClient().getCurrency();
+            TransactionCost transactionCost = OBProvider.getInstance().get(TransactionCost.class);
+            transactionCost.setInventoryTransaction(trx);
+            transactionCost.setCostDate(trx.getTransactionProcessDate());
+            transactionCost.setClient(trx.getClient());
+            transactionCost.setOrganization(trx.getOrganization());
+            transactionCost.setCost(BigDecimal.ZERO);
+            transactionCost.setCurrency(trx.getClient().getCurrency());
+            transactionCost.setAccountingDate(trx.getGoodsShipmentLine() != null ? trx
+                .getGoodsShipmentLine().getShipmentReceipt().getAccountingDate() : trx
+                .getMovementDate());
+            List<TransactionCost> trxCosts = trx.getTransactionCostList();
+            trxCosts.add(transactionCost);
+            trx.setTransactionCostList(trxCosts);
+            OBDal.getInstance().save(trx);
           }
-        } else {
-          // Insert transaction cost record big ZERO cost.
-          cur = trx.getClient().getCurrency();
-          TransactionCost transactionCost = OBProvider.getInstance().get(TransactionCost.class);
-          transactionCost.setInventoryTransaction(trx);
-          transactionCost.setCostDate(trx.getTransactionProcessDate());
-          transactionCost.setClient(trx.getClient());
-          transactionCost.setOrganization(trx.getOrganization());
-          transactionCost.setCost(BigDecimal.ZERO);
-          transactionCost.setCurrency(trx.getClient().getCurrency());
-          transactionCost.setAccountingDate(trx.getGoodsShipmentLine() != null ? trx
-              .getGoodsShipmentLine().getShipmentReceipt().getAccountingDate() : trx
-              .getMovementDate());
-          List<TransactionCost> trxCosts = trx.getTransactionCostList();
-          trxCosts.add(transactionCost);
-          trx.setTransactionCostList(trxCosts);
+
+          trx.setCostCalculated(true);
+          trx.setCostingStatus("CC");
+          trx.setCurrency(cur);
+          trx.setTransactionCost(trxCost);
+          trx.setProcessed(true);
           OBDal.getInstance().save(trx);
+
+          InventoryCountLine initICL = trx.getPhysicalInventoryLine().getRelatedInventory();
+          initICL.setCost(cost);
+          OBDal.getInstance().save(initICL);
+
+          if ((i % 100) == 0) {
+            OBDal.getInstance().flush();
+            OBDal.getInstance().getSession().clear();
+            cri = OBDal.getInstance().get(CostingRuleInit.class, cri.getId());
+          }
+          i++;
         }
+      } finally {
+        trxs.close();
+      }
 
-        trx.setCostCalculated(true);
-        trx.setCostingStatus("CC");
-        trx.setCurrency(cur);
-        trx.setTransactionCost(trxCost);
-        trx.setProcessed(true);
-        OBDal.getInstance().save(trx);
-        icl = OBDal.getInstance().get(InventoryCountLine.class, icl.getId());
-        InventoryCountLine initICL = getInitIcl(cri.getInitInventory(), icl);
-        initICL.setCost(cost);
-        OBDal.getInstance().save(initICL);
-      }
       OBDal.getInstance().flush();
+      cri = OBDal.getInstance().get(CostingRuleInit.class, cri.getId());
       new InventoryCountProcess().processInventory(cri.getInitInventory(), false);
     }
     if (!existsPreviousRule) {
@@ -585,30 +632,38 @@
     return iclQry.uniqueResult();
   }
 
-  private void updateInitInventoriesTrxDate(Date startingDate, String ruleId) {
+  private ScrollableResults getInventoryLineTransactions(InventoryCount inventory) {
     StringBuffer where = new StringBuffer();
-    where.append(" as trx");
-    where.append("   join trx." + MaterialTransaction.PROPERTY_PHYSICALINVENTORYLINE + " as il");
-    where.append(" where il." + InventoryCountLine.PROPERTY_PHYSINVENTORY + ".id IN (");
-    where.append("    select cri." + CostingRuleInit.PROPERTY_INITINVENTORY + ".id");
-    where.append("    from " + CostingRuleInit.ENTITY_NAME + " as cri");
-    where.append("    where cri." + CostingRuleInit.PROPERTY_COSTINGRULE + ".id = :cr");
-    where.append("    )");
+    where.append(MaterialTransaction.PROPERTY_PHYSICALINVENTORYLINE + "."
+        + InventoryCountLine.PROPERTY_PHYSINVENTORY + "." + InventoryCount.PROPERTY_ID
+        + " = :inventory");
     OBQuery<MaterialTransaction> trxQry = OBDal.getInstance().createQuery(
         MaterialTransaction.class, where.toString());
-    trxQry.setNamedParameter("cr", ruleId);
-    trxQry.setFetchSize(1000);
-    ScrollableResults trxs = trxQry.scroll(ScrollMode.FORWARD_ONLY);
-    int i = 0;
-    while (trxs.next()) {
-      MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
-      trx.setTransactionProcessDate(startingDate);
-      OBDal.getInstance().save(trx);
-      if ((i % 100) == 0) {
-        OBDal.getInstance().flush();
-        OBDal.getInstance().getSession().clear();
-      }
-    }
-    trxs.close();
+    trxQry.setNamedParameter("inventory", inventory.getId());
+    return trxQry.scroll(ScrollMode.FORWARD_ONLY);
+  }
+
+  private void updateInitInventoriesTrxDate(Date startingDate, String ruleId) {
+    StringBuffer update = new StringBuffer();
+    update.append(" update " + MaterialTransaction.ENTITY_NAME + " as trx");
+    update.append(" set trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " = :date");
+    update.append(" where exists (");
+    update.append("    select 1");
+    update.append("    from " + InventoryCountLine.ENTITY_NAME + " as il");
+    update.append("    join il." + InventoryCountLine.PROPERTY_PHYSINVENTORY + " as i");
+    update.append("    join i." + InventoryCount.PROPERTY_COSTINGRULEINITINITINVENTORYLIST
+        + " as cri");
+    update.append("    where cri." + CostingRuleInit.PROPERTY_COSTINGRULE + ".id = :cr");
+    update.append("    and il." + InventoryCountLine.PROPERTY_ID + " = trx."
+        + MaterialTransaction.PROPERTY_PHYSICALINVENTORYLINE + ".id");
+    update.append(" )");
+
+    Query queryUpdate = OBDal.getInstance().getSession().createQuery(update.toString());
+    queryUpdate.setDate("date", startingDate);
+    queryUpdate.setString("cr", ruleId);
+    queryUpdate.executeUpdate();
+
+    OBDal.getInstance().flush();
+    OBDal.getInstance().getSession().clear();
   }
 }
--- a/src/org/openbravo/costing/CostingRuleProcessOnProcessHandler.java	Mon Feb 15 12:11:46 2016 +0100
+++ b/src/org/openbravo/costing/CostingRuleProcessOnProcessHandler.java	Mon Feb 15 12:28:37 2016 +0100
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2014-2015 Openbravo SLU
+ * All portions are Copyright (C) 2014-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -159,7 +159,7 @@
     pQry.setFilterOnReadableOrganization(false);
     pQry.setNamedParameter("porgs", naturalOrgs);
     pQry.setNamedParameter("childOrgs", childOrgs);
-    return pQry.count() > 0;
+    pQry.setMaxResult(1);
+    return pQry.uniqueResult() != null;
   }
-
 }
--- a/src/org/openbravo/erpCommon/ad_forms/AcctServer.java	Mon Feb 15 12:11:46 2016 +0100
+++ b/src/org/openbravo/erpCommon/ad_forms/AcctServer.java	Mon Feb 15 12:28:37 2016 +0100
@@ -11,7 +11,7 @@
  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
  * created by ComPiere are Copyright (C) ComPiere, Inc.;   All Rights Reserved.
  * Contributor(s): Openbravo SLU
- * Contributions are Copyright (C) 2001-2015 Openbravo S.L.U.
+ * Contributions are Copyright (C) 2001-2016 Openbravo S.L.U.
  ******************************************************************************
  */
 package org.openbravo.erpCommon.ad_forms;
@@ -2954,8 +2954,7 @@
   public HashMap<String, BigDecimal> getPaymentDetailWriteOffAndAmount(
       List<FIN_PaymentDetail> paymentDetails, FIN_PaymentSchedule ps, FIN_PaymentSchedule psi,
       FIN_PaymentSchedule pso, int currentPaymentDetailIndex, final FieldProvider fieldProvider) {
-    FIN_PaymentDetail paymentDetail = OBDal.getInstance().get(FIN_PaymentDetail.class,
-        paymentDetails.get(currentPaymentDetailIndex));
+    FIN_PaymentDetail paymentDetail = paymentDetails.get(currentPaymentDetailIndex);
     String paymentDetailNextId = null;
     String paymentDetailPreviousId = null;
     if (currentPaymentDetailIndex < paymentDetails.size() - 1) {
--- a/src/org/openbravo/erpCommon/ad_forms/DocMatchInv.java	Mon Feb 15 12:11:46 2016 +0100
+++ b/src/org/openbravo/erpCommon/ad_forms/DocMatchInv.java	Mon Feb 15 12:28:37 2016 +0100
@@ -11,7 +11,7 @@
  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
  * created by ComPiere are Copyright (C) ComPiere, Inc.;   All Rights Reserved.
  * Contributor(s): Openbravo SLU
- * Contributions are Copyright (C) 2001-2014 Openbravo S.L.U.
+ * Contributions are Copyright (C) 2001-2015 Openbravo S.L.U.
  ******************************************************************************
  */
 package org.openbravo.erpCommon.ad_forms;
@@ -313,7 +313,17 @@
     String strInvoiceCurrency = invoiceData[0].cCurrencyId;
     String strIsSOTrx = invoiceData[0].issotrx;
     String strRecordId = invoiceData[0].cInvoiceId;
-    String strReceiptDate = data[0].getField("ORDERDATEACCT");
+    String strReceiptDate = data[0].getField("orderAcctDate");
+    int invoiceCurrencyPrecission = 2;
+    try {
+      OBContext.setAdminMode();
+      invoiceCurrencyPrecission = OBDal.getInstance().get(Currency.class, strInvoiceCurrency)
+          .getStandardPrecision().intValue();
+    } catch (Exception ignore) {
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+
     BigDecimal bdExpenses = new BigDecimal(strExpenses).multiply(
         new BigDecimal(data[0].getField("QTY"))).divide(
         new BigDecimal(data[0].getField("QTYINVOICED")));
@@ -330,9 +340,6 @@
     docLine.m_C_Campaign_ID = data[0].getField("INOUTCAMPAING");
     docLine.m_C_Activity_ID = data[0].getField("INOUTACTIVITY");
     docLine.m_C_Costcenter_ID = data[0].getField("INOUTCOSCENTER");
-    // Calculate Difference amount in schema currency
-    bdCost = new BigDecimal(getConvertedAmt(bdCost.toString(), costCurrency.getId(),
-        as.m_C_Currency_ID, strReceiptDate, "", vars.getClient(), vars.getOrg(), conn));
 
     if (ZERO.compareTo(bdCost) == 0) {
       strMessage = "@MatchedInvIsZero@";
@@ -343,32 +350,22 @@
       DocLine_Material line = (DocLine_Material) p_inOutlines[i];
       BigDecimal lineAmount = bdCost.multiply(new BigDecimal(line.m_qty)).divide(
           new BigDecimal(data[0].getField("MOVEMENTQTY")),
-          OBDal.getInstance().get(Currency.class, as.m_C_Currency_ID).getStandardPrecision()
-              .intValue(), BigDecimal.ROUND_HALF_UP);
+          costCurrency.getStandardPrecision().intValue(), BigDecimal.ROUND_HALF_UP);
       if (i == p_inOutlines.length - 1) {
         lineAmount = bdCost.subtract(totalInOutLines);
       }
       dr = fact.createLine(line, getAccount(AcctServer.ACCTTYPE_NotInvoicedReceipts, as, conn),
-          as.m_C_Currency_ID, lineAmount.toString(), Fact_Acct_Group_ID, nextSeqNo(SeqNo),
-          DocumentType, conn);
+          costCurrency.getId(), lineAmount.toString(), "0", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
+          DocumentType, strReceiptDate, conn);
       totalInOutLines = totalInOutLines.add(lineAmount);
     }
 
-    bdExpenses = convertAmount(bdExpenses, strIsSOTrx.equalsIgnoreCase("Y") ? true : false,
-        DateAcct, TABLEID_Invoice, strRecordId, strInvoiceCurrency, as.m_C_Currency_ID, docLine,
-        as, fact, Fact_Acct_Group_ID, SeqNo, conn, false);
-
-    BigDecimal bdExpensesAcctCurrency = new BigDecimal(
-        getConvertedAmt(bdExpenses.toString(), strInvoiceCurrency, as.m_C_Currency_ID, DateAcct,
-            "", vars.getClient(), vars.getOrg(), conn));
-
-    BigDecimal bdDifference = bdExpensesAcctCurrency.subtract(bdCost);
-
     if (dr == null) {
       log4j.warn("createFact - unable to calculate line with "
           + " cost of the product to not invoiced receipt account.");
       return null;
     }
+
     ProductInfo p = new ProductInfo(data[0].getField("M_Product_Id"), conn);
     BigDecimal totalLines = BigDecimal.ZERO;
     for (int i = 0; i < p_lines.length; i++) {
@@ -376,16 +373,14 @@
       BigDecimal lineAmount = BigDecimal.ZERO;
       BigDecimal linenetamt = new BigDecimal(invoiceData[0].linenetamt);
       if (!(linenetamt.compareTo(BigDecimal.ZERO) == 0)) {
-        lineAmount = bdExpensesAcctCurrency.multiply(new BigDecimal(line.getAmount())).divide(
-            linenetamt,
-            OBDal.getInstance().get(Currency.class, strInvoiceCurrency).getStandardPrecision()
-                .intValue(), BigDecimal.ROUND_HALF_UP);
+        lineAmount = bdExpenses.multiply(new BigDecimal(line.getAmount())).divide(linenetamt,
+            invoiceCurrencyPrecission, BigDecimal.ROUND_HALF_UP);
         if (i == p_lines.length - 1) {
-          lineAmount = bdExpensesAcctCurrency.subtract(totalLines);
+          lineAmount = bdExpenses.subtract(totalLines);
         }
         cr = fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Expense, as, conn),
-            as.m_C_Currency_ID, "0", lineAmount.toString(), Fact_Acct_Group_ID, nextSeqNo(SeqNo),
-            DocumentType, conn);
+            strInvoiceCurrency, "0", lineAmount.toString(), Fact_Acct_Group_ID, nextSeqNo(SeqNo),
+            DocumentType, DateAcct, conn);
         totalLines = totalLines.add(lineAmount);
       }
     }
@@ -404,6 +399,17 @@
     }
     updateProductInfo(as.getC_AcctSchema_ID(), conn, con); // only API
 
+    bdExpenses = convertAmount(bdExpenses, strIsSOTrx.equalsIgnoreCase("Y") ? true : false,
+        DateAcct, TABLEID_Invoice, strRecordId, strInvoiceCurrency, as.m_C_Currency_ID, docLine,
+        as, fact, Fact_Acct_Group_ID, SeqNo, conn, false);
+
+    BigDecimal bdExpensesAcctCurrency = new BigDecimal(
+        getConvertedAmt(bdExpenses.toString(), strInvoiceCurrency, as.m_C_Currency_ID, DateAcct,
+            "", vars.getClient(), vars.getOrg(), conn));
+    // Calculate Difference amount in schema currency
+    bdCost = new BigDecimal(getConvertedAmt(bdCost.toString(), costCurrency.getId(),
+        as.m_C_Currency_ID, strReceiptDate, "", vars.getClient(), vars.getOrg(), conn));
+    BigDecimal bdDifference = bdExpensesAcctCurrency.subtract(bdCost);
     if (bdDifference.signum() != 0) {
       BigDecimal totalDiffLines = BigDecimal.ZERO;
       for (int i = 0; i < p_inOutlines.length; i++) {
--- a/src/org/openbravo/erpCommon/businessUtility/PriceAdjustment.java	Mon Feb 15 12:11:46 2016 +0100
+++ b/src/org/openbravo/erpCommon/businessUtility/PriceAdjustment.java	Mon Feb 15 12:28:37 2016 +0100
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2014-2015 Openbravo SLU 
+ * All portions are Copyright (C) 2014-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -147,7 +147,8 @@
     String hql = "as p ";
     hql += "where active = true ";
     hql += "and client = :client ";
-    hql += "and (endingDate is null or endingDate>:date) ";
+    hql += "and (endingDate is null or trunc(endingDate) + 1 > :date) ";
+    hql += "and trunc(startingDate)<=:date ";
     hql += "and p.discountType.id = '5D4BAF6BB86D4D2C9ED3D5A6FC051579' ";
     hql += "and (minQuantity is null or minQuantity <= :qty) ";
     hql += "and (maxQuantity is null or maxQuantity >= :qty) ";
--- a/src/org/openbravo/erpCommon/info/Location_F1.html	Mon Feb 15 12:11:46 2016 +0100
+++ b/src/org/openbravo/erpCommon/info/Location_F1.html	Mon Feb 15 12:28:37 2016 +0100
@@ -19,7 +19,7 @@
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<title>New address entrance</title>
+<title>Location selector</title>
 <link rel="shortcut icon" href="../../../../../web/images/favicon.ico" type="image/x-icon" />
 
 <link rel="stylesheet" type="text/css" href="../../../../../web/skins/Default/Openbravo_ERP_250.css" id="paramCSS"></link>