Merged from PI
authorAsier Martirena <asier.martirena@openbravo.com>
Wed, 15 Mar 2017 18:56:27 +0100
changeset 32047 a9dbec18faa5
parent 31454 542e2ea80324 (current diff)
parent 32046 1549a54a672f (diff)
child 32048 8e900e1372ab
Merged from PI
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_COLUMN.xml
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_FIELD.xml
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_REFERENCE.xml
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/OBUISEL_SELECTOR.xml
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentProcess.java
modules/org.openbravo.apachejdbcconnectionpool/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.apachejdbcconnectionpool/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.base.weld/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.base.weld/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.application/src-db/database/sourcedata/AD_MESSAGE.xml
modules/org.openbravo.client.application/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.application/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.application/src/org/openbravo/client/application/ApplicationComponentProvider.java
modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachImplementationManager.java
modules/org.openbravo.client.htmlwidget/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.htmlwidget/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.kernel/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.kernel/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.querylist/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.querylist/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.widgets/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.widgets/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.financial.paymentreport/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.financial.paymentreport/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.reports.ordersawaitingdelivery/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.reports.ordersawaitingdelivery/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.service.datasource/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.service.datasource/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.service.integration.google/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.service.integration.google/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.service.integration.openid/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.service.integration.openid/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.service.json/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.service.json/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.userinterface.selector/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.userinterface.selector/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.userinterface.skin.250to300Comp/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.userinterface.skin.250to300Comp/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.userinterface.smartclient/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.userinterface.smartclient/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.utility.cleanup.log/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.utility.cleanup.log/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.v3.datasets/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.v3.datasets/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.v3.framework/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.v3.framework/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.v3/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.v3/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
src-db/database/build.xml
src-db/database/lib/dbsourcemanager.jar
src-db/database/model/functions/C_ORDER_POST1.xml
src-db/database/model/functions/M_INOUT_POST.xml
src-db/database/model/postscript-PostgreSql.sql
src-db/database/model/tables/AD_COLUMN.xml
src-db/database/model/tables/C_BPARTNER.xml
src-db/database/model/tables/C_ORDER.xml
src-db/database/model/tables/C_ORDERLINE.xml
src-db/database/model/tables/M_INOUT.xml
src-db/database/model/tables/M_PRODUCT.xml
src-db/database/model/views/C_INVOICE_CANDIDATE_V.xml
src-db/database/sourcedata/AD_COLUMN.xml
src-db/database/sourcedata/AD_ELEMENT.xml
src-db/database/sourcedata/AD_FIELD.xml
src-db/database/sourcedata/AD_MESSAGE.xml
src-db/database/sourcedata/AD_MODULE.xml
src-db/database/sourcedata/AD_REFERENCE.xml
src-db/database/sourcedata/AD_REF_LIST.xml
src-db/database/sourcedata/AD_TAB.xml
src-db/database/sourcedata/AD_TREENODE.xml
src-db/database/sourcedata/AD_VAL_RULE.xml
src-db/database/sourcedata/AD_WINDOW.xml
src-db/database/sourcedata/M_OFFER_TYPE.xml
src-db/database/sourcedata/OBUIAPP_PROCESS.xml
src-test/src/org/openbravo/test/AllAntTaskTests.java
src-test/src/org/openbravo/test/base/OBBaseTest.java
src-test/src/org/openbravo/test/costing/TestCosting.java
src-test/src/org/openbravo/test/dal/DalPerformanceCriteriaTest.java
src-wad/src/org/openbravo/wad/ComboReloads.javaxml
src-wad/src/org/openbravo/wad/ComboReloads.xml
src-wad/src/org/openbravo/wad/ConfigurationSortTab_Relation.xml
src-wad/src/org/openbravo/wad/ConfigurationSortTab_Relation.xmlxml
src-wad/src/org/openbravo/wad/Configuration_Edition.xml
src-wad/src/org/openbravo/wad/Configuration_Edition.xmlxml
src-wad/src/org/openbravo/wad/Configuration_Relation.xml
src-wad/src/org/openbravo/wad/Configuration_Relation.xmlxml
src-wad/src/org/openbravo/wad/TableLink_data.xsql
src-wad/src/org/openbravo/wad/TemplateSortTab_Relation.html
src-wad/src/org/openbravo/wad/TemplateSortTab_Relation.xml
src-wad/src/org/openbravo/wad/Template_Edition.html
src-wad/src/org/openbravo/wad/Template_Edition.xml
src-wad/src/org/openbravo/wad/Template_Relation.html
src-wad/src/org/openbravo/wad/Template_Relation.xml
src-wad/src/org/openbravo/wad/controls/WADGrid.java
src-wad/src/org/openbravo/wad/datasourceSortTab.xml
src-wad/src/org/openbravo/wad/datasourceSortTab.xsqlxml
src-wad/src/org/openbravo/wad/javasourceSortTab.javaxml
src-wad/src/org/openbravo/wad/javasourceSortTab.xml
src/org/openbravo/base/secureApp/HttpSecureAppServlet.java
src/org/openbravo/common/actionhandler/SetNewBPCurrency.java
src/org/openbravo/dal/core/OBInterceptor.java
src/org/openbravo/dal/core/SessionHandler.java
src/org/openbravo/dal/service/OBCriteria.java
src/org/openbravo/dal/service/OBDal.java
src/org/openbravo/dal/service/OBQuery.java
src/org/openbravo/erpCommon/ad_forms/MaterialReceiptPending.java
src/org/openbravo/erpCommon/ad_forms/MaterialReceiptPending_data.xsql
src/org/openbravo/erpCommon/ad_reports/ReportInvoicesJR.java
src/org/openbravo/erpCommon/ad_reports/ReportSalesOrderInvoicedJasper.java
src/org/openbravo/erpCommon/ad_reports/ReportSalesOrderProvidedJR.java
src/org/openbravo/erpCommon/businessUtility/CancelAndReplaceUtils.java
src/org/openbravo/erpCommon/utility/reporting/Report.java
src/org/openbravo/erpCommon/utility/reporting/ReportManager.java
src/org/openbravo/erpCommon/utility/reporting/TemplateInfo.java
src/org/openbravo/erpCommon/utility/reporting/printing/PrintController.java
src/org/openbravo/service/importprocess/ImportEntryProcessor.java
--- a/.hgsigs	Thu Mar 16 08:47:42 2017 +0100
+++ b/.hgsigs	Wed Mar 15 18:56:27 2017 +0100
@@ -203,4 +203,10 @@
 b91eab932a2640f7395e9c1b7d237c08303d0788 0 iEYEABECAAYFAlfGHnMACgkQCX/oGf+2qkNXHQCgysf6qFN75kW873qTx3i0S9a2qjAAoI0R/AZCW4a6RPrNiFfjaWsOE3+v
 b79e30a5b3532f45101cedce0f3bb6b0a86b5780 0 iEYEABECAAYFAlfz21YACgkQCX/oGf+2qkMqZgCgodjBPp4aS6GrpBTpumtr8DsFNAYAmwS3mdHHNYX8g8y4yIwjMDzmQG+o
 892fdbc643c7c5c52298aae76502ab2283a32433 0 iEYEABECAAYFAlg0JDIACgkQCX/oGf+2qkM+5gCeMkJ6j6tr/FN8cPHlBLGdnf/6F08AoNBmFRFQ/osVwBtifI+b3ZzXEx+X
+e03ab293da7be8c989b20cb7b1ecf4bbf3c7c990 0 iEYEABECAAYFAlh959EACgkQCX/oGf+2qkOFNwCgi/qs8UguivvKA1tlKRKQoIsQqDIAoOGm7DqYBaR6v3aZtvaLmdvffaUh
+81d470b918d385d47e958fe4c2d679cde07c9989 0 iEYEABECAAYFAliHS1kACgkQCX/oGf+2qkN/qgCeOAsukTY2FG0bVzdhXHw/K58kqlEAnAjixxvtQPM4PVmDYqzQDkGdqqtT
 555379f85b18b37ee1c36b4137c75eca80da7267 0 iEYEABECAAYFAlhSQ0UACgkQCX/oGf+2qkN2yQCg5zq8YEVnWK3wy859qvLYbrEhBY4AoKsfpep+GEj+oGGlmOiOqESGPxxH
+fa51600e25b24b2eb3739898d293168ea94748a7 0 iEYEABECAAYFAlh/u8wACgkQCX/oGf+2qkPTnwCfZ29b107GdizLBcC+tzdP3HlnmUUAoN2kMLXvfTYSRLAQG/ziGm5P6kYA
+9753e90ea3e81f850f904feb531120b4e185394a 0 iEYEABECAAYFAliG6A8ACgkQCX/oGf+2qkPeeQCg6D9p++eslvzqEVlYK8RS0uzgZNsAoMELVWkte/AM/ilPxZ4vP37myscv
+a131c85d1d3d55b852f97622ce068baf80b7fe67 0 iEYEABECAAYFAli+qu8ACgkQCX/oGf+2qkNTOACfTznbhwkwUplXd8QjHIuJ7uBJdK4An3KWtbUrBZleCwS1xH3aa2n9p9bM
+3a7510a5ee0b43ac0a65e4eae9b089f42158bbe0 0 iEYEABECAAYFAljGfFgACgkQCX/oGf+2qkOgoQCgx3u3UhiV8NyyiBZLsFjlwicCp1EAoPAl4mZZ6/wURPq39Ef6Rtbe1BRb
--- a/.hgtags	Thu Mar 16 08:47:42 2017 +0100
+++ b/.hgtags	Wed Mar 15 18:56:27 2017 +0100
@@ -214,4 +214,10 @@
 d0dee6596f281e29afcd159544992498896e93ff 3.0PR16Q3.1
 f252db9dde915c15574e3d5fa505bd1154e39c74 3.0PR16Q3.2
 0c8c781e34c94d084b495d00a541d8d57a3903ea 3.0PR16Q3.3
+ed52b01e833ecc6407392f97ffd7d6531bd9bf2f 3.0PR16Q3.4
+ad0be95cec9715cc07fd82615c0de55f7c4a95b4 3.0PR16Q3.5
 cd98953b932b72cc3c694904fc8f8549463ba84a 3.0PR16Q4
+b93f495b2cde680cf6558d93d72051429f4b9031 3.0PR16Q4.1
+31c79a32ce3a6b555dadb35c70d63113be6312e7 3.0PR16Q4.2
+eaeb76d8cd4ec1caf5bf43bc9b4111424d799a03 3.0PR16Q4.3
+273c24deef8f21e870cf563073cc653582a9fe9e 3.0PR17Q1
--- a/config/Openbravo.properties.template	Thu Mar 16 08:47:42 2017 +0100
+++ b/config/Openbravo.properties.template	Wed Mar 15 18:56:27 2017 +0100
@@ -10,7 +10,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) 2007-2015 Openbravo SLU 
+# * All portions are Copyright (C) 2007-2017 Openbravo SLU 
 # * All Rights Reserved. 
 # * Contributor(s):  ______________________________________.
 # ************************************************************************
@@ -99,6 +99,7 @@
 db.pool.testOnReturn=false
 db.pool.validationQuery=SELECT 1 FROM DUAL
 db.pool.validationInterval=30000
+db.pool.jmxEnabled=false
 
 ##################
 # Tomcat manager #
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_GEN_PAYMENTSCHEDULE_INV.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_GEN_PAYMENTSCHEDULE_INV.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -16,7 +16,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) 2010-2016 Openbravo SLU
+* All portions are Copyright (C) 2010-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -1155,6 +1155,7 @@
   ELSIF (p_docaction = 'RC') THEN
     DECLARE
       v_count NUMBER;
+      v_prepaymentamt NUMBER;
     BEGIN
       v_delete_paymentplan := TRUE;
       SELECT c_invoice_id INTO v_reversalinvoice_id
@@ -1180,6 +1181,12 @@
       IF (v_count <> 0) THEN
         v_delete_paymentplan := FALSE;
       END IF;
+      SELECT prepaymentamt INTO v_prepaymentamt
+      FROM c_invoice
+      WHERE c_invoice_id = p_record_id;
+      IF (v_prepaymentamt <> 0) THEN
+        v_delete_paymentplan := FALSE;
+      END IF;
     END;
   END IF;
 
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_COLUMN.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_COLUMN.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -11335,8 +11335,7 @@
 <!--D5B4BD05344C4B44AB7ED2F6CF9C86F6-->  <ISKEY><![CDATA[N]]></ISKEY>
 <!--D5B4BD05344C4B44AB7ED2F6CF9C86F6-->  <ISPARENT><![CDATA[N]]></ISPARENT>
 <!--D5B4BD05344C4B44AB7ED2F6CF9C86F6-->  <ISMANDATORY><![CDATA[N]]></ISMANDATORY>
-<!--D5B4BD05344C4B44AB7ED2F6CF9C86F6-->  <ISUPDATEABLE><![CDATA[Y]]></ISUPDATEABLE>
-<!--D5B4BD05344C4B44AB7ED2F6CF9C86F6-->  <READONLYLOGIC><![CDATA['Y']]></READONLYLOGIC>
+<!--D5B4BD05344C4B44AB7ED2F6CF9C86F6-->  <ISUPDATEABLE><![CDATA[N]]></ISUPDATEABLE>
 <!--D5B4BD05344C4B44AB7ED2F6CF9C86F6-->  <ISIDENTIFIER><![CDATA[N]]></ISIDENTIFIER>
 <!--D5B4BD05344C4B44AB7ED2F6CF9C86F6-->  <SEQNO><![CDATA[410]]></SEQNO>
 <!--D5B4BD05344C4B44AB7ED2F6CF9C86F6-->  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_FIELD.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_FIELD.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -22505,7 +22505,7 @@
 <!--FBEA6835AE0543FE8821B907BD5D0F0B-->  <ISDISPLAYED><![CDATA[Y]]></ISDISPLAYED>
 <!--FBEA6835AE0543FE8821B907BD5D0F0B-->  <DISPLAYLOGIC><![CDATA[@EM_Aprm_Finacc_Trans_Origin@!'']]></DISPLAYLOGIC>
 <!--FBEA6835AE0543FE8821B907BD5D0F0B-->  <DISPLAYLENGTH><![CDATA[32]]></DISPLAYLENGTH>
-<!--FBEA6835AE0543FE8821B907BD5D0F0B-->  <ISREADONLY><![CDATA[N]]></ISREADONLY>
+<!--FBEA6835AE0543FE8821B907BD5D0F0B-->  <ISREADONLY><![CDATA[Y]]></ISREADONLY>
 <!--FBEA6835AE0543FE8821B907BD5D0F0B-->  <SEQNO><![CDATA[80]]></SEQNO>
 <!--FBEA6835AE0543FE8821B907BD5D0F0B-->  <ISSAMELINE><![CDATA[N]]></ISSAMELINE>
 <!--FBEA6835AE0543FE8821B907BD5D0F0B-->  <ISFIELDONLY><![CDATA[N]]></ISFIELDONLY>
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/ProcessInvoice.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/ProcessInvoice.java	Wed Mar 15 18:56:27 2017 +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) 2010-2016 Openbravo SLU
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -340,6 +340,9 @@
           }
         }
 
+        boolean voidingPrepaidInvoice = "RC".equals(strdocaction)
+            && invoice.getPrepaymentamt().compareTo(BigDecimal.ZERO) > 0;
+
         final ProcessInstance pinstance = CallProcess.getInstance().call(process, strC_Invoice_ID,
             parameters);
 
@@ -358,7 +361,107 @@
             revInvoiceCriteria.setMaxResults(1);
             ReversedInvoice revInvoice = (ReversedInvoice) revInvoiceCriteria.uniqueResult();
 
-            if (revInvoice != null && dummyPayment != null) {
+            boolean processPayment = false;
+
+            if (voidingPrepaidInvoice) {
+              processPayment = true;
+
+              FIN_Payment orderPayment = null;
+
+              List<FIN_PaymentSchedule> fpsList = invoice.getFINPaymentScheduleList();
+
+              // Searching for invoice payment
+              for (FIN_PaymentSchedule fps : fpsList) {
+                List<FIN_PaymentScheduleDetail> fpsdList = fps
+                    .getFINPaymentScheduleDetailInvoicePaymentScheduleList();
+                for (FIN_PaymentScheduleDetail fpsd : fpsdList) {
+                  FIN_PaymentDetail pd = fpsd.getPaymentDetails();
+                  orderPayment = pd.getFinPayment();
+                  break;
+                }
+                if (orderPayment != null) {
+                  break;
+                }
+              }
+
+              fpsList.addAll(revInvoice.getInvoice().getFINPaymentScheduleList());
+
+              List<FIN_PaymentScheduleDetail> fpsdList = new ArrayList<>();
+
+              for (FIN_PaymentSchedule fps : fpsList) {
+                fpsdList.addAll(fps.getFINPaymentScheduleDetailInvoicePaymentScheduleList());
+              }
+
+              final DocumentType docType = FIN_Utility.getDocumentType(invoice.getOrganization(),
+                  orderPayment.isReceipt() ? AcctServer.DOCTYPE_ARReceipt
+                      : AcctServer.DOCTYPE_APPayment);
+              final String strPaymentDocumentNo = FIN_Utility.getDocumentNo(docType,
+                  docType.getTable() != null ? docType.getTable().getDBTableName() : "");
+
+              // Creating a dummy payment
+              dummyPayment = dao.getNewPayment(orderPayment.isReceipt(), invoice.getOrganization(),
+                  orderPayment.getDocumentType(), strPaymentDocumentNo,
+                  invoice.getBusinessPartner(), invoice.getPaymentMethod(),
+                  orderPayment.getAccount(), "0", voidDate != null ? voidDate : new Date(),
+                  invoice.getDocumentNo(), invoice.getCurrency(),
+                  orderPayment.getFinancialTransactionConvertRate(), null);
+              OBDal.getInstance().save(dummyPayment);
+
+              invoice.setOutstandingAmount(BigDecimal.ZERO);
+
+              // Updating dummy payment lines with invoice and reverse invoice
+              for (FIN_PaymentScheduleDetail fpsd : fpsdList) {
+                FIN_PaymentDetail psdOldPaymentDetail = fpsd.getPaymentDetails();
+
+                // Create a payment detail
+                FIN_PaymentDetail pd = OBProvider.getInstance().get(FIN_PaymentDetail.class);
+                pd.setOrganization(dummyPayment.getOrganization());
+                pd.setFinPayment(dummyPayment);
+                pd.setAmount(fpsd.getAmount());
+                pd.setRefund(false);
+                OBDal.getInstance().save(pd);
+
+                // Remove the reference to the order payment schedule
+                fpsd.setOrderPaymentSchedule(null);
+                fpsd.setPaymentDetails(pd);
+
+                pd.getFINPaymentScheduleDetailList().add(fpsd);
+                OBDal.getInstance().save(fpsd);
+
+                dummyPayment.getFINPaymentDetailList().add(pd);
+
+                if (psdOldPaymentDetail != null) {
+                  for (FIN_PaymentScheduleDetail orderPSD : psdOldPaymentDetail
+                      .getFINPaymentScheduleDetailList()) {
+                    if (!StringUtils.equals(orderPSD.getId(), fpsd.getId())) {
+                      // Update order received amount
+                      orderPSD.setAmount(orderPSD.getAmount().add(fpsd.getAmount()));
+                      OBDal.getInstance().save(orderPSD);
+                    }
+                  }
+                  FIN_PaymentSchedule ps = fpsd.getInvoicePaymentSchedule();
+                  ps.setPaidAmount(BigDecimal.ZERO);
+                  ps.setOutstandingAmount(fpsd.getAmount());
+                  OBDal.getInstance().save(ps);
+
+                  // Update invoice outstanding amount
+                  if (StringUtils.equals(ps.getInvoice().getId(), invoice.getId())) {
+                    invoice.setOutstandingAmount(invoice.getOutstandingAmount().add(
+                        fpsd.getAmount()));
+                  }
+                }
+              }
+              OBDal.getInstance().save(dummyPayment);
+
+              revInvoice.getInvoice().setPrepaymentamt(BigDecimal.ZERO);
+
+              invoice.setTotalPaid(BigDecimal.ZERO);
+              invoice.setPrepaymentamt(BigDecimal.ZERO);
+
+              OBDal.getInstance().save(invoice);
+              OBDal.getInstance().save(revInvoice.getInvoice());
+            } else if (revInvoice != null && dummyPayment != null) {
+              processPayment = true;
 
               List<FIN_PaymentDetail> paymentDetails = new ArrayList<FIN_PaymentDetail>();
               List<FIN_PaymentScheduleDetail> paymentScheduleDetails = dao
@@ -378,7 +481,9 @@
               }
               dummyPayment.getFINPaymentDetailList().addAll(paymentDetails);
               OBDal.getInstance().save(dummyPayment);
+            }
 
+            if (processPayment) {
               // Process dummy payment related with both actual invoice and reversed invoice
               OBError message = FIN_AddPayment.processPayment(vars, this, "P", dummyPayment);
               if ("Error".equals(message.getType())) {
@@ -493,7 +598,7 @@
             // account defined or invoice's payment method is not inside BP's financial
             // account or the business partner's currency is not equal to the invoice's currency do
             // not cancel credit
-            if (BigDecimal.ZERO.compareTo(invoice.getGrandTotalAmount()) != 0
+            if (BigDecimal.ZERO.compareTo(invoice.getGrandTotalAmount()) < 0
                 && isPaymentMethodConfigured(invoice)
                 && !isInvoiceWithPayments(invoice)
                 && (AcctServer.DOCTYPE_ARInvoice.equals(invoiceDocCategory) || AcctServer.DOCTYPE_APInvoice
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Wed Mar 15 18:56:27 2017 +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) 2010-2016 Openbravo SLU
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  Enterprise Intelligence Systems (http://www.eintel.com.au).
  *************************************************************************
@@ -23,11 +23,15 @@
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
 import org.apache.commons.lang.StringUtils;
+import org.hibernate.Query;
+import org.hibernate.Session;
 import org.hibernate.criterion.Criterion;
 import org.hibernate.criterion.DetachedCriteria;
 import org.hibernate.criterion.Projections;
@@ -1970,24 +1974,41 @@
 
     try {
       OBContext.setAdminMode(true);
-      OBCriteria<FIN_Payment> obcPayment = OBDal.getInstance().createCriteria(FIN_Payment.class);
-      obcPayment.add(Restrictions.eq(FIN_Payment.PROPERTY_BUSINESSPARTNER, bp));
-      obcPayment.add(Restrictions.eq(FIN_Payment.PROPERTY_RECEIPT, isReceipt));
-      obcPayment.add(Restrictions.ne(FIN_Payment.PROPERTY_GENERATEDCREDIT, BigDecimal.ZERO));
-      obcPayment.add(Restrictions.neProperty(FIN_Payment.PROPERTY_GENERATEDCREDIT,
-          FIN_Payment.PROPERTY_USEDCREDIT));
+
       final Organization legalEntity = FIN_Utility.getLegalEntityOrg(org);
       Set<String> orgIds = OBContext.getOBContext().getOrganizationStructureProvider()
           .getChildTree(legalEntity.getId(), true);
-      obcPayment.add(Restrictions.in("organization.id", orgIds));
+
+      final Map<String, Object> params = new HashMap<String, Object>();
+
+      final StringBuffer hql = new StringBuffer("select p ");
+      hql.append(" from " + FIN_Payment.ENTITY_NAME + " as p ");
+      hql.append(" where p." + FIN_Payment.PROPERTY_BUSINESSPARTNER + ".id = :bpartnerId ");
+      hql.append("  and p." + FIN_Payment.PROPERTY_RECEIPT + " = :isReceipt ");
+      hql.append("  and p." + FIN_Payment.PROPERTY_ORGANIZATION + ".id in (:orgIds) ");
+      hql.append("  and obequals(p." + FIN_Payment.PROPERTY_GENERATEDCREDIT + ", p."
+          + FIN_Payment.PROPERTY_USEDCREDIT + ") = 'N' ");
+      hql.append("  and p." + FIN_Payment.PROPERTY_GENERATEDCREDIT + " <> 0 ");
       if (currency != null) {
-        obcPayment.add(Restrictions.eq(FIN_Payment.PROPERTY_CURRENCY, currency));
+        hql.append(" and p." + FIN_Payment.PROPERTY_CURRENCY + ".id = :currencyId");
+        params.put("currencyId", currency.getId());
       }
-      obcPayment.addOrderBy(FIN_Payment.PROPERTY_PAYMENTDATE, true);
-      obcPayment.addOrderBy(FIN_Payment.PROPERTY_DOCUMENTNO, true);
 
-      List<FIN_Payment> paymentList = new ArrayList<FIN_Payment>();
-      for (FIN_Payment fp : obcPayment.list()) {
+      hql.append(" order by p." + FIN_Payment.PROPERTY_PAYMENTDATE + " asc, ");
+      hql.append(" p." + FIN_Payment.PROPERTY_DOCUMENTNO + " asc ");
+
+      params.put("bpartnerId", bp.getId());
+      params.put("isReceipt", isReceipt);
+      params.put("orgIds", orgIds);
+
+      final Session session = OBDal.getInstance().getSession();
+      final Query query = session.createQuery(hql.toString());
+      query.setProperties(params);
+
+      @SuppressWarnings("unchecked")
+      final List<FIN_Payment> queryList = query.list();
+      final List<FIN_Payment> paymentList = new ArrayList<FIN_Payment>();
+      for (FIN_Payment fp : queryList) {
         if ((FIN_Utility.seqnumberpaymentstatus(fp.getStatus())) >= (FIN_Utility
             .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(fp)))) {
           paymentList.add(fp);
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/executionprocess/LeaveAsCredit.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/executionprocess/LeaveAsCredit.java	Wed Mar 15 18:56:27 2017 +0100
@@ -1,13 +1,33 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.0  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License.
+ * The Original Code is Openbravo ERP.
+ * The Initial Developer of the Original Code is Openbravo SLU
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ *************************************************************************
+ */
 package org.openbravo.advpaymentmngt.executionprocess;
 
 import java.math.BigDecimal;
 
 import javax.servlet.ServletException;
 
+import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
 import org.openbravo.advpaymentmngt.utility.FIN_PaymentExecutionProcess;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.model.financialmgmt.payment.FIN_Payment;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentScheduleDetail;
 import org.openbravo.model.financialmgmt.payment.PaymentRun;
 import org.openbravo.model.financialmgmt.payment.PaymentRunPayment;
 
@@ -15,6 +35,7 @@
 
   @Override
   public OBError execute(PaymentRun paymentRun) throws ServletException {
+    AdvPaymentMngtDao dao = new AdvPaymentMngtDao();
     paymentRun.setStatus("PE");
     OBDal.getInstance().save(paymentRun);
     for (PaymentRunPayment paymentRunPayment : paymentRun.getFinancialMgmtPaymentRunPaymentList()) {
@@ -22,6 +43,20 @@
       if (payment.getAmount().compareTo(BigDecimal.ZERO) < 0) {
         payment.setGeneratedCredit(payment.getAmount().negate());
         payment.setAmount(BigDecimal.ZERO);
+        // Set payment as processed = No to add payment detail for credit amount
+        if (payment.isProcessed()) {
+          payment.setProcessed(false);
+          OBDal.getInstance().save(payment);
+          OBDal.getInstance().flush();
+        }
+        // Add schedule detail for credit amount
+        FIN_PaymentScheduleDetail creditScheduleDetail = dao.getNewPaymentScheduleDetail(
+            payment.getOrganization(), payment.getGeneratedCredit());
+        // Add payment detail for credit amount schedule detail
+        dao.getNewPaymentDetail(payment, creditScheduleDetail, payment.getGeneratedCredit(),
+            BigDecimal.ZERO, false, null);
+        // Reset payment as processed = Yes
+        payment.setProcessed(true);
       }
       payment.setStatus(payment.isReceipt() ? "RPR" : "PPM");
       paymentRunPayment.setResult("S");
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentProcess.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentProcess.java	Wed Mar 15 18:56:27 2017 +0100
@@ -90,8 +90,7 @@
       final String paymentDate = (String) bundle.getParams().get("paymentdate");
       final boolean doFlush = bundle.getParams().get("doFlush") != null ? (Boolean) bundle
           .getParams().get("doFlush") : true;
-      processPayment(payment, strAction, paymentDate, comingFrom,
-          selectedCreditLineIds, doFlush);
+      processPayment(payment, strAction, paymentDate, comingFrom, selectedCreditLineIds, doFlush);
       bundle.setResult(msg);
     } catch (Exception e) {
       log4j.error(e.getMessage());
--- a/modules/org.openbravo.advpaymentmngt/web/org.openbravo.advpaymentmngt/js/ob-aprm-addPayment.js	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.advpaymentmngt/web/org.openbravo.advpaymentmngt/js/ob-aprm-addPayment.js	Wed Mar 15 18:56:27 2017 +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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2014-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -312,6 +312,7 @@
     OB.APRM.AddPayment.updateInvOrderTotal(this.view.theForm, grid);
   }
   OB.APRM.AddPayment.tryToUpdateActualExpected(this.view.theForm);
+  OB.APRM.AddPayment.allowCreditToUse(this.view.theForm);
 };
 
 OB.APRM.AddPayment.glitemsOnLoadGrid = function (grid) {
@@ -623,6 +624,27 @@
       delete orderInvoice.obaprmAllRecordsSelectedByUser;
     }
   }
+  OB.APRM.AddPayment.allowCreditToUse(view.theForm);
+};
+
+OB.APRM.AddPayment.allowCreditToUse = function (form) {
+  var expectedPayment = new BigDecimal(String(form.getItem('expected_payment').getValue() || 0)),
+      creditToUseGrid, creditToUseSection, creditToUse = form.getItem('credit_to_use');
+  creditToUseGrid = creditToUse.canvas.viewGrid;
+  creditToUseSection = creditToUse.section;
+  creditToUse.showIf = function () {
+    return expectedPayment.signum() >= 0;
+  };
+  if (expectedPayment.signum() < 0) {
+    if (creditToUseGrid.getSelectedRecords() && creditToUseGrid.getSelectedRecords().size() > 0) {
+      creditToUseGrid.deselectAllRecords();
+    }
+    creditToUseSection.collapseSection();
+  } else {
+    if (creditToUseGrid && creditToUseGrid.data) {
+      creditToUseSection.expandSection();
+    }
+  }
 };
 
 OB.APRM.AddPayment.userSelectAllRecords = function () {
--- a/modules/org.openbravo.apachejdbcconnectionpool/src/org/openbravo/apachejdbcconnectionpool/ConnectionInitializerInterceptor.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.apachejdbcconnectionpool/src/org/openbravo/apachejdbcconnectionpool/ConnectionInitializerInterceptor.java	Wed Mar 15 18:56:27 2017 +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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2014-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -38,6 +38,8 @@
 public class ConnectionInitializerInterceptor extends JdbcInterceptor implements
     PoolInterceptorProvider {
 
+  private static final String INITIALIZED = "OB_INITIALIZED";
+
   String rbdms = (String) OBPropertiesProvider.getInstance().getOpenbravoProperties()
       .get("bbdd.rdbms");
 
@@ -49,9 +51,11 @@
   public void reset(ConnectionPool parent, PooledConnection con) {
     if (con != null) {
       HashMap<Object, Object> attributes = con.getAttributes();
-      Boolean connectionInitialized = (Boolean) attributes.get("OB_INITIALIZED");
+      Boolean connectionInitialized = (Boolean) attributes.get(INITIALIZED);
       if (connectionInitialized == null || connectionInitialized == false) {
-        SessionInfo.initDB(con.getConnection(), rbdms);
+        if (!isReadOnlyPool(parent)) {
+          SessionInfo.initDB(con.getConnection(), rbdms);
+        }
         PreparedStatement pstmt = null;
         try {
           final Properties props = OBPropertiesProvider.getInstance().getOpenbravoProperties();
@@ -69,11 +73,18 @@
             throw new OBException(e);
           }
         }
-        attributes.put("OB_INITIALIZED", true);
+        attributes.put(INITIALIZED, true);
       }
     }
   }
 
+  private boolean isReadOnlyPool(ConnectionPool connectionPool) {
+    if (connectionPool == null || connectionPool.getPoolProperties().isDefaultReadOnly() == null) {
+      return false;
+    }
+    return connectionPool.getPoolProperties().isDefaultReadOnly();
+  }
+
   @Override
   public String getPoolInterceptorsClassNames() {
     String fullClassName = this.getClass().getName();
--- a/modules/org.openbravo.apachejdbcconnectionpool/src/org/openbravo/apachejdbcconnectionpool/JdbcExternalConnectionPool.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.apachejdbcconnectionpool/src/org/openbravo/apachejdbcconnectionpool/JdbcExternalConnectionPool.java	Wed Mar 15 18:56:27 2017 +0100
@@ -11,25 +11,34 @@
  * 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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2014-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
  */
 package org.openbravo.apachejdbcconnectionpool;
 
+import java.lang.management.ManagementFactory;
 import java.sql.Connection;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Properties;
 
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
 import javax.naming.Context;
 import javax.naming.InitialContext;
 
+import org.apache.commons.lang.StringUtils;
 import org.apache.tomcat.jdbc.pool.DataSource;
 import org.apache.tomcat.jdbc.pool.PoolProperties;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.session.OBPropertiesProvider;
 import org.openbravo.base.session.SessionFactoryController;
+import org.openbravo.dal.core.DalContextListener;
 import org.openbravo.database.ExternalConnectionPool;
 import org.openbravo.database.PoolInterceptorProvider;
 import org.slf4j.Logger;
@@ -37,16 +46,19 @@
 
 /**
  * JdbcExternalConnectionPool manages all the functionality of the Apache JDBC Connection Pool. This
- * class provides convenience methods to get a connection, close the pool and other actions.
+ * class can handle different pools (data sources) at the same time. All these pools are eventually
+ * making use of the Apache JDBC Connection Pool. This class provides convenience methods to get a
+ * connection from a pool, close the different pools and other actions.
  */
 public class JdbcExternalConnectionPool extends ExternalConnectionPool {
 
   final static private Logger log = LoggerFactory.getLogger(JdbcExternalConnectionPool.class);
 
-  private DataSource dataSource = null;
+  private Map<String, DataSource> availableDataSources = null;
+  private DataSource defaultDataSource = null;
 
   /**
-   * This method loads all the interceptors of apache jdbc connection pool injected with weld.
+   * This method loads all the interceptors of Apache JDBC Connection Pool injected with weld.
    */
   @Override
   public void loadInterceptors(List<PoolInterceptorProvider> interceptors) {
@@ -54,30 +66,75 @@
     for (PoolInterceptorProvider interceptor : interceptors) {
       currentInterceptors += interceptor.getPoolInterceptorsClassNames();
     }
-    this.getDataSource().setJdbcInterceptors(currentInterceptors);
+    for (DataSource ds : availableDataSources.values()) {
+      ds.setJdbcInterceptors(currentInterceptors);
+    }
   }
 
   /**
-   * Gets the data source of apache jdbc connection pool.
+   * Gets the default data source, which was obtained from the Apache JDBC Connection Pool.
+   * 
+   * @return the {@code DataSource} of the default pool
    */
   public DataSource getDataSource() {
+    if (defaultDataSource == null) {
+      defaultDataSource = availableDataSources.get(DEFAULT_POOL);
+    }
+    return defaultDataSource;
+  }
+
+  /**
+   * This method provides a connection from the default pool. The connection pool is initialized in
+   * the first call to this method.
+   * 
+   * a {@code Connection} retrieved from the default pool
+   */
+  @Override
+  public Connection getConnection() {
+    if (availableDataSources == null) {
+      initPool();
+    }
+    return getConnectionFromDS(getDataSource());
+  }
+
+  /**
+   * This method provides a connection from the pool whose name is specified as parameter. The
+   * connection pool is initialized in the first call to this method.
+   * 
+   * @param poolName
+   *          the name of the pool used to retrieve the connection
+   * @return a {@code Connection} retrieved from the pool passed as parameter
+   */
+  @Override
+  public Connection getConnection(String poolName) {
+    if (availableDataSources == null) {
+      initPool();
+    }
+    DataSource ds = getDataSourceByName(poolName);
+    return getConnectionFromDS(ds);
+  }
+
+  private DataSource getDataSourceByName(String poolName) {
+    if (DEFAULT_POOL.equals(poolName)) {
+      return getDataSource();
+    }
+    DataSource dataSource = availableDataSources.get(poolName);
+    if (dataSource == null) {
+      log.debug(
+          "Connection pool with name {} is not available, using default connection pool to retrieve the connection",
+          poolName);
+      dataSource = getDataSource();
+    }
     return dataSource;
   }
 
-  /**
-   * This method provided a connection of apache jdbc connection pool. Apache jdbc connection pool
-   * is initialized in the first call to this method.
-   */
-  @Override
-  public Connection getConnection() {
-    if (dataSource == null) {
-      initPool();
-    }
+  private Connection getConnectionFromDS(DataSource datasource) {
     Connection connection = null;
     try {
-      connection = dataSource.getConnection();
+      connection = datasource.getConnection();
+
       // All connections are setting autoCommit to true. DAL is taking into account his logical and
-      // DAL is setting autoCommint to false to maintain transactional way of working.
+      // DAL is setting autoCommit to false to maintain transactional way of working.
       connection.setAutoCommit(true);
     } catch (Exception e) {
       log.error("Error while retrieving connection: ", e);
@@ -87,23 +144,64 @@
   }
 
   private void initPool() {
-    dataSource = new DataSource();
-    dataSource.setPoolProperties(getPoolProperties());
+    availableDataSources = new HashMap<>(1);
+    DataSource defaultDS = new DataSource();
+    defaultDS.setPoolProperties(getPoolProperties(""));
+    availableDataSources.put(DEFAULT_POOL, defaultDS);
+    if (isReadOnlyPoolDefined()) {
+      PoolProperties p = getPoolProperties("readonly");
+      p.setDefaultReadOnly(true);
+
+      log.info("Read only pool: " + p.getUrl());
+
+      DataSource ro = new DataSource();
+      ro.setPoolProperties(p);
+      availableDataSources.put(READONLY_POOL, ro);
+    }
+
+    for (Entry<String, DataSource> dse : availableDataSources.entrySet()) {
+      DataSource ds = dse.getValue();
+      try {
+        if (ds.isJmxEnabled()) {
+          String context = "";
+          if (DalContextListener.getServletContext() != null) {
+            context = "context="
+                + DalContextListener.getServletContext().getContextPath().replace("/", "") + ",";
+          }
+
+          // pool needs to be created before it's registered
+          ds.createPool();
+          MBeanServer mbs = null;
+          mbs = ManagementFactory.getPlatformMBeanServer();
+          try {
+            ObjectName name = new ObjectName("Openbravo:" + context + "name=Pool-" + dse.getKey());
+            mbs.registerMBean(ds.getPool().getJmxPool(), name);
+          } catch (InstanceAlreadyExistsException alreadyRegistered) {
+            log.debug("JMX instance already registred for pool {}, bean name: {}", dse.getKey(),
+                alreadyRegistered.getMessage());
+          } catch (Exception ignored) {
+            log.error("Could not register {} pool as jmx bean", dse.getKey(), ignored);
+          }
+        }
+      } catch (Exception e) {
+        log.error("Error creating pool {}", dse.getKey(), e);
+      }
+    }
   }
 
-  private PoolProperties getPoolProperties() {
-    Properties poolPropertiesConfig = OBPropertiesProvider.getInstance().getOpenbravoProperties();
+  private PoolProperties getPoolProperties(String poolName) {
+    Properties props = OBPropertiesProvider.getInstance().getOpenbravoProperties();
 
     PoolProperties poolProperties = new PoolProperties();
 
     poolProperties.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
         + "org.openbravo.apachejdbcconnectionpool.ConnectionInitializerInterceptor;");
 
-    if (SessionFactoryController.isJNDIModeOn(poolPropertiesConfig)) {
+    if (SessionFactoryController.isJNDIModeOn(props)) {
       try {
         Context initctx = new InitialContext();
         Context ctx = (Context) initctx.lookup("java:/comp/env");
-        javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup(poolPropertiesConfig
+        javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup(props
             .getProperty("JNDI.resourceName"));
         poolProperties.setDataSource(ds);
         return poolProperties;
@@ -113,12 +211,12 @@
       }
     }
 
-    String obUrl = poolPropertiesConfig.getProperty("bbdd.url");
-    String sid = poolPropertiesConfig.getProperty("bbdd.sid");
-    String driver = poolPropertiesConfig.getProperty("bbdd.driver");
-    String username = poolPropertiesConfig.getProperty("bbdd.user");
-    String password = poolPropertiesConfig.getProperty("bbdd.password");
-    String rbdms = poolPropertiesConfig.getProperty("bbdd.rdbms");
+    String obUrl = getStringProperty(props, "bbdd.url", poolName);
+    String sid = getStringProperty(props, "bbdd.sid", poolName);
+    String driver = getStringProperty(props, "bbdd.driver", poolName);
+    String username = getStringProperty(props, "bbdd.user", poolName);
+    String password = getStringProperty(props, "bbdd.password", poolName);
+    String rbdms = getStringProperty(props, "bbdd.rdbms", poolName);
 
     if ("POSTGRE".equals(rbdms)) {
       poolProperties.setUrl(obUrl + "/" + sid);
@@ -129,124 +227,146 @@
     poolProperties.setUsername(username);
     poolProperties.setPassword(password);
 
-    if (poolPropertiesConfig.getProperty("db.pool.initialSize") != null) {
-      poolProperties.setInitialSize(getIntProperty(poolPropertiesConfig, "db.pool.initialSize"));
+    if (getStringProperty(props, "db.pool.initialSize", poolName) != null) {
+      poolProperties.setInitialSize(getIntProperty(props, "db.pool.initialSize", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.maxActive") != null) {
-      poolProperties.setMaxActive(getIntProperty(poolPropertiesConfig, "db.pool.maxActive"));
+    if (getStringProperty(props, "db.pool.maxActive", poolName) != null) {
+      poolProperties.setMaxActive(getIntProperty(props, "db.pool.maxActive", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.minIdle") != null) {
-      poolProperties.setMinIdle(getIntProperty(poolPropertiesConfig, "db.pool.minIdle"));
+    if (getStringProperty(props, "db.pool.minIdle", poolName) != null) {
+      poolProperties.setMinIdle(getIntProperty(props, "db.pool.minIdle", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.timeBetweenEvictionRunsMillis") != null) {
-      poolProperties.setTimeBetweenEvictionRunsMillis(getIntProperty(poolPropertiesConfig,
-          "db.pool.timeBetweenEvictionRunsMillis"));
+    if (getStringProperty(props, "db.pool.timeBetweenEvictionRunsMillis", poolName) != null) {
+      poolProperties.setTimeBetweenEvictionRunsMillis(getIntProperty(props,
+          "db.pool.timeBetweenEvictionRunsMillis", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.minEvictableIdleTimeMillis") != null) {
-      poolProperties.setMinEvictableIdleTimeMillis(getIntProperty(poolPropertiesConfig,
-          "db.pool.minEvictableIdleTimeMillis"));
+    if (getStringProperty(props, "db.pool.minEvictableIdleTimeMillis", poolName) != null) {
+      poolProperties.setMinEvictableIdleTimeMillis(getIntProperty(props,
+          "db.pool.minEvictableIdleTimeMillis", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.removeAbandoned") != null) {
-      poolProperties.setRemoveAbandoned(getBooleanProperty(poolPropertiesConfig,
-          "db.pool.removeAbandoned"));
+    if (getStringProperty(props, "db.pool.removeAbandoned", poolName) != null) {
+      poolProperties.setRemoveAbandoned(getBooleanProperty(props, "db.pool.removeAbandoned",
+          poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.testWhileIdle") != null) {
-      poolProperties.setTestWhileIdle(getBooleanProperty(poolPropertiesConfig,
-          "db.pool.testWhileIdle"));
+    if (getStringProperty(props, "db.pool.testWhileIdle", poolName) != null) {
+      poolProperties.setTestWhileIdle(getBooleanProperty(props, "db.pool.testWhileIdle", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.testOnBorrow") != null) {
-      poolProperties.setTestOnBorrow(getBooleanProperty(poolPropertiesConfig,
-          "db.pool.testOnBorrow"));
+    if (getStringProperty(props, "db.pool.testOnBorrow", poolName) != null) {
+      poolProperties.setTestOnBorrow(getBooleanProperty(props, "db.pool.testOnBorrow", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.testOnReturn") != null) {
-      poolProperties.setTestOnReturn(getBooleanProperty(poolPropertiesConfig,
-          "db.pool.testOnReturn"));
+    if (getStringProperty(props, "db.pool.testOnReturn", poolName) != null) {
+      poolProperties.setTestOnReturn(getBooleanProperty(props, "db.pool.testOnReturn", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.validationInterval") != null) {
-      poolProperties.setValidationInterval(getIntProperty(poolPropertiesConfig,
-          "db.pool.validationInterval"));
+    if (getStringProperty(props, "db.pool.validationInterval", poolName) != null) {
+      poolProperties.setValidationInterval(getIntProperty(props, "db.pool.validationInterval",
+          poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.validationQuery") != null) {
+    if (getStringProperty(props, "db.pool.validationQuery", poolName) != null) {
+      poolProperties.setValidationQuery(getStringProperty(props, "db.pool.validationQuery",
+          poolName));
+    }
+    if (getStringProperty(props, "db.pool.defaultTransactionIsolation", poolName) != null) {
+      poolProperties.setDefaultTransactionIsolation(getIntProperty(props,
+          "db.pool.defaultTransactionIsolation", poolName));
+    }
+    if (getStringProperty(props, "db.pool.maxIdle", poolName) != null) {
+      poolProperties.setMaxIdle(getIntProperty(props, "db.pool.maxIdle", poolName));
+    }
+    if (getStringProperty(props, "db.pool.maxWait", poolName) != null) {
+      poolProperties.setMaxWait(getIntProperty(props, "db.pool.maxWait", poolName));
+    }
+    if (getStringProperty(props, "db.pool.numTestsPerEvictionRun", poolName) != null) {
+      poolProperties.setNumTestsPerEvictionRun(getIntProperty(props,
+          "db.pool.numTestsPerEvictionRun", poolName));
+    }
+    if (getStringProperty(props, "db.pool.removeAbandonedTimeout", poolName) != null) {
+      poolProperties.setRemoveAbandonedTimeout(getIntProperty(props,
+          "db.pool.removeAbandonedTimeout", poolName));
+    }
+    if (getStringProperty(props, "db.pool.accessToUnderlyingConnectionAllowed", poolName) != null) {
+      poolProperties.setAccessToUnderlyingConnectionAllowed(getBooleanProperty(props,
+          "db.pool.accessToUnderlyingConnectionAllowed", poolName));
+    }
+    if (getStringProperty(props, "db.pool.defaultAutoCommit", poolName) != null) {
+      poolProperties.setDefaultAutoCommit(getBooleanProperty(props, "db.pool.defaultAutoCommit",
+          poolName));
+    }
+    if (getStringProperty(props, "db.pool.defaultReadOnly", poolName) != null) {
+      poolProperties.setDefaultReadOnly(getBooleanProperty(props, "db.pool.defaultReadOnly",
+          poolName));
+    }
+    if (getStringProperty(props, "db.pool.logAbandoned", poolName) != null) {
+      poolProperties.setLogAbandoned(getBooleanProperty(props, "db.pool.logAbandoned", poolName));
+    }
+    if (getStringProperty(props, "db.pool.testOnConnect", poolName) != null) {
+      poolProperties.setTestOnConnect(getBooleanProperty(props, "db.pool.testOnConnect", poolName));
+    }
+    if (getStringProperty(props, "db.pool.connectionProperties", poolName) != null) {
+      poolProperties.setConnectionProperties(getStringProperty(props,
+          "db.pool.connectionProperties", poolName));
+    }
+    if (getStringProperty(props, "db.pool.defaultCatalog", poolName) != null) {
       poolProperties
-          .setValidationQuery(poolPropertiesConfig.getProperty("db.pool.validationQuery"));
+          .setDefaultCatalog(getStringProperty(props, "db.pool.defaultCatalog", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.defaultTransactionIsolation") != null) {
-      poolProperties.setDefaultTransactionIsolation(getIntProperty(poolPropertiesConfig,
-          "db.pool.defaultTransactionIsolation"));
+    if (getStringProperty(props, "db.pool.validatorClassName", poolName) != null) {
+      poolProperties.setValidatorClassName(getStringProperty(props, "db.pool.validatorClassName",
+          poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.maxIdle") != null) {
-      poolProperties.setMaxIdle(getIntProperty(poolPropertiesConfig, "db.pool.maxIdle"));
+    if (getStringProperty(props, "db.pool.initSQL", poolName) != null) {
+      poolProperties.setInitSQL(getStringProperty(props, "db.pool.initSQL", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.maxWait") != null) {
-      poolProperties.setMaxWait(getIntProperty(poolPropertiesConfig, "db.pool.maxWait"));
+    if (getStringProperty(props, "db.pool.name", poolName) != null) {
+      poolProperties.setName(getStringProperty(props, "db.pool.name", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.numTestsPerEvictionRun") != null) {
-      poolProperties.setNumTestsPerEvictionRun(getIntProperty(poolPropertiesConfig,
-          "db.pool.numTestsPerEvictionRun"));
+    if (getStringProperty(props, "db.pool.jmxEnabled", poolName) != null) {
+      poolProperties.setJmxEnabled(getBooleanProperty(props, "db.pool.jmxEnabled", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.removeAbandonedTimeout") != null) {
-      poolProperties.setRemoveAbandonedTimeout(getIntProperty(poolPropertiesConfig,
-          "db.pool.removeAbandonedTimeout"));
+    if (getStringProperty(props, "db.pool.logAbandoned", poolName) != null) {
+      poolProperties.setLogAbandoned(getBooleanProperty(props, "db.pool.logAbandoned", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.accessToUnderlyingConnectionAllowed") != null) {
-      poolProperties.setAccessToUnderlyingConnectionAllowed(getBooleanProperty(
-          poolPropertiesConfig, "db.pool.accessToUnderlyingConnectionAllowed"));
+    if (getStringProperty(props, "db.pool.suspectTimeout", poolName) != null) {
+      poolProperties.setSuspectTimeout(getIntProperty(props, "db.pool.suspectTimeout", poolName));
     }
-    if (poolPropertiesConfig.getProperty("db.pool.defaultAutoCommit") != null) {
-      poolProperties.setDefaultAutoCommit(getBooleanProperty(poolPropertiesConfig,
-          "db.pool.defaultAutoCommit"));
-    }
-    if (poolPropertiesConfig.getProperty("db.pool.defaultReadOnly") != null) {
-      poolProperties.setDefaultReadOnly(getBooleanProperty(poolPropertiesConfig,
-          "db.pool.defaultReadOnly"));
-    }
-    if (poolPropertiesConfig.getProperty("db.pool.logAbandoned") != null) {
-      poolProperties.setLogAbandoned(getBooleanProperty(poolPropertiesConfig,
-          "db.pool.logAbandoned"));
-    }
-    if (poolPropertiesConfig.getProperty("db.pool.testOnConnect") != null) {
-      poolProperties.setTestOnConnect(getBooleanProperty(poolPropertiesConfig,
-          "db.pool.testOnConnect"));
-    }
-    if (poolPropertiesConfig.getProperty("db.pool.connectionProperties") != null) {
-      poolProperties.setConnectionProperties(poolPropertiesConfig
-          .getProperty("db.pool.connectionProperties"));
-    }
-    if (poolPropertiesConfig.getProperty("db.pool.defaultCatalog") != null) {
-      poolProperties.setDefaultCatalog(poolPropertiesConfig.getProperty("db.pool.defaultCatalog"));
-    }
-    if (poolPropertiesConfig.getProperty("db.pool.validatorClassName") != null) {
-      poolProperties.setValidatorClassName(poolPropertiesConfig
-          .getProperty("db.pool.validatorClassName"));
-    }
-    if (poolPropertiesConfig.getProperty("db.pool.initSQL") != null) {
-      poolProperties.setInitSQL(poolPropertiesConfig.getProperty("db.pool.initSQL"));
-    }
-    if (poolPropertiesConfig.getProperty("db.pool.name") != null) {
-      poolProperties.setName(poolPropertiesConfig.getProperty("db.pool.name"));
-    }
-
     return poolProperties;
   }
 
-  private boolean getBooleanProperty(Properties properties, String propertyName) {
-    return ("true".equals(properties.getProperty(propertyName)));
+  private boolean isReadOnlyPoolDefined() {
+    // to define readonly pool, its url is enough
+    return OBPropertiesProvider.getInstance().getOpenbravoProperties()
+        .containsKey("bbdd.readonly.url");
   }
 
-  private int getIntProperty(Properties properties, String propertyName) {
-    return Integer.parseInt(properties.getProperty(propertyName).trim());
+  private boolean getBooleanProperty(Properties properties, String propertyName, String poolName) {
+    return "true".equals(getStringProperty(properties, propertyName, poolName));
+  }
+
+  private int getIntProperty(Properties properties, String propertyName, String poolName) {
+    return Integer.parseInt(getStringProperty(properties, propertyName, poolName).trim());
+  }
+
+  /** gets specific property for pool if present, default property if not */
+  private String getStringProperty(Properties props, String key, String poolName) {
+    if (StringUtils.isEmpty(poolName)) {
+      // return default property if the pool name is not provided
+      return props.getProperty(key);
+    }
+    String poolSpecificKey = key.replaceFirst("\\.", "." + poolName + ".");
+    return props.containsKey(poolSpecificKey) ? props.getProperty(poolSpecificKey) : props
+        .getProperty(key);
   }
 
   /**
-   * This method closes apache jdbc connection pool.
+   * This method closes all the data sources retrieved from the Apache JDBC Connection Pool.
    */
   @Override
   public void closePool() {
-    DataSource ds = getDataSource();
-    if (ds != null) {
-      // Closes the pool and all idle connections. true parameter is for close the active
-      // connections too.
-      ds.close(true);
+    for (DataSource ds : availableDataSources.values()) {
+      if (ds != null) {
+        // Closes the pool and all idle connections. true parameter is for close the active
+        // connections too.
+        ds.close(true);
+      }
     }
     super.closePool();
   }
--- a/modules/org.openbravo.base.weld/src-test/org/openbravo/base/weld/test/testinfrastructure/DalPersistanceEventTest.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.base.weld/src-test/org/openbravo/base/weld/test/testinfrastructure/DalPersistanceEventTest.java	Wed Mar 15 18:56:27 2017 +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) 2015 Openbravo SLU
+ * All portions are Copyright (C) 2015-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -19,12 +19,17 @@
 
 package org.openbravo.base.weld.test.testinfrastructure;
 
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+import org.jboss.arquillian.junit.InSequence;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
-import org.openbravo.base.weld.test.WeldBaseTest;
+import org.openbravo.client.application.test.event.ObserverBaseTest;
+import org.openbravo.client.application.test.event.OrderLineTestObserver;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.erpCommon.utility.OBMessageUtils;
 import org.openbravo.model.common.geography.Country;
@@ -36,12 +41,39 @@
  * @author alostale
  *
  */
-public class DalPersistanceEventTest extends WeldBaseTest {
+public class DalPersistanceEventTest extends ObserverBaseTest {
   @Rule
   public ExpectedException exception = ExpectedException.none();
 
   @Test
-  public void persisntaceObserversShouldBeExecuted() {
+  @InSequence(1)
+  public void beginTrxObserversShouldBeExecutedOnFirstTest() {
+    assertThat("begin transaction observer executions",
+        OrderLineTestObserver.getNumberOfStartedTrxs(), is(1));
+  }
+
+  @Test
+  @InSequence(2)
+  public void beginTrxObserversShouldBeExecutedOnSubsequentTests() {
+    assertThat("begin transaction observer executions",
+        OrderLineTestObserver.getNumberOfStartedTrxs(), is(1));
+  }
+
+  @Test
+  @InSequence(3)
+  public void endTrxObserversShouldBeExecuted() {
+    int initiallyClosedTrxs = OrderLineTestObserver.getNumberOfClosedTrxs();
+
+    OBDal.getInstance().commitAndClose();
+
+    assertThat("initial end transaction observer executions", initiallyClosedTrxs, is(0));
+    assertThat("end transaction observer executions",
+        OrderLineTestObserver.getNumberOfClosedTrxs(), is(1));
+  }
+
+  @Test
+  @InSequence(4)
+  public void persistanceObserversShouldBeExecuted() {
     try {
       setSystemAdministratorContext();
       Country newCountry = OBProvider.getInstance().get(Country.class);
--- a/modules/org.openbravo.client.application/src-db/database/model/tables/OBUIAPP_PARAMETER.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-db/database/model/tables/OBUIAPP_PARAMETER.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -192,12 +192,15 @@
       </foreign-key>
       <index name="OBUIAPP_PARAMETER_ATTMET_IDX" unique="false">
         <index-column name="C_ATTACHMENT_METHOD_ID"/>
+        <whereClause><![CDATA[C_ATTACHMENT_METHOD_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="OBUIAPP_PARAMETER_PROCESS" unique="false">
         <index-column name="OBUIAPP_PROCESS_ID"/>
+        <whereClause><![CDATA[OBUIAPP_PROCESS_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="OBUIAPP_PARAMETER_TAB_IDX" unique="false">
         <index-column name="AD_TAB_ID"/>
+        <whereClause><![CDATA[AD_TAB_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="OBUIAPP_PARAM_SHOWTITLE_CHK"><![CDATA[DISPLAYTITLE IN ('Y', 'N')]]></check>
       <check name="OBUIAPP_PARAMETER_CENTR_CHK"><![CDATA[ISCENTRALLYMAINTAINED IN ('Y', 'N')]]></check>
--- a/modules/org.openbravo.client.application/src-db/database/model/tables/OBUIAPP_PARAMETER_VALUE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-db/database/model/tables/OBUIAPP_PARAMETER_VALUE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -71,6 +71,7 @@
       </foreign-key>
       <index name="OBUIAPP_PARAMVAL_FILE_IDX" unique="false">
         <index-column name="C_FILE_ID"/>
+        <whereClause><![CDATA[C_FILE_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="OBUIAPP_PARAMVAL_PARAM_IDX" unique="false">
         <index-column name="OBUIAPP_PARAMETER_ID"/>
--- a/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_COLUMN.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_COLUMN.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -774,7 +774,7 @@
 <!--08AF323AC6C066ADE050007F0100548B-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--08AF323AC6C066ADE050007F0100548B-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
 <!--08AF323AC6C066ADE050007F0100548B-->  <NAME><![CDATA[Use PDF as XLS Template]]></NAME>
-<!--08AF323AC6C066ADE050007F0100548B-->  <HELP><![CDATA[Determines whether the PDF Template needs to be used to generate the XLS instead of defining a specific template for it.]]></HELP>
+<!--08AF323AC6C066ADE050007F0100548B-->  <HELP><![CDATA[Determines whether the PDF Template needs to be used to generate the Excel report instead of defining a specific template for it.]]></HELP>
 <!--08AF323AC6C066ADE050007F0100548B-->  <COLUMNNAME><![CDATA[USE_Pdf_As_Xls_Template]]></COLUMNNAME>
 <!--08AF323AC6C066ADE050007F0100548B-->  <AD_TABLE_ID><![CDATA[C7CAB786F3EF4DF0B5E7B9AC6EC7DED8]]></AD_TABLE_ID>
 <!--08AF323AC6C066ADE050007F0100548B-->  <AD_REFERENCE_ID><![CDATA[20]]></AD_REFERENCE_ID>
--- a/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_DATASET_TABLE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_DATASET_TABLE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -65,7 +65,7 @@
 <!--7AA152F1C7D340CD9C29F2D4926EBFE0-->  <AD_TABLE_ID><![CDATA[C7CAB786F3EF4DF0B5E7B9AC6EC7DED8]]></AD_TABLE_ID>
 <!--7AA152F1C7D340CD9C29F2D4926EBFE0-->  <INCLUDEALLCOLUMNS><![CDATA[Y]]></INCLUDEALLCOLUMNS>
 <!--7AA152F1C7D340CD9C29F2D4926EBFE0-->  <WHERECLAUSE><![CDATA[obuiapp_process_id in (select obuiapp_process_id from obuiapp_process where ad_module_id in (:moduleid))]]></WHERECLAUSE>
-<!--7AA152F1C7D340CD9C29F2D4926EBFE0-->  <EXCLUDEAUDITINFO><![CDATA[N]]></EXCLUDEAUDITINFO>
+<!--7AA152F1C7D340CD9C29F2D4926EBFE0-->  <EXCLUDEAUDITINFO><![CDATA[Y]]></EXCLUDEAUDITINFO>
 <!--7AA152F1C7D340CD9C29F2D4926EBFE0-->  <ISBUSINESSOBJECT><![CDATA[N]]></ISBUSINESSOBJECT>
 <!--7AA152F1C7D340CD9C29F2D4926EBFE0-->  <AD_MODULE_ID><![CDATA[9BA0836A3CD74EE4AB48753A47211BCC]]></AD_MODULE_ID>
 <!--7AA152F1C7D340CD9C29F2D4926EBFE0--></AD_DATASET_TABLE>
--- a/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_ELEMENT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_ELEMENT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -46,8 +46,8 @@
 <!--08AF323AC6C766ADE050007F0100548B-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--08AF323AC6C766ADE050007F0100548B-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
 <!--08AF323AC6C766ADE050007F0100548B-->  <COLUMNNAME><![CDATA[XLS_Template]]></COLUMNNAME>
-<!--08AF323AC6C766ADE050007F0100548B-->  <NAME><![CDATA[XLS Template]]></NAME>
-<!--08AF323AC6C766ADE050007F0100548B-->  <PRINTNAME><![CDATA[XLS Template]]></PRINTNAME>
+<!--08AF323AC6C766ADE050007F0100548B-->  <NAME><![CDATA[Excel Template]]></NAME>
+<!--08AF323AC6C766ADE050007F0100548B-->  <PRINTNAME><![CDATA[Excel Template]]></PRINTNAME>
 <!--08AF323AC6C766ADE050007F0100548B-->  <HELP><![CDATA[JRXML template to export to Excel the report when a specific template is required for excel]]></HELP>
 <!--08AF323AC6C766ADE050007F0100548B-->  <AD_MODULE_ID><![CDATA[9BA0836A3CD74EE4AB48753A47211BCC]]></AD_MODULE_ID>
 <!--08AF323AC6C766ADE050007F0100548B-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
@@ -59,9 +59,9 @@
 <!--08AF323AC6C866ADE050007F0100548B-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--08AF323AC6C866ADE050007F0100548B-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
 <!--08AF323AC6C866ADE050007F0100548B-->  <COLUMNNAME><![CDATA[USE_Pdf_As_Xls_Template]]></COLUMNNAME>
-<!--08AF323AC6C866ADE050007F0100548B-->  <NAME><![CDATA[Use PDF as XLS Template]]></NAME>
-<!--08AF323AC6C866ADE050007F0100548B-->  <PRINTNAME><![CDATA[Use PDF as XLS Template]]></PRINTNAME>
-<!--08AF323AC6C866ADE050007F0100548B-->  <HELP><![CDATA[Determines whether the PDF Template needs to be used to generate the XLS instead of defining a specific template for it.]]></HELP>
+<!--08AF323AC6C866ADE050007F0100548B-->  <NAME><![CDATA[Use PDF as Excel Template]]></NAME>
+<!--08AF323AC6C866ADE050007F0100548B-->  <PRINTNAME><![CDATA[Use PDF as Excel Template]]></PRINTNAME>
+<!--08AF323AC6C866ADE050007F0100548B-->  <HELP><![CDATA[Determines whether the PDF Template needs to be used to generate the Excel report instead of defining a specific template for it.]]></HELP>
 <!--08AF323AC6C866ADE050007F0100548B-->  <AD_MODULE_ID><![CDATA[9BA0836A3CD74EE4AB48753A47211BCC]]></AD_MODULE_ID>
 <!--08AF323AC6C866ADE050007F0100548B-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
 <!--08AF323AC6C866ADE050007F0100548B--></AD_ELEMENT>
--- a/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_FIELD.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_FIELD.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -605,7 +605,7 @@
 <!--08AEFECA5A607AECE050007F0100529C-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
 <!--08AEFECA5A607AECE050007F0100529C-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--08AEFECA5A607AECE050007F0100529C-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
-<!--08AEFECA5A607AECE050007F0100529C-->  <NAME><![CDATA[XLS Template]]></NAME>
+<!--08AEFECA5A607AECE050007F0100529C-->  <NAME><![CDATA[Excel Template]]></NAME>
 <!--08AEFECA5A607AECE050007F0100529C-->  <HELP><![CDATA[JRXML template to export to Excel the report when a specific template is required for excel]]></HELP>
 <!--08AEFECA5A607AECE050007F0100529C-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
 <!--08AEFECA5A607AECE050007F0100529C-->  <AD_TAB_ID><![CDATA[2B7B3CCDC940436F93437445AA7752F3]]></AD_TAB_ID>
@@ -633,8 +633,8 @@
 <!--08AEFECA5A617AECE050007F0100529C-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
 <!--08AEFECA5A617AECE050007F0100529C-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--08AEFECA5A617AECE050007F0100529C-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
-<!--08AEFECA5A617AECE050007F0100529C-->  <NAME><![CDATA[Use PDF as XLS Template]]></NAME>
-<!--08AEFECA5A617AECE050007F0100529C-->  <HELP><![CDATA[Determines whether the PDF Template needs to be used to generate the XLS instead of defining a specific template for it.]]></HELP>
+<!--08AEFECA5A617AECE050007F0100529C-->  <NAME><![CDATA[Use PDF as Excel Template]]></NAME>
+<!--08AEFECA5A617AECE050007F0100529C-->  <HELP><![CDATA[Determines whether the PDF Template needs to be used to generate the Excel report instead of defining a specific template for it.]]></HELP>
 <!--08AEFECA5A617AECE050007F0100529C-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
 <!--08AEFECA5A617AECE050007F0100529C-->  <AD_TAB_ID><![CDATA[2B7B3CCDC940436F93437445AA7752F3]]></AD_TAB_ID>
 <!--08AEFECA5A617AECE050007F0100529C-->  <AD_COLUMN_ID><![CDATA[08AF323AC6C066ADE050007F0100548B]]></AD_COLUMN_ID>
@@ -8516,7 +8516,7 @@
 <!--FCD55C499D894E95B322C17919EAB3E4-->  <AD_COLUMN_ID><![CDATA[0E78BBBD0F814831A4E5837C677666FD]]></AD_COLUMN_ID>
 <!--FCD55C499D894E95B322C17919EAB3E4-->  <IGNOREINWAD><![CDATA[N]]></IGNOREINWAD>
 <!--FCD55C499D894E95B322C17919EAB3E4-->  <ISDISPLAYED><![CDATA[Y]]></ISDISPLAYED>
-<!--FCD55C499D894E95B322C17919EAB3E4-->  <DISPLAYLOGIC><![CDATA[@Uipattern@='M']]></DISPLAYLOGIC>
+<!--FCD55C499D894E95B322C17919EAB3E4-->  <DISPLAYLOGIC><![CDATA[@Uipattern@='M' | @Uipattern@='OBUIAPP_PickAndExecute']]></DISPLAYLOGIC>
 <!--FCD55C499D894E95B322C17919EAB3E4-->  <DISPLAYLENGTH><![CDATA[1]]></DISPLAYLENGTH>
 <!--FCD55C499D894E95B322C17919EAB3E4-->  <ISREADONLY><![CDATA[N]]></ISREADONLY>
 <!--FCD55C499D894E95B322C17919EAB3E4-->  <SEQNO><![CDATA[110]]></SEQNO>
--- a/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_MESSAGE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-db/database/sourcedata/AD_MESSAGE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -1911,7 +1911,7 @@
 <!--CDBC4895920A424CB8715EC232729ABD-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--CDBC4895920A424CB8715EC232729ABD-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
 <!--CDBC4895920A424CB8715EC232729ABD-->  <VALUE><![CDATA[OBUIAPP_XLSExport]]></VALUE>
-<!--CDBC4895920A424CB8715EC232729ABD-->  <MSGTEXT><![CDATA[Export to XLS]]></MSGTEXT>
+<!--CDBC4895920A424CB8715EC232729ABD-->  <MSGTEXT><![CDATA[Export to Excel]]></MSGTEXT>
 <!--CDBC4895920A424CB8715EC232729ABD-->  <MSGTYPE><![CDATA[I]]></MSGTYPE>
 <!--CDBC4895920A424CB8715EC232729ABD-->  <AD_MODULE_ID><![CDATA[9BA0836A3CD74EE4AB48753A47211BCC]]></AD_MODULE_ID>
 <!--CDBC4895920A424CB8715EC232729ABD-->  <ISINCLUDEINI18N><![CDATA[N]]></ISINCLUDEINI18N>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/ADCSInitialization.java	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,200 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html 
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License. 
+ * The Original Code is Openbravo ERP. 
+ * The Initial Developer of the Original Code is Openbravo SLU 
+ * All portions are Copyright (C) 2017 Openbravo SLU 
+ * All Rights Reserved. 
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+
+package org.openbravo.client.application.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.Matchers.empty;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+import javax.inject.Inject;
+
+import org.hibernate.Query;
+import org.junit.Test;
+import org.openbravo.base.exception.OBException;
+import org.openbravo.base.secureApp.VariablesSecureApp;
+import org.openbravo.base.weld.test.WeldBaseTest;
+import org.openbravo.client.application.attachment.AttachmentUtils;
+import org.openbravo.client.application.window.ApplicationDictionaryCachedStructures;
+import org.openbravo.client.kernel.RequestContext;
+import org.openbravo.dal.service.OBDal;
+import org.openbravo.model.ad.ui.Field;
+import org.openbravo.model.ad.utility.AttachmentMethod;
+import org.openbravo.test.base.HiddenObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test cases to ensure correct concurrent initialization of ADCS.
+ * 
+ * @author alostale
+ *
+ */
+public class ADCSInitialization extends WeldBaseTest {
+  private static final Logger log = LoggerFactory.getLogger(ADCSInitialization.class);
+
+  @Inject
+  ApplicationDictionaryCachedStructures adcs;
+
+  List<Exception> exceptions = new ArrayList<>();
+
+  @Test
+  public void aDCSshouldBeCorrectlyInitialized() {
+    assumeTrue("Cache can be used (no modules in development)", adcs.useCache());
+
+    int maxThreads = Runtime.getRuntime().availableProcessors() * 2;
+    log.info("Starting ADCS initialization with {} threads.", maxThreads);
+    ExecutorService executor = Executors.newFixedThreadPool(maxThreads);
+    for (int i = 0; i < maxThreads; i++) {
+      executor.execute(new ADCSEagerInitializator(i));
+    }
+
+    executor.shutdown();
+    try {
+      executor.awaitTermination(20L, TimeUnit.MINUTES);
+    } catch (InterruptedException e) {
+      log.error("Error in execution", e);
+    }
+    if (!exceptions.isEmpty()) {
+      log.error("Executed with " + exceptions.size() + " exceptions");
+      for (Exception e : exceptions) {
+        log.error("-------------------");
+        log.error("Exception", e);
+        log.error("-------------------");
+      }
+    }
+    assertThat("Exceptions while initializating ADCS", exceptions, is(empty()));
+  }
+
+  /** Initializes ADCS eagerly */
+  private class ADCSEagerInitializator implements Runnable {
+    private int threadNum;
+    private boolean initialized = false;
+    private int retries = 0;
+    private static final int MAX_RETRIES = 5;
+
+    public ADCSEagerInitializator(int threadNum) {
+      this.threadNum = threadNum;
+    }
+
+    @Override
+    public void run() {
+      initialize();
+      try {
+        eagerADCSInitialization();
+      } catch (Exception e) {
+        synchronized (exceptions) {
+          exceptions.add(e);
+        }
+        if (retries < MAX_RETRIES) {
+          retries++;
+          run();
+        } else {
+          // give up
+          throw new OBException("Reached max number of retries after exception " + retries);
+        }
+      }
+    }
+
+    private void initialize() {
+      if (initialized) {
+        return;
+      }
+
+      try {
+        Thread.sleep(threadNum * 500);
+      } catch (InterruptedException ignored) {
+      }
+
+      // We need vars in context to initialize combos: this is not an issue because vars is only
+      // used for system settings such as sql formats
+      VariablesSecureApp fakedVars = new VariablesSecureApp(null, null, null);
+      try {
+        HiddenObjectHelper.set(RequestContext.get(), "variablesSecureApp", fakedVars);
+      } catch (Exception e) {
+        log.error("Errror initializating context", e);
+      }
+
+      setSystemAdministratorContext();
+    }
+
+    @SuppressWarnings("unchecked")
+    private void eagerADCSInitialization() throws Exception {
+      log.info("Starting eager initialization");
+
+      Query queryTabs = OBDal
+          .getInstance()
+          .getSession()
+          .createQuery(
+              "select t.id from ADTab t where t.active=true order by t.window.id, t.id "
+                  + (threadNum % 2 == 0 ? "asc" : "desc"));
+
+      List<String> tabs = queryTabs.list();
+      long t = System.currentTimeMillis();
+      int i = 0;
+      for (String tabId : tabs) {
+        adcs.getTab(tabId);
+
+        if (++i % 100 == 0) {
+          log.info("tab {}/{}", i, tabs.size());
+        }
+      }
+      log.info("Intialized all tabs in {} ms", System.currentTimeMillis() - t);
+
+      Query queryCombo = OBDal
+          .getInstance()
+          .getSession()
+          .createQuery(
+              "select f.id from ADField f where f.active=true and f.column.reference.id in ('18','17','19')");
+
+      List<String> combos = queryCombo.list();
+      long t1 = System.currentTimeMillis();
+      i = 0;
+      for (String comboId : combos) {
+        adcs.getComboTableData(OBDal.getInstance().getProxy(Field.class, comboId));
+
+        if (++i % 100 == 0) {
+          log.info("combo {}/{}", i, combos.size());
+        }
+      }
+      log.info("Intialized all combos in {} ms", System.currentTimeMillis() - t1);
+
+      AttachmentMethod attMethod = AttachmentUtils.getDefaultAttachmentMethod();
+      i = 0;
+      t1 = System.currentTimeMillis();
+      for (String tabId : tabs) {
+        adcs.getMethodMetadataParameters(attMethod.getId(), tabId);
+
+        if (++i % 100 == 0) {
+          log.info("att method {}/{}", i, tabs.size());
+        }
+      }
+      log.info("Intialized all attachemnt methods in {} ms", System.currentTimeMillis() - t1);
+
+      log.info("Completed eager initialization in {} ms", System.currentTimeMillis() - t);
+    }
+  }
+}
--- a/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/StandardWindowTest.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/StandardWindowTest.java	Wed Mar 15 18:56:27 2017 +0100
@@ -11,20 +11,34 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2010-2011 Openbravo SLU
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
  */
 package org.openbravo.client.application.test;
 
+import static org.hamcrest.Matchers.isEmptyString;
+import static org.junit.Assert.assertThat;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Level;
 import org.junit.Ignore;
 import org.junit.Test;
+import org.openbravo.base.secureApp.VariablesSecureApp;
 import org.openbravo.base.weld.test.WeldBaseTest;
 import org.openbravo.client.application.window.StandardWindowComponent;
+import org.openbravo.client.kernel.ComponentGenerator;
+import org.openbravo.client.kernel.RequestContext;
 import org.openbravo.dal.service.OBDal;
+import org.openbravo.model.ad.module.Module;
 import org.openbravo.model.ad.ui.Tab;
 import org.openbravo.model.ad.ui.Window;
+import org.openbravo.test.base.HiddenObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Tests generation of the javascript for standard windows
@@ -32,6 +46,8 @@
  * @author iperdomo
  */
 public class StandardWindowTest extends WeldBaseTest {
+  private static final Logger log = LoggerFactory.getLogger(StandardWindowTest.class);
+  private static final String USER_INTERFACE_APP_MOD = "9BA0836A3CD74EE4AB48753A47211BCC";
 
   /**
    * Tests generating the javascript for all windows, printing one of them.
@@ -40,17 +56,59 @@
   public void testStandardViewGeneration() throws Exception {
     setSystemAdministratorContext();
 
-    for (Window window : OBDal.getInstance().createQuery(Window.class, "").list()) {
-      if (hasAtLeastOneActiveTab(window)) {
-        System.err.println(window.getName());
-        try {
-          generateForWindow(window);
-        } catch (Throwable t) {
-          System.err.println("ERROR for window " + window.getName() + " " + window.getId());
-          throw new Error(t);
+    // set user interface application module in dev to enable jslint
+    Module uiapp = OBDal.getInstance().get(Module.class, USER_INTERFACE_APP_MOD);
+    boolean wasInDev = uiapp.isInDevelopment();
+    if (!wasInDev) {
+      uiapp.setInDevelopment(true);
+    }
+
+    String errorMsg = "";
+    try {
+      VariablesSecureApp fakedVars = new VariablesSecureApp(null, null, null);
+      try {
+        HiddenObjectHelper.set(RequestContext.get(), "variablesSecureApp", fakedVars);
+      } catch (Exception e) {
+        log.error("Errror initializating context", e);
+      }
+
+      List<Window> allWindows = OBDal.getInstance().createQuery(Window.class, "").list();
+      int i = 0;
+      setTestLogAppenderLevel(Level.WARN);
+      List<String> errors = new ArrayList<>();
+      for (Window window : allWindows) {
+        if (hasAtLeastOneActiveTab(window)) {
+          log.info("window {} of {}: {}", new Object[] { ++i, allWindows.size(), window.getName() });
+          try {
+            generateForWindow(window);
+          } catch (Throwable t) {
+            log.error(t.getMessage(), t);
+          }
+        }
+        for (String error : getTestLogAppender().getMessages(Level.ERROR)) {
+          errors.add("ERROR - Window " + window.getName() + " - " + window.getId() + ": " + error);
+        }
+
+        for (String warn : getTestLogAppender().getMessages(Level.WARN)) {
+          errors.add("WARN - Window " + window.getName() + " - " + window.getId() + ": " + warn);
+        }
+        getTestLogAppender().reset();
+      }
+      log.info("Generated {} windows", allWindows.size());
+      if (!errors.isEmpty()) {
+        log.error("{} errors detected:", errors.size());
+        for (String error : errors) {
+          log.error(error);
+          errorMsg += error + "\n";
         }
       }
+    } finally {
+      if (!wasInDev) {
+        uiapp.setInDevelopment(false);
+      }
     }
+
+    assertThat("Errors generating windows", errorMsg, isEmptyString());
   }
 
   /**
@@ -66,10 +124,7 @@
   private void generateForWindow(Window window) {
     final StandardWindowComponent component = super.getWeldComponent(StandardWindowComponent.class);
     component.setWindow(window);
-    final String jsCode = component.generate();
-    if (window.getId().equals("102")) {
-      System.err.println(jsCode);
-    }
+    ComponentGenerator.getInstance().generate(component);
   }
 
   private boolean hasAtLeastOneActiveTab(Window window) {
--- a/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/event/DatasourceEventObserver.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/event/DatasourceEventObserver.java	Wed Mar 15 18:56:27 2017 +0100
@@ -19,6 +19,7 @@
 
 package org.openbravo.client.application.test.event;
 
+import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.is;
 import static org.junit.Assert.assertThat;
 
@@ -125,14 +126,62 @@
         is(OrderLineTestObserver.FORCED_DESCRIPTION));
   }
 
+  /**
+   * The OrderLine observer updates an order line's header. This action should fire the Order
+   * observer and just once.
+   */
+  @Test
+  public void observerFiredByChildObjectObserverShouldBeExecuteOnce() throws JSONException {
+    observerExecutionType = ObserverExecutionType.UPDATE_PARENT_RANDOM;
+
+    OrderLine ol = pickARandomOrderLine();
+
+    String randomDescription = Long.toString(System.currentTimeMillis());
+    datasourceUpdate(ol, randomDescription);
+
+    int[] executions = { OrderTestObserver.getNumberOfExecutions(),
+        OrderLineTestObserver.getNumberOfExecutions() };
+    assertThat("Observers executions", new int[] { 1, 1 }, equalTo(executions));
+  }
+
+  /**
+   * The Order observer updates an order line. This action should fire the OrderLine observer and
+   * just once.
+   */
+  @Test
+  public void observerFiredByParentObjectObserverShouldBeExecuteOnce() throws JSONException {
+    // Use ON_NOOP execution type to avoid subsequent actions from the OrderLine observer
+    observerExecutionType = ObserverExecutionType.ON_NOOP;
+
+    Order order = pickARandomOrderLine().getSalesOrder();
+
+    String randomDescription = Long.toString(System.currentTimeMillis());
+    datasourceUpdate(order, randomDescription);
+
+    int[] executions = { OrderTestObserver.getNumberOfExecutions(),
+        OrderLineTestObserver.getNumberOfExecutions() };
+    assertThat("Observers executions", new int[] { 1, 1 }, equalTo(executions));
+  }
+
   private JSONObject datasourceUpdate(OrderLine ol, String randomDescription) throws JSONException {
-    final DataSourceService dataSource = dataSourceServiceProvider
-        .getDataSource(OrderLine.ENTITY_NAME);
-
     JSONObject data = new JSONObject();
     data.put(JsonConstants.ID, ol.getId());
     data.put(OrderLine.PROPERTY_DESCRIPTION, randomDescription);
 
+    return datasourceUpdate(OrderLine.ENTITY_NAME, data);
+  }
+
+  private JSONObject datasourceUpdate(Order order, String randomDescription) throws JSONException {
+    JSONObject data = new JSONObject();
+    data.put(JsonConstants.ID, order.getId());
+    data.put(Order.PROPERTY_DESCRIPTION, randomDescription);
+
+    return datasourceUpdate(Order.ENTITY_NAME, data);
+  }
+
+  private JSONObject datasourceUpdate(String entityName, JSONObject data) throws JSONException {
+    final DataSourceService dataSource = dataSourceServiceProvider.getDataSource(entityName);
+
     JSONObject content = new JSONObject();
     content.put(JsonConstants.DATA, data);
 
--- a/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/event/ObserverBaseTest.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/event/ObserverBaseTest.java	Wed Mar 15 18:56:27 2017 +0100
@@ -29,12 +29,13 @@
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.ad.datamodel.Table;
+import org.openbravo.model.common.order.Order;
 import org.openbravo.model.common.order.OrderLine;
 
 /** Base class to test Dal observer execution. Handles state of {@link OrderLineTestObserver}. */
 public class ObserverBaseTest extends WeldBaseTest {
   protected enum ObserverExecutionType {
-    OFF, UPDATE_DESCRIPTION, CREATE_NOTE, COUNT_LINES, UPDATE_PARENT, ON_NOOP
+    OFF, UPDATE_DESCRIPTION, CREATE_NOTE, COUNT_LINES, UPDATE_PARENT, UPDATE_PARENT_RANDOM, ON_NOOP
   }
 
   protected static ObserverExecutionType observerExecutionType = ObserverExecutionType.OFF;
@@ -45,8 +46,11 @@
   }
 
   @Before
-  public void resetObserverCount() {
+  @Override
+  public void setUp() throws Exception {
+    OrderTestObserver.resetExecutionCount();
     OrderLineTestObserver.resetExecutionCount();
+    super.setUp();
   }
 
   protected OrderLine pickARandomOrderLine() {
@@ -54,6 +58,10 @@
         .uniqueResult();
   }
 
+  protected Order pickARandomOrder() {
+    return (Order) OBDal.getInstance().createCriteria(Order.class).setMaxResults(1).uniqueResult();
+  }
+
   protected int countNotes(BaseOBObject obj) {
     OBContext.setAdminMode(true);
     try {
--- a/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/event/OrderLineTestObserver.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/event/OrderLineTestObserver.java	Wed Mar 15 18:56:27 2017 +0100
@@ -28,6 +28,8 @@
 import org.openbravo.client.kernel.event.EntityNewEvent;
 import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
 import org.openbravo.client.kernel.event.EntityUpdateEvent;
+import org.openbravo.client.kernel.event.TransactionBeginEvent;
+import org.openbravo.client.kernel.event.TransactionCompletedEvent;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.ad.datamodel.Table;
 import org.openbravo.model.common.order.Order;
@@ -44,6 +46,8 @@
   static final String FORCED_DESCRIPTION = "test description";
   private static Entity[] entities = { ModelProvider.getInstance().getEntity(OrderLine.ENTITY_NAME) };
   private static int executionCount = 0;
+  private static int beginTrx = 0;
+  private static int endTrx = 0;
 
   public void onUpdate(@Observes EntityUpdateEvent event) {
     if (!isValidEvent(event)) {
@@ -51,8 +55,6 @@
     }
 
     switch (ObserverBaseTest.observerExecutionType) {
-    case OFF:
-      return;
     case UPDATE_DESCRIPTION:
       event.setCurrentState(entities[0].getProperty(OrderLine.PROPERTY_DESCRIPTION),
           FORCED_DESCRIPTION);
@@ -73,11 +75,17 @@
           FORCED_DESCRIPTION + numOfLines);
       break;
     case UPDATE_PARENT:
-      Order order = ((OrderLine) event.getTargetInstance()).getSalesOrder();
-      order.setDescription(FORCED_DESCRIPTION);
+      Order orderWithForcedDescription = ((OrderLine) event.getTargetInstance()).getSalesOrder();
+      orderWithForcedDescription.setDescription(FORCED_DESCRIPTION);
+      break;
+    case UPDATE_PARENT_RANDOM:
+      Order orderWithRandomDescription = ((OrderLine) event.getTargetInstance()).getSalesOrder();
+      orderWithRandomDescription.setDescription(Long.toString(System.currentTimeMillis()));
       break;
     case ON_NOOP:
       break;
+    default:
+      return;
     }
 
     executionCount++;
@@ -113,6 +121,14 @@
     executionCount++;
   }
 
+  public void onTransactionBegin(@Observes TransactionBeginEvent event) {
+    beginTrx++;
+  }
+
+  public void onTransactionCompleted(@Observes TransactionCompletedEvent event) {
+    endTrx++;
+  }
+
   @Override
   protected Entity[] getObservedEntities() {
     return entities;
@@ -120,9 +136,19 @@
 
   static void resetExecutionCount() {
     executionCount = 0;
+    beginTrx = 0;
+    endTrx = 0;
   }
 
   static int getNumberOfExecutions() {
     return executionCount;
   }
+
+  public static int getNumberOfStartedTrxs() {
+    return beginTrx;
+  }
+
+  public static int getNumberOfClosedTrxs() {
+    return endTrx;
+  }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/event/OrderTestObserver.java	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,86 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html 
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License.
+ * The Original Code is Openbravo ERP.
+ * The Initial Developer of the Original Code is Openbravo SLU
+ * All portions are Copyright (C) 2017 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+package org.openbravo.client.application.test.event;
+
+import java.util.List;
+
+import javax.enterprise.event.Observes;
+
+import org.openbravo.base.model.Entity;
+import org.openbravo.base.model.ModelProvider;
+import org.openbravo.base.model.Property;
+import org.openbravo.client.application.test.event.ObserverBaseTest.ObserverExecutionType;
+import org.openbravo.client.kernel.event.EntityDeleteEvent;
+import org.openbravo.client.kernel.event.EntityNewEvent;
+import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
+import org.openbravo.client.kernel.event.EntityUpdateEvent;
+import org.openbravo.model.common.order.Order;
+import org.openbravo.model.common.order.OrderLine;
+
+public class OrderTestObserver extends EntityPersistenceEventObserver {
+  private static Entity[] entities = { ModelProvider.getInstance().getEntity(Order.ENTITY_NAME) };
+  private static int executionCount = 0;
+
+  @Override
+  protected Entity[] getObservedEntities() {
+    return entities;
+  }
+
+  public void onUpdate(@Observes EntityUpdateEvent event) {
+    if (!isValidEvent(event)) {
+      return;
+    }
+    if (ObserverBaseTest.observerExecutionType == ObserverExecutionType.ON_NOOP) {
+      final Order order = (Order) event.getTargetInstance();
+      final List<OrderLine> orderLineList = order.getOrderLineList();
+      if (!orderLineList.isEmpty()) {
+        orderLineList.get(0).setDescription(Long.toString(System.currentTimeMillis()));
+        event.setCurrentState(getOrderLineListProperty(), orderLineList);
+      }
+    }
+    executionCount++;
+  }
+
+  public void onNew(@Observes EntityNewEvent event) {
+    if (!isValidEvent(event)) {
+      return;
+    }
+    executionCount++;
+  }
+
+  public void onDelete(@Observes EntityDeleteEvent event) {
+    if (!isValidEvent(event)) {
+      return;
+    }
+    executionCount++;
+  }
+
+  static int getNumberOfExecutions() {
+    return executionCount;
+  }
+
+  static void resetExecutionCount() {
+    executionCount = 0;
+  }
+
+  private Property getOrderLineListProperty() {
+    final Entity orderEntity = ModelProvider.getInstance().getEntity(Order.ENTITY_NAME);
+    return orderEntity.getProperty(Order.PROPERTY_ORDERLINELIST);
+  }
+}
--- a/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/event/PersistanceObserver.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/event/PersistanceObserver.java	Wed Mar 15 18:56:27 2017 +0100
@@ -49,6 +49,7 @@
     observerExecutionType = ObserverExecutionType.ON_NOOP;
     OBContext.setAdminMode(false);
     OrderLine ol = OBProvider.getInstance().get(OrderLine.class);
+    ol.setSalesOrder(pickARandomOrder());
     OBDal.getInstance().save(ol);
     assertThat("Observer executions", OrderLineTestObserver.getNumberOfExecutions(), is(1));
 
@@ -114,6 +115,7 @@
     observerExecutionType = ObserverExecutionType.ON_NOOP;
     OBContext.setAdminMode(false);
     OrderLine ol = OBProvider.getInstance().get(OrderLine.class);
+    ol.setSalesOrder(pickARandomOrder());
     OBDal.getInstance().save(ol);
 
     try {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/AlertActionHandler_data.xsql	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/AlertActionHandler_data.xsql	Wed Mar 15 18:56:27 2017 +0100
@@ -12,7 +12,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) 2013 Openbravo SLU
+ * All portions are Copyright (C) 2013-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -30,7 +30,7 @@
       <Field name="supportContact" value=""/>
     </SqlMethod>
 
-   <SqlMethod name="setLastPing" type="preparedStatement" return="rowCount">
+   <SqlMethod name="setLastPing" type="preparedStatement" return="rowCount" saveContextInfo="false">
     <Sql><![CDATA[
         UPDATE AD_Session
         SET last_session_ping = NOW()
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/ApplicationUtils.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/ApplicationUtils.java	Wed Mar 15 18:56:27 2017 +0100
@@ -48,6 +48,7 @@
 public class ApplicationUtils {
 
   private static Logger log = Logger.getLogger(ApplicationUtils.class);
+  private static final String BUTTON_REFERENCE = "28";
 
   static boolean showWindowInClassicMode(Window window) {
     List<String> reasonsToBeShownInClassic = new ArrayList<String>();
@@ -228,6 +229,6 @@
     if (field.getColumn() == null) {
       return false;
     }
-    return "28".equals(field.getColumn().getReference().getId());
+    return BUTTON_REFERENCE.equals(field.getColumn().getReference().getId());
   }
 }
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/StorePropertyActionHandler.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/StorePropertyActionHandler.java	Wed Mar 15 18:56:27 2017 +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) 2009-2011 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,6 +28,7 @@
 import org.openbravo.client.kernel.StaticResourceComponent;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
+import org.openbravo.database.SessionInfo;
 import org.openbravo.erpCommon.businessUtility.Preferences;
 import org.openbravo.model.ad.access.Role;
 import org.openbravo.model.ad.access.User;
@@ -84,6 +85,7 @@
 
       Preferences.setPreferenceValue(propertyName, cleanedData, true, client, org, user, role,
           window, null);
+      SessionInfo.auditThisThread(false);
       OBDal.getInstance().flush();
       return new JSONObject("{msg: 'Property Stored'}");
     } catch (Exception e) {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/ViewComponent.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/ViewComponent.java	Wed Mar 15 18:56:27 2017 +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) 2010-2016 Openbravo SLU
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -117,6 +117,7 @@
   }
 
   protected String generateWindow(Window window) {
+    setIdentifier("Window: " + window.getName() + " - " + window.getId());
     standardWindowComponent.setWindow(window);
     standardWindowComponent.setParameters(getParameters());
     final String jsCode = standardWindowComponent.generate();
@@ -143,6 +144,7 @@
       }
     }
     component.setId(viewImpDef.getId());
+    setIdentifier("View " + viewName + " - " + viewImpDef.getId());
     component.setComponentTemplate(viewImpDef.getTemplate());
     component.setParameters(getParameters());
 
@@ -151,6 +153,7 @@
   }
 
   protected String generateProcess(Process process) {
+    setIdentifier("Process: " + process.getName() + " - " + process.getId());
     parameterWindowComponent.setProcess(process);
     parameterWindowComponent.setParameters(getParameters());
     parameterWindowComponent.setPoup(false);
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/WindowSettingsActionHandler.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/WindowSettingsActionHandler.java	Wed Mar 15 18:56:27 2017 +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) 2011-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -72,13 +72,12 @@
   private Instance<ExtraWindowSettingsInjector> extraSettings;
 
   protected JSONObject execute(Map<String, Object> parameters, String data) {
-
     try {
       OBContext.setAdminMode();
       final String windowId = (String) parameters.get("windowId");
       final Window window = OBDal.getInstance().get(Window.class, windowId);
       final String roleId = OBContext.getOBContext().getRole().getId();
-      final DalConnectionProvider dalConnectionProvider = new DalConnectionProvider();
+      final DalConnectionProvider dalConnectionProvider = new DalConnectionProvider(false);
       final JSONObject jsonUIPattern = new JSONObject();
       final String windowType = window.getWindowType();
       for (Tab tab : window.getADTabList()) {
@@ -257,6 +256,8 @@
       throw new OBException(e);
     } finally {
       OBContext.restorePreviousMode();
+      // clear anything we have in session as there's no change to make faster flush
+      OBDal.getInstance().getSession().clear();
     }
   }
 }
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/WindowsInClassicModeTask.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/WindowsInClassicModeTask.java	Wed Mar 15 18:56:27 2017 +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) 2011 Openbravo SLU 
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -46,12 +46,12 @@
       }
       if (classicWindowMessages.size() > 0) {
         log.info("Module: " + module.getName());
-        log.info("The following windows will be shown in classic mode:");
+        log.info("The following windows are not correctly defined for Openbravo 3, they might be incorrectly visualized:");
         for (String message : classicWindowMessages) {
           log.info("  " + message);
         }
       }
     }
-    log.info("The rest of the windows will be shown in new mode.");
+    log.info("The rest of the windows are correctly defined.");
   }
 }
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachImplementationManager.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachImplementationManager.java	Wed Mar 15 18:56:27 2017 +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) 2015-2016 Openbravo SLU
+ * All portions are Copyright (C) 2015-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/process/BaseProcessActionHandler.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/process/BaseProcessActionHandler.java	Wed Mar 15 18:56:27 2017 +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) 2010-2016 Openbravo SLU
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -96,7 +96,7 @@
       // Set information for audit trail
       SessionInfo.setProcessType("PD");
       SessionInfo.setProcessId(processId);
-      SessionInfo.setDBSessionInfo(OBDal.getInstance().getConnection(false));
+      SessionInfo.saveContextInfoIntoDB(OBDal.getInstance().getConnection(false));
 
       // Adds compatibility with legacy process definitions
       // If the handler of the process definition has not been updated, then it expects the
@@ -216,5 +216,9 @@
     return fixRequestMap(parameters, null);
   }
 
+  protected static ResponseActionsBuilder getResponseBuilder() {
+    return new ResponseActionsBuilder();
+  }
+
   protected abstract JSONObject doExecute(Map<String, Object> parameters, String content);
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/process/ResponseActionsBuilder.java	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,335 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License.
+ * The Original Code is Openbravo ERP.
+ * The Initial Developer of the Original Code is Openbravo SLU
+ * All portions are Copyright (C) 2017 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+package org.openbravo.client.application.process;
+
+import org.codehaus.jettison.json.JSONArray;
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper that can be used to build the standard response actions of a
+ * {@link BaseProcessActionHandler} in an easy way.
+ */
+public class ResponseActionsBuilder {
+  private static final Logger log = LoggerFactory.getLogger(ResponseActionsBuilder.class);
+
+  private JSONArray responseActions;
+  private JSONObject retryExecutionMsg;
+  private boolean retryExecution;
+  private boolean showResultsInProcessView;
+
+  public enum MessageType {
+    SUCCESS("success"), ERROR("error"), INFO("info"), WARNING("warning");
+
+    private final String type;
+
+    MessageType(String type) {
+      this.type = type;
+    }
+
+    private String getType() {
+      return this.type;
+    }
+  }
+
+  public enum Command {
+    DEFAULT("DEFAULT"), NEW("NEW");
+
+    private final String commandName;
+
+    Command(String commandName) {
+      this.commandName = commandName;
+    }
+
+    private String getCommandName() {
+      return this.commandName;
+    }
+  }
+
+  ResponseActionsBuilder() {
+    responseActions = new JSONArray();
+  }
+
+  /**
+   * It shows a message in the current active view.
+   * 
+   * @param msgType
+   *          The message type.
+   * @param msgTitle
+   *          The title of the message.
+   * @param msgText
+   *          The text of the message.
+   * @return a ResponseActionsBuilder that contains a 'show message in view' response action.
+   */
+  public ResponseActionsBuilder showMsgInView(MessageType msgType, String msgTitle, String msgText) {
+    addResponseAction("showMsgInView", buildResponseMessage(msgType, msgTitle, msgText));
+    return this;
+  }
+
+  /**
+   * @see ResponseActionsBuilder#showMsgInProcessView(MessageType, String, String)
+   */
+  public ResponseActionsBuilder showMsgInProcessView(MessageType msgType, String msgText) {
+    showMsgInProcessView(msgType, "", msgText);
+    return this;
+  }
+
+  /**
+   * @see ResponseActionsBuilder#showMsgInProcessView(MessageType, String, String, boolean)
+   */
+  public ResponseActionsBuilder showMsgInProcessView(MessageType msgType, String msgTitle,
+      String msgText) {
+    showMsgInProcessView(msgType, msgTitle, msgText, false);
+    return this;
+  }
+
+  /**
+   * It shows a message in the view that invoked the process.
+   * 
+   * @param msgType
+   *          The message type.
+   * @param msgTitle
+   *          The title of the message.
+   * @param msgText
+   *          The text of the message.
+   * @param force
+   *          If it should force the message to be show in the pop-up. Typically it is used in error
+   *          cases together with the retryExecution action.
+   * @return a ResponseActionsBuilder that contains a 'show message in process view' response
+   *         action.
+   */
+  public ResponseActionsBuilder showMsgInProcessView(MessageType msgType, String msgTitle,
+      String msgText, boolean force) {
+    try {
+      final JSONObject messageInfo = buildResponseMessage(msgType, msgTitle, msgText);
+      if (force) {
+        messageInfo.put("force", force);
+      }
+      addResponseAction("showMsgInProcessView", messageInfo);
+    } catch (JSONException ignore) {
+    }
+    return this;
+  }
+
+  /**
+   * @see ResponseActionsBuilder#openDirectTab(String, String, boolean)
+   */
+  public ResponseActionsBuilder openDirectTab(String tabId, boolean wait) {
+    openDirectTab(tabId, null, wait);
+    return this;
+  }
+
+  /**
+   * @see ResponseActionsBuilder#openDirectTab(String, String, Command, boolean)
+   */
+  public ResponseActionsBuilder openDirectTab(String tabId, String recordId, boolean wait) {
+    openDirectTab(tabId, recordId, Command.DEFAULT, wait);
+    return this;
+  }
+
+  /**
+   * @see ResponseActionsBuilder#openDirectTab(String, String, Command, String, boolean)
+   */
+  public ResponseActionsBuilder openDirectTab(String tabId, String recordId, Command command,
+      boolean wait) {
+    openDirectTab(tabId, recordId, command, null, wait);
+    return this;
+  }
+
+  /**
+   * Opens a view using a tab id and record id. The tab can be a child tab. If the record id is not
+   * set then the tab is opened in grid mode.
+   * 
+   * @param tabId
+   *          The id of the tab to be opened.
+   * @param recordId
+   *          The id of the record to be opened.
+   * @param command
+   *          The command to be used to open the tab ('DEFAULT', 'NEW').
+   * @param criteria
+   *          A removable filtering criteria which will be automatically added to the open tab
+   * @param wait
+   *          If true, the next response action will not be started until this one finishes.
+   * @return a ResponseActionsBuilder that contains a 'open direct tab' response action.
+   */
+  public ResponseActionsBuilder openDirectTab(String tabId, String recordId, Command command,
+      String criteria, boolean wait) {
+    try {
+      final JSONObject openDirectTab = new JSONObject();
+      openDirectTab.put("tabId", tabId);
+      openDirectTab.put("recordId", recordId);
+      openDirectTab.put("command", command.getCommandName());
+      if (criteria != null) {
+        openDirectTab.put("criteria", criteria);
+      }
+      openDirectTab.put("wait", wait);
+      addResponseAction("openDirectTab", openDirectTab);
+    } catch (JSONException ignore) {
+    }
+    return this;
+  }
+
+  /**
+   * It sets a given value in the selector caller field (if it exists).
+   * 
+   * @param recordId
+   *          The id of the record to be set in the selector.
+   * @param recordIdentifier
+   *          The identifier of the record to be set in the selector.
+   * @return a ResponseActionsBuilder that contains a 'set selector value' response action.
+   */
+  public ResponseActionsBuilder setSelectorValueFromRecord(String recordId, String recordIdentifier) {
+    try {
+      final JSONObject setSelectorValueFromRecord = new JSONObject();
+      final JSONObject record = new JSONObject();
+      record.put("value", recordId);
+      record.put("map", recordIdentifier);
+      setSelectorValueFromRecord.put("record", record);
+      addResponseAction("setSelectorValueFromRecord", setSelectorValueFromRecord);
+    } catch (JSONException ignore) {
+    }
+    return this;
+  }
+
+  /**
+   * It refreshes the grid where the process button is defined. This is commonly used when the
+   * process adds or deletes records from that grid.
+   * 
+   * @return a ResponseActionsBuilder that contains a 'refresh grid' response action.
+   */
+  public ResponseActionsBuilder refreshGrid() {
+    addResponseAction("refreshGrid", new JSONObject());
+    return this;
+  }
+
+  /**
+   * It refreshes a grid parameter defined within a parameter window. This can be useful for those
+   * parameter windows which are not closed after the execution of the action handler, for example
+   * those process definitions which are directly opened from the application menu.
+   * 
+   * @param gridName
+   *          The name of the grid parameter.
+   * @return a ResponseActionsBuilder that contains a 'refresh grid parameter' response action.
+   */
+  public ResponseActionsBuilder refreshGridParameter(String gridName) {
+    try {
+      final JSONObject refreshGrid = new JSONObject();
+      refreshGrid.put("gridName", gridName);
+      addResponseAction("refreshGridParameter", refreshGrid);
+    } catch (JSONException ignore) {
+    }
+    return this;
+  }
+
+  /**
+   * Allows to re-execute the process again, by enabling the process UI. This is useful to do
+   * backend validations as this allows the user to fix data and resubmit again.
+   * 
+   * @return a ResponseActionsBuilder configured to retry the process execution.
+   */
+  public ResponseActionsBuilder retryExecution() {
+    retryExecution = true;
+    return this;
+  }
+
+  /**
+   * Allows to re-execute the process again, by enabling the process UI. This is useful to do
+   * backend validations as this allows the user to fix data and resubmit again. In addition, a
+   * message will be displayed with the severity and the text specified with the parameters of this
+   * method.
+   * 
+   * @param msgType
+   *          The message type.
+   * @param msgText
+   *          The text of the message.
+   * @return a ResponseActionsBuilder configured to retry the process execution.
+   */
+  public ResponseActionsBuilder retryExecution(MessageType msgType, String msgText) {
+    try {
+      retryExecution = true;
+      retryExecutionMsg = new JSONObject();
+      retryExecutionMsg.put("msgType", msgType.getType());
+      retryExecutionMsg.put("text", msgText);
+    } catch (JSONException ignore) {
+    }
+    return this;
+  }
+
+  /**
+   * Allows to configure the response to show the result of a process directly in the process window
+   * itself.
+   * 
+   * @return a ResponseActionsBuilder configured to show the result in the process window itself.
+   */
+  public ResponseActionsBuilder showResultsInProcessView() {
+    showResultsInProcessView = true;
+    return this;
+  }
+
+  /**
+   * Generates the JSON with the response actions to be executed once the process has finished.
+   * 
+   * @return a JSONObject with the response actions.
+   */
+  public JSONObject build() {
+    try {
+      final JSONObject result = new JSONObject();
+      if (responseActions.length() > 0) {
+        result.put("responseActions", responseActions);
+      }
+      if (retryExecution) {
+        result.put("retryExecution", true);
+        if (retryExecutionMsg != null) {
+          result.put("message", retryExecutionMsg);
+        }
+      }
+      if (showResultsInProcessView) {
+        result.put("showResultsInProcessView", true);
+      }
+      return result;
+    } catch (JSONException jsonex) {
+      log.error("Error building process response actions", jsonex);
+      return new JSONObject();
+    }
+  }
+
+  private void addResponseAction(String actionName, JSONObject actionData) {
+    try {
+      final JSONObject responseAction = new JSONObject();
+      responseAction.put(actionName, actionData);
+      responseActions.put(responseAction);
+    } catch (JSONException jsonex) {
+      log.error("Error adding response action {}", actionName, jsonex);
+    }
+  }
+
+  private JSONObject buildResponseMessage(MessageType msgType, String msgTitle, String msgText) {
+    JSONObject message = new JSONObject();
+    try {
+      message.put("msgType", msgType.getType());
+      message.put("msgTitle", msgTitle);
+      message.put("msgText", msgText);
+    } catch (JSONException ignore) {
+    }
+    return message;
+  }
+
+}
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/report/BaseReportActionHandler.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/report/BaseReportActionHandler.java	Wed Mar 15 18:56:27 2017 +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-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2014-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -56,6 +56,7 @@
 import org.openbravo.client.application.Parameter;
 import org.openbravo.client.application.ReportDefinition;
 import org.openbravo.client.application.process.BaseProcessActionHandler;
+import org.openbravo.client.application.process.ResponseActionsBuilder.MessageType;
 import org.openbravo.client.application.report.ReportingUtils.ExportType;
 import org.openbravo.client.kernel.KernelConstants;
 import org.openbravo.client.kernel.RequestContext;
@@ -64,6 +65,7 @@
 import org.openbravo.dal.core.DalContextListener;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.database.ConnectionProvider;
+import org.openbravo.database.SessionInfo;
 import org.openbravo.erpCommon.utility.OBMessageUtils;
 import org.openbravo.userinterface.selector.reference.FKMultiSelectorUIDefinition;
 import org.openbravo.utils.FileUtility;
@@ -109,42 +111,28 @@
       }
       return;
     }
+    SessionInfo.auditThisThread(false);
     super.execute();
   }
 
   @Override
   protected JSONObject doExecute(Map<String, Object> parameters, String content) {
 
-    JSONObject result = new JSONObject();
     try {
-      result.put("retryExecution", true);
-      result.put("showResultsInProcessView", true);
+      JSONObject result = getResponseBuilder().retryExecution().showResultsInProcessView().build();
 
       final JSONObject jsonContent = new JSONObject(content);
       final String action = jsonContent.getString(ApplicationConstants.BUTTON_VALUE);
       doGenerateReport(result, parameters, jsonContent, action);
 
       return result;
-    } catch (OBException e) {
-      log.error("Error generating report id: {}", parameters.get("reportId"), e);
-      JSONObject msg = new JSONObject();
-      try {
-        msg.put("severity", "error");
-        msg.put("text", OBMessageUtils.translateError(e.getMessage()).getMessage());
-        result.put("message", msg);
-      } catch (JSONException ignore) {
-      }
-      return result;
     } catch (Exception e) {
       log.error("Error generating report id: {}", parameters.get("reportId"), e);
-      JSONObject msg = new JSONObject();
-      try {
-        msg.put("severity", "error");
-        msg.put("text", OBMessageUtils.translateError(e.getMessage()).getMessage());
-        result.put("message", msg);
-      } catch (JSONException ignore) {
-      }
-      return result;
+      return getResponseBuilder()
+          .retryExecution()
+          .showResultsInProcessView()
+          .showMsgInProcessView(MessageType.ERROR,
+              OBMessageUtils.translateError(e.getMessage()).getMessage()).build();
     }
   }
 
@@ -183,6 +171,8 @@
       expType = ExportType.PDF;
     } else if (strFileName.endsWith("." + ExportType.XLS.getExtension())) {
       expType = ExportType.XLS;
+    } else if (strFileName.endsWith("." + ExportType.XLSX.getExtension())) {
+      expType = ExportType.XLSX;
     } else {
       throw new IllegalArgumentException("Trying to download report file with unsupported type "
           + strFileName);
@@ -263,6 +253,7 @@
     String strJRPath = "";
     switch (expType) {
     case XLS:
+    case XLSX:
       if (report.isUsePDFAsXLSTemplate()) {
         strJRPath = report.getPDFTemplate();
       } else {
@@ -314,7 +305,7 @@
         parameters.get("reportId"));
 
     doValidations(report, parameters, jsonContent);
-    final ExportType expType = ExportType.getExportType(action);
+    final ExportType expType = getExportType(action);
 
     String strFileName = getReportFileName(report, parameters, expType);
     String strTmpFileName = UUID.randomUUID().toString() + "." + expType.getExtension();
@@ -362,6 +353,13 @@
     result.put("responseActions", actions);
   }
 
+  private ExportType getExportType(String action) {
+    if (ExportType.XLS.hasExtension(action)) {
+      return ReportingUtils.getExcelExportType();
+    }
+    return ExportType.getExportType(action);
+  }
+
   /**
    * Override this method to add validations to the report before it is generated.
    * 
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/report/ReportingUtils.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/report/ReportingUtils.java	Wed Mar 15 18:56:27 2017 +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-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -36,6 +36,7 @@
 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpSession;
 
+import org.apache.commons.lang.StringUtils;
 import org.openbravo.base.ConfigParameters;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.session.OBPropertiesProvider;
@@ -45,6 +46,7 @@
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.database.ConnectionProvider;
+import org.openbravo.erpCommon.businessUtility.Preferences;
 import org.openbravo.erpCommon.utility.JRFormatFactory;
 import org.openbravo.erpCommon.utility.OBMessageUtils;
 import org.openbravo.model.ad.utility.FileType;
@@ -68,7 +70,9 @@
 import net.sf.jasperreports.engine.export.JRCsvExporter;
 import net.sf.jasperreports.engine.export.JRPdfExporter;
 import net.sf.jasperreports.engine.export.JRTextExporter;
+import net.sf.jasperreports.engine.export.JRXlsAbstractExporter;
 import net.sf.jasperreports.engine.export.JRXlsExporter;
+import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
 import net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer;
 import net.sf.jasperreports.engine.util.JRSwapFile;
 import net.sf.jasperreports.engine.xml.JRXmlLoader;
@@ -82,6 +86,7 @@
 import net.sf.jasperreports.export.SimpleTextReportConfiguration;
 import net.sf.jasperreports.export.SimpleWriterExporterOutput;
 import net.sf.jasperreports.export.SimpleXlsReportConfiguration;
+import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;
 import net.sf.jasperreports.export.type.HtmlSizeUnitEnum;
 import net.sf.jasperreports.j2ee.servlets.ImageServlet;
 import net.sf.jasperreports.web.util.WebHtmlResourceHandler;
@@ -348,7 +353,10 @@
       saveTxtReportToFile(jasperPrint, target);
       break;
     case XLS:
-      saveExcelReportToFile(jasperPrint, exportParameters, target);
+      saveExcelReportToFile(new JRXlsExporter(), jasperPrint, exportParameters, target);
+      break;
+    case XLSX:
+      saveExcelReportToFile(new JRXlsxExporter(), jasperPrint, exportParameters, target);
       break;
     case XML:
       JasperExportManager.exportReportToXmlFile(jasperPrint, target.getAbsolutePath(), true);
@@ -389,7 +397,12 @@
       saveTxtReportToOutputStream(jasperPrint, outputStream);
       break;
     case XLS:
-      saveExcelReportToOutputStream(jasperPrint, exportParameters, outputStream);
+      saveExcelReportToOutputStream(new JRXlsExporter(), jasperPrint, exportParameters,
+          outputStream);
+      break;
+    case XLSX:
+      saveExcelReportToOutputStream(new JRXlsxExporter(), jasperPrint, exportParameters,
+          outputStream);
       break;
     case XML:
       JasperExportManager.exportReportToXmlStream(jasperPrint, outputStream);
@@ -533,7 +546,7 @@
   }
 
   /**
-   * Generates an XLS report from a pre-compiled report and returns it into a file.
+   * Generates an Excel report from a pre-compiled report and returns it into a file.
    * 
    * @param jasperPrint
    *          JasperPrint object which contains a compiled report.
@@ -545,9 +558,9 @@
    *           In case there is any error generating the report an exception is thrown with the
    *           error message.
    */
-  private static void saveExcelReportToFile(JasperPrint jasperPrint,
-      Map<Object, Object> exportParameters, File file) throws JRException {
-    final JRXlsExporter excelExporter = new JRXlsExporter();
+  @SuppressWarnings({ "unchecked", "rawtypes" })
+  private static void saveExcelReportToFile(JRXlsAbstractExporter excelExporter,
+      JasperPrint jasperPrint, Map<Object, Object> exportParameters, File file) throws JRException {
     SimpleExporterInput exporterInput = new SimpleExporterInput(jasperPrint);
     SimpleOutputStreamExporterOutput exporterOutput = new SimpleOutputStreamExporterOutput(file);
 
@@ -566,7 +579,7 @@
   }
 
   /**
-   * Generates an XLS report from a pre-compiled report and returns it into an output stream.
+   * Generates an Excel report from a pre-compiled report and returns it into an output stream.
    * 
    * @param jasperPrint
    *          JasperPrint object which contains a compiled report.
@@ -578,9 +591,10 @@
    *           In case there is any error generating the report an exception is thrown with the
    *           error message.
    */
-  private static void saveExcelReportToOutputStream(JasperPrint jasperPrint,
-      Map<Object, Object> exportParameters, OutputStream outputStream) throws JRException {
-    final JRXlsExporter excelExporter = new JRXlsExporter();
+  @SuppressWarnings({ "unchecked", "rawtypes" })
+  private static void saveExcelReportToOutputStream(JRXlsAbstractExporter excelExporter,
+      JasperPrint jasperPrint, Map<Object, Object> exportParameters, OutputStream outputStream)
+      throws JRException {
     SimpleExporterInput exporterInput = new SimpleExporterInput(jasperPrint);
     SimpleOutputStreamExporterOutput exporterOutput = new SimpleOutputStreamExporterOutput(
         outputStream);
@@ -624,6 +638,30 @@
   }
 
   /**
+   * Generates an XLSX report using the SimpleExporterInput, SimpleOutputStreamExporterOutput and
+   * SimpleXlsxReportConfiguration received as parameters.
+   * 
+   * @param exporterInput
+   *          SimpleExporterInput object with the input data.
+   * @param exporterOutput
+   *          SimpleOutputStreamExporterOutput object with the output data.
+   * @param exportConfiguration
+   *          SimpleXlsxReportConfiguration with the configuration data.
+   * @throws JRException
+   *           In case there is any error generating the report an exception is thrown with the
+   *           error message.
+   */
+  public static void saveExcelReport(SimpleExporterInput exporterInput,
+      SimpleOutputStreamExporterOutput exporterOutput,
+      SimpleXlsxReportConfiguration exportConfiguration) throws JRException {
+    final JRXlsxExporter excelExporter = new JRXlsxExporter();
+    excelExporter.setExporterInput(exporterInput);
+    excelExporter.setExporterOutput(exporterOutput);
+    excelExporter.setConfiguration(exportConfiguration);
+    excelExporter.exportReport();
+  }
+
+  /**
    * Generates a CSV report from a pre-compiled report and returns it into a file.
    * 
    * @param jasperPrint
@@ -943,8 +981,9 @@
 
       if (jasperFilePath.endsWith("jrxml")) {
         String strBaseDesign = getBaseDesignPath();
-        JasperReport jReport = getTranslatedJasperReport(new DalConnectionProvider(false),
-            jasperFilePath, language, strBaseDesign);
+        JasperReport jReport = getTranslatedJasperReport(
+            DalConnectionProvider.getReadOnlyConnectionProvider(), jasperFilePath, language,
+            strBaseDesign);
         if (connectionProvider != null) {
           if (compileSubreports) {
             processSubReports(jasperFilePath, parameters, strBaseDesign, connectionProvider,
@@ -975,8 +1014,8 @@
             }
           }
         } else {
-          jasperPrint = JasperFillManager.fillReport(jReport, parameters, OBDal.getInstance()
-              .getConnection());
+          jasperPrint = JasperFillManager.fillReport(jReport, parameters, OBDal
+              .getReadOnlyInstance().getConnection());
         }
       } else {
         jasperPrint = JasperFillManager.fillReport(jasperFilePath, parameters);
@@ -1218,7 +1257,7 @@
    *          Map of parameters where the standard process definition parameters are added.
    */
   private static void addProcessDefinitionParameters(Map<String, Object> parameters) {
-    parameters.put(JASPER_PARAM_HBSESSION, OBDal.getInstance().getSession());
+    parameters.put(JASPER_PARAM_HBSESSION, OBDal.getReadOnlyInstance().getSession());
     parameters.put(JASPER_PARAM_OBCONTEXT, OBContext.getOBContext());
 
     {
@@ -1299,6 +1338,32 @@
   }
 
   /**
+   * Returns the format to be used when exporting Excel reports.
+   * 
+   * @return a ExportType with the default Excel format (XLS or XLSX).
+   */
+  public static ExportType getExcelExportType() {
+    try {
+      OBContext.setAdminMode(true);
+      try {
+        OBContext context = OBContext.getOBContext();
+        String preferenceValue = Preferences.getPreferenceValue("ExcelExportFormat", true,
+            context.getCurrentClient(), context.getCurrentOrganization(), context.getUser(),
+            context.getRole(), null);
+        ExportType exportType = ExportType.getExportType(preferenceValue);
+        if (ExportType.XLS == exportType || ExportType.XLSX == exportType) {
+          return exportType;
+        }
+      } catch (Exception ignore) {
+        // preference not found: return default excel format
+      }
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+    return ExportType.XLSX;
+  }
+
+  /**
    * enum with the supported Export Outputs. Includes custom properties to be used when the report
    * is generated.
    */
@@ -1306,7 +1371,7 @@
     // When IS_IGNORE_PAGINATION is set to true, the report-filling engine will generate the
     // document on a single, very long page. Running the generated report to any output format, a
     // single page document will be visualized. This is the desired behavior for some document
-    // types, such as HTML, XML or XLS.
+    // types, such as HTML, XML, XLS or XLSX.
     // This flag should be false for documents with page-oriented layout, like PDF, to allow the
     // possibility to navigate between pages.
     /**
@@ -1355,6 +1420,15 @@
       }
     }), //
     /**
+     * XLSX export type
+     */
+    @SuppressWarnings("serial")
+    XLSX("xlsx", "", new HashMap<String, Object>() {
+      {
+        put("IS_IGNORE_PAGINATION", true);
+      }
+    }), //
+    /**
      * XML export type
      */
     @SuppressWarnings("serial")
@@ -1364,27 +1438,31 @@
       }
     });
     private final String extension;
-    private final String fileType;
+    private final String contentType;
     private final Map<String, Object> params;
 
     ExportType(String extension, String strFileTypeId, Map<String, Object> params) {
       this.extension = extension;
+      this.contentType = getContentType(strFileTypeId);
+      this.params = params;
+    }
+
+    private String getContentType(String fileTypeId) {
       OBContext.setAdminMode(true);
       try {
-        FileType type = OBDal.getInstance().get(FileType.class, strFileTypeId);
+        FileType type = OBDal.getReadOnlyInstance().get(FileType.class, fileTypeId);
         if (type != null) {
-          fileType = type.getFormat();
+          return type.getFormat();
+        } else if ("html".equals(extension) || "csv".equals(extension)) {
+          return "text/" + extension;
+        } else if ("xlsx".equals(extension)) {
+          return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
         } else {
-          if ("html".equals(extension) || "csv".equals(extension)) {
-            fileType = "text/" + extension;
-          } else {
-            fileType = "application/" + extension;
-          }
+          return "application/" + extension;
         }
       } finally {
         OBContext.restorePreviousMode();
       }
-      this.params = params;
     }
 
     /**
@@ -1398,7 +1476,7 @@
      * @return a String with the content type.
      */
     public String getContentType() {
-      return fileType;
+      return contentType;
     }
 
     /**
@@ -1412,7 +1490,8 @@
     }
 
     /**
-     * Returns the corresponding ExportType item based on the action.
+     * Returns the corresponding ExportType item based on the action. This method is
+     * case-insensitive.
      * 
      * @param action
      *          a String that defines the export type.
@@ -1422,17 +1501,19 @@
      *           an exception is thrown with the error message.
      */
     public static ExportType getExportType(String action) throws OBException {
-      if ("CSV".equals(action)) {
+      if (ExportType.CSV.hasExtension(action)) {
         return ExportType.CSV;
-      } else if ("HTML".equals(action)) {
+      } else if (ExportType.HTML.hasExtension(action)) {
         return ExportType.HTML;
-      } else if ("PDF".equals(action)) {
+      } else if (ExportType.PDF.hasExtension(action)) {
         return ExportType.PDF;
-      } else if ("TXT".equals(action)) {
+      } else if (ExportType.TXT.hasExtension(action)) {
         return ExportType.TXT;
-      } else if ("XLS".equals(action)) {
+      } else if (ExportType.XLS.hasExtension(action)) {
         return ExportType.XLS;
-      } else if ("XML".equals(action)) {
+      } else if (ExportType.XLSX.hasExtension(action)) {
+        return ExportType.XLSX;
+      } else if (ExportType.XML.hasExtension(action)) {
         return ExportType.XML;
       } else {
         throw new OBException(OBMessageUtils.getI18NMessage("OBUIAPP_UnsupportedAction",
@@ -1441,6 +1522,22 @@
     }
 
     /**
+     * Checks if the extension of the the ExportType is the same as the one passed as parameter.
+     * This method is case-insensitive.
+     * 
+     * @param fileExtension
+     *          a String containing a file extension name.
+     * @return true if the extension of the ExportType is the same as the one passed as parameter,
+     *         false otherwise.
+     */
+    public boolean hasExtension(String fileExtension) {
+      if (StringUtils.isEmpty(fileExtension)) {
+        return false;
+      }
+      return extension.equals(fileExtension.toLowerCase());
+    }
+
+    /**
      * Checks if temporary file name is a valid one: has extension and the name is a uuid.
      * 
      * @param tmpFileName
@@ -1472,7 +1569,13 @@
     return tmpFolder;
   }
 
-  private static String getBaseDesignPath() {
+  /**
+   * Returns the relative path to the default design sub-folder within the context's base design
+   * folder.
+   * 
+   * @return a String with the relative path to the default design sub-folder.
+   */
+  public static String getBaseDesign() {
     ServletContext servletContext = DalContextListener.getServletContext();
     ConfigParameters configParameters = ConfigParameters.retrieveFrom(servletContext);
 
@@ -1482,6 +1585,11 @@
     if (!base.startsWith("/")) {
       base = "/" + base;
     }
-    return servletContext.getRealPath(base + "/" + design);
+    return base + "/" + design;
+  }
+
+  private static String getBaseDesignPath() {
+    ServletContext servletContext = DalContextListener.getServletContext();
+    return servletContext.getRealPath(getBaseDesign());
   }
 }
\ No newline at end of file
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/ApplicationDictionaryCachedStructures.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/ApplicationDictionaryCachedStructures.java	Wed Mar 15 18:56:27 2017 +0100
@@ -11,21 +11,20 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2011-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
  */
 package org.openbravo.client.application.window;
 
-import java.io.Serializable;
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 
-import javax.enterprise.context.SessionScoped;
+import javax.annotation.PostConstruct;
+import javax.enterprise.context.ApplicationScoped;
 
 import org.hibernate.Hibernate;
 import org.hibernate.Query;
@@ -58,29 +57,52 @@
  * caching occurs to obtain better performance in FIC computations. For this cache to be used, the
  * system needs to be on 'production' mode, that is, all the modules need to be not in development
  */
-@SessionScoped
-public class ApplicationDictionaryCachedStructures implements Serializable {
-  private static final long serialVersionUID = 1L;
-
-  private Map<String, Tab> tabMap = new HashMap<String, Tab>();
-  private Map<String, Table> tableMap = new HashMap<String, Table>();
-  private Map<String, List<Field>> fieldMap = new HashMap<String, List<Field>>();
-  private Map<String, List<Column>> columnMap = new HashMap<String, List<Column>>();
-  private Map<String, List<AuxiliaryInput>> auxInputMap = new HashMap<String, List<AuxiliaryInput>>();
-  private Map<String, ComboTableData> comboTableDataMap = new ConcurrentHashMap<String, ComboTableData>();
-  private Map<String, List<Parameter>> attMethodMetadataMap = new ConcurrentHashMap<String, List<Parameter>>();
-  private List<String> initializedWindows = new ArrayList<String>();
-
+@ApplicationScoped
+public class ApplicationDictionaryCachedStructures {
   private static final Logger log = LoggerFactory
       .getLogger(ApplicationDictionaryCachedStructures.class);
 
+  private Map<String, Tab> tabMap;
+  private Map<String, Table> tableMap;
+  private Map<String, List<Field>> fieldMap;
+  private Map<String, List<Column>> columnMap;
+  private Map<String, List<AuxiliaryInput>> auxInputMap;
+  private Map<String, ComboTableData> comboTableDataMap;
+  private Map<String, List<Parameter>> attMethodMetadataMap;
+  private List<String> initializedWindows;
+
   private boolean useCache;
 
-  public ApplicationDictionaryCachedStructures() {
+  private Map<String, Object> tabLocks;
+  private Object getTabLock = new Object();
+  private Object initializeWindowLock = new Object();
+  private Map<String, Object> windowLocks;
+
+  /**
+   * Resets cache and sets whether cache should be used.
+   *
+   * This method is automatically invoked on creation.
+   */
+  @PostConstruct
+  public void init() {
+    log.debug("Resetting cache");
+    tabMap = new ConcurrentHashMap<>();
+    tableMap = new ConcurrentHashMap<>();
+    fieldMap = new ConcurrentHashMap<>();
+    columnMap = new ConcurrentHashMap<>();
+    auxInputMap = new ConcurrentHashMap<>();
+    comboTableDataMap = new ConcurrentHashMap<>();
+    attMethodMetadataMap = new ConcurrentHashMap<>();
+    initializedWindows = new ArrayList<String>();
+    tabLocks = new ConcurrentHashMap<>();
+    windowLocks = new ConcurrentHashMap<>();
+
     // The cache will only be active when there are no modules in development in the system
-    final String query = "select m from ADModule m where m.inDevelopment=true";
+    final String query = "select 1 from ADModule m where m.inDevelopment=true";
     final Query indevelMods = OBDal.getInstance().getSession().createQuery(query);
+    indevelMods.setMaxResults(1);
     useCache = indevelMods.list().size() == 0;
+    log.info("ADCS initialized, use cache: {}", useCache);
   }
 
   /**
@@ -95,21 +117,36 @@
    *          , ID of the tab to look for
    * @return Tab for the tabId, from cache if it is enabled
    */
-  public synchronized Tab getTab(String tabId) {
+  public Tab getTab(String tabId) {
     log.debug("get tab {}", tabId);
-    if (useCache() && tabMap.containsKey(tabId)) {
+    if (!useCache()) {
+      // not using cache, initialize just current tab and go
+      return OBDal.getInstance().get(Tab.class, tabId);
+    }
+
+    if (tabMap.containsKey(tabId)) {
       log.debug("got tab {} from cache", tabId);
       return tabMap.get(tabId);
     }
-    Tab tab = OBDal.getInstance().get(Tab.class, tabId);
-    if (!useCache()) {
-      // not using cache, initialize just current tab and go
+
+    // tab is not cached: lock at method level to acquire a lock to initialize it
+    synchronized (getTabLock) {
+      // now we can safely check if lock for tab is not set and create it
+      if (!tabLocks.containsKey(tabId)) {
+        tabLocks.put(tabId, new Object());
+      }
+    }
+
+    // lock for tab id, so it only gets initialized once
+    synchronized (tabLocks.get(tabId)) {
+      if (tabMap.containsKey(tabId)) {
+        // another thread already cached this tab
+        return tabMap.get(tabId);
+      }
+      Tab tab = OBDal.getInstance().get(Tab.class, tabId);
+      initializeWindow(tab.getWindow().getId());
       return tab;
-    } else {
-      // using cache, do complete initialization
-      initializeWindow(tab.getWindow().getId());
     }
-    return tab;
   }
 
   /**
@@ -119,11 +156,26 @@
     if (!useCache() || initializedWindows.contains(windowId)) {
       return;
     }
-    Window window = OBDal.getInstance().get(Window.class, windowId);
-    for (Tab tab : window.getADTabList()) {
-      initializeTab(tab);
+    synchronized (initializeWindowLock) {
+      if (!windowLocks.containsKey(windowId)) {
+        windowLocks.put(windowId, new Object());
+      }
     }
-    initializedWindows.add(windowId);
+
+    synchronized (windowLocks.get(windowId)) {
+      if (initializedWindows.contains(windowId)) {
+        return;
+      }
+
+      Window window = OBDal.getInstance().get(Window.class, windowId);
+      for (Tab tab : window.getADTabList()) {
+        initializeTab(tab);
+      }
+
+      synchronized (initializedWindows) {
+        initializedWindows.add(windowId);
+      }
+    }
   }
 
   /**
@@ -136,14 +188,16 @@
   private void initializeTab(Tab tab) {
     String tabId = tab.getId();
     initializeDALObject(tab);
+
+    // initialize other elements related with the tab
+    getAuxiliarInputList(tab);
+    getFieldsOfTab(tab);
+    initializeDALObject(tab.getTable());
+    getColumnsOfTable(tab.getTable().getId());
+
     if (useCache()) {
       tabMap.put(tabId, tab);
     }
-    // initialize other elements related with the tab
-    getAuxiliarInputList(tabId);
-    getFieldsOfTab(tabId);
-    initializeDALObject(tab.getTable());
-    getColumnsOfTable(tab.getTable().getId());
   }
 
   public Table getTable(String tableId) {
@@ -164,6 +218,10 @@
       return fieldMap.get(tabId);
     }
     Tab tab = getTab(tabId);
+    return getFieldsOfTab(tab);
+  }
+
+  public List<Field> getFieldsOfTab(Tab tab) {
     String tableId = tab.getTable().getId();
     List<Field> fields = tab.getADFieldList();
     for (Field f : fields) {
@@ -180,7 +238,7 @@
       }
     }
     if (useCache()) {
-      fieldMap.put(tabId, fields);
+      fieldMap.put(tab.getId(), fields);
     }
     return fields;
   }
@@ -201,7 +259,6 @@
   }
 
   private void initializeColumn(Column c) {
-
     initializeDALObject(c.getValidation());
     if (c.getValidation() != null) {
       initializeDALObject(c.getValidation().getValidationCode());
@@ -221,7 +278,6 @@
     if (c.getReferenceSearchKey() != null) {
       initializeReference(c.getReferenceSearchKey());
     }
-
   }
 
   private void initializeReference(Reference reference) {
@@ -229,17 +285,22 @@
     for (ReferencedTable t : reference.getADReferencedTableList()) {
       initializeDALObject(t);
     }
+
     initializeDALObject(reference.getOBUISELSelectorList());
     for (Selector s : reference.getOBUISELSelectorList()) {
       initializeDALObject(s);
       SelectorField displayField = s.getDisplayfield();
       initializeDALObject(displayField);
     }
+
+    initializeDALObject(reference.getADReferencedTreeList());
     for (ReferencedTree t : reference.getADReferencedTreeList()) {
       initializeDALObject(t);
       ReferencedTreeField displayField = t.getDisplayfield();
       initializeDALObject(displayField);
     }
+
+    initializeDALObject(reference.getADListList());
     for (org.openbravo.model.ad.domain.List list : reference.getADListList()) {
       initializeDALObject(list);
     }
@@ -251,21 +312,33 @@
       return auxInputMap.get(tabId);
     }
     Tab tab = getTab(tabId);
+    return getAuxiliarInputList(tab);
+  }
+
+  private List<AuxiliaryInput> getAuxiliarInputList(Tab tab) {
     initializeDALObject(tab.getADAuxiliaryInputList());
     List<AuxiliaryInput> auxInputs = new ArrayList<AuxiliaryInput>(tab.getADAuxiliaryInputList());
     for (AuxiliaryInput auxIn : auxInputs) {
       initializeDALObject(auxIn);
     }
     if (useCache()) {
-      auxInputMap.put(tabId, auxInputs);
+      auxInputMap.put(tab.getId(), auxInputs);
     }
     return auxInputs;
   }
 
-  private synchronized void initializeDALObject(Object obj) {
-    Hibernate.initialize(obj);
+  private void initializeDALObject(Object obj) {
+    if (obj == null) {
+      return;
+    }
+    synchronized (obj) {
+      Hibernate.initialize(obj);
+    }
   }
 
+  /**
+   * @deprecated use {@link #getComboTableData(Field)}
+   */
   public ComboTableData getComboTableData(VariablesSecureApp vars, String ref, String colName,
       String objectReference, String validation, String orgList, String clientList) {
     String comboId = ref + colName + objectReference + validation + orgList + clientList;
@@ -283,7 +356,30 @@
       comboTableDataMap.put(comboId, comboTableData);
     }
     return comboTableData;
+  }
 
+  /**
+   * Returns the combo for the given field from cache if present, if not it also gets cached if
+   * applicable.
+   */
+  public ComboTableData getComboTableData(Field field) {
+    String comboId = field.getId();
+    if (useCache() && comboTableDataMap.get(comboId) != null) {
+      return comboTableDataMap.get(comboId);
+    }
+
+    ComboTableData comboTableData;
+    try {
+      comboTableData = ComboTableData.getTableComboDataFor(field);
+    } catch (Exception e) {
+      throw new OBException("Error while computing combo table data for field " + field, e);
+    }
+
+    log.debug("Combo - cacheable: {} id: {}", comboTableData.canBeCached(), comboId);
+    if (useCache() && comboTableData.canBeCached()) {
+      comboTableDataMap.put(comboId, comboTableData);
+    }
+    return comboTableData;
   }
 
   /**
@@ -340,7 +436,8 @@
     }
   }
 
-  private boolean useCache() {
+  /** Can cache be used, AD components are cacheable if there are no modules in development */
+  public boolean useCache() {
     return useCache;
   }
 }
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/FormInitializationComponent.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/FormInitializationComponent.java	Wed Mar 15 18:56:27 2017 +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) 2010-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -77,7 +77,6 @@
 import org.openbravo.erpCommon.ad_callouts.SimpleCalloutInformationProvider;
 import org.openbravo.erpCommon.utility.Utility;
 import org.openbravo.model.ad.datamodel.Column;
-import org.openbravo.model.ad.domain.Preference;
 import org.openbravo.model.ad.domain.ReferencedTable;
 import org.openbravo.model.ad.ui.AuxiliaryInput;
 import org.openbravo.model.ad.ui.Field;
@@ -1599,19 +1598,10 @@
                     .getLanguage()));
             message.put("severity", "TYPE_ERROR");
             messages.add(message);
-            // Create preference to activate classic window only for HttpServlet callouts and in
-            // other cases error is shown.
-            if (calloutInformationProvider instanceof HttpServletCalloutInformationProvider) {
-              createNewPreferenceForWindow(tab.getWindow());
-              log.warn("An EXECUTE element has been found in the response of the callout "
-                  + calloutClassName
-                  + ". A preference has been created for the window "
-                  + tab.getWindow().getName()
-                  + " so that it's shown in classic mode until this problem is fixed. This requires to build the system to generate this classic window.");
-            } else {
-              log.error("An EXECUTE element has been found in the response of the SimpleCallout "
-                  + calloutClassName + ".");
-            }
+            log.warn("Callout "
+                + calloutClassName
+                + " returned EXECUTE command which is no longer supported, it should be fixed. Window-tab: "
+                + tab.getWindow().getName() + " - " + tab.getName());
           }
         }
       } else {
@@ -1728,29 +1718,6 @@
         .getJavaClassName());
   }
 
-  /**
-   * This method will create a new preference to show the given window in classic mode, if there is
-   * a preference doesn't already exist
-   * 
-   * @param window
-   */
-  private void createNewPreferenceForWindow(Window window) {
-    OBCriteria<Preference> prefCriteria = OBDao.getFilteredCriteria(Preference.class,
-        Restrictions.eq(Preference.PROPERTY_PROPERTY, "OBUIAPP_UseClassicMode"),
-        Restrictions.eq(Preference.PROPERTY_WINDOW, window));
-    if (prefCriteria.count() > 0) {
-      // Preference already exists. We don't create a new one.
-      return;
-    }
-    Preference newPref = OBProvider.getInstance().get(Preference.class);
-    newPref.setWindow(window);
-    newPref.setProperty("OBUIAPP_UseClassicMode");
-    newPref.setSearchKey("Y");
-    newPref.setPropertyList(true);
-    OBDal.getInstance().save(newPref);
-    OBDal.getInstance().flush();
-  }
-
   private void addCalloutToList(Column col, List<String> listOfCallouts,
       List<String> lastFieldChangedList) {
     if (col.getCallout().getADModelImplementationList() == null
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/OBViewFieldHandler.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/OBViewFieldHandler.java	Wed Mar 15 18:56:27 2017 +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) 2011-2016 Openbravo SLU
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -23,8 +23,10 @@
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 import javax.script.ScriptEngine;
 import javax.script.ScriptEngineManager;
@@ -122,7 +124,7 @@
     final List<Field> adFields = new ArrayList<Field>(tab.getADFieldList());
     Collections.sort(adFields, new FormFieldComparator());
 
-    final List<Field> fieldsInDynamicExpression = new ArrayList<Field>();
+    final Set<String> fieldsInDynamicExpression = new HashSet<>();
     final Map<Field, String> displayLogicMap = new HashMap<Field, String>();
     final Map<Field, String> displayLogicGridMap = new HashMap<Field, String>();
     final Map<Field, String> readOnlyLogicMap = new HashMap<Field, String>();
@@ -146,9 +148,7 @@
       log.debug(f.getTab().getId() + " - " + f.getName() + " >>> " + parser.getJSExpression());
 
       for (Field fieldExpression : parser.getFields()) {
-        if (!fieldsInDynamicExpression.contains(fieldExpression)) {
-          fieldsInDynamicExpression.add(fieldExpression);
-        }
+        fieldsInDynamicExpression.add(fieldExpression.getId());
         // All the properties that are used in the display logic of the buttons must be included in
         // the list of grid mandatory columns
         if ("Button".equals(f.getColumn().getReference().getName())) {
@@ -183,9 +183,7 @@
       log.debug(f.getTab().getId() + " - " + f.getName() + " >>> " + parser.getJSExpression());
 
       for (Field fieldExpression : parser.getFields()) {
-        if (!fieldsInDynamicExpression.contains(fieldExpression)) {
-          fieldsInDynamicExpression.add(fieldExpression);
-        }
+        fieldsInDynamicExpression.add(fieldExpression.getId());
       }
     }
 
@@ -204,9 +202,7 @@
       log.debug(f.getTab().getId() + " - " + f.getName() + " >>> " + parser.getJSExpression());
 
       for (Field fieldExpression : parser.getFields()) {
-        if (!fieldsInDynamicExpression.contains(fieldExpression)) {
-          fieldsInDynamicExpression.add(fieldExpression);
-        }
+        fieldsInDynamicExpression.add(fieldExpression.getId());
       }
     }
 
@@ -288,7 +284,7 @@
         final OBClientClassField viewField = new OBClientClassField();
 
         viewField.setField(field);
-        viewField.setRedrawOnChange(fieldsInDynamicExpression.contains(field));
+        viewField.setRedrawOnChange(fieldsInDynamicExpression.contains(field.getId()));
         viewField.setShowIf(displayLogicMap.get(field) != null ? displayLogicMap.get(field) : "");
         viewField.setDisplayLogicGrid(displayLogicGridMap.get(field) != null ? displayLogicGridMap
             .get(field) : "");
@@ -338,7 +334,7 @@
 
         viewField.setField(field);
         viewField.setId(field);
-        viewField.setRedrawOnChange(fieldsInDynamicExpression.contains(field));
+        viewField.setRedrawOnChange(fieldsInDynamicExpression.contains(field.getId()));
         viewField.setShowIf(displayLogicMap.get(field) != null ? displayLogicMap.get(field) : "");
         viewField.setDisplayLogicGrid(displayLogicGridMap.get(field) != null ? displayLogicGridMap
             .get(field) : "");
@@ -726,6 +722,7 @@
           result.append(", canFilter: " + canFilter.toString());
         }
       }
+      result.append(", showHover: true");
       return result.toString();
     }
 
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/OBViewTab.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/OBViewTab.java	Wed Mar 15 18:56:27 2017 +0100
@@ -757,7 +757,6 @@
   }
 
   public class ButtonField {
-    private static final String AD_DEF_ERROR = "AD definition error: process parameter (%s) is using %s reference without %s";
     private String id;
     private String label;
     private String url;
@@ -803,9 +802,6 @@
         if ("OBUIAPP_PickAndExecute".equals(uiPattern)) {
           // TODO: modal should be a parameter in the process definition?
           modal = false;
-          for (org.openbravo.client.application.Parameter p : newProcess.getOBUIAPPParameterList()) {
-            processParameter(p);
-          }
         }
       } else if (column.getProcess() != null) {
         process = column.getProcess();
@@ -845,6 +841,7 @@
 
       if (labelValues == null) {
         labelValues = new ArrayList<Value>();
+
         if (column.getReferenceSearchKey() != null) {
           for (org.openbravo.model.ad.domain.List valueList : column.getReferenceSearchKey()
               .getADListList()) {
@@ -874,20 +871,6 @@
       }
     }
 
-    private void processParameter(org.openbravo.client.application.Parameter p) {
-      if (p.getReference().getId().equals(ApplicationConstants.BUTTON_LIST_REFERENCE_ID)) {
-        labelValues = new ArrayList<Value>();
-        for (org.openbravo.model.ad.domain.List valueList : p.getReferenceSearchKey()
-            .getADListList()) {
-          labelValues.add(new Value(valueList));
-        }
-        if (labelValues.size() == 0) {
-          log.error(String.format(AD_DEF_ERROR, p.getId(), "Button List", "a list associated"));
-        }
-        return;
-      }
-    }
-
     public boolean isAutosave() {
       return autosave;
     }
--- a/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/form/formitem/ob-formitem-fk-filter.js	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/form/formitem/ob-formitem-fk-filter.js	Wed Mar 15 18:56:27 2017 +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) 2011-2016 Openbravo SLU
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -574,12 +574,14 @@
     }
   },
 
-  // for Table reference the displayProperty is used in the filtering criteria instead of OB.Constants.IDENTIFIER
-  // see issue https://issues.openbravo.com/view.php?id=30800
+  // for Table references the property name used in the criteria depends on the type of filtering
+  // when the filtering is done in the server, the displayProperty is used
+  // on adaptive filtering (client side), OB.Constants.IDENTIFIER is used
   getDisplayProperty: function () {
     var theGrid = this.grid,
         name = this.name;
-    if (theGrid && name && theGrid.getField(name) && theGrid.getField(name).displayProperty) {
+    // Use willFetchData() to identify whether we are performing adaptive filtering
+    if (theGrid && name && theGrid.getField(name) && theGrid.getField(name).displayProperty && this.form.grid.sourceWidget.willFetchData()) {
       return name + OB.Constants.FIELDSEPARATOR + theGrid.getField(name).displayProperty;
     }
     return null;
--- a/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/process/ob-parameter-window-view.js	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/process/ob-parameter-window-view.js	Wed Mar 15 18:56:27 2017 +0100
@@ -290,11 +290,15 @@
         }
       };
       if (refreshParent) {
-        if (this.callerField && this.callerField.view && typeof this.callerField.view.onRefreshFunction === 'function') {
-          // In this case we are inside a process called from another process, so we want to refresh the caller process instead of the main window.
-          this.callerField.view.onRefreshFunction(this.callerField.view);
+        if (this.button && this.button.multiRecord) {
+          this.buttonOwnerView.refresh(afterRefreshCallback);
         } else {
-          this.buttonOwnerView.refreshCurrentRecord(afterRefreshCallback);
+          if (this.callerField && this.callerField.view && typeof this.callerField.view.onRefreshFunction === 'function') {
+            // In this case we are inside a process called from another process, so we want to refresh the caller process instead of the main window.
+            this.callerField.view.onRefreshFunction(this.callerField.view);
+          } else {
+            this.buttonOwnerView.refreshCurrentRecord(afterRefreshCallback);
+          }
         }
       }
 
@@ -312,9 +316,21 @@
 
   doProcess: function (btnValue) {
     var i, tmp, view = this,
-        grid, allProperties = this.getUnderLyingRecordContext(false, true, false, true),
-        selection, len, allRows, params, tab, actionHandlerCall, clientSideValidationFail;
-    // activeView = view.parentWindow && view.parentWindow.activeView,  ???.
+        grid, allProperties, selection, len, allRows, params, tab, actionHandlerCall, clientSideValidationFail, selectedRecords, recordIds;
+
+    if (this.button && this.button.multiRecord) {
+      selectedRecords = this.buttonOwnerView.viewGrid.getSelectedRecords();
+      recordIds = [];
+      for (i = 0; i < selectedRecords.length; i++) {
+        recordIds.push(selectedRecords.get(i).id);
+      }
+      allProperties = {
+        recordIds: recordIds
+      };
+    } else {
+      allProperties = this.getUnderLyingRecordContext(false, true, false, true);
+    }
+
     if (this.resultLayout && this.resultLayout.destroy) {
       this.resultLayout.destroy();
       delete this.resultLayout;
--- a/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/toolbar/ob-action-button.js	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/toolbar/ob-action-button.js	Wed Mar 15 18:56:27 2017 +0100
@@ -65,7 +65,7 @@
         me = this,
         standardWindow = this.view.standardWindow,
         autosaveButton = this.autosave,
-        param, allProperties, sessionProperties, callbackFunction, popupParams, errorCallback;
+        param, allProperties, sessionProperties, callbackFunction, popupParams, errorCallback, parameters;
     //Modified check from 'rowNum to 'rowNum ! = null' to handle case where rowNum is 0.
     if (rowNum !== null && !theView.viewGrid.getSelectedRecord()) {
       // Current selection was lost, restore it
@@ -91,17 +91,20 @@
 
     // obuiapp_process definition
     if (this.newDefinition) {
+      parameters = {
+        paramWindow: true,
+        processId: me.processId,
+        windowId: me.windowId,
+        windowTitle: me.windowTitle || me.realTitle,
+        actionHandler: me.command,
+        button: me,
+        uiPattern: me.uiPattern
+      };
+      if (me.uiPattern === 'M') {
+        parameters.buttons = me.labelValue;
+      }
       callbackFunction = function () {
-        standardWindow.openProcess({
-          paramWindow: true,
-          processId: me.processId,
-          windowId: me.windowId,
-          windowTitle: me.windowTitle || me.realTitle,
-          actionHandler: me.command,
-          button: me,
-          buttons: me.labelValue,
-          uiPattern: me.uiPattern
-        });
+        standardWindow.openProcess(parameters);
         me.opening = false; // Activate again the button
       };
 
@@ -302,7 +305,7 @@
       readonly = false;
       this.visible = true;
       for (i = 0; i < selection.length; i++) {
-        currentValues = selection[i];
+        currentValues = isc.shallowClone(selection[i]);
         OB.Utilities.fixNull250(currentValues);
         this.visible = this.visible && (!this.displayIf || (context && this.displayIf(this.contextView.viewForm, currentValues, context)));
         readonly = readonly || (this.readOnlyIf && context && this.readOnlyIf(this.contextView.viewForm, currentValues, context));
--- a/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/utilities/ob-onchange-functions.js	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/utilities/ob-onchange-functions.js	Wed Mar 15 18:56:27 2017 +0100
@@ -40,4 +40,20 @@
   if (item.getValue() === 'OBUIAPP_Report' && !classNameItem.getValue()) {
     classNameItem.setValue('org.openbravo.client.application.report.BaseReportActionHandler');
   }
+};
+
+//**  {{{OB.OnChange.agingProcessDefinitionOverdue}}}**
+//Used by the parameters Overdue Days in Payable and Receivables Aging Balance Process Definition Reports.
+//A warning message is shown if the range of overdue days is not correct.
+OB.OnChange.agingProcessDefinitionOverdue = function (item, view, form, grid) {
+  var column1 = form.getItem('Column1').getValue();
+  var column2 = form.getItem('Column2').getValue();
+  var column3 = form.getItem('Column3').getValue();
+  var column4 = form.getItem('Column4').getValue();
+  if (column1 && column2 && column3 && column4 && !((column1 < column2 && column2 < column3 && column3 < column4))) {
+    item.setValue('');
+    view.messageBar.setMessage(isc.OBMessageBar.TYPE_WARNING, null, OB.I18N.getLabel('OBUIAPP_OverdueNotValid'));
+  } else {
+    view.messageBar.hide();
+  }
 };
\ No newline at end of file
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/BaseComponent.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/BaseComponent.java	Wed Mar 15 18:56:27 2017 +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) 2010-2011 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -57,6 +57,8 @@
   // data object can be a grid object or a selector etc.
   private Map<String, Object> parameters = new HashMap<String, Object>();
   private String id;
+  private String identifier;
+
   private Module module = null;
 
   private List<Component> dependencies = new ArrayList<Component>();
@@ -125,6 +127,15 @@
     this.id = id;
   }
 
+  protected void setIdentifier(String identifier) {
+    this.identifier = identifier;
+  }
+
+  /** returns a human readable identifier to be used in logging */
+  String getIdentifier() {
+    return identifier == null ? id : identifier;
+  }
+
   public abstract Object getData();
 
   public Map<String, Object> getParameters() {
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/ComponentGenerator.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/ComponentGenerator.java	Wed Mar 15 18:56:27 2017 +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) 2010-2011 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -68,8 +68,14 @@
           final String errors = JSLintChecker.getInstance().check(
               component.getModule().getName() + "." + component.getId(), originalResult);
           if (errors != null) {
-            log.error("Error parsing component "
-                + (component.getId() != null ? component.getId() : "") + "\n" + errors);
+            String identifier;
+            if (component instanceof BaseComponent) {
+              identifier = ((BaseComponent) component).getIdentifier();
+            } else {
+              identifier = component.getId();
+            }
+            log.error("Error parsing component " + (identifier != null ? identifier : "") + "\n"
+                + errors);
           }
         }
       }
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/BinaryUIDefinition.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/BinaryUIDefinition.java	Wed Mar 15 18:56:27 2017 +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) 2010-2013 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -40,6 +40,11 @@
   }
 
   @Override
+  public boolean showHover() {
+    return false;
+  }
+
+  @Override
   public String getParentType() {
     return "image";
   }
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/EnumUIDefinition.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/EnumUIDefinition.java	Wed Mar 15 18:56:27 2017 +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) 2010-2012 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -58,8 +58,8 @@
     if (field.getColumn().getDBColumnName().compareToIgnoreCase("documentno") == 0) {
       length = new Long(20);
     }
-    return getShowHoverGridFieldSettings(field) + ", length:" + length + ", displaylength:"
-        + displaylength + super.getGridFieldProperties(field);
+    return ", length:" + length + ", displaylength:" + displaylength
+        + super.getGridFieldProperties(field);
   }
 
   @Override
@@ -67,8 +67,7 @@
     JSONObject value;
     try {
       value = new JSONObject(super.getFieldProperties(field, getValueFromSession));
-      if (!getValueFromSession
-          && (field.getColumn().getReference().getId()).equals("28")
+      if (!getValueFromSession && (field.getColumn().getReference().getId()).equals("28")
           && !value.has("value")) {
         // When reference is button, set 'N' as default if there is default
         value.put("value", "N");
@@ -85,8 +84,7 @@
   public String getFieldPropertiesWithoutCombo(Field field, boolean getValueFromSession) {
     try {
       JSONObject value = new JSONObject(super.getFieldProperties(field, getValueFromSession));
-      if (!getValueFromSession
-          && (field.getColumn().getReference().getId()).equals("28")
+      if (!getValueFromSession && (field.getColumn().getReference().getId()).equals("28")
           && !value.has("value")) {
         // When reference is button, set 'N' as default if there is default
         value.put("value", "N");
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/ForeignKeyUIDefinition.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/ForeignKeyUIDefinition.java	Wed Mar 15 18:56:27 2017 +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) 2010-2015 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -102,7 +102,7 @@
       displayField = ", displayField: '" + getDisplayFieldName(field, prop) + "'";
     }
     return displayField + ", displaylength:" + displaylength + ",fkField: true"
-        + super.getGridFieldProperties(field) + getShowHoverGridFieldSettings(field);
+        + super.getGridFieldProperties(field);
   }
 
   /**
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/ImageUIDefinition.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/ImageUIDefinition.java	Wed Mar 15 18:56:27 2017 +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) 2010-2011 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -50,6 +50,11 @@
   }
 
   @Override
+  public boolean showHover() {
+    return false;
+  }
+
+  @Override
   public String getFieldProperties(Field field) {
     String fieldProperties = super.getFieldProperties(field);
     try {
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/LinkUIDefinition.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/LinkUIDefinition.java	Wed Mar 15 18:56:27 2017 +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) 2011 Openbravo SLU
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -53,8 +53,8 @@
     if (field.getColumn().getDBColumnName().compareToIgnoreCase("documentno") == 0) {
       length = new Long(20);
     }
-    return getShowHoverGridFieldSettings(field) + ", length: " + length + ", displaylength:"
-        + displaylength + super.getGridFieldProperties(field);
+    return ", length: " + length + ", displaylength:" + displaylength
+        + super.getGridFieldProperties(field);
   }
 
   @Override
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/PasswordUIDefinition.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/PasswordUIDefinition.java	Wed Mar 15 18:56:27 2017 +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) 2011 Openbravo SLU 
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -51,8 +51,8 @@
 
   // disable hover as it would show useless raw-value
   @Override
-  protected String getShowHoverGridFieldSettings(Field field) {
-    return "";
+  public boolean showHover() {
+    return false;
   }
 
 }
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/StringUIDefinition.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/StringUIDefinition.java	Wed Mar 15 18:56:27 2017 +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) 2010-2011 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -79,8 +79,8 @@
     if (field.getColumn().getDBColumnName().compareToIgnoreCase("documentno") == 0 && length == 0) {
       length = new Long(20);
     }
-    return getShowHoverGridFieldSettings(field) + (length != null ? ", length:" + length : "")
-        + ", displaylength:" + displaylength + super.getGridFieldProperties(field);
+    return (length != null ? ", length:" + length : "") + ", displaylength:" + displaylength
+        + super.getGridFieldProperties(field);
   }
 
   public String getFieldProperties(Field field) {
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/UIDefinition.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/reference/UIDefinition.java	Wed Mar 15 18:56:27 2017 +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) 2010-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -469,6 +469,7 @@
     if (canFilter != null) {
       result.append(", canFilter: " + canFilter.toString());
     }
+    result.append(getShowHoverGridFieldSettings(field));
     return result.toString();
   }
 
@@ -568,7 +569,21 @@
   // but then the value should be converted to the translated
   // value of the enum
   protected String getShowHoverGridFieldSettings(Field field) {
-    return ", showHover: true";
+    if (showHover()) {
+      return ", showHover: true";
+    }
+    return "";
+  }
+
+  /**
+   * This method determines if the UI definition should include the showHover property as part of
+   * the grid field properties. Returns {@code true} by default.
+   * 
+   * @return {@code true} if fields using this UI definition should display their text on a hover
+   *         box, otherwise return {@code false}
+   */
+  public boolean showHover() {
+    return true;
   }
 
   protected String getGridFieldName(Field fld) {
@@ -612,33 +627,9 @@
       boolean comboreload = rq.getRequestParameter("donotaddcurrentelement") != null
           && rq.getRequestParameter("donotaddcurrentelement").equals("true");
 
-      String objectReference = "";
-      if (field.getColumn().getReferenceSearchKey() != null) {
-        objectReference = field.getColumn().getReferenceSearchKey().getId();
-      }
-      String validation = "";
-      if (field.getColumn().getValidation() != null) {
-        validation = field.getColumn().getValidation().getId();
-      }
-      String orgList = Utility.getReferenceableOrg(vars, vars.getStringParameter("inpadOrgId"));
-      String clientList = Utility.getContext(new DalConnectionProvider(false), vars,
-          "#User_Client", field.getTab().getWindow().getId());
-      if (field.getColumn().getDBColumnName().equalsIgnoreCase("AD_CLIENT_ID")) {
-        clientList = Utility.getContext(new DalConnectionProvider(false), vars, "#User_Client",
-            field.getTab().getWindow().getId(),
-            Integer.parseInt(field.getTab().getTable().getDataAccessLevel()));
-        clientList = vars.getSessionValue("#User_Client");
-        orgList = null;
-      }
-      if (field.getColumn().getDBColumnName().equalsIgnoreCase("AD_ORG_ID")) {
-        orgList = Utility.getContext(new DalConnectionProvider(false), vars, "#User_Org", field
-            .getTab().getWindow().getId(),
-            Integer.parseInt(field.getTab().getTable().getDataAccessLevel()));
-      }
       ApplicationDictionaryCachedStructures cachedStructures = WeldUtils
           .getInstanceFromStaticBeanManager(ApplicationDictionaryCachedStructures.class);
-      ComboTableData comboTableData = cachedStructures.getComboTableData(vars, ref, field
-          .getColumn().getDBColumnName(), objectReference, validation, orgList, clientList);
+      ComboTableData comboTableData = cachedStructures.getComboTableData(field);
       FieldProvider tabData = generateTabData(field.getTab().getADFieldList(), field, columnValue);
       Map<String, String> parameters = comboTableData.fillSQLParametersIntoMap(
           new DalConnectionProvider(false), vars, tabData, field.getTab().getWindow().getId(),
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/templates/application-js.ftl	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/templates/application-js.ftl	Wed Mar 15 18:56:27 2017 +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) 2009-2016 Openbravo SLU
+ * All portions are Copyright (C) 2009-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -63,6 +63,7 @@
         WHERE_PARAMETER : '_where',
         SQL_WHERE_PARAMETER : '_sqlWhere',
         ORG_PARAMETER : '_org',
+        CALCULATE_ORGS: '_calculateOrgs',
         ORDERBY_PARAMETER : '_orderBy',
         SQL_ORDERBY_PARAMETER : '_sqlOrderBy',
         FILTER_PARAMETER : '_filter',
--- a/modules/org.openbravo.client.myob/src-db/database/model/modifiedTables/OBUIAPP_PARAMETER.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.myob/src-db/database/model/modifiedTables/OBUIAPP_PARAMETER.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -10,6 +10,7 @@
       </foreign-key>
       <index name="EM_OBKMO_PARAM_WIDGET" unique="false">
         <index-column name="EM_OBKMO_WIDGET_CLASS_ID"/>
+        <whereClause><![CDATA[EM_OBKMO_WIDGET_CLASS_ID IS NOT NULL]]></whereClause>
       </index>
     </table>
   </database>
--- a/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/widgetinform/WidgetInFormUIDefinition.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/widgetinform/WidgetInFormUIDefinition.java	Wed Mar 15 18:56:27 2017 +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) 2011 Openbravo SLU 
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -66,4 +66,9 @@
     }
   }
 
+  @Override
+  public boolean showHover() {
+    return false;
+  }
+
 }
--- a/modules/org.openbravo.client.querylist/src-db/database/model/tables/OBCQL_WIDGET_QUERY.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.querylist/src-db/database/model/tables/OBCQL_WIDGET_QUERY.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -66,6 +66,7 @@
       </index>
       <index name="OBCQL_WIDGET_QUERY_DS" unique="false">
         <index-column name="OBSERDS_DATASOURCE_ID"/>
+        <whereClause><![CDATA[OBSERDS_DATASOURCE_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="OBCQL_WIDGET_QUERY_ACTIVECHK"><![CDATA[ISACTIVE IN ('Y', 'N')]]></check>
     </table>
--- a/modules/org.openbravo.client.widgets/src-db/database/sourcedata/OBCQL_WIDGET_QUERY.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.widgets/src-db/database/sourcedata/OBCQL_WIDGET_QUERY.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -51,6 +51,7 @@
 and @optional_filters@
 and ol.client.id = :client
 and ol.product.name like :pname
+and ol.organization.id in (:organizationList)
 group by product.name, product.uOM.name, product.id, product.uOM.id 
 order by sum(orderedQuantity) desc]]></HQL>
 <!--CFDF8EE593F04CFE9709F5AD19A3A573-->  <TYPE><![CDATA[HQL]]></TYPE>
--- a/modules/org.openbravo.client.widgets/src-db/database/sourcedata/OBUIAPP_PARAMETER.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.client.widgets/src-db/database/sourcedata/OBUIAPP_PARAMETER.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -559,6 +559,32 @@
 <!--D1BE41F04FD14C3A9E6980369BC97E87-->  <EM_OBKMO_WIDGET_CLASS_ID><![CDATA[5291D3D3B07B4CFC87928071377740E8]]></EM_OBKMO_WIDGET_CLASS_ID>
 <!--D1BE41F04FD14C3A9E6980369BC97E87--></OBUIAPP_PARAMETER>
 
+<!--D4B555A658964D3C87B4D06F828832FA--><OBUIAPP_PARAMETER>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <OBUIAPP_PARAMETER_ID><![CDATA[D4B555A658964D3C87B4D06F828832FA]]></OBUIAPP_PARAMETER_ID>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <AD_MODULE_ID><![CDATA[FF8080812D842086012D844F3CC0003E]]></AD_MODULE_ID>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <NAME><![CDATA[Organization List]]></NAME>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <DESCRIPTION><![CDATA[List of Organizations this Role can access]]></DESCRIPTION>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <HELP><![CDATA[The Organization List indicates the Organizations (by organization id) that this Role can access.  Multiple Organizations are delimited by a comma ','.]]></HELP>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <SEQNO><![CDATA[30]]></SEQNO>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <AD_REFERENCE_ID><![CDATA[10]]></AD_REFERENCE_ID>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <COLUMNNAME><![CDATA[organizationList]]></COLUMNNAME>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <FIELDLENGTH><![CDATA[0]]></FIELDLENGTH>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <ISMANDATORY><![CDATA[N]]></ISMANDATORY>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <AD_ELEMENT_ID><![CDATA[478]]></AD_ELEMENT_ID>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <ISFIXED><![CDATA[Y]]></ISFIXED>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <FIXEDVALUE><![CDATA[OB.getContext().getReadableOrganizations()]]></FIXEDVALUE>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <EVALUATEFIXEDVALUE><![CDATA[Y]]></EVALUATEFIXEDVALUE>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <STARTINNEWLINE><![CDATA[N]]></STARTINNEWLINE>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <DISPLAYEDROWS><![CDATA[5]]></DISPLAYEDROWS>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <DISPLAYTITLE><![CDATA[Y]]></DISPLAYTITLE>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <ATT_SHOWINDESCRIPTION><![CDATA[N]]></ATT_SHOWINDESCRIPTION>
+<!--D4B555A658964D3C87B4D06F828832FA-->  <EM_OBKMO_WIDGET_CLASS_ID><![CDATA[CD1B06C4ED974B5F905A5A01B097DF4E]]></EM_OBKMO_WIDGET_CLASS_ID>
+<!--D4B555A658964D3C87B4D06F828832FA--></OBUIAPP_PARAMETER>
+
 <!--D57E85EA046B475C94EEE74A9CF67C78--><OBUIAPP_PARAMETER>
 <!--D57E85EA046B475C94EEE74A9CF67C78-->  <OBUIAPP_PARAMETER_ID><![CDATA[D57E85EA046B475C94EEE74A9CF67C78]]></OBUIAPP_PARAMETER_ID>
 <!--D57E85EA046B475C94EEE74A9CF67C78-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/ComboTableDatasourceService.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/ComboTableDatasourceService.java	Wed Mar 15 18:56:27 2017 +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-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2014-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -37,7 +37,6 @@
 import org.openbravo.data.FieldProvider;
 import org.openbravo.erpCommon.utility.ComboTableData;
 import org.openbravo.erpCommon.utility.FieldProviderFactory;
-import org.openbravo.erpCommon.utility.Utility;
 import org.openbravo.model.ad.datamodel.Column;
 import org.openbravo.model.ad.ui.Field;
 import org.openbravo.service.db.DalConnectionProvider;
@@ -67,7 +66,6 @@
     FieldProvider[] fps = null;
     String fieldId = parameters.get("fieldId");
     String windowId = parameters.get("windowId");
-    Entity targetEntity = null;
     String filterString = null;
 
     int startRow = -1, endRow = -1, num = 0;
@@ -76,8 +74,6 @@
     try {
       field = OBDal.getInstance().get(Field.class, fieldId);
       column = field.getColumn();
-      targetEntity = ModelProvider.getInstance().getEntityByTableId(
-          column.getTable().getId());
 
       if (!StringUtils.isEmpty(parameters.get("criteria"))) {
         String criteria = parameters.get("criteria");
@@ -112,39 +108,10 @@
 
       RequestContext rq = RequestContext.get();
       VariablesSecureApp vars = rq.getVariablesSecureApp();
-      String ref = column.getReference().getId();
-      String objectReference = "";
-
-      if (column.getReferenceSearchKey() != null) {
-        objectReference = column.getReferenceSearchKey().getId();
-      }
-      String validation = "";
-      if (column.getValidation() != null) {
-        validation = column.getValidation().getId();
-      }
-
-      String orgList = Utility.getReferenceableOrg(vars, vars.getStringParameter("inpadOrgId"));
-      String clientList = Utility.getContext(new DalConnectionProvider(false), vars,
-          "#User_Client", windowId);
-      int accessLevel = targetEntity.getAccessLevel().getDbValue();
-      if (column.getDBColumnName().equalsIgnoreCase("AD_CLIENT_ID")) {
-        clientList = Utility.getContext(new DalConnectionProvider(false), vars, "#User_Client",
-            windowId, accessLevel);
-        if (clientList == null) {
-          clientList = vars.getSessionValue("#User_Client");
-        }
-        orgList = null;
-      }
-
-      if (column.getDBColumnName().equalsIgnoreCase("AD_ORG_ID")) {
-        orgList = Utility.getContext(new DalConnectionProvider(false), vars, "#User_Org", windowId,
-            accessLevel);
-      }
 
       ApplicationDictionaryCachedStructures cachedStructures = WeldUtils
           .getInstanceFromStaticBeanManager(ApplicationDictionaryCachedStructures.class);
-      ComboTableData comboTableData = cachedStructures.getComboTableData(vars, ref,
-          column.getDBColumnName(), objectReference, validation, orgList, clientList);
+      ComboTableData comboTableData = cachedStructures.getComboTableData(field);
       Map<String, String> newParameters = null;
 
       newParameters = comboTableData.fillSQLParametersIntoMap(new DalConnectionProvider(false),
@@ -242,8 +209,7 @@
       // check access to current entity
       field = OBDal.getInstance().get(Field.class, fieldId);
       column = field.getColumn();
-      targetEntity = ModelProvider.getInstance().getEntityByTableId(
-          column.getTable().getId());
+      targetEntity = ModelProvider.getInstance().getEntityByTableId(column.getTable().getId());
       OBContext.getOBContext().getEntityAccessChecker().checkReadableAccess(targetEntity);
     } finally {
       OBContext.restorePreviousMode();
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DataSourceServlet.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DataSourceServlet.java	Wed Mar 15 18:56:27 2017 +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) 2009-2016 Openbravo SLU
+ * All portions are Copyright (C) 2009-2017 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -835,8 +835,6 @@
       ServletException {
     final Map<String, String> parameters = getParameterMap(request);
 
-    setSessionInfo();
-
     try {
       if (DataSourceConstants.FETCH_OPERATION.equals(parameters
           .get(DataSourceConstants.OPERATION_TYPE_PARAM))) {
@@ -865,7 +863,6 @@
   public void doDelete(HttpServletRequest request, HttpServletResponse response)
       throws IOException, ServletException {
     final Map<String, String> parameters = getParameterMap(request);
-    setSessionInfo();
     try {
       // checks and set parameters, if not valid then go away
       if (!checkSetParameters(request, response, parameters)) {
@@ -908,7 +905,6 @@
   public void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException,
       ServletException {
     final Map<String, String> parameters = getParameterMap(request);
-    setSessionInfo();
     try {
       if (!hasAccess(request, parameters.get(JsonConstants.TAB_PARAMETER))) {
         throw new OBUserException("AccessTableNoView");
@@ -926,14 +922,6 @@
     }
   }
 
-  private void setSessionInfo() {
-    // FIXME: Because of issue #15331 connection is initialized with temporary audit table before
-    // setting session info
-    // Reset Session Info in DB manually as it was set in the service but actual information is not
-    // available till now.
-    SessionInfo.setDBSessionInfo(OBDal.getInstance().getConnection());
-  }
-
   private boolean checkSetParameters(HttpServletRequest request, HttpServletResponse response,
       Map<String, String> parameters) throws IOException {
     if (!request.getRequestURI().contains("/" + servletPathPart)) {
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/AdvancedQueryBuilder.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/AdvancedQueryBuilder.java	Wed Mar 15 18:56:27 2017 +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) 2009-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -25,6 +25,7 @@
 import java.util.Calendar;
 import java.util.Date;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -329,37 +330,27 @@
 
   private String addWhereOrgParameters(String where) {
     String localWhereClause = where;
+
     // add the organization parameter
+    StringBuilder orgPart = new StringBuilder();
+    Set<String> orgs = new HashSet<String>();
     if (filterParameters.containsKey(JsonConstants.ORG_PARAMETER)) {
       final String value = filterParameters.get(JsonConstants.ORG_PARAMETER);
-      final StringBuilder orgPart = new StringBuilder();
       if (entity.isOrganizationEnabled() && value != null && value.length() > 0) {
-        final Set<String> orgs = OBContext.getOBContext().getOrganizationStructureProvider()
-            .getNaturalTree(value);
-        if (orgs.size() > 0) {
-          if (getMainAlias() != null) {
-            orgPart.append(" " + getMainAlias() + ".organization in (");
-          } else {
-            orgPart.append(" organization in (");
-          }
-          boolean addComma = false;
-          for (String org : orgs) {
-            if (addComma) {
-              orgPart.append(",");
-            }
-            orgPart.append("'" + org + "'");
-            addComma = true;
-          }
-          orgPart.append(") ");
-        }
+        orgs = OBContext.getOBContext().getOrganizationStructureProvider().getNaturalTree(value);
+        orgPart = buildOrgPartWhereClause(orgs);
       }
-      if (localWhereClause == null || localWhereClause.length() == 0) {
-        localWhereClause = orgPart.length() > 0 ? orgPart.toString() : "";
-      } else {
-        localWhereClause = "(" + localWhereClause + ")"
-            + (orgPart.length() > 0 ? " and " + orgPart.toString() : "");
+      localWhereClause = buildLocalWhereClause(localWhereClause, orgPart);
+    } else if (filterParameters.containsKey(JsonConstants.CALCULATE_ORGS)) {
+      // add natural tree of writable organizations
+      final Set<String> orgsWritables = OBContext.getOBContext().getWritableOrganizations();
+      for (final String o : orgsWritables) {
+        orgs.addAll(OBContext.getOBContext().getOrganizationStructureProvider().getNaturalTree(o));
       }
+      orgPart = buildOrgPartWhereClause(orgs);
+      localWhereClause = buildLocalWhereClause(localWhereClause, orgPart);
     }
+
     // add the special whereParameter
     final String whereParameter = filterParameters.get(JsonConstants.WHERE_AND_FILTER_CLAUSE);
     if (whereParameter != null && !whereParameter.equals("null") && whereParameter.length() > 0) {
@@ -372,6 +363,37 @@
     return localWhereClause;
   }
 
+  private String buildLocalWhereClause(String localWhere, StringBuilder orgPart) {
+    if (localWhere == null || localWhere.length() == 0) {
+      return (orgPart.length() > 0 ? orgPart.toString() : "");
+    } else {
+      return ("(" + localWhere + ")" + (orgPart.length() > 0 ? " and " + orgPart.toString() : ""));
+    }
+  }
+
+  private StringBuilder buildOrgPartWhereClause(Set<String> organizations) {
+    StringBuilder buildOrgPart = new StringBuilder();
+    if (organizations.size() > 0) {
+      if (getMainAlias() != null) {
+        String organizationEntity = Organization.ENTITY_NAME.equals(entity.toString()) ? ".id"
+            : ".organization";
+        buildOrgPart.append(" " + getMainAlias() + organizationEntity + " in (");
+      } else {
+        buildOrgPart.append(" organization in (");
+      }
+      boolean addComma = false;
+      for (String org : organizations) {
+        if (addComma) {
+          buildOrgPart.append(",");
+        }
+        buildOrgPart.append("'" + org + "'");
+        addComma = true;
+      }
+      buildOrgPart.append(") ");
+    }
+    return buildOrgPart;
+  }
+
   private String substituteParameters(String where) {
 
     // add some default filter parameters which are substituted
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/DefaultJsonDataService.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/DefaultJsonDataService.java	Wed Mar 15 18:56:27 2017 +0100
@@ -605,6 +605,7 @@
             || key.equals(JsonConstants.WHERE_PARAMETER)
             || key.equals(JsonConstants.WHERE_AND_FILTER_CLAUSE)
             || key.equals(JsonConstants.ORG_PARAMETER)
+            || key.equals(JsonConstants.CALCULATE_ORGS)
             || key.equals(JsonConstants.TARGETRECORDID_PARAMETER)
             || (key.startsWith(DataEntityQueryService.PARAM_DELIMITER) && key
                 .endsWith(DataEntityQueryService.PARAM_DELIMITER))
@@ -756,20 +757,11 @@
       if (!rowClient.equals(currentClientId)) {
         jsonObject.put("_readOnly", true);
       } else {
-        boolean writable = false;
-        for (String orgId : OBContext.getOBContext().getWritableOrganizations()) {
-          if (orgId.equals(rowOrganization)) {
-            writable = true;
-            break;
-          }
-        }
-        if (isOrganizationEntity(jsonObject)) {
-          for (String orgId : OBContext.getOBContext().getDeactivatedOrganizations()) {
-            if (orgId.equals(rowOrganization)) {
-              writable = true;
-              break;
-            }
-          }
+        boolean writable = OBContext.getOBContext().getWritableOrganizations()
+            .contains(rowOrganization);
+        if (!writable && isOrganizationEntity(jsonObject)) {
+          writable = OBContext.getOBContext().getDeactivatedOrganizations()
+              .contains(rowOrganization);
         }
         if (!writable) {
           jsonObject.put("_readOnly", true);
@@ -779,11 +771,8 @@
   }
 
   private boolean isOrganizationEntity(JSONObject json) throws JSONException {
-    if (json.has(JsonConstants.ENTITYNAME)
-        && (Organization.ENTITY_NAME.equals(json.get(JsonConstants.ENTITYNAME)))) {
-      return true;
-    }
-    return false;
+    return json.has(JsonConstants.ENTITYNAME)
+        && Organization.ENTITY_NAME.equals(json.get(JsonConstants.ENTITYNAME));
   }
 
   /**
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/JsonConstants.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/JsonConstants.java	Wed Mar 15 18:56:27 2017 +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) 2009-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -44,6 +44,7 @@
    * organization.
    */
   public static final String ORG_PARAMETER = "_org";
+  public static final String CALCULATE_ORGS = "_calculateOrgs";
 
   public static final String NO_ACTIVE_FILTER = "_noActiveFilter";
   public static final String ONLYCOUNT_PARAMETER = "_onlyCount";
--- a/modules/org.openbravo.userinterface.selector/src-db/database/model/tables/OBUISEL_SELECTOR_TRL.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.userinterface.selector/src-db/database/model/tables/OBUISEL_SELECTOR_TRL.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -78,6 +78,7 @@
       </foreign-key>
       <index name="OBUISEL_SELECTOR_TRL_LANGUAGE" unique="false">
         <index-column name="AD_LANGUAGE"/>
+        <whereClause><![CDATA[AD_LANGUAGE IS NOT NULL]]></whereClause>
       </index>
       <unique name="OBUISEL_SEL_TRL_ADLANG_UN">
         <unique-column name="OBUISEL_SELECTOR_ID"/>
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/SelectorComponent.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/SelectorComponent.java	Wed Mar 15 18:56:27 2017 +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) 2009-2016 Openbravo SLU
+ * All portions are Copyright (C) 2009-2017 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -921,6 +921,10 @@
         }
 
       }
+
+      if (uiDefinition != null && uiDefinition.showHover()) {
+        result.add(createLocalSelectorFieldProperty("showHover", true));
+      }
       return result;
     }
 
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/reference/SelectorUIReference.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/reference/SelectorUIReference.java	Wed Mar 15 18:56:27 2017 +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) 2010-2011 Openbravo SLU 
+ * All portions are Copyright (C) 2010-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -19,6 +19,9 @@
 
 package org.openbravo.userinterface.selector.reference;
 
+import static org.openbravo.erpCommon.utility.ComboTableData.CLIENT_LIST_PARAM_HOLDER;
+import static org.openbravo.erpCommon.utility.ComboTableData.ORG_LIST_PARAM_HOLDER;
+
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -230,17 +233,13 @@
               && !parentFieldName.equals("")) {
             tables += " on " + tableName + "." + parentFieldName + " = td" + myIndex + "." + name
                 + "\n";
-            tables += "AND td" + myIndex + ".AD_Client_ID IN (" + comboTableData.getClientList()
-                + ") \n";
-            tables += "AND td" + myIndex + ".AD_Org_ID IN (" + comboTableData.getOrgList() + ")";
+            tables += "AND td" + myIndex + ".AD_Client_ID IN (" + CLIENT_LIST_PARAM_HOLDER + ") \n";
+            tables += "AND td" + myIndex + ".AD_Org_ID IN (" + ORG_LIST_PARAM_HOLDER + ")";
           } else {
-            comboTableData.addWhereField(
-                "td" + myIndex + ".AD_Client_ID IN (" + comboTableData.getClientList() + ")",
-                "CLIENT_LIST");
-            if (comboTableData.getOrgList() != null)
-              comboTableData.addWhereField(
-                  "td" + myIndex + ".AD_Org_ID IN (" + comboTableData.getOrgList() + ")",
-                  "ORG_LIST");
+            comboTableData.addWhereField("td" + myIndex + ".AD_Client_ID IN ("
+                + CLIENT_LIST_PARAM_HOLDER + ")", "CLIENT_LIST");
+            comboTableData.addWhereField("td" + myIndex + ".AD_Org_ID IN (" + ORG_LIST_PARAM_HOLDER
+                + ")", "ORG_LIST");
           }
           comboTableData.addFromField(tables, "td" + myIndex);
           if (tableName == null || tableName.equals("")) {
--- a/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-multi-selector-item.js	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-multi-selector-item.js	Wed Mar 15 18:56:27 2017 +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-2014 Openbravo SLU
+ * All portions are Copyright (C) 2012-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -137,6 +137,20 @@
       };
 
       this.selectorWindow.selectorGrid.recordDoubleClick = function (viewer, record, recordnum, field, fieldnum) {};
+
+      // overridden to support hover on the header for the checkbox field
+      this.selectorWindow.selectorGrid.setFieldProperties = function (field, properties) {
+        var localField = field;
+        if (isc.isA.Number(localField)) {
+          localField = this.fields[localField];
+        }
+        if (this.isCheckboxField(localField) && properties) {
+          properties.showHover = true;
+          properties.prompt = OB.I18N.getLabel('OBUIAPP_GridSelectAllColumnPrompt');
+        }
+
+        return this.Super('setFieldProperties', arguments);
+      };
     }
 
     this.optionCriteria = {
--- a/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-selector-filter-select-item.js	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-selector-filter-select-item.js	Wed Mar 15 18:56:27 2017 +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) 2011-2012 Openbravo SLU
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -23,8 +23,14 @@
   filterDataBoundPickList: function (requestProperties, dropCache) {
     requestProperties = requestProperties || {};
     requestProperties.params = requestProperties.params || {};
-    // on purpose not passing the third boolean param
-    var contextInfo = this.selectorWindow.selector.form.view.getContextInfo(false, true);
+    // selector can be placed on a standard window view or on a process definition view.
+    var contextInfo;
+    if (this.selectorWindow.selector && this.selectorWindow.selector.form && this.selectorWindow.selector.form.view) {
+      // on purpose not passing the third boolean param
+      contextInfo = this.selectorWindow.selector.form.view.getContextInfo(false, true);
+    } else if (this.selectorWindow.selector && this.selectorWindow.selector.form && this.selectorWindow.selector.form.paramWindow) {
+      contextInfo = this.selectorWindow.selector.form.paramWindow.getContextInfo(false, true);
+    }
 
     // also add the special ORG parameter
     if (this.selectorWindow.selector.form.getField('organization')) {
--- a/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-selector-item.js	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-selector-item.js	Wed Mar 15 18:56:27 2017 +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) 2011-2016 Openbravo SLU
+ * All portions are Copyright (C) 2011-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -699,7 +699,7 @@
     // Dropdown selector that shows more than one column.
     if (this.pickListFields.length > 1) {
       // calculate width of checkBox and first fields before selector field in viewGrid
-      if (this.form.view && !this.form.view.isShowingForm) {
+      if (this.form.view && !this.form.view.isShowingForm && this.grid) {
         while (i < this.grid.fields.size() && nameField.localeCompare(this.grid.fields.get(i).valueField) !== 0) {
           leftFieldsWidth = leftFieldsWidth + this.grid.fields.get(i).width;
           i++;
@@ -1187,8 +1187,8 @@
   prepareDSRequest: function (params, selector, requestType) {
     function setOrgIdParam(params) {
       if (!params.inpadOrgId) {
-        // look for an ad_org_id parameter. If there is no such parameter or its value is empty, use the current user organization
-        params.inpadOrgId = params.ad_org_id || params.AD_Org_ID || OB.User.organizationId;
+        // look for an ad_org_id parameter. If there is no such parameter or its value is empty, selector will be filter by natural tree of writable organizations
+        params.inpadOrgId = params.ad_org_id || params.AD_Org_ID;
       }
     }
 
@@ -1232,6 +1232,8 @@
     // also add the special ORG parameter
     if (params.inpadOrgId) {
       params[OB.Constants.ORG_PARAMETER] = params.inpadOrgId;
+    } else {
+      params[OB.Constants.CALCULATE_ORGS] = true;
     }
 
     // adds the selector id to filter used to get filter information
--- a/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-selector-widget.js	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-selector-widget.js	Wed Mar 15 18:56:27 2017 +0100
@@ -13,7 +13,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) 2009-2014 Openbravo SLU
+ * All portions are Copyright (C) 2009-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -880,8 +880,8 @@
 
         filterData: function (criteria, callback, requestProperties) {
           requestProperties = requestProperties || {};
-          requestProperties.params = requestProperties.params | {};
-          requestProperties.params._selectorDefinitionId = this.selectorDefinitionId;
+          requestProperties.params = requestProperties.params || {};
+          requestProperties.params._selectorDefinitionId = this.selector.selectorDefinitionId;
           if (!criteria) {
             criteria = {};
           }
@@ -895,7 +895,7 @@
 
           criteria[OB.Constants.TEXT_MATCH_PARAMETER_OVERRIDE] = this.selector.popupTextMatchStyle;
 
-          criteria._selectorDefinitionId = this.selectorDefinitionId;
+          criteria._selectorDefinitionId = this.selector.selectorDefinitionId;
           criteria._requestType = 'Window';
 
           // and call the super
@@ -920,8 +920,8 @@
           criteria._requestType = 'Window';
 
           requestProperties = requestProperties || {};
-          requestProperties.params = requestProperties.params | {};
-          requestProperties.params._selectorDefinitionId = this.selectorDefinitionId;
+          requestProperties.params = requestProperties.params || {};
+          requestProperties.params._selectorDefinitionId = this.selector.selectorDefinitionId;
 
           // and call the super
           return this.Super('fetchData', [criteria, callback, requestProperties]);
--- a/modules/org.openbravo.v3/src-db/database/sourcedata/AD_MODULE_MERGE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/modules/org.openbravo.v3/src-db/database/sourcedata/AD_MODULE_MERGE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -10,6 +10,26 @@
 <!--10FBB7E64CFC495EB32B3C6F17D10197-->  <MERGED_MODULE_NAME><![CDATA[Inventory Average Cost transactions]]></MERGED_MODULE_NAME>
 <!--10FBB7E64CFC495EB32B3C6F17D10197--></AD_MODULE_MERGE>
 
+<!--12D2973485914E9AB38702464C531896--><AD_MODULE_MERGE>
+<!--12D2973485914E9AB38702464C531896-->  <AD_MODULE_MERGE_ID><![CDATA[12D2973485914E9AB38702464C531896]]></AD_MODULE_MERGE_ID>
+<!--12D2973485914E9AB38702464C531896-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--12D2973485914E9AB38702464C531896-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--12D2973485914E9AB38702464C531896-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--12D2973485914E9AB38702464C531896-->  <AD_MODULE_ID><![CDATA[0138E7A89B5E4DC3932462252801FFBC]]></AD_MODULE_ID>
+<!--12D2973485914E9AB38702464C531896-->  <MERGED_MODULE_UUID><![CDATA[391979C3E1A44A9D814B3F9756FC57F4]]></MERGED_MODULE_UUID>
+<!--12D2973485914E9AB38702464C531896-->  <MERGED_MODULE_NAME><![CDATA[Aging Balance Report]]></MERGED_MODULE_NAME>
+<!--12D2973485914E9AB38702464C531896--></AD_MODULE_MERGE>
+
+<!--766B82ABD28C42E999EF034F80F73992--><AD_MODULE_MERGE>
+<!--766B82ABD28C42E999EF034F80F73992-->  <AD_MODULE_MERGE_ID><![CDATA[766B82ABD28C42E999EF034F80F73992]]></AD_MODULE_MERGE_ID>
+<!--766B82ABD28C42E999EF034F80F73992-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--766B82ABD28C42E999EF034F80F73992-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--766B82ABD28C42E999EF034F80F73992-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--766B82ABD28C42E999EF034F80F73992-->  <AD_MODULE_ID><![CDATA[0138E7A89B5E4DC3932462252801FFBC]]></AD_MODULE_ID>
+<!--766B82ABD28C42E999EF034F80F73992-->  <MERGED_MODULE_UUID><![CDATA[FF80808131D1689F0131D170F19A0006]]></MERGED_MODULE_UUID>
+<!--766B82ABD28C42E999EF034F80F73992-->  <MERGED_MODULE_NAME><![CDATA[Report: Cash Flow Forecast]]></MERGED_MODULE_NAME>
+<!--766B82ABD28C42E999EF034F80F73992--></AD_MODULE_MERGE>
+
 <!--9AF40DD3765F4F048F3C9764C3A82796--><AD_MODULE_MERGE>
 <!--9AF40DD3765F4F048F3C9764C3A82796-->  <AD_MODULE_MERGE_ID><![CDATA[9AF40DD3765F4F048F3C9764C3A82796]]></AD_MODULE_MERGE_ID>
 <!--9AF40DD3765F4F048F3C9764C3A82796-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/referencedata/sampledata/QA_Testing/C_BPARTNER.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/referencedata/sampledata/QA_Testing/C_BPARTNER.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -240,6 +240,7 @@
   <SHOWPRICEINORDER><![CDATA[Y]]></SHOWPRICEINORDER>
   <INVOICEGROUPING><![CDATA[000000000000000]]></INVOICEGROUPING>
   <ISWORKER><![CDATA[N]]></ISWORKER>
+  <PO_BP_TAXCATEGORY_ID><![CDATA[5114F4D014194A10A1425BFABA6932EE]]></PO_BP_TAXCATEGORY_ID>
   <PO_PAYMENTMETHOD_ID><![CDATA[42E87E97974E4B35849A430B8F6F2884]]></PO_PAYMENTMETHOD_ID>
   <PO_FINANCIAL_ACCOUNT_ID><![CDATA[F8126A62836F47AB9044CB2149D978ED]]></PO_FINANCIAL_ACCOUNT_ID>
   <CUSTOMER_BLOCKING><![CDATA[N]]></CUSTOMER_BLOCKING>
--- a/referencedata/sampledata/QA_Testing/C_TAX.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/referencedata/sampledata/QA_Testing/C_TAX.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -1,6 +1,69 @@
 <?xml version='1.0' encoding='UTF-8'?>
 <data>
 <C_TAX>
+  <C_TAX_ID><![CDATA[0854025824E14FA9AD025289A79EEC05]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:53:26.717]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:21:06.857]]></UPDATED>
+  <NAME><![CDATA[IEPS 53%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
+  <RATE><![CDATA[53]]></RATE>
+  <PARENT_TAX_ID><![CDATA[BFAF793D760E411D9F6D0DFC7FE6D601]]></PARENT_TAX_ID>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[B46133FD2AB5460E93520EF475DAF99C]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[20]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
+  <C_TAX_ID><![CDATA[2F7F287739AB43258EA15D58E48C1334]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:27:25.676]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:27:25.676]]></UPDATED>
+  <NAME><![CDATA[IEPS 26.5%+16%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[Y]]></ISSUMMARY>
+  <RATE><![CDATA[0]]></RATE>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[EB150691C65F46E09BEE9591A6067867]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[10]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
   <C_TAX_ID><![CDATA[3271411A5AFB490A91FB618B6B789C24]]></C_TAX_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[43D590B4814049C6B85C6545E8264E37]]></AD_ORG_ID>
@@ -30,6 +93,38 @@
 </C_TAX>
 
 <C_TAX>
+  <C_TAX_ID><![CDATA[34240B260C6F4908897D1438E16CA6E6]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:10:39.464]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-23 11:32:52.905]]></UPDATED>
+  <NAME><![CDATA[Super Tax 50%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
+  <RATE><![CDATA[50]]></RATE>
+  <PARENT_TAX_ID><![CDATA[854F97A169FF4CFF8FAF504F84139CD2]]></PARENT_TAX_ID>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[AA65D2E06E4140FCA3BA95A9B130F248]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[20]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
   <C_TAX_ID><![CDATA[37222B873B6447D7A1FEC837799B222F]]></C_TAX_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[43D590B4814049C6B85C6545E8264E37]]></AD_ORG_ID>
@@ -97,9 +192,9 @@
   <ISACTIVE><![CDATA[Y]]></ISACTIVE>
   <CREATED><![CDATA[2013-07-04 23:38:17.089]]></CREATED>
   <CREATEDBY><![CDATA[0]]></CREATEDBY>
-  <UPDATED><![CDATA[2013-07-04 23:38:17.089]]></UPDATED>
+  <UPDATED><![CDATA[2017-02-23 00:43:44.368]]></UPDATED>
   <NAME><![CDATA[VAT(3)+CHARGE(0.5)]]></NAME>
-  <UPDATEDBY><![CDATA[0]]></UPDATEDBY>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
   <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
   <ISSUMMARY><![CDATA[Y]]></ISSUMMARY>
   <RATE><![CDATA[3.50]]></RATE>
@@ -108,7 +203,7 @@
   <C_TAXCATEGORY_ID><![CDATA[4028E6C72959682B01295ADC1CF70229]]></C_TAXCATEGORY_ID>
   <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
   <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
-  <SOPOTYPE><![CDATA[S]]></SOPOTYPE>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
   <CASCADE><![CDATA[N]]></CASCADE>
   <C_BP_TAXCATEGORY_ID><![CDATA[5114F4D014194A10A1425BFABA6932EE]]></C_BP_TAXCATEGORY_ID>
   <LINE><![CDATA[10]]></LINE>
@@ -129,9 +224,9 @@
   <ISACTIVE><![CDATA[Y]]></ISACTIVE>
   <CREATED><![CDATA[2013-07-04 23:38:17.09]]></CREATED>
   <CREATEDBY><![CDATA[0]]></CREATEDBY>
-  <UPDATED><![CDATA[2013-07-04 23:38:17.09]]></UPDATED>
+  <UPDATED><![CDATA[2017-02-23 00:46:02.455]]></UPDATED>
   <NAME><![CDATA[VAT 3%]]></NAME>
-  <UPDATEDBY><![CDATA[0]]></UPDATEDBY>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
   <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
   <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
   <RATE><![CDATA[3.00]]></RATE>
@@ -154,6 +249,70 @@
 </C_TAX>
 
 <C_TAX>
+  <C_TAX_ID><![CDATA[5F54E74EEFDD468188BB179F128D49AB]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:37:33.033]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:37:33.033]]></UPDATED>
+  <NAME><![CDATA[VAT 4%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
+  <RATE><![CDATA[4]]></RATE>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[37BBE1A339404FA5A8F9976FF5692603]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[10]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
+  <C_TAX_ID><![CDATA[63BFE8774A4947ABB5151780ABE392AF]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:11:45.127]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-23 11:34:43.339]]></UPDATED>
+  <NAME><![CDATA[Super Tax 25%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
+  <RATE><![CDATA[25]]></RATE>
+  <PARENT_TAX_ID><![CDATA[854F97A169FF4CFF8FAF504F84139CD2]]></PARENT_TAX_ID>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[AA65D2E06E4140FCA3BA95A9B130F248]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[Y]]></CASCADE>
+  <LINE><![CDATA[30]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <C_TAXBASE_ID><![CDATA[34240B260C6F4908897D1438E16CA6E6]]></C_TAXBASE_ID>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
   <C_TAX_ID><![CDATA[667A8194F0264B0AAA997B8B51F72024]]></C_TAX_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
@@ -186,6 +345,101 @@
 </C_TAX>
 
 <C_TAX>
+  <C_TAX_ID><![CDATA[795DCCA3A72A4147A8C8F1DBFC99C004]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:29:25.155]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:29:33.624]]></UPDATED>
+  <NAME><![CDATA[IEPS 26.5% VAT 16%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
+  <RATE><![CDATA[16]]></RATE>
+  <PARENT_TAX_ID><![CDATA[2F7F287739AB43258EA15D58E48C1334]]></PARENT_TAX_ID>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[EB150691C65F46E09BEE9591A6067867]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[30]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNATAX]]></BASEAMOUNT>
+  <C_TAXBASE_ID><![CDATA[E6B01B49600B4859828FF4D268BA5140]]></C_TAXBASE_ID>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
+  <C_TAX_ID><![CDATA[854F97A169FF4CFF8FAF504F84139CD2]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:09:44.032]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:53:18.587]]></UPDATED>
+  <NAME><![CDATA[Super Tax]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[Y]]></ISSUMMARY>
+  <RATE><![CDATA[0]]></RATE>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[AA65D2E06E4140FCA3BA95A9B130F248]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[10]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
+  <C_TAX_ID><![CDATA[8E929CE97C7946F8BB808B9CC3F6D5F2]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-01-12 10:20:32.719]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-23 00:46:37.436]]></UPDATED>
+  <NAME><![CDATA[VAT 20%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
+  <RATE><![CDATA[20]]></RATE>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[15A62A22F9604828A1C38F0834722AAB]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[10]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
   <C_TAX_ID><![CDATA[9EDA6E6317CF4E5E97E3C412467923FA]]></C_TAX_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[5EFF95EB540740A3B10510D9814EFAD5]]></AD_ORG_ID>
@@ -217,15 +471,48 @@
 </C_TAX>
 
 <C_TAX>
+  <C_TAX_ID><![CDATA[A3D779898E5C4542930F31D823B18162]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:55:07.97]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:21:14.478]]></UPDATED>
+  <NAME><![CDATA[IEPS 53% VAT 16%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
+  <RATE><![CDATA[16]]></RATE>
+  <PARENT_TAX_ID><![CDATA[BFAF793D760E411D9F6D0DFC7FE6D601]]></PARENT_TAX_ID>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[B46133FD2AB5460E93520EF475DAF99C]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[30]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNATAX]]></BASEAMOUNT>
+  <C_TAXBASE_ID><![CDATA[0854025824E14FA9AD025289A79EEC05]]></C_TAXBASE_ID>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
   <C_TAX_ID><![CDATA[BA7059430C0A43A9B86A21C4EECF3A21]]></C_TAX_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[43D590B4814049C6B85C6545E8264E37]]></AD_ORG_ID>
   <ISACTIVE><![CDATA[Y]]></ISACTIVE>
   <CREATED><![CDATA[2013-07-04 23:38:17.09]]></CREATED>
   <CREATEDBY><![CDATA[0]]></CREATEDBY>
-  <UPDATED><![CDATA[2013-07-04 23:38:17.09]]></UPDATED>
+  <UPDATED><![CDATA[2017-02-23 00:43:32.855]]></UPDATED>
   <NAME><![CDATA[Exempt 10%]]></NAME>
-  <UPDATEDBY><![CDATA[0]]></UPDATEDBY>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
   <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
   <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
   <RATE><![CDATA[0.00]]></RATE>
@@ -246,6 +533,37 @@
 </C_TAX>
 
 <C_TAX>
+  <C_TAX_ID><![CDATA[BFAF793D760E411D9F6D0DFC7FE6D601]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:50:26.696]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:50:26.696]]></UPDATED>
+  <NAME><![CDATA[IEPS 53%+16%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[Y]]></ISSUMMARY>
+  <RATE><![CDATA[0]]></RATE>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[B46133FD2AB5460E93520EF475DAF99C]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[10]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
   <C_TAX_ID><![CDATA[BFD013B889E14A20A37180311E557D04]]></C_TAX_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[5EFF95EB540740A3B10510D9814EFAD5]]></AD_ORG_ID>
@@ -283,7 +601,7 @@
   <ISACTIVE><![CDATA[Y]]></ISACTIVE>
   <CREATED><![CDATA[2015-05-20 16:35:13.925]]></CREATED>
   <CREATEDBY><![CDATA[100]]></CREATEDBY>
-  <UPDATED><![CDATA[2015-05-20 16:35:13.925]]></UPDATED>
+  <UPDATED><![CDATA[2017-02-23 00:44:31.797]]></UPDATED>
   <NAME><![CDATA[As Per BOM]]></NAME>
   <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
   <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
@@ -306,15 +624,78 @@
 </C_TAX>
 
 <C_TAX>
+  <C_TAX_ID><![CDATA[DBFCCC14B64147168F0F516F82FAF38B]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:38:11.694]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:38:11.694]]></UPDATED>
+  <NAME><![CDATA[VAT 21%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
+  <RATE><![CDATA[21]]></RATE>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[D2785E2729CD404F911047015CCCC0E8]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[10]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
+  <C_TAX_ID><![CDATA[E6B01B49600B4859828FF4D268BA5140]]></C_TAX_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:28:13.211]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:28:13.211]]></UPDATED>
+  <NAME><![CDATA[IEPS 26.5%]]></NAME>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
+  <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
+  <RATE><![CDATA[26.5]]></RATE>
+  <PARENT_TAX_ID><![CDATA[2F7F287739AB43258EA15D58E48C1334]]></PARENT_TAX_ID>
+  <C_COUNTRY_ID><![CDATA[106]]></C_COUNTRY_ID>
+  <TO_COUNTRY_ID><![CDATA[106]]></TO_COUNTRY_ID>
+  <C_TAXCATEGORY_ID><![CDATA[EB150691C65F46E09BEE9591A6067867]]></C_TAXCATEGORY_ID>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ISTAXEXEMPT><![CDATA[N]]></ISTAXEXEMPT>
+  <SOPOTYPE><![CDATA[B]]></SOPOTYPE>
+  <CASCADE><![CDATA[N]]></CASCADE>
+  <LINE><![CDATA[20]]></LINE>
+  <ISWITHHOLDINGTAX><![CDATA[N]]></ISWITHHOLDINGTAX>
+  <ISNOTAXABLE><![CDATA[N]]></ISNOTAXABLE>
+  <ISTAXUNDEDUCTABLE><![CDATA[N]]></ISTAXUNDEDUCTABLE>
+  <ISTAXDEDUCTABLE><![CDATA[N]]></ISTAXDEDUCTABLE>
+  <ISNOVAT><![CDATA[N]]></ISNOVAT>
+  <BASEAMOUNT><![CDATA[LNA]]></BASEAMOUNT>
+  <DOCTAXAMOUNT><![CDATA[D]]></DOCTAXAMOUNT>
+  <ISCASHVAT><![CDATA[N]]></ISCASHVAT>
+</C_TAX>
+
+<C_TAX>
   <C_TAX_ID><![CDATA[F9D9AF81F4FA459C9CE7A2D9697DF1E4]]></C_TAX_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
   <ISACTIVE><![CDATA[Y]]></ISACTIVE>
   <CREATED><![CDATA[2013-07-04 23:38:16.873]]></CREATED>
   <CREATEDBY><![CDATA[0]]></CREATEDBY>
-  <UPDATED><![CDATA[2013-07-04 23:38:16.873]]></UPDATED>
+  <UPDATED><![CDATA[2017-02-23 00:46:02.447]]></UPDATED>
   <NAME><![CDATA[VAT 10%]]></NAME>
-  <UPDATEDBY><![CDATA[0]]></UPDATEDBY>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
   <VALIDFROM><![CDATA[2000-01-01 00:00:00.0]]></VALIDFROM>
   <ISSUMMARY><![CDATA[N]]></ISSUMMARY>
   <RATE><![CDATA[10.00]]></RATE>
--- a/referencedata/sampledata/QA_Testing/C_TAXCATEGORY.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/referencedata/sampledata/QA_Testing/C_TAXCATEGORY.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -1,6 +1,20 @@
 <?xml version='1.0' encoding='UTF-8'?>
 <data>
 <C_TAXCATEGORY>
+  <C_TAXCATEGORY_ID><![CDATA[15A62A22F9604828A1C38F0834722AAB]]></C_TAXCATEGORY_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-01-12 10:19:36.408]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-01-12 10:19:36.408]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[VAT 20%]]></NAME>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ASBOM><![CDATA[N]]></ASBOM>
+</C_TAXCATEGORY>
+
+<C_TAXCATEGORY>
   <C_TAXCATEGORY_ID><![CDATA[1955F4CC846840D4832A49BAAC67A45C]]></C_TAXCATEGORY_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
@@ -15,6 +29,20 @@
 </C_TAXCATEGORY>
 
 <C_TAXCATEGORY>
+  <C_TAXCATEGORY_ID><![CDATA[37BBE1A339404FA5A8F9976FF5692603]]></C_TAXCATEGORY_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:37:08.506]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:37:08.506]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[VAT 4%]]></NAME>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ASBOM><![CDATA[N]]></ASBOM>
+</C_TAXCATEGORY>
+
+<C_TAXCATEGORY>
   <C_TAXCATEGORY_ID><![CDATA[4028E6C72959682B01295ADC0FB80217]]></C_TAXCATEGORY_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
@@ -45,6 +73,48 @@
 </C_TAXCATEGORY>
 
 <C_TAXCATEGORY>
+  <C_TAXCATEGORY_ID><![CDATA[AA65D2E06E4140FCA3BA95A9B130F248]]></C_TAXCATEGORY_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:09:16.136]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 13:09:16.136]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[Super Tax]]></NAME>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ASBOM><![CDATA[N]]></ASBOM>
+</C_TAXCATEGORY>
+
+<C_TAXCATEGORY>
+  <C_TAXCATEGORY_ID><![CDATA[B46133FD2AB5460E93520EF475DAF99C]]></C_TAXCATEGORY_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:42:57.195]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:51:59.277]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[IEPS 53%+16%]]></NAME>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ASBOM><![CDATA[N]]></ASBOM>
+</C_TAXCATEGORY>
+
+<C_TAXCATEGORY>
+  <C_TAXCATEGORY_ID><![CDATA[D2785E2729CD404F911047015CCCC0E8]]></C_TAXCATEGORY_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:37:52.83]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:37:52.83]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[VAT 21%]]></NAME>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ASBOM><![CDATA[N]]></ASBOM>
+</C_TAXCATEGORY>
+
+<C_TAXCATEGORY>
   <C_TAXCATEGORY_ID><![CDATA[E02F948001F44F479D709EBC6911E310]]></C_TAXCATEGORY_ID>
   <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
   <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
@@ -58,4 +128,18 @@
   <ASBOM><![CDATA[N]]></ASBOM>
 </C_TAXCATEGORY>
 
+<C_TAXCATEGORY>
+  <C_TAXCATEGORY_ID><![CDATA[EB150691C65F46E09BEE9591A6067867]]></C_TAXCATEGORY_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:26:57.66]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:26:57.66]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[IEPS 26.5%+16%]]></NAME>
+  <ISDEFAULT><![CDATA[N]]></ISDEFAULT>
+  <ASBOM><![CDATA[N]]></ASBOM>
+</C_TAXCATEGORY>
+
 </data>
--- a/referencedata/sampledata/QA_Testing/C_TAXCATEGORY_TRL.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/referencedata/sampledata/QA_Testing/C_TAXCATEGORY_TRL.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -16,6 +16,36 @@
 </C_TAXCATEGORY_TRL>
 
 <C_TAXCATEGORY_TRL>
+  <C_TAXCATEGORY_TRL_ID><![CDATA[68B24A02CC7742B7BD5665555800A328]]></C_TAXCATEGORY_TRL_ID>
+  <C_TAXCATEGORY_ID><![CDATA[37BBE1A339404FA5A8F9976FF5692603]]></C_TAXCATEGORY_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:37:08.506]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:37:08.506]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[VAT 4%]]></NAME>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+</C_TAXCATEGORY_TRL>
+
+<C_TAXCATEGORY_TRL>
+  <C_TAXCATEGORY_TRL_ID><![CDATA[84B01A8D2C134C198D945C13C96732C8]]></C_TAXCATEGORY_TRL_ID>
+  <C_TAXCATEGORY_ID><![CDATA[D2785E2729CD404F911047015CCCC0E8]]></C_TAXCATEGORY_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:37:52.83]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:37:52.83]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[VAT 21%]]></NAME>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+</C_TAXCATEGORY_TRL>
+
+<C_TAXCATEGORY_TRL>
   <C_TAXCATEGORY_TRL_ID><![CDATA[8F0608498EEE4DCDB19CE57895A71B04]]></C_TAXCATEGORY_TRL_ID>
   <C_TAXCATEGORY_ID><![CDATA[4028E6C72959682B01295ADC0FB80217]]></C_TAXCATEGORY_ID>
   <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
@@ -63,6 +93,51 @@
 </C_TAXCATEGORY_TRL>
 
 <C_TAXCATEGORY_TRL>
+  <C_TAXCATEGORY_TRL_ID><![CDATA[B6647EDD6CF449A5B2EE371E7E2CBA53]]></C_TAXCATEGORY_TRL_ID>
+  <C_TAXCATEGORY_ID><![CDATA[B46133FD2AB5460E93520EF475DAF99C]]></C_TAXCATEGORY_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:42:57.195]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:52:03.929]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[IEPS 53%+16%]]></NAME>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+</C_TAXCATEGORY_TRL>
+
+<C_TAXCATEGORY_TRL>
+  <C_TAXCATEGORY_TRL_ID><![CDATA[CB36412EF0744F1BA048AE980076B0E3]]></C_TAXCATEGORY_TRL_ID>
+  <C_TAXCATEGORY_ID><![CDATA[15A62A22F9604828A1C38F0834722AAB]]></C_TAXCATEGORY_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-01-12 10:19:36.408]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-01-12 10:19:36.408]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[VAT 20%]]></NAME>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+</C_TAXCATEGORY_TRL>
+
+<C_TAXCATEGORY_TRL>
+  <C_TAXCATEGORY_TRL_ID><![CDATA[CF8E04972A184BF1919B5D4BA8E81E20]]></C_TAXCATEGORY_TRL_ID>
+  <C_TAXCATEGORY_ID><![CDATA[EB150691C65F46E09BEE9591A6067867]]></C_TAXCATEGORY_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:26:57.66]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:26:57.66]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[IEPS 26.5%+16%]]></NAME>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+</C_TAXCATEGORY_TRL>
+
+<C_TAXCATEGORY_TRL>
   <C_TAXCATEGORY_TRL_ID><![CDATA[D9F4DC116E8C45B78AED82D3C6D76A0B]]></C_TAXCATEGORY_TRL_ID>
   <C_TAXCATEGORY_ID><![CDATA[1955F4CC846840D4832A49BAAC67A45C]]></C_TAXCATEGORY_ID>
   <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
@@ -109,4 +184,19 @@
   <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
 </C_TAXCATEGORY_TRL>
 
+<C_TAXCATEGORY_TRL>
+  <C_TAXCATEGORY_TRL_ID><![CDATA[FB121C91DC6B48EBB5471E18D948922E]]></C_TAXCATEGORY_TRL_ID>
+  <C_TAXCATEGORY_ID><![CDATA[AA65D2E06E4140FCA3BA95A9B130F248]]></C_TAXCATEGORY_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:09:16.136]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 13:09:16.136]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <NAME><![CDATA[Super Tax]]></NAME>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+</C_TAXCATEGORY_TRL>
+
 </data>
--- a/referencedata/sampledata/QA_Testing/C_TAX_ACCT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/referencedata/sampledata/QA_Testing/C_TAX_ACCT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -16,6 +16,21 @@
 </C_TAX_ACCT>
 
 <C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[150828D425A44FCFAECD9B8AC1282214]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[2F7F287739AB43258EA15D58E48C1334]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:27:25.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:27:25.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
   <C_TAX_ACCT_ID><![CDATA[35C0A054712B4716B13CD709E210C1B0]]></C_TAX_ACCT_ID>
   <C_TAX_ID><![CDATA[58A7B9D1DDDD442CAD08052C1B735AFC]]></C_TAX_ID>
   <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
@@ -46,6 +61,21 @@
 </C_TAX_ACCT>
 
 <C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[3823C7720D05414FAB64F84CD14FF3B9]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[0854025824E14FA9AD025289A79EEC05]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:53:26.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:53:26.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
   <C_TAX_ACCT_ID><![CDATA[3A15B58510E343C8B68C8DA1156EA18E]]></C_TAX_ACCT_ID>
   <C_TAX_ID><![CDATA[D85D2465A01C464BA75E053D36FC28EC]]></C_TAX_ID>
   <C_ACCTSCHEMA_ID><![CDATA[432EAC71E1B8451E97C7F54718C4A06B]]></C_ACCTSCHEMA_ID>
@@ -61,6 +91,36 @@
 </C_TAX_ACCT>
 
 <C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[3A72DEC52B1A4A97A503E2B2FBF7ED72]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[8E929CE97C7946F8BB808B9CC3F6D5F2]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-01-12 10:20:32.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-01-12 10:20:32.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[52552176EE4C4AE394743B1A26A5BC90]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[34240B260C6F4908897D1438E16CA6E6]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:10:39.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 13:10:39.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
   <C_TAX_ACCT_ID><![CDATA[574B7B9BD7474412B01BCFF4C67E0BAA]]></C_TAX_ACCT_ID>
   <C_TAX_ID><![CDATA[9EDA6E6317CF4E5E97E3C412467923FA]]></C_TAX_ID>
   <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
@@ -76,6 +136,21 @@
 </C_TAX_ACCT>
 
 <C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[5B2DE9170CE44017BCEEF0CA504A2461]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[A3D779898E5C4542930F31D823B18162]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:55:07.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:55:07.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
   <C_TAX_ACCT_ID><![CDATA[615636DAD37248EDAC76C34988A5BAD5]]></C_TAX_ACCT_ID>
   <C_TAX_ID><![CDATA[BFD013B889E14A20A37180311E557D04]]></C_TAX_ID>
   <C_ACCTSCHEMA_ID><![CDATA[432EAC71E1B8451E97C7F54718C4A06B]]></C_ACCTSCHEMA_ID>
@@ -136,6 +211,21 @@
 </C_TAX_ACCT>
 
 <C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[799F20135ACF490EB3A3D8FC95FF474C]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[854F97A169FF4CFF8FAF504F84139CD2]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:09:44.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 13:09:44.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
   <C_TAX_ACCT_ID><![CDATA[79E71EA9A1894365B2807E84340C5287]]></C_TAX_ACCT_ID>
   <C_TAX_ID><![CDATA[667A8194F0264B0AAA997B8B51F72024]]></C_TAX_ID>
   <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
@@ -151,6 +241,21 @@
 </C_TAX_ACCT>
 
 <C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[7A0BD3E75106443598195FA7B340A082]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[DBFCCC14B64147168F0F516F82FAF38B]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:38:11.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:38:11.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
   <C_TAX_ACCT_ID><![CDATA[7DA0E6FDD8E84745BB9A8DE3B9201C2C]]></C_TAX_ACCT_ID>
   <C_TAX_ID><![CDATA[58A7B9D1DDDD442CAD08052C1B735AFC]]></C_TAX_ID>
   <C_ACCTSCHEMA_ID><![CDATA[432EAC71E1B8451E97C7F54718C4A06B]]></C_ACCTSCHEMA_ID>
@@ -166,6 +271,51 @@
 </C_TAX_ACCT>
 
 <C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[87E169FED3254C6289B95B6D9730F064]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[795DCCA3A72A4147A8C8F1DBFC99C004]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:29:25.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:29:25.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[9316E613E3754291AB637358A6A61D6A]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[E6B01B49600B4859828FF4D268BA5140]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:28:13.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:28:13.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[9D832BE6D2174F50BE110EA65A4477A1]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[BFAF793D760E411D9F6D0DFC7FE6D601]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:50:26.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:50:26.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
   <C_TAX_ACCT_ID><![CDATA[AD4982231AA44C519CB8243A30143603]]></C_TAX_ACCT_ID>
   <C_TAX_ID><![CDATA[D85D2465A01C464BA75E053D36FC28EC]]></C_TAX_ID>
   <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
@@ -181,6 +331,21 @@
 </C_TAX_ACCT>
 
 <C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[C49BC8FD7D91430D9BA690F7B7FF6312]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[5F54E74EEFDD468188BB179F128D49AB]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:37:33.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:37:33.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
+<C_TAX_ACCT>
   <C_TAX_ACCT_ID><![CDATA[C5E9543386354A8C8D8AA923E076859D]]></C_TAX_ACCT_ID>
   <C_TAX_ID><![CDATA[5690F12F2C934F5384FA94F063F63C5F]]></C_TAX_ID>
   <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
@@ -270,4 +435,19 @@
   <T_CREDIT_ACCT><![CDATA[FA66D8B235134769BD64835BBEA60C97]]></T_CREDIT_ACCT>
 </C_TAX_ACCT>
 
+<C_TAX_ACCT>
+  <C_TAX_ACCT_ID><![CDATA[FDB0376E606544F5B1FFB67998304609]]></C_TAX_ACCT_ID>
+  <C_TAX_ID><![CDATA[63BFE8774A4947ABB5151780ABE392AF]]></C_TAX_ID>
+  <C_ACCTSCHEMA_ID><![CDATA[9A68A0F8D72D4580B3EC3CAA00A5E1F0]]></C_ACCTSCHEMA_ID>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:11:45.0]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 13:11:45.0]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <T_DUE_ACCT><![CDATA[BC820B24C87A448B9B64CB10A9F2EE5F]]></T_DUE_ACCT>
+  <T_CREDIT_ACCT><![CDATA[36D9402834944B238108749A27CE6A70]]></T_CREDIT_ACCT>
+</C_TAX_ACCT>
+
 </data>
--- a/referencedata/sampledata/QA_Testing/C_TAX_TRL.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/referencedata/sampledata/QA_Testing/C_TAX_TRL.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -46,6 +46,21 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[12166AD7A926420AAD7C1A40EF078B24]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[DBFCCC14B64147168F0F516F82FAF38B]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:38:11.694]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:38:11.694]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[VAT 21%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[1D776C914FF94F6B87FFFA732A34FBBA]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[9EDA6E6317CF4E5E97E3C412467923FA]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
@@ -61,6 +76,36 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[259AAF8E3A634914BDEFAFDB1DFA5DD5]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[63BFE8774A4947ABB5151780ABE392AF]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:11:45.127]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 13:11:45.127]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[Super Tax 25%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[2CE7745C2CD74D39AA04C051DB8F0981]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[8E929CE97C7946F8BB808B9CC3F6D5F2]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-01-12 10:20:32.719]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-01-12 10:20:32.719]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[VAT 20%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[2D51D64BA7854CF5A9A1A4D1AA160CA7]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[BFD013B889E14A20A37180311E557D04]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[es_ES]]></AD_LANGUAGE>
@@ -76,6 +121,21 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[2FAFFA5516FD4DB2B94944329C4B447B]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[E6B01B49600B4859828FF4D268BA5140]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:28:13.211]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:28:13.211]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[IEPS 26.5%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[30E2D8FB29B0456ABB8C53DA954C8CF0]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[5690F12F2C934F5384FA94F063F63C5F]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
@@ -91,6 +151,21 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[3C14D4557F074789932F6B0AE440E502]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[795DCCA3A72A4147A8C8F1DBFC99C004]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:29:25.155]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:29:25.155]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[IEPS 26.5% VAT 16%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[3CABD299D1064AC5B868F475F74DF432]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[F9D9AF81F4FA459C9CE7A2D9697DF1E4]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[es_ES]]></AD_LANGUAGE>
@@ -106,6 +181,21 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[3E9A1B3F1F794262BE797BB733145B30]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[2F7F287739AB43258EA15D58E48C1334]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 09:27:25.676]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 09:27:25.676]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[IEPS 26.5%+16%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[55BE44C5A86A426A83463CCBB3330B70]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[F9D9AF81F4FA459C9CE7A2D9697DF1E4]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
@@ -136,6 +226,21 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[69EF6EF89BA347B0BAA14F93CB1A234D]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[854F97A169FF4CFF8FAF504F84139CD2]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:09:44.032]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 13:09:44.032]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[Super Tax]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[71F1D4842B8541EFB0AAB1B671A9329F]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[5A74E390B82747F9A5754C8EB1BDB47A]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
@@ -166,6 +271,21 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[8299988FE107473DBE6D4BFE2E05C7DF]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[5F54E74EEFDD468188BB179F128D49AB]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 11:37:33.033]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 11:37:33.033]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[VAT 4%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[84F77945630447EE88BCF6E7FE818DE4]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[9EDA6E6317CF4E5E97E3C412467923FA]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[es_ES]]></AD_LANGUAGE>
@@ -181,6 +301,21 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[850E8FEC762A4E46B0C7A3A78B36517E]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[34240B260C6F4908897D1438E16CA6E6]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-21 13:10:39.464]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-21 13:10:39.464]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[Super Tax 50%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[8E03E163FE374ABB8FF954F755AFA460]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[5A74E390B82747F9A5754C8EB1BDB47A]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[es_ES]]></AD_LANGUAGE>
@@ -196,6 +331,21 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[919E420FFA9D495E9AECD98B1436558E]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[A3D779898E5C4542930F31D823B18162]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:55:07.97]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:55:07.97]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[IEPS 53% VAT 16%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[990427C98D5F4ACDAB41DBA0297FB58A]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[5690F12F2C934F5384FA94F063F63C5F]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[es_ES]]></AD_LANGUAGE>
@@ -226,6 +376,21 @@
 </C_TAX_TRL>
 
 <C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[A7BA822E1F9044E9BE1301297B2BCCFB]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[BFAF793D760E411D9F6D0DFC7FE6D601]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:50:26.696]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:50:26.696]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[IEPS 53%+16%]]></NAME>
+</C_TAX_TRL>
+
+<C_TAX_TRL>
   <C_TAX_TRL_ID><![CDATA[B9D29BDAEA804D19B9E158684987AB84]]></C_TAX_TRL_ID>
   <C_TAX_ID><![CDATA[667A8194F0264B0AAA997B8B51F72024]]></C_TAX_ID>
   <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
@@ -285,4 +450,19 @@
   <NAME><![CDATA[VAT(3)+CHARGE(0.5)]]></NAME>
 </C_TAX_TRL>
 
+<C_TAX_TRL>
+  <C_TAX_TRL_ID><![CDATA[FE4BABD49DF44E3094C928A768B1BB58]]></C_TAX_TRL_ID>
+  <C_TAX_ID><![CDATA[0854025824E14FA9AD025289A79EEC05]]></C_TAX_ID>
+  <AD_LANGUAGE><![CDATA[en_US]]></AD_LANGUAGE>
+  <AD_CLIENT_ID><![CDATA[4028E6C72959682B01295A070852010D]]></AD_CLIENT_ID>
+  <AD_ORG_ID><![CDATA[357947E87C284935AD1D783CF6F099A1]]></AD_ORG_ID>
+  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+  <CREATED><![CDATA[2017-02-22 08:53:26.717]]></CREATED>
+  <CREATEDBY><![CDATA[100]]></CREATEDBY>
+  <UPDATED><![CDATA[2017-02-22 08:53:26.717]]></UPDATED>
+  <UPDATEDBY><![CDATA[100]]></UPDATEDBY>
+  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+  <NAME><![CDATA[IEPS 53%]]></NAME>
+</C_TAX_TRL>
+
 </data>
--- a/src-core/src/org/openbravo/data/Sql.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-core/src/org/openbravo/data/Sql.java	Wed Mar 15 18:56:27 2017 +0100
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2010 Openbravo S.L.U.
+ * Copyright (C) 2001-2017 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -34,6 +34,7 @@
   Vector<Object> vecFieldAdded; // vector of fields added to the Class
   String strSequenceName = null;
   boolean boolOptional = false;
+  boolean saveContextInfo = true;
   static Logger log4j = Logger.getLogger(Sql.class); // log4j
 
   public Sql() {
--- a/src-core/src/org/openbravo/data/Sqlc.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-core/src/org/openbravo/data/Sqlc.java	Wed Mar 15 18:56:27 2017 +0100
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2016 Openbravo S.L.U.
+ * Copyright (C) 2001-2017 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -92,6 +92,7 @@
 
   static Logger log4j = Logger.getLogger(Sqlc.class); // log4j
   private static boolean includeQueryTimeOut;
+  private boolean sessionInfoImported;
 
   private List<String> scrollableFunctionNames = new ArrayList<String>();
   private boolean hasCountField;
@@ -109,6 +110,7 @@
     sqlcAccessModifier = "";
     scrollableFunctionNames = new ArrayList<String>();
     hasCountField = false;
+    sessionInfoImported = false;
   }
 
   public static void main(String argv[]) throws Exception {
@@ -466,6 +468,8 @@
           sql.sqlImport = amap.getValue(i);
         } else if (amap.getQName(i).equals("useQueryProfile")) {
           sql.useQueryProfile = "true".equalsIgnoreCase(amap.getValue(i));
+        } else if (amap.getQName(i).equals("saveContextInfo")) {
+          sql.saveContextInfo = "true".equalsIgnoreCase(amap.getValue(i));
         }
       }
       if (sqlPackage != null)
@@ -775,7 +779,10 @@
     out1.append("import org.openbravo.data.UtilSql;\n");
     if (includeQueryTimeOut) {
       out1.append("import org.openbravo.service.db.QueryTimeOutUtil;\n");
-      out1.append("import org.openbravo.database.SessionInfo;\n");
+      if (!sessionInfoImported) {
+        out1.append("import org.openbravo.database.SessionInfo;\n");
+        sessionInfoImported = true;
+      }
     }
 
     if (sql.sqlImport != null) {
@@ -1395,6 +1402,20 @@
     printSQLBody();
     printSQLParameters();
 
+    if (sql.saveContextInfo && !"executeQuery".equals(sql.executeType)) {
+      if (!sessionInfoImported) {
+        out1.append("import org.openbravo.database.SessionInfo;\n");
+        sessionInfoImported = true;
+      }
+      out2.append("      SessionInfo.saveContextInfoIntoDB(");
+      if (sql.sqlConnection.equals("true")) {
+        out2.append("conn");
+      } else {
+        out2.append("connectionProvider.getConnection()");
+      }
+      out2.append(");\n");
+    }
+
     if (sql.executeType.equals("executeQuery")) {
       out2.append("      result = st." + sql.executeType + "(");
       if (sql.sqlType.equals("statement"))
--- a/src-core/src/org/openbravo/database/ConnectionProviderImpl.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-core/src/org/openbravo/database/ConnectionProviderImpl.java	Wed Mar 15 18:56:27 2017 +0100
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2015 Openbravo S.L.U.
+ * Copyright (C) 2001-2017 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -235,9 +235,6 @@
     if (conn == null) {
       conn = getNewConnection(poolName);
       SessionInfo.setSessionConnection(conn);
-    } else {
-      // Update session info if needed
-      SessionInfo.setDBSessionInfo(conn, true);
     }
     return conn;
   }
@@ -278,10 +275,6 @@
     try {
       conn = DriverManager
           .getConnection("jdbc:apache:commons:dbcp:" + contextName + "_" + poolName);
-      // Set session info for the connection, but do not attach the connection to
-      // the session since
-      // it shouldn't be reused
-      SessionInfo.setDBSessionInfo(conn);
     } catch (SQLException ex) {
       log4j.error("Error getting connection", ex);
       throw new NoConnectionAvailableException(
@@ -340,7 +333,6 @@
     if (conn == null)
       throw new NoConnectionAvailableException("CouldnĀ“t get an available connection");
     conn.setAutoCommit(false);
-    SessionInfo.setDBSessionInfo(conn);
     return conn;
   }
 
--- a/src-core/src/org/openbravo/database/ExternalConnectionPool.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-core/src/org/openbravo/database/ExternalConnectionPool.java	Wed Mar 15 18:56:27 2017 +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. 
  ************************************************************************
  */
@@ -29,6 +29,8 @@
 public abstract class ExternalConnectionPool {
 
   static Logger log = Logger.getLogger(ExternalConnectionPool.class);
+  public static final String DEFAULT_POOL = "DEFAULT";
+  public static final String READONLY_POOL = "RO";
 
   private static ExternalConnectionPool instance;
 
@@ -52,6 +54,13 @@
   }
 
   /**
+   * @return the singleton instance of the external connection pool
+   */
+  public final static ExternalConnectionPool getInstance() {
+    return instance;
+  }
+
+  /**
    * If the external connection pool should be closed this method should be overwritten
    */
   public void closePool() {
@@ -72,4 +81,19 @@
    */
   public abstract Connection getConnection();
 
+  /**
+   * This method is intended to be overridden by external connection multi-pools. This kind of pools
+   * can handle several datasources and this method allows to select from which of them the
+   * connection should be taken.
+   * 
+   * @param poolName
+   *          The name of the external connection pool
+   * 
+   * @return A Connection from the external connection pool whose name is passed as parameter
+   * 
+   */
+  public Connection getConnection(String poolName) {
+    return getConnection();
+  }
+
 }
--- a/src-core/src/org/openbravo/database/JNDIConnectionProvider.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-core/src/org/openbravo/database/JNDIConnectionProvider.java	Wed Mar 15 18:56:27 2017 +0100
@@ -1,6 +1,6 @@
 /*
  * 
- * Copyright (C) 2001-2015 Openbravo S.L.U. Licensed under the Apache Software
+ * Copyright (C) 2001-2017 Openbravo S.L.U. Licensed under the Apache Software
  * License version 2.0 You may obtain a copy of the License at
  * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
  * or agreed to in writing, software distributed under the License is
@@ -125,8 +125,6 @@
       throw new NoConnectionAvailableException(e.getMessage());
     }
 
-    SessionInfo.setDBSessionInfo(conn);
-
     return conn;
   }
 
--- a/src-core/src/org/openbravo/database/RDBMSIndependent.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-core/src/org/openbravo/database/RDBMSIndependent.java	Wed Mar 15 18:56:27 2017 +0100
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2015 Openbravo S.L.U.
+ * Copyright (C) 2001-2017 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -60,10 +60,13 @@
       strSql.append(sql);
 
     PreparedStatement st = null;
-    if (conn == null)
+    if (conn == null) {
+      SessionInfo.saveContextInfoIntoDB(connectionProvider.getConnection());
       st = connectionProvider.getPreparedStatement(strSql.toString());
-    else
+    } else {
+      SessionInfo.saveContextInfoIntoDB(conn);
       st = connectionProvider.getPreparedStatement(conn, strSql.toString());
+    }
     ResultSet result;
     Vector<String> total = new Vector<String>();
 
--- a/src-core/src/org/openbravo/database/SessionInfo.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-core/src/org/openbravo/database/SessionInfo.java	Wed Mar 15 18:56:27 2017 +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) 2009-2016 Openbravo SLU
+ * All portions are Copyright (C) 2009-2017 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -68,6 +68,8 @@
    */
   private static ThreadLocal<String> moduleId = new ThreadLocal<String>();
 
+  private static ThreadLocal<Boolean> auditThisThread = new ThreadLocal<Boolean>();
+
   /**
    * Sets all session information to null. Called at the end of http-request handling, to reset the
    * audit information for that thread.
@@ -81,6 +83,7 @@
     moduleId.set(null);
     command.set(null);
     queryProfile.set(null);
+    auditThisThread.set(true);
     // if there is an open connection associated to get current request, close it
     Connection conn = sessionConnection.get();
     try {
@@ -113,6 +116,10 @@
       PreparedStatement psQuery = null;
       PreparedStatement psCreate = null;
       try {
+        if (conn.isReadOnly()) {
+          return;
+        }
+
         psQuery = getPreparedStatement(
             conn,
             "select count(*) from information_schema.tables where table_name='ad_context_info' and table_type = 'LOCAL TEMPORARY'");
@@ -138,15 +145,14 @@
   }
 
   /**
-   * Inserts in the session table the information about the Openbravo session.
-   * 
-   * This methods optimizes the ad_context_info update away, if the 'user'-info associated with a
-   * connection didn't change
-   * 
-   * @param conn
-   *          Connection where the session information will be stored in
-   * @param onlyIfChanged
-   *          Updates database info only in case there are changes since the last time it was set
+   * @deprecated In most of the cases, this method is no longer required to be invoked: it was used
+   *             to manually set in database audit info. Now, this is in an smarter manner only if
+   *             needed from DAL/SQLC. When this method is still in use, it should be reviewed
+   *             whether it is no longer needed because of this automatic mechanism or if it is
+   *             required because new mechanism doesn't detect it (ie. DB modifications directly
+   *             with jdbc), in which case saveContextInfoIntoDB method is recommended to make
+   *             explicit in the code this need
+   * @see #saveContextInfoIntoDB(Connection)
    */
   static void setDBSessionInfo(Connection conn, boolean onlyIfChanged) {
     if (!isAuditActive || (onlyIfChanged && (changedInfo.get() == null || !changedInfo.get()))) {
@@ -156,24 +162,51 @@
       }
       return;
     }
-    setDBSessionInfo(conn);
+    saveContextInfoIntoDB(conn);
   }
 
   /**
-   * Inserts in the session table the information about the Openbravo session.
+   * @deprecated In most of the cases this method is no longer required to be invoked
+   * @see #saveContextInfoIntoDB(Connection)
+   */
+  public static void setDBSessionInfo(Connection conn) {
+    saveContextInfoIntoDB(conn);
+  }
+
+  /**
+   * Saves currently stored context information into DB. Generally, this method shouldn't be
+   * directly invoked, as the Platform already does it when flushing changes to DB. Only in case
+   * Openbravo platform is bypassed (ie. DB operations performed on a manually obtained connection),
+   * this method must be manually invoked.
    * 
    * @param conn
-   *          Connection where the session information will be stored in
+   *          The connection where the session information will be stored in, note it must be the
+   *          same one performing DB modifications so audit trail triggers can retrieve the session
+   *          information.
    */
-  public static void setDBSessionInfo(Connection conn) {
+  public static void saveContextInfoIntoDB(Connection conn) {
     if (!isAuditActive) {
       return;
     }
-    log4j.debug("set session info");
-    // Clean up temporary table
+
     PreparedStatement psCleanUp = null;
     PreparedStatement psInsert = null;
     try {
+      // When working with DAL sessionConnection is not set. This allows to have in the same thread
+      // a connection for DAL within its session with autocommit false and another one for sqlc with
+      // autocommit true.
+      boolean infoModified = Boolean.TRUE.equals(changedInfo.get())
+          || sessionConnection.get() == null || !conn.equals(sessionConnection.get());
+      if (!infoModified || Boolean.FALSE.equals(auditThisThread.get()) || conn.isReadOnly()) {
+        return;
+      }
+
+      if (log4j.isDebugEnabled()) {
+        log4j.debug("saving DB context info " + SessionInfo.getUserId() + " - "
+            + SessionInfo.getSessionId() + " - " + SessionInfo.getProcessType() + " - "
+            + SessionInfo.getProcessId());
+      }
+
       psCleanUp = getPreparedStatement(conn, "delete from ad_context_info");
       psCleanUp.executeUpdate();
 
@@ -185,7 +218,11 @@
       psInsert.setString(3, SessionInfo.getProcessType());
       psInsert.setString(4, SessionInfo.getProcessId());
       psInsert.executeUpdate();
-      changedInfo.set(false);
+      if (conn.equals(sessionConnection.get())) {
+        // Handling only for the sqlc connection, as DAL should be automatically handled so that
+        // this method is invoked only once.
+        changedInfo.set(false);
+      }
     } catch (Exception e) {
       log4j.error("Error setting audit info", e);
     } finally {
@@ -356,4 +393,9 @@
   public static void setUsageAuditActive(boolean usageAuditActive) {
     SessionInfo.usageAuditActive = usageAuditActive;
   }
+
+  /** Set this value to {@code false} to prevent context info to be set in DB */
+  public static void auditThisThread(boolean shouldAudit) {
+    auditThisThread.set(shouldAudit);
+  }
 }
--- a/src-core/src/org/openbravo/uiTranslation/TextInterfacesData.java	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-core/src/org/openbravo/uiTranslation/TextInterfacesData.java	Wed Mar 15 18:56:27 2017 +0100
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2008-2010 Openbravo S.L.U.
+ * Copyright (C) 2008-2017 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -67,7 +67,7 @@
     strSql = strSql
         + "      select "
         + "		  text.filename as filename, text.text as text, text.isused as isUsed, text.ad_module_id as moduleId,"
-        + "		  texttrl.ad_language as trlLang, texttrl.text as trlText, texttrl.istranslated as isTranslated, 3 as orderSeq"
+        + "		  texttrl.ad_language as trlLang, texttrl.text as trlText, texttrl.istranslated as isTranslated, 1 as orderSeq"
         + "		from " + "		  ad_textinterfaces text," + "		  ad_textinterfaces_trl texttrl"
         + "		where" + "		  text.ad_textinterfaces_id = texttrl.ad_textinterfaces_id "
         + "		  and text.filename = '";
@@ -79,7 +79,7 @@
         + "		UNION"
         + "		select "
         + "		  text.filename as filename, text.text as text, text.isused as isUsed, text.ad_module_id as moduleId,"
-        + "		  texttrl.ad_language as trlLang, texttrl.text as trlText, texttrl.istranslated as isTranslated, 2 as orderSeq"
+        + "		  texttrl.ad_language as trlLang, texttrl.text as trlText, texttrl.istranslated as isTranslated, 3 as orderSeq"
         + "		from " + "		  ad_textinterfaces text," + "		  ad_textinterfaces_trl texttrl"
         + "		where" + "		  text.ad_textinterfaces_id = texttrl.ad_textinterfaces_id "
         + "		  and text.filename is null" + "		  and text.isused = 'Y' and texttrl.ad_language = '";
@@ -89,7 +89,7 @@
         + "		  text.ad_module_id as moduleId, '";
     strSql = strSql + ((language == null || language.equals("")) ? "" : language);
     strSql = strSql + "' as trlLang, "
-        + "		  text.text as trlText, 'N' as isTranslated, 1 as orderSeq" + "		from "
+        + "		  text.text as trlText, 'N' as isTranslated, 2 as orderSeq" + "		from "
         + "		  ad_textinterfaces text" + "		where" + "		  text.ad_textinterfaces_id NOT IN "
         + "			(SELECT t.ad_textinterfaces_id" + "			  FROM ad_textInterfaces t,"
         + "				  ad_textinterfaces_trl trl" + "			  WHERE "
@@ -105,19 +105,6 @@
 
     try {
       st = connectionProvider.getPreparedStatement(strSql);
-      if (htmlFile != null && !(htmlFile.equals(""))) {
-      }
-      if (language != null && !(language.equals(""))) {
-      }
-      if (language != null && !(language.equals(""))) {
-      }
-      if (language != null && !(language.equals(""))) {
-      }
-      if (language != null && !(language.equals(""))) {
-      }
-      if (htmlFile != null && !(htmlFile.equals(""))) {
-      }
-
       result = st.executeQuery();
       while (result.next()) {
         TextInterfacesData objectTextInterfacesData = new TextInterfacesData();
--- a/src-db/database/build.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/build.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -12,7 +12,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-2015 Openbravo SLU 
+ * All portions are Copyright (C) 2001-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -29,6 +29,7 @@
   <property environment="env" />
   <property name="forcedRecreation" value=""/>
   <property name="execute.modulescripts" value="true"/>
+  <property name="max.threads" value="-1"/>
   <condition property="bbdd.owner.url" value="${bbdd.url}/${bbdd.sid}" else="${bbdd.url}">
     <and>
       <equals arg1="${bbdd.rdbms}" arg2="POSTGRE" />
@@ -72,7 +73,7 @@
   </target>
 
   <target name="update.database">
-    <alterdatabasedataall driver="${bbdd.driver}" url="${bbdd.owner.url}" user="${bbdd.user}" password="${bbdd.password}" excludeobjects="com.openbravo.db.OpenbravoExcludeFilter" model="model" filter="com.openbravo.db.OpenbravoMetadataFilter" input="sourcedata" object="${bbdd.object}" failonerror="false" verbosity="${bbdd.verbosity}" basedir="${base.modules}/" dirFilter="*/src-db/database/model" datadir="${base.modules}/" dataFilter="*/src-db/database/sourcedata" userId="0" adminMode="true" propertiesFile="${base.config}/Openbravo.properties" force="${force}" onlyIfModified="${onlyIfModified}" forcedRecreation="${forcedRecreation}" executeModuleScripts="${execute.modulescripts}"/>
+    <alterdatabasedataall driver="${bbdd.driver}" url="${bbdd.owner.url}" user="${bbdd.user}" password="${bbdd.password}" excludeobjects="com.openbravo.db.OpenbravoExcludeFilter" model="model" filter="com.openbravo.db.OpenbravoMetadataFilter" input="sourcedata" object="${bbdd.object}" failonerror="false" verbosity="${bbdd.verbosity}" basedir="${base.modules}/" dirFilter="*/src-db/database/model" datadir="${base.modules}/" dataFilter="*/src-db/database/sourcedata" userId="0" adminMode="true" propertiesFile="${base.config}/Openbravo.properties" force="${force}" onlyIfModified="${onlyIfModified}" forcedRecreation="${forcedRecreation}" executeModuleScripts="${execute.modulescripts}" threads="${max.threads}"/>
     <antcall target="database.postupdate.${bbdd.rdbms}" />
     <antcall target="update.dbupdate.timestamp" />
   </target>
@@ -99,6 +100,7 @@
       <arg value="${strict.template.application}"/>
       <arg value="${forcedRecreation}"/>
       <arg value="${execute.modulescripts}"/>
+      <arg value="${max.threads}"/>
       <classpath refid="runtime-classpath" />
       <syspropertyset>
          <propertyref name="java.security.egd" />
@@ -156,7 +158,7 @@
       <taskdef name="exportdatabase" classname="org.openbravo.ddlutils.task.ExportDatabase">
         <classpath refid="runtime-classpath" />
       </taskdef>
-      <exportdatabase driver="${bbdd.driver}" url="${bbdd.owner.url}" user="${bbdd.user}" password="${bbdd.password}" excludeobjects="com.openbravo.db.OpenbravoExcludeFilter" model="model" moduledir="${base.modules}" verbosity="${bbdd.verbosity}" output="sourcedata" codeRevision="${code.revision}" userId="0" adminMode="true" propertiesFile="${base.config}/Openbravo.properties" force="${force}" validateModel="${validate.model}" testAPI="${isMinorVersion}" datasetList="AD,ADRD" rd="${rd}" checkTranslationConsistency="${checkTranslationConsistency}"/>
+      <exportdatabase driver="${bbdd.driver}" url="${bbdd.owner.url}" user="${bbdd.user}" password="${bbdd.password}" excludeobjects="com.openbravo.db.OpenbravoExcludeFilter" model="model" moduledir="${base.modules}" verbosity="${bbdd.verbosity}" output="sourcedata" codeRevision="${code.revision}" userId="0" adminMode="true" propertiesFile="${base.config}/Openbravo.properties" force="${force}" validateModel="${validate.model}" testAPI="${isMinorVersion}" datasetList="AD,ADRD" rd="${rd}" checkTranslationConsistency="${checkTranslationConsistency}" threads="${max.threads}"/>
       <antcall target="update.dbupdate.timestamp" />
   </target>
 
Binary file src-db/database/lib/dbsourcemanager.jar has changed
--- a/src-db/database/model/excludeFilter.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/excludeFilter.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -67,4 +67,24 @@
     <excludedFunction name="ADD_HMS"/>
     <excludedFunction name="PG\_%"/> <!-- PostgreSQL extension functions -->
     <excludedTrigger name="AU\_%"/> <!-- Audit trail triggers -->
+    <excludedFunction name="GIN_EXTRACT_QUERY_TRGM"/>
+    <excludedFunction name="GIN_EXTRACT_VALUE_TRGM"/>
+    <excludedFunction name="GIN_TRGM_CONSISTENT"/>
+    <excludedFunction name="GTRGM_COMPRESS"/>
+    <excludedFunction name="GTRGM_CONSISTENT"/>
+    <excludedFunction name="GTRGM_DECOMPRESS"/>
+    <excludedFunction name="GTRGM_DISTANCE"/>
+    <excludedFunction name="GTRGM_IN"/>
+    <excludedFunction name="GTRGM_OUT"/>
+    <excludedFunction name="GTRGM_PENALTY"/>
+    <excludedFunction name="GTRGM_PICKSPLIT"/>
+    <excludedFunction name="GTRGM_SAME"/>
+    <excludedFunction name="GTRGM_UNION"/>
+    <excludedFunction name="SET_LIMIT"/>
+    <excludedFunction name="SHOW_LIMIT"/>
+    <excludedFunction name="SHOW_TRGM"/>
+    <excludedFunction name="SIMILARITY"/>
+    <excludedFunction name="SIMILARITY_DIST"/>
+    <excludedFunction name="SIMILARITY_OP"/>
+    <excludedFunction name="OBEQUALS"/>
   </vector>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-db/database/model/functions/C_CONVERT_DOC_CURRENCY.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,82 @@
+<?xml version="1.0"?>
+  <database name="FUNCTION C_CONVERT_DOC_CURRENCY">
+    <function name="C_CONVERT_DOC_CURRENCY" type="NUMERIC">
+      <parameter name="p_amount" type="NUMERIC" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_curfrom_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_curto_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_convdate" type="TIMESTAMP" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_c_invoice_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_fin_payment_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_fin_finacc_transaction_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_client_id" type="VARCHAR" mode="in">
+        <default><![CDATA[0]]></default>
+      </parameter>
+      <parameter name="p_org_id" type="VARCHAR" mode="in">
+        <default><![CDATA[0]]></default>
+      </parameter>
+      <body><![CDATA[/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2011 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+  v_Rate NUMBER;
+  v_ConvDate DATE;
+BEGIN
+
+  IF(p_Amount=0 OR p_CurFrom_ID=p_CurTo_ID) THEN
+    RETURN p_Amount;
+  END IF;
+
+  if (p_convdate > now()) then
+    v_ConvDate:=now();
+  else
+    v_ConvDate:=p_convdate;
+  end if;
+
+  if (p_fin_finacc_transaction_id is not null) then
+    select foreign_convert_rate into v_rate from fin_finacc_transaction fat where fin_finacc_transaction_id=p_fin_finacc_transaction_id;
+  elsif (p_fin_payment_id is not null) then
+    select finacc_txn_convert_rate into v_rate from fin_payment where fin_payment_id=p_fin_payment_id;
+  elsif (p_c_invoice_id is not null) then
+    select rate into v_Rate from c_conversion_rate_document where c_invoice_id=p_c_invoice_id and c_currency_id=p_curfrom_id and c_currency_id_to=p_curto_id;
+  end if;
+
+  if (v_Rate is not null) then
+    return ROUND(p_Amount * v_Rate, C_GET_CURRENCY_PRECISION(p_CurTo_ID, 'A'));
+  else
+    RETURN C_CURRENCY_CONVERT(p_amount, p_curfrom_id, p_curto_id, p_convdate, null, p_client_id, p_org_id);
+  end if;
+
+EXCEPTION
+WHEN OTHERS THEN
+  DBMS_OUTPUT.PUT_LINE(SQLERRM);
+  RAISE;
+END C_CONVERT_DOC_CURRENCY
+]]></body>
+    </function>
+  </database>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-db/database/model/functions/C_GET_NET_AMOUNT_FROM_GROSS.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,59 @@
+<?xml version="1.0"?>
+  <database name="FUNCTION C_GET_NET_AMOUNT_FROM_GROSS">
+    <function name="C_GET_NET_AMOUNT_FROM_GROSS" type="NUMERIC">
+      <parameter name="p_tax_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_grossamt" type="NUMERIC" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_alternatetaxbaseamt" type="NUMERIC" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_stdprecision" type="NUMERIC" mode="in">
+        <default><![CDATA[NULL]]></default>
+      </parameter>
+      <body><![CDATA[/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2017 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+
+v_ResultStr VARCHAR(2000) := '';
+v_calcPrecision NUMBER:= 50;
+v_TaxAmount NUMBER;
+v_NetAmount NUMBER;
+
+BEGIN --BODY
+
+  IF (p_grossamt = 0) THEN
+    RETURN 0;
+  END IF;
+
+  v_TaxAmount := C_GET_TAX_AMT_FROM_NET(p_tax_id, p_grossamt, p_alternatetaxbaseamt, v_calcPrecision, 0);
+  v_NetAmount := ROUND(p_grossamt * (p_grossamt  / (p_grossamt + v_TaxAmount)), v_calcPrecision);
+  IF (p_stdprecision IS NOT NULL) THEN
+    v_NetAmount := ROUND(v_NetAmount, p_stdprecision);
+  END IF;
+  RETURN v_NetAmount;
+
+EXCEPTION
+WHEN OTHERS THEN
+  v_ResultStr:= '@ERROR=' || SQLERRM;
+  DBMS_OUTPUT.PUT_LINE(v_ResultStr) ;
+  RAISE;
+END C_GET_NET_AMOUNT_FROM_GROSS
+]]></body>
+    </function>
+  </database>
--- a/src-db/database/model/functions/C_INVOICELINETAX_INSERT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/C_INVOICELINETAX_INSERT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -40,7 +40,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) 2010-2016 Openbravo SLU
+* All portions are Copyright (C) 2010-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -78,7 +78,7 @@
       v_TaxBaseAmount:=0;
     END IF;
     IF (v_BaseAmount='TAX' OR v_BaseAmount='LNATAX' OR v_BaseAmount='TBATAX') THEN
-      SELECT COALESCE(SUM(TAXAMT),0) + v_TaxBaseAmount
+      SELECT COALESCE(SUM(TAXAMT), 0) + v_TaxBaseAmount
       INTO v_TaxBaseAmount
       FROM C_INVOICELINETAX, C_TAX
       WHERE C_INVOICELINETAX.C_TAX_ID = C_TAX.C_TAX_ID
@@ -103,12 +103,12 @@
       INSERT
       INTO C_INVOICELINETAX (
       C_InvoiceLineTax_ID, C_InvoiceLine_ID, C_Invoice_ID, C_Tax_ID, AD_Client_ID, AD_Org_ID,
-      IsActive, Created, CreatedBy, Updated,
-      UpdatedBy, TaxBaseAmt, TaxAmt, Line)
+      IsActive, Created, CreatedBy, Updated, UpdatedBy,
+      TaxBaseAmt, TaxAmt, Line)
       VALUES (
       GET_UUID(), p_invoiceline_id, p_invoice_id, p_tax_id, v_Client_ID, p_org_id,
-      'Y', now(), p_user_id, now(),
-      p_user_id, v_TaxBaseAmount, ROUND(v_TaxBaseAmount*v_Rate / 100, p_StdPrecision), v_LineNo);
+      'Y', now(), p_user_id, now(), p_user_id,
+      v_TaxBaseAmount, ROUND(ROUND(v_TaxBaseAmount, p_StdPrecision) * v_Rate/100, p_StdPrecision), v_LineNo);
     ELSE
       FOR Cur_Taxes IN
         (SELECT C_Tax_ID, RATE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-db/database/model/functions/C_INVOICETAX_ADJUSTMENT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,187 @@
+<?xml version="1.0"?>
+  <database name="FUNCTION C_INVOICETAX_ADJUSTMENT">
+    <function name="C_INVOICETAX_ADJUSTMENT" type="NULL">
+      <parameter name="p_invoice_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_precision" type="NUMERIC" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_action" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <body><![CDATA[/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2017 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+-- Variables
+v_taxAmt C_INVOICETAX.TaxAmt%TYPE;
+v_amount C_INVOICELINE.Line_Gross_Amount%TYPE;
+TYPE RECORD IS REF CURSOR;
+CUR_Tax RECORD;
+CUR_Line RECORD;
+
+BEGIN --BODY
+
+  -- Round and Adjust taxes
+  IF (p_action = 'CO') THEN
+
+    -- Disable triggers
+    INSERT INTO AD_Session_Status (ad_session_status_id, ad_client_id, ad_org_id, isactive, created, createdby, updated, updatedby, isimporting)
+    VALUES (get_uuid(), '0', '0', 'Y', now(), '0', now(), '0', 'Y');
+
+    -- Round
+    UPDATE C_INVOICELINETAX
+    SET TaxBaseAmt = round(TaxBaseAmt, p_precision)
+    WHERE C_Invoice_ID = p_invoice_id;
+
+    UPDATE C_INVOICETAX
+    SET TaxBaseAmt = round(TaxBaseAmt, p_precision)
+    WHERE C_Invoice_ID = p_invoice_id
+    AND Recalculate = 'Y';
+
+    -- Adjust
+    FOR CUR_Tax IN (
+      SELECT it.C_Tax_ID, COALESCE((MIN(it.DocTaxBaseAmt) + MIN(it.DocTaxAmt)) - (SUM(ilt.LineTaxBaseAmt) + SUM(ilt.LineTaxAmt)), 0) as TaxAdjustment, COALESCE(MIN(it.DocTaxBaseAmt) - SUM(ilt.LineTaxBaseAmt), 0) as LineAdjustment
+      FROM (
+        SELECT c_tax_get_root(it.c_tax_id) as C_Tax_ID, CASE WHEN MIN(it.TaxBaseAmt) > 0 THEN MIN(it.TaxBaseAmt) ELSE MAX(it.TaxBaseAmt) END as DocTaxBaseAmt, SUM(it.TaxAmt) as DocTaxAmt, MIN(it.Line) as Line
+        FROM C_InvoiceTax it
+        JOIN C_Tax t
+        ON it.C_Tax_ID = t.C_Tax_ID
+        WHERE it.C_Invoice_ID = p_invoice_id
+        AND it.Recalculate = 'Y'
+        AND t.DocTaxAmount = 'D'
+        GROUP BY c_tax_get_root(it.c_tax_id)
+      ) it
+      JOIN (
+        SELECT c_tax_get_root(ilt.c_tax_id) as C_Tax_ID, CASE WHEN MIN(ilt.TaxBaseAmt) > 0 THEN MIN(ilt.TaxBaseAmt) ELSE MAX(ilt.TaxBaseAmt) END as LineTaxBaseAmt, SUM(ilt.TaxAmt) as LineTaxAmt
+        FROM C_InvoiceLineTax ilt
+        JOIN C_Tax t
+        ON ilt.C_Tax_ID = t.C_Tax_ID
+        WHERE ilt.C_Invoice_ID = p_invoice_id
+        AND t.DocTaxAmount = 'D'
+        GROUP BY ilt.C_InvoiceLine_ID, c_tax_get_root(ilt.c_tax_id)
+      ) ilt
+      ON ilt.C_Tax_ID = it.C_Tax_ID
+      GROUP BY it.C_Tax_ID, it.Line
+      HAVING COALESCE(MIN(it.DocTaxBaseAmt), 0) <> COALESCE(SUM(ilt.LineTaxBaseAmt), 0)
+      OR COALESCE(MIN(it.DocTaxBaseAmt) + MIN(it.DocTaxAmt), 0) <> COALESCE(SUM(ilt.LineTaxBaseAmt) + SUM(ilt.LineTaxAmt), 0)
+      ORDER BY it.Line
+    )
+    LOOP
+      -- Adjust TaxAmt
+      IF (CUR_Tax.TaxAdjustment <> 0) THEN
+        FOR CUR_Line IN (
+          SELECT it.C_InvoiceTax_ID, it.C_Tax_ID, t.Line
+          FROM C_InvoiceTax it
+          JOIN C_Tax t
+          ON it.C_Tax_ID = t.C_Tax_ID
+          WHERE it.C_Invoice_ID = p_invoice_id
+          AND it.Recalculate = 'Y'
+          AND c_tax_get_root(it.C_Tax_ID) = CUR_Tax.C_Tax_ID
+          ORDER BY ABS(it.TaxAmt) DESC, t.Line DESC
+        )
+        LOOP
+          UPDATE C_INVOICETAX
+          SET TaxAmt = TaxAmt - CUR_Tax.TaxAdjustment
+          WHERE C_InvoiceTax_ID = CUR_Line.C_InvoiceTax_ID;
+
+          UPDATE C_INVOICETAX it
+          SET TaxBaseAmt = TaxBaseAmt - CUR_Tax.TaxAdjustment
+          WHERE it.C_Invoice_ID = p_invoice_id
+          AND it.Recalculate = 'Y'
+          AND c_tax_get_root(it.C_Tax_ID) = CUR_Tax.C_Tax_ID
+          AND EXISTS (
+            SELECT 1
+            FROM C_Tax t
+            WHERE t.C_Tax_ID = it.C_Tax_ID
+            AND ((t.Cascade = 'Y'
+            AND t.Line > CUR_Line.Line)
+            OR (t.BaseAmount IN ('TAX', 'LNATAX', 'TBATAX')
+            AND C_TAX_ISMEMBER(t.C_TaxBase_ID, CUR_Line.C_Tax_ID) = 1
+            AND t.IsSummary = 'N'))
+          );
+
+          EXIT;
+        END LOOP;
+      END IF;
+
+      -- Adjust LineNetAmt
+      IF (CUR_Tax.LineAdjustment <> 0) THEN
+        FOR CUR_Line IN (
+          SELECT il.C_InvoiceLine_ID
+          FROM C_InvoiceLine il
+          WHERE il.C_Invoice_ID = p_invoice_id
+          AND EXISTS (
+            SELECT 1
+            FROM C_InvoiceLineTax ilt
+            WHERE il.C_InvoiceLine_ID = ilt.C_InvoiceLine_ID
+            AND c_tax_get_root(ilt.C_Tax_ID) = CUR_Tax.c_Tax_ID
+          )
+          ORDER BY ABS(il.LineNetAmt) DESC, il.Line DESC
+        )
+        LOOP
+          UPDATE C_INVOICELINE
+          SET LineNetAmt = LineNetAmt + CUR_Tax.LineAdjustment
+          WHERE C_InvoiceLine_ID = CUR_Line.C_InvoiceLine_ID;
+
+          -- TODO: Adjust C_InvoiceLineTax accordingly
+
+          EXIT;
+        END LOOP;
+      END IF;
+    END LOOP;
+
+    -- Enable triggers
+    DELETE FROM AD_Session_Status
+    WHERE isimporting = 'Y';
+
+  -- Recalculate amounts and taxes
+  ELSIF (p_action = 'RE') THEN
+
+    -- Remove header amounts and taxes
+    DELETE FROM C_INVOICETAX WHERE C_Invoice_ID = p_invoice_id AND Recalculate = 'Y';
+    SELECT COALESCE(SUM(TaxAmt), 0) INTO v_taxAmt FROM C_INVOICETAX WHERE C_Invoice_ID = p_invoice_id AND Recalculate = 'N';
+    UPDATE C_INVOICE SET TotalLines = 0, GrandTotal = v_taxAmt WHERE C_Invoice_ID = p_invoice_id;
+
+    FOR Cur_line IN (
+      SELECT C_InvoiceLine_ID
+      FROM C_INVOICELINE
+      WHERE C_Invoice_ID = p_invoice_id
+    ) LOOP
+
+      -- Disable triggers
+      INSERT INTO AD_Session_Status (ad_session_status_id, ad_client_id, ad_org_id, isactive, created, createdby, updated, updatedby, isimporting)
+      VALUES (get_uuid(), '0', '0', 'Y', now(), '0', now(), '0', 'Y');
+
+      -- Remove line amounts and taxes
+      DELETE FROM C_INVOICELINETAX WHERE C_InvoiceLine_ID = Cur_line.C_InvoiceLine_ID;
+      SELECT Line_Gross_Amount INTO v_amount FROM C_INVOICELINE WHERE C_InvoiceLine_ID = Cur_line.C_InvoiceLine_ID;
+      UPDATE C_INVOICELINE SET Line_Gross_Amount = 0 WHERE C_InvoiceLine_ID = Cur_line.C_InvoiceLine_ID;
+
+      -- Enable triggers
+      DELETE FROM AD_Session_Status
+      WHERE isimporting = 'Y';
+
+      -- Recalculate amounts and taxes
+      UPDATE C_INVOICELINE SET Line_Gross_Amount = v_amount WHERE C_InvoiceLine_ID = Cur_line.C_InvoiceLine_ID;
+
+    END LOOP;
+
+  END IF;
+END C_INVOICETAX_ADJUSTMENT
+]]></body>
+    </function>
+  </database>
--- a/src-db/database/model/functions/C_INVOICE_POST.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/C_INVOICE_POST.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -22,7 +22,7 @@
   * parts created by ComPiere are Copyright (C) ComPiere, Inc.;
   * All Rights Reserved.
   * Contributor(s): Openbravo SLU
-  * Contributions are Copyright (C) 2001-2016 Openbravo, S.L.U.
+  * Contributions are Copyright (C) 2001-2017 Openbravo, S.L.U.
   *
   * Specifically, this derivative work is based upon the following Compiere
   * file and version.
@@ -152,7 +152,8 @@
   Cur_InvoiceNetLine RECORD;
 
   v_LineMax NUMBER:=0;
-  v_precision NUMBER;
+  v_pricePrecision C_Currency.PricePrecision%TYPE;
+  v_stdPrecision C_Currency.StdPrecision%TYPE;
   v_gross_unit_price NUMBER;
   v_line_gross_amount NUMBER;
   v_Isquantityvariable CHAR(1);
@@ -172,8 +173,8 @@
 
   v_iscashvat C_Invoice.IsCashVat%TYPE;
   v_invoiceline_qtysum NUMBER;
-  v_PriceList_ID varchar2(32);
   v_prepaymentamt NUMBER;
+  v_prepayment_inorders NUMBER;
   v_hasTaxes NUMBER;
    
 BEGIN
@@ -213,23 +214,25 @@
   END IF;
 BEGIN --BODY
 
-  /*Invoiceline acct dimension*/
-  SELECT C_INVOICE.ISSOTRX , C_INVOICE.c_bpartner_id
-  INTO v_IsSOTrx, v_BPartner_ID
-  FROM C_INVOICE
-  WHERE C_INVOICE_ID = v_Record_ID;
+  SELECT i.ISSOTRX , i.c_bpartner_id, i.DocAction, c.PricePrecision, c.StdPrecision, p.IsTaxIncluded
+  INTO v_IsSOTrx, v_BPartner_ID, v_DocAction, v_pricePrecision, v_stdPrecision, v_isTaxIncluded
+  FROM C_INVOICE i
+  JOIN C_CURRENCY c
+  ON i.C_CURRENCY_ID = c.C_CURRENCY_ID
+  JOIN M_PRICELIST p
+  ON i.M_PRICELIST_ID = p.M_PRICELIST_ID
+  WHERE i.C_INVOICE_ID = v_Record_ID;
 
-  SELECT CASE WHEN (m.ISSOTRX='Y') THEN customer_blocking  ELSE vendor_blocking END ,  
-  CASE WHEN (m.ISSOTRX='Y') THEN so_invoice_blocking ELSE po_invoice_blocking  END, name, DocAction
-  INTO v_bpartner_blocked, v_invoiceBlocking, v_bpartner_name, v_DocAction
-  FROM C_INVOICE m, C_BPartner bp
-  WHERE m.c_bpartner_id=bp.c_bpartner_id
-  AND m.C_INVOICE_ID=v_Record_ID
-  AND m.C_BPARTNER_ID=v_BPartner_ID;
+  SELECT CASE WHEN (v_IsSOTrx = 'Y') THEN customer_blocking ELSE vendor_blocking END,
+  CASE WHEN (v_IsSOTrx = 'Y') THEN so_invoice_blocking ELSE po_invoice_blocking END, name
+  INTO v_bpartner_blocked, v_invoiceBlocking, v_bpartner_name
+  FROM C_BPartner bp
+  WHERE bp.c_bpartner_id = v_BPartner_ID;
   IF (v_DocAction = 'CO' AND v_bpartner_blocked = 'Y' AND v_invoiceBlocking = 'Y') THEN
     RAISE_APPLICATION_ERROR(-20000,'@ThebusinessPartner@'||' '|| v_bpartner_name ||' '||'@BusinessPartnerBlocked@');
   END IF;
 
+  /*Invoiceline acct dimension*/
   IF (v_IsSOTrx = 'N') THEN
     FOR Cur_line IN
       (SELECT C_INVOICELINE.C_InvoiceLine_ID,
@@ -257,14 +260,14 @@
       i.AD_Client_ID, i.AD_Org_ID, i.UpdatedBy, i.DocumentNo,
       i.C_Order_ID, i.IsSOTrx, i.C_BPartner_ID, i.AD_User_ID,
       i.C_Currency_ID, i.POReference, i.Posted,
-      i.c_Project_Id, i.C_WithHolding_ID, i.IsCashVat, i.M_PriceList_ID, i.prepaymentamt
+      i.c_Project_Id, i.C_WithHolding_ID, i.IsCashVat, i.prepaymentamt
   INTO v_Processing, v_Processed, v_DocAction, v_DocStatus,
       v_DocType_ID, v_DocTypeTarget_ID,
       v_PaymentRule, v_PaymentTerm, v_DateAcct, v_DateInvoiced,
       v_Client_ID, v_Org_ID, v_UpdatedBy, v_DocumentNo,
       v_Order_ID, v_IsSOTrx, v_BPartner_ID, v_BPartner_User_ID,
       v_Currency_ID, v_POReference, v_Posted,
-      v_C_Project_Id, cWithHoldID, v_iscashvat, v_PriceList_ID, v_prepaymentamt
+      v_C_Project_Id, cWithHoldID, v_iscashvat, v_prepaymentamt
   FROM C_INVOICE i
   WHERE i.C_Invoice_ID=v_Record_ID FOR UPDATE;
 
@@ -272,11 +275,6 @@
   INTO  v_isreturndoctype    
   FROM  c_doctype dt  
   WHERE dt.c_doctype_id= v_DocTypeTarget_ID;
-
-  SELECT pl.istaxincluded
-  INTO   v_istaxincluded
-  FROM   m_pricelist pl 
-  WHERE pl.m_pricelist_id= v_PriceList_ID;
   
   DBMS_OUTPUT.PUT_LINE('Invoice_ID=' || v_Record_ID ||', DocAction=' || v_DocAction || ', DocStatus=' || v_DocStatus || ', DocType_ID=' || v_DocType_ID || ', DocTypeTarget_ID=' || v_DocTypeTarget_ID) ;
   /**
@@ -1071,6 +1069,7 @@
       DELETE FROM C_INVOICELINE
       WHERE C_INVOICE_DISCOUNT_ID IS NOT NULL
         AND C_INVOICE_ID=v_Record_ID;
+
       END_PROCESSING:=TRUE;
     END IF;
   END IF;--END_PROCESSING
@@ -1199,9 +1198,6 @@
     SELECT MAX(LINE) INTO v_InvoiceLineSeqNo
     FROM C_INVOICELINE
     WHERE C_INVOICE_ID=v_Record_ID;
-    SELECT PricePrecision INTO v_precision
-    FROM C_INVOICE i, C_CURRENCY c
-    WHERE i.C_INVOICE_ID = v_Record_ID AND i.C_CURRENCY_ID = c.C_CURRENCY_ID;
     FOR Cur_CInvoiceDiscount IN
       (SELECT C_INVOICE_DISCOUNT.C_INVOICE_DISCOUNT_ID, C_DISCOUNT.DISCOUNT, C_DISCOUNT.M_PRODUCT_ID, C_DISCOUNT.NAME,
            C_INVOICE_DISCOUNT.CASCADE, C_DISCOUNT.C_DISCOUNT_ID, M_PRODUCT.C_UOM_ID,
@@ -1233,7 +1229,7 @@
           ELSE
             v_line_gross_amount:=(-1) * Cur_TaxDiscount.LINEGROSSAMT * Cur_CInvoiceDiscount.Discount/100;
           END IF;
-          v_Discount:= C_GET_NET_PRICE_FROM_GROSS(Cur_TaxDiscount.C_TAX_ID, v_line_gross_amount, 0, v_precision, 1);
+          v_Discount:= C_GET_NET_AMOUNT_FROM_GROSS(Cur_TaxDiscount.C_TAX_ID, v_line_gross_amount, 0, v_stdPrecision);
           v_gross_unit_price:= v_line_gross_amount;
         ELSE
           IF (Cur_CInvoiceDiscount.CASCADE='Y') THEN
@@ -1297,7 +1293,7 @@
            0, Cur_CInvoiceDiscount.C_UOM_ID, Cur_TaxDiscount.C_TAX_ID, NULL,
            NULL, NULL, 'N' ,
            NULL, NULL, v_Discount,
-           ROUND(v_gross_unit_price, v_precision), v_Discount  ,ROUND(v_line_gross_amount, v_precision),
+           ROUND(v_gross_unit_price, v_pricePrecision), v_Discount  ,ROUND(v_line_gross_amount, v_pricePrecision),
            v_isdeferred_inv, v_defplantype_inv, v_periodnumber_inv, v_period_inv,
            NULL, NULL
           );
@@ -1796,11 +1792,21 @@
     END IF;
   END IF;--FINISH_PROCESS
   IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
+    --Update the prepayment amount from orders related to the invoice lines.
+    SELECT COALESCE(SUM(fps.paidamt),0)
+      INTO v_prepayment_inorders
+    FROM fin_payment_schedule fps
+      JOIN c_order o ON o.c_order_id=fps.c_order_id
+      JOIN c_orderline ol ON ol.c_order_id = o.c_order_id
+      JOIN c_invoiceline il ON il.c_orderline_id = ol.c_orderline_id
+    WHERE il.c_invoice_id = v_Record_ID;
+
     -- Finish up -------------------------------------------------------------
     UPDATE C_INVOICE
     SET DocStatus='CO',
         Processed='Y',
         DocAction='RE',
+        PrepaymentAmt=v_prepayment_inorders,
         Updated=now(),
         UpdatedBy=v_UpdatedBy
     WHERE C_Invoice_ID=v_Record_ID;
@@ -1819,6 +1825,11 @@
     -- Commented by cromero 19102006 END IF;
   END IF;--FINISH_PROCESS
 
+  -- Round and Adjust taxes when 'CO' and Recalculate amounts and taxes when 'RE'
+  IF (v_isTaxIncluded = 'Y' AND v_DocAction IN ('CO', 'RE')) THEN
+    C_INVOICETAX_ADJUSTMENT(v_Record_ID, v_stdPrecision, v_DocAction);
+  END IF;
+
   --C_Invoice_Post - Finish_Process Extension Point
   SELECT count(*) INTO v_count FROM DUAL
   WHERE EXISTS (SELECT 1 FROM ad_ep_procedures WHERE ad_extension_points_id = 'CBE7DD2E561E4D3D8257ECEA5F19687F');
--- a/src-db/database/model/functions/C_ORDERLINETAX_INSERT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/C_ORDERLINETAX_INSERT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -40,7 +40,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) 2010-2016 Openbravo SLU
+* All portions are Copyright (C) 2010-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -51,7 +51,7 @@
   v_TaxBaseAmount NUMBER;
   v_BaseAmount C_TAX.BASEAMOUNT%TYPE;
   v_C_TaxBase_ID C_TAX.C_TAXBASE_ID%TYPE;
-  v_LineNo C_INVOICETAX.LINE%TYPE;
+  v_LineNo C_ORDERTAX.LINE%TYPE;
   v_Rate C_TAX.RATE%TYPE;
   v_Client_ID VARCHAR2(32) ;
   v_istaxincluded CHAR(1);
@@ -78,7 +78,7 @@
       v_TaxBaseAmount:=0;
     END IF;
     IF (v_BaseAmount='TAX' OR v_BaseAmount='LNATAX' OR v_BaseAmount='TBATAX') THEN
-      SELECT COALESCE(SUM(TAXAMT),0) + v_TaxBaseAmount
+      SELECT COALESCE(SUM(TAXAMT), 0) + v_TaxBaseAmount
       INTO v_TaxBaseAmount
       FROM C_ORDERLINETAX, C_TAX
       WHERE C_ORDERLINETAX.C_TAX_ID = C_TAX.C_TAX_ID
@@ -103,12 +103,12 @@
       INSERT
       INTO C_ORDERLINETAX (
       C_OrderLineTax_ID, C_OrderLine_ID, C_Order_ID, C_Tax_ID, AD_Client_ID, AD_Org_ID,
-      IsActive, Created, CreatedBy, Updated,
-      UpdatedBy, TaxBaseAmt, TaxAmt, Line)
+      IsActive, Created, CreatedBy, Updated, UpdatedBy,
+      TaxBaseAmt, TaxAmt, Line)
       VALUES (
       GET_UUID(), p_orderline_id, p_order_id, p_tax_id, v_Client_ID, p_org_id,
-      'Y', now(), p_user_id, now(),
-      p_user_id, v_TaxBaseAmount, ROUND(v_TaxBaseAmount*v_Rate / 100, p_StdPrecision), v_LineNo);
+      'Y', now(), p_user_id, now(), p_user_id,
+      v_TaxBaseAmount, ROUND(ROUND(v_TaxBaseAmount, p_StdPrecision) * v_Rate/100, p_StdPrecision), v_LineNo);
     ELSE
       FOR Cur_Taxes IN
         (SELECT C_Tax_ID, RATE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-db/database/model/functions/C_ORDERTAX_ADJUSTMENT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,181 @@
+<?xml version="1.0"?>
+  <database name="FUNCTION C_ORDERTAX_ADJUSTMENT">
+    <function name="C_ORDERTAX_ADJUSTMENT" type="NULL">
+      <parameter name="p_order_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_precision" type="NUMERIC" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_action" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <body><![CDATA[/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2017 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+-- Variables
+v_amount C_ORDERLINE.Line_Gross_Amount%TYPE;
+TYPE RECORD IS REF CURSOR;
+CUR_Tax RECORD;
+CUR_Line RECORD;
+
+BEGIN --BODY
+
+  -- Round and Adjust taxes
+  IF (p_action = 'CO') THEN
+
+    -- Disable triggers
+    INSERT INTO AD_Session_Status (ad_session_status_id, ad_client_id, ad_org_id, isactive, created, createdby, updated, updatedby, isimporting)
+    VALUES (get_uuid(), '0', '0', 'Y', now(), '0', now(), '0', 'Y');
+
+    -- Round
+    UPDATE C_ORDERLINETAX
+    SET TaxBaseAmt = round(TaxBaseAmt, p_precision)
+    WHERE C_Order_ID = p_order_id;
+
+    UPDATE C_ORDERTAX
+    SET TaxBaseAmt = round(TaxBaseAmt, p_precision)
+    WHERE C_Order_ID = p_order_id;
+
+    -- Adjust
+    FOR CUR_Tax IN (
+      SELECT ot.C_Tax_ID, COALESCE((MIN(ot.DocTaxBaseAmt) + MIN(ot.DocTaxAmt)) - (SUM(olt.LineTaxBaseAmt) + SUM(olt.LineTaxAmt)), 0) as TaxAdjustment, COALESCE(MIN(ot.DocTaxBaseAmt) - SUM(olt.LineTaxBaseAmt), 0) as LineAdjustment
+      FROM (
+        SELECT c_tax_get_root(ot.c_tax_id) as C_Tax_ID, CASE WHEN MIN(ot.TaxBaseAmt) > 0 THEN MIN(ot.TaxBaseAmt) ELSE MAX(ot.TaxBaseAmt) END as DocTaxBaseAmt, SUM(ot.TaxAmt) as DocTaxAmt, MIN(ot.Line) as Line
+        FROM C_OrderTax ot
+        JOIN C_Tax t
+        ON ot.C_Tax_ID = t.C_Tax_ID
+        WHERE ot.C_Order_ID = p_order_id
+        AND t.DocTaxAmount = 'D'
+        GROUP BY c_tax_get_root(ot.c_tax_id)
+      ) ot
+      JOIN (
+        SELECT c_tax_get_root(olt.c_tax_id) as C_Tax_ID, CASE WHEN MIN(olt.TaxBaseAmt) > 0 THEN MIN(olt.TaxBaseAmt) ELSE MAX(olt.TaxBaseAmt) END as LineTaxBaseAmt, SUM(olt.TaxAmt) as LineTaxAmt
+        FROM C_OrderLineTax olt
+        JOIN C_Tax t
+        ON olt.C_Tax_ID = t.C_Tax_ID
+        WHERE olt.C_Order_ID = p_order_id
+        AND t.DocTaxAmount = 'D'
+        GROUP BY olt.C_OrderLine_ID, c_tax_get_root(olt.c_tax_id)
+      ) olt
+      ON olt.C_Tax_ID = ot.C_Tax_ID
+      GROUP BY ot.C_Tax_ID, ot.Line
+      HAVING COALESCE(MIN(ot.DocTaxBaseAmt), 0) <> COALESCE(SUM(olt.LineTaxBaseAmt), 0)
+      OR COALESCE(MIN(ot.DocTaxBaseAmt) + MIN(ot.DocTaxAmt), 0) <> COALESCE(SUM(olt.LineTaxBaseAmt) + SUM(olt.LineTaxAmt), 0)
+      ORDER BY ot.Line
+    )
+    LOOP
+      -- Adjust TaxAmt
+      IF (CUR_Tax.TaxAdjustment <> 0) THEN
+        FOR CUR_Line IN (
+          SELECT ot.C_OrderTax_ID, ot.C_Tax_ID, t.Line
+          FROM C_OrderTax ot
+          JOIN C_Tax t
+          ON ot.C_Tax_ID = t.C_Tax_ID
+          WHERE ot.C_Order_ID = p_order_id
+          AND c_tax_get_root(ot.C_Tax_ID) = CUR_Tax.C_Tax_ID
+          ORDER BY ABS(ot.TaxAmt) DESC, t.Line DESC
+        )
+        LOOP
+          UPDATE C_ORDERTAX
+          SET TaxAmt = TaxAmt - CUR_Tax.TaxAdjustment
+          WHERE C_OrderTax_ID = CUR_Line.C_OrderTax_ID;
+
+          UPDATE C_ORDERTAX ot
+          SET TaxBaseAmt = TaxBaseAmt - CUR_Tax.TaxAdjustment
+          WHERE ot.C_Order_ID = p_order_id
+          AND c_tax_get_root(ot.C_Tax_ID) = CUR_Tax.C_Tax_ID
+          AND EXISTS (
+            SELECT 1
+            FROM C_Tax t
+            WHERE t.C_Tax_ID = ot.C_Tax_ID
+            AND ((t.Cascade = 'Y'
+            AND t.Line > CUR_Line.Line)
+            OR (t.BaseAmount IN ('TAX', 'LNATAX', 'TBATAX')
+            AND C_TAX_ISMEMBER(t.C_TaxBase_ID, CUR_Line.C_Tax_ID) = 1
+            AND t.IsSummary = 'N'))
+          );
+
+          EXIT;
+        END LOOP;
+      END IF;
+
+      -- Adjust LineNetAmt
+      IF (CUR_Tax.LineAdjustment <> 0) THEN
+        FOR CUR_Line IN (
+          SELECT ol.C_OrderLine_ID
+          FROM C_OrderLine ol
+          WHERE ol.C_Order_ID = p_order_id
+          AND EXISTS (
+            SELECT 1
+            FROM C_OrderLineTax olt
+            WHERE ol.C_OrderLine_ID = olt.C_OrderLine_ID
+            AND c_tax_get_root(olt.C_Tax_ID) = CUR_Tax.c_Tax_ID
+          )
+          ORDER BY ABS(ol.LineNetAmt) DESC, ol.Line DESC
+        )
+        LOOP
+          UPDATE C_ORDERLINE
+          SET LineNetAmt = LineNetAmt + CUR_Tax.LineAdjustment
+          WHERE C_OrderLine_ID = CUR_Line.C_OrderLine_ID;
+
+          -- TODO: Adjust C_OrderLineTax accordingly
+
+          EXIT;
+        END LOOP;
+      END IF;
+    END LOOP;
+
+    -- Enable triggers
+    DELETE FROM AD_Session_Status
+    WHERE isimporting = 'Y';
+
+  -- Recalculate amounts and taxes
+  ELSIF (p_action = 'RE') THEN
+
+    -- Remove header amounts and taxes
+    DELETE FROM C_ORDERTAX WHERE C_Order_ID = p_order_id;
+    UPDATE C_ORDER SET TotalLines = 0, GrandTotal = 0 WHERE C_Order_ID = p_order_id;
+
+    FOR Cur_line IN (
+      SELECT C_OrderLine_ID
+      FROM C_ORDERLINE
+      WHERE C_Order_ID = p_order_id
+    ) LOOP
+
+      -- Disable triggers
+      INSERT INTO AD_Session_Status (ad_session_status_id, ad_client_id, ad_org_id, isactive, created, createdby, updated, updatedby, isimporting)
+      VALUES (get_uuid(), '0', '0', 'Y', now(), '0', now(), '0', 'Y');
+
+      -- Remove line amounts and taxes
+      DELETE FROM C_ORDERLINETAX WHERE C_OrderLine_ID = Cur_line.C_OrderLine_ID;
+      SELECT Line_Gross_Amount INTO v_amount FROM C_ORDERLINE WHERE C_OrderLine_ID = Cur_line.C_OrderLine_ID;
+      UPDATE C_ORDERLINE SET Line_Gross_Amount = 0 WHERE C_OrderLine_ID = Cur_line.C_OrderLine_ID;
+
+      -- Enable triggers
+      DELETE FROM AD_Session_Status
+      WHERE isimporting = 'Y';
+
+      -- Recalculate amounts and taxes
+      UPDATE C_ORDERLINE SET Line_Gross_Amount = v_amount WHERE C_OrderLine_ID = Cur_line.C_OrderLine_ID;
+
+    END LOOP;
+
+  END IF;
+END C_ORDERTAX_ADJUSTMENT
+]]></body>
+    </function>
+  </database>
--- a/src-db/database/model/functions/C_ORDER_POST1.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/C_ORDER_POST1.xml	Wed Mar 15 18:56:27 2017 +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) 2001-2016 Openbravo SLU
+* All portions are Copyright (C) 2001-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -95,7 +95,6 @@
   v_c_Bpartner_ID VARCHAR2(32);
   v_c_currency_ID VARCHAR2(32);
   v_C_PROJECT_ID VARCHAR2(32);
-  v_PriceList_ID VARCHAR2(32);
   FINISH_PROCESS BOOLEAN:=FALSE;
   END_PROCESSING BOOLEAN:=FALSE;
   v_CBPartner_ID VARCHAR2(32);
@@ -109,7 +108,8 @@
   Cur_TaxDiscount RECORD;
   v_OrderLine VARCHAR2(32);
   v_Discount NUMBER;
-  v_precision NUMBER;
+  v_pricePrecision C_Currency.PricePrecision%TYPE;
+  v_stdPrecision C_Currency.StdPrecision%TYPE;
   Cur_OrderLine RECORD;
   v_DiscountExist NUMBER;
   v_gross_unit_price NUMBER;
@@ -157,13 +157,17 @@
     END IF;
     DBMS_OUTPUT.PUT_LINE('  Record_ID=' || v_Record_ID) ;
   BEGIN --BODY
-  
+
+  SELECT o.ISSOTRX, o.c_bpartner_id, o.DocAction, c.PricePrecision, c.StdPrecision, p.IsTaxIncluded
+  INTO v_IsSOTrx, v_c_Bpartner_ID, v_DocAction, v_pricePrecision, v_stdPrecision, v_isTaxIncluded
+  FROM C_ORDER o
+  JOIN C_CURRENCY c
+  ON o.C_CURRENCY_ID = c.C_CURRENCY_ID
+  JOIN M_PRICELIST p
+  ON o.M_PRICELIST_ID = p.M_PRICELIST_ID
+  WHERE o.C_ORDER_ID = v_Record_ID;
+
   /*Orderline acct dimension*/
-  SELECT C_ORDER.ISSOTRX , C_ORDER.c_bpartner_id, DocAction
-  INTO v_IsSOTrx, v_c_Bpartner_ID, v_DocAction
-  FROM C_ORDER
-  WHERE C_ORDER_ID = v_Record_ID;
-  
   IF (v_IsSOTrx = 'N') THEN
     FOR Cur_line IN
       (SELECT C_ORDERLINE.C_OrderLine_ID,
@@ -215,19 +219,14 @@
       C_DocType_ID, C_DocTypeTarget_ID, c_order.AD_Client_ID,
       c_order.AD_Org_ID, c_order.UpdatedBy, M_Warehouse_ID, TRUNC(DateOrdered),
       Issotrx, c_Bpartner_Id, c_order.c_currency_id, C_PROJECT_ID,
-      C_BPartner_ID, M_PriceList_ID, invoicerule, c_order.IsCashVat
+      C_BPartner_ID, invoicerule, c_order.IsCashVat
     INTO v_IsProcessing, v_IsProcessed, v_DocAction, v_DocStatus,
       v_DocType_ID, v_DocTypeTarget_ID, v_Client_ID,
       v_Org_ID, v_UpdatedBy, v_M_Warehouse_ID, v_Date,
       v_isSoTrx, v_c_Bpartner_Id, v_c_currency_id, v_C_PROJECT_ID,
-      v_CBPartner_ID, v_PriceList_ID, v_invoicerule, v_iscashvat
+      v_CBPartner_ID, v_invoicerule, v_iscashvat
     FROM C_ORDER
     WHERE C_Order_ID=v_Record_ID  FOR UPDATE  ;
-
-    SELECT m_pricelist.istaxincluded
-    INTO v_istaxincluded
-    FROM m_pricelist 
-    WHERE m_pricelist_id= v_PriceList_ID;
     
     -- Get current DocSubTypeSO
     SELECT DocSubTypeSO
@@ -966,14 +965,10 @@
         v_CumDiscount:=0;
         v_OldCumDiscount:=0;
         v_Line:=10;
-        v_precision:=0;
         SELECT MAX(LINE)
           INTO v_OrderLineSeqNo
         FROM C_ORDERLINE
         WHERE C_ORDER_ID=v_Record_ID;
-        SELECT PricePrecision INTO v_precision
-        FROM C_ORDER o, C_CURRENCY c
-        WHERE o.C_ORDER_ID = v_Record_ID AND  o.C_CURRENCY_ID = c.C_CURRENCY_ID;
         FOR Cur_COrderDiscount IN
            (SELECT C_ORDER_DISCOUNT.C_ORDER_DISCOUNT_ID, C_DISCOUNT.DISCOUNT, C_DISCOUNT.M_PRODUCT_ID, C_DISCOUNT.NAME,
               C_ORDER_DISCOUNT.CASCADE, C_DISCOUNT.C_DISCOUNT_ID, M_PRODUCT.C_UOM_ID
@@ -1005,7 +1000,7 @@
               ELSE
                 v_line_gross_amount:=(-1) * Cur_TaxDiscount.LINEGROSSAMT * Cur_COrderDiscount.Discount/100;
               END IF;
-              v_Discount:= C_GET_NET_PRICE_FROM_GROSS(Cur_TaxDiscount.C_TAX_ID, v_line_gross_amount, 0, v_precision, 1);
+              v_Discount:= C_GET_NET_AMOUNT_FROM_GROSS(Cur_TaxDiscount.C_TAX_ID, v_line_gross_amount, 0, v_stdPrecision);
               v_gross_unit_price:= v_line_gross_amount;
             ELSE
               IF (Cur_COrderDiscount.CASCADE='Y') THEN
@@ -1044,11 +1039,11 @@
                   now(), now(), now(), now(), Cur_COrderDiscount.NAME,
                   Cur_COrderDiscount.M_PRODUCT_ID, v_M_Warehouse_ID, 'N', Cur_COrderDiscount.C_UOM_ID, 1,
                   0, 0, 0, NULL, v_c_currency_id,
-                  ROUND(v_Discount,v_precision), ROUND(v_Discount,v_precision), ROUND(v_Discount,v_precision), ROUND(v_Discount,v_precision), 0, 0,
+                  ROUND(v_Discount, v_pricePrecision), ROUND(v_Discount, v_pricePrecision), ROUND(v_Discount, v_pricePrecision), ROUND(v_Discount, v_pricePrecision), 0, 0,
                   NULL, NULL, Cur_TaxDiscount.C_TAX_ID, NULL, NULL,
                   NULL, 'N', NULL, NULL, NULL, NULL,
-                  NULL, ROUND(v_Discount,v_precision), NULL,
-                  ROUND(v_gross_unit_price, v_precision), ROUND(v_Discount,v_precision),ROUND(v_line_gross_amount, v_precision)
+                  NULL, ROUND(v_Discount, v_pricePrecision), NULL,
+                  ROUND(v_gross_unit_price, v_pricePrecision), ROUND(v_Discount, v_pricePrecision),ROUND(v_line_gross_amount, v_pricePrecision)
                 );
 
               UPDATE C_ORDERLINE
@@ -1056,7 +1051,7 @@
               WHERE C_ORDERLINE_ID=v_OrderLine;
             ELSE
               UPDATE C_ORDERLINE 
-              SET pricelist = ROUND(v_Discount,v_precision), priceactual = ROUND(v_Discount,v_precision), pricelimit = ROUND(v_Discount,v_precision), linenetamt = ROUND(v_Discount,v_precision), pricestd = ROUND(v_Discount,v_precision)
+              SET pricelist = ROUND(v_Discount, v_pricePrecision), priceactual = ROUND(v_Discount, v_pricePrecision), pricelimit = ROUND(v_Discount, v_pricePrecision), linenetamt = ROUND(v_Discount, v_pricePrecision), pricestd = ROUND(v_Discount, v_pricePrecision)
               WHERE C_ORDERLINE.C_ORDER_DISCOUNT_ID = Cur_COrderDiscount.C_ORDER_DISCOUNT_ID
                 AND C_ORDERLINE.C_TAX_ID = Cur_TaxDiscount.C_TAX_ID;
             END IF;
@@ -1865,6 +1860,11 @@
       END IF;
     END IF;--FINISH_PROCESS
 
+    -- Round and Adjust taxes when 'CO' and Recalculate amounts and taxes when 'RE'
+    IF (v_isTaxIncluded = 'Y' AND v_DocAction IN ('CO', 'RE')) THEN
+      C_ORDERTAX_ADJUSTMENT(v_Record_ID, v_stdPrecision, v_DocAction);
+    END IF;
+
     --C_Order_Post - Finish_Process Extension Point
     SELECT count(*) INTO v_count
     FROM DUAL
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-db/database/model/functions/FIN_AGING_GETDOCNO.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,52 @@
+<?xml version="1.0"?>
+  <database name="FUNCTION FIN_AGING_GETDOCNO">
+    <function name="FIN_AGING_GETDOCNO" type="NVARCHAR">
+      <parameter name="p_poreference" type="NVARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_documentno" type="NVARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_adorgid" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <body><![CDATA[/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2016 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+
+v_hasSupplierRef NUMBER:= 0;
+
+BEGIN
+
+  SELECT count(*)
+  INTO v_hasSupplierRef
+  FROM AD_ORGINFO oi
+  WHERE oi.ad_org_id = p_adorgid
+  AND oi.em_aprm_payment_desc = 'Supplier Reference';
+
+  IF (v_hasSupplierRef = 0) THEN
+    RETURN p_documentno;
+  ELSE
+    RETURN p_poreference;
+  END IF;
+
+EXCEPTION
+WHEN OTHERS THEN
+  RETURN p_documentno;
+END FIN_AGING_GETDOCNO
+]]></body>
+    </function>
+  </database>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-db/database/model/functions/FIN_AGING_INVOICECURRENCY_RATE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,70 @@
+<?xml version="1.0"?>
+  <database name="FUNCTION FIN_AGING_INVOICECURRENCY_RATE">
+    <function name="FIN_AGING_INVOICECURRENCY_RATE" type="NUMERIC">
+      <parameter name="p_invoice_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_curto_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_curfrom_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <body><![CDATA[/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2016 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+
+v_count NUMBER:=0;
+v_rate NUMBER:=1;
+v_client_id c_invoice.ad_client_id%TYPE;
+v_org_id c_invoice.ad_org_id%TYPE;
+v_dateacct c_invoice.dateacct%TYPE;
+
+BEGIN
+
+IF(p_curfrom_id <> p_curto_id) THEN  
+  SELECT count(*) 
+  INTO v_count 
+  FROM c_conversion_rate_document 
+  WHERE c_invoice_id = p_invoice_id
+  and c_currency_id = p_curfrom_id
+  and c_currency_id_to = p_curto_id;
+
+  IF(v_count = 1) THEN
+    SELECT rate 
+    INTO v_rate 
+    FROM c_conversion_rate_document 
+    WHERE c_invoice_id = p_invoice_id  
+    and c_currency_id = p_curfrom_id
+    and c_currency_id_to = p_curto_id;  
+  ELSE 
+    SELECT dateacct, ad_client_id, ad_org_id 
+    into v_dateacct, v_client_id, v_org_id
+    from c_invoice 
+    where c_invoice_id = p_invoice_id;
+    v_rate:=c_currency_rate(p_curfrom_id, p_curto_id, v_dateacct, 'S', v_client_id, v_org_id);  
+  END IF;
+END IF;
+
+RETURN v_rate;
+
+EXCEPTION
+WHEN OTHERS THEN  
+  RETURN NULL;
+END FIN_AGING_INVOICECURRENCY_RATE
+]]></body>
+    </function>
+  </database>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-db/database/model/functions/FIN_AGING_ISDOUBTFULTDEBT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,53 @@
+<?xml version="1.0"?>
+  <database name="FUNCTION FIN_AGING_ISDOUBTFULTDEBT">
+    <function name="FIN_AGING_ISDOUBTFULTDEBT" type="CHAR">
+      <parameter name="p_finpaymentschedule_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_currentdate" type="TIMESTAMP" mode="in">
+        <default/>
+      </parameter>
+      <body><![CDATA[/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2016 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+ v_count NUMBER:=0;
+BEGIN 
+  SELECT count(*)
+  INTO v_count
+  FROM DUAL
+  WHERE EXISTS (SELECT  1           
+                FROM fin_doubtful_debt dd
+                WHERE dd.fin_payment_schedule_id = p_finpaymentschedule_id
+                AND EXISTS (select 1
+                            from fin_doubtful_debt_run ddr
+                            where ddr.fin_doubtful_debt_run_id = dd.fin_doubtful_debt_run_id
+                            and ddr.rundate <= p_currentdate)
+                );
+  
+  IF v_count = 0 THEN
+    RETURN 'N';
+  ELSE
+    RETURN 'Y';
+  END IF;
+  
+  
+EXCEPTION
+WHEN OTHERS THEN
+  RETURN 'N';
+END FIN_AGING_ISDOUBTFULTDEBT
+]]></body>
+    </function>
+  </database>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-db/database/model/functions/FIN_AGING_PAYMENTCURRENCY_RATE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -0,0 +1,70 @@
+<?xml version="1.0"?>
+  <database name="FUNCTION FIN_AGING_PAYMENTCURRENCY_RATE">
+    <function name="FIN_AGING_PAYMENTCURRENCY_RATE" type="NUMERIC">
+      <parameter name="p_payment_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_curto_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <parameter name="p_curfrom_id" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <body><![CDATA[/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2016 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+
+v_count NUMBER:=0;
+v_rate NUMBER:=1;
+v_client_id fin_payment.ad_client_id%TYPE;
+v_org_id fin_payment.ad_org_id%TYPE;
+v_paymentdate fin_payment.paymentdate%TYPE;
+
+BEGIN
+
+IF(p_curfrom_id <> p_curto_id) THEN  
+  SELECT count(*) 
+  INTO v_count 
+  FROM c_conversion_rate_document 
+  WHERE fin_payment_id = p_payment_id
+  and c_currency_id = p_curfrom_id
+  and c_currency_id_to = p_curto_id;
+
+  IF(v_count = 1) THEN
+    SELECT rate 
+    INTO v_rate 
+    FROM c_conversion_rate_document 
+    WHERE fin_payment_id = p_payment_id  
+    and c_currency_id = p_curfrom_id
+    and c_currency_id_to = p_curto_id;  
+  ELSE 
+    SELECT paymentdate, ad_client_id, ad_org_id 
+    into v_paymentdate, v_client_id, v_org_id
+    from fin_payment 
+    where fin_payment_id = p_payment_id;
+    v_rate:=c_currency_rate(p_curfrom_id, p_curto_id, v_paymentdate, 'S', v_client_id, v_org_id);  
+  END IF;
+END IF;
+
+RETURN v_rate;
+
+EXCEPTION
+WHEN OTHERS THEN  
+  RETURN NULL;
+END FIN_AGING_PAYMENTCURRENCY_RATE
+]]></body>
+    </function>
+  </database>
--- a/src-db/database/model/functions/MA_STANDARD_COST.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/MA_STANDARD_COST.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -16,13 +16,14 @@
  * 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-2013 Openbravo SLU
+ * All portions are Copyright (C) 2001-2017 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************/
   v_ResultStr             VARCHAR2(2000) := '';
   v_Message               VARCHAR2(2000) := '';
   v_Result NUMBER:= 1;
+  v_Client_ID VARCHAR2(32);
 
   p_User VARCHAR2(32);
   p_Currency VARCHAR2(32);
@@ -42,7 +43,29 @@
 BEGIN --BODY
 		v_Count:=0;
 		v_Message:='-';
-			FOR Cur_Sequences IN
+			
+
+  FOR Cur_Parameter IN (SELECT i.ad_client_id, i.Record_ID, i.AD_User_ID, p.ParameterName, 
+                               p.P_String, p.P_Number, p.P_Date, i.UpdatedBy, ad_client.c_currency_id
+                        FROM AD_PINSTANCE i LEFT JOIN AD_PINSTANCE_PARA p ON i.AD_PInstance_ID=p.AD_PInstance_ID,
+                             AD_CLIENT
+                        WHERE i.AD_PInstance_ID=p_PInstance_ID
+                          AND i.ad_client_ID = ad_client.ad_client_id
+                        ORDER BY p.SeqNo) LOOP
+    p_User := Cur_Parameter.AD_User_ID;
+    p_CalcDate := now();
+    p_Currency := cur_parameter.C_Currency_ID;
+    v_Client_ID := cur_parameter.ad_client_id;
+    IF (Cur_Parameter.ParameterName = 'C_Budget_ID') THEN
+      p_Budget_ID := Cur_Parameter.P_String;
+    ELSIF (Cur_Parameter.ParameterName = 'MA_Processplan_ID') THEN
+      p_ProcessPlan := Cur_Parameter.P_String;
+    ELSIF (Cur_Parameter.ParameterName = 'CalcDate') THEN
+      p_CalcDate := COALESCE(Cur_Parameter.P_Date, TRUNC(now()));
+    END IF;
+  END LOOP;
+
+  FOR Cur_Sequences IN
 			(
 			SELECT pp.name||'-'||ppv.documentno AS ProcessPlan
 			FROM MA_SEQUENCEPRODUCT sp, MA_SEQUENCE s
@@ -50,6 +73,7 @@
 			LEFT JOIN MA_ProcessPlan pp ON pp.MA_ProcessPlan_ID = ppv.MA_ProcessPlan_ID
 			WHERE sp.PRODUCTIONTYPE='+'
 			AND sp.MA_SEQUENCE_ID = s.MA_SEQUENCE_ID
+                        AND s.AD_CLIENT_ID = v_Client_ID
 			AND EXISTS
 			(SELECT 1
 			FROM MA_SEQUENCEPRODUCT
@@ -65,25 +89,6 @@
 				RAISE_APPLICATION_ERROR(-20000,'@P+AndP-InSamePlan@'||' Check Process Plan'||v_Message);
 			END IF;
 
-  FOR Cur_Parameter IN (SELECT i.ad_client_id, i.Record_ID, i.AD_User_ID, p.ParameterName, 
-                               p.P_String, p.P_Number, p.P_Date, i.UpdatedBy, ad_client.c_currency_id
-                        FROM AD_PINSTANCE i LEFT JOIN AD_PINSTANCE_PARA p ON i.AD_PInstance_ID=p.AD_PInstance_ID,
-                             AD_CLIENT
-                        WHERE i.AD_PInstance_ID=p_PInstance_ID
-                          AND i.ad_client_ID = ad_client.ad_client_id
-                        ORDER BY p.SeqNo) LOOP
-    p_User := Cur_Parameter.AD_User_ID;
-    p_CalcDate := now();
-    p_Currency := cur_parameter.C_Currency_ID;
-    IF (Cur_Parameter.ParameterName = 'C_Budget_ID') THEN
-      p_Budget_ID := Cur_Parameter.P_String;
-    ELSIF (Cur_Parameter.ParameterName = 'MA_Processplan_ID') THEN
-      p_ProcessPlan := Cur_Parameter.P_String;
-    ELSIF (Cur_Parameter.ParameterName = 'CalcDate') THEN
-      p_CalcDate := COALESCE(Cur_Parameter.P_Date, TRUNC(now()));
-    END IF;
-  END LOOP;
-
   --Initialize, set sequences as calculated = 'N'
   UPDATE MA_SEquence
   SET calculated = 'N'
@@ -92,6 +97,7 @@
                            WHERE s.MA_ProcessPlan_Version_ID = ppv.MA_ProcessPlan_Version_ID
                              AND ppv.DateFrom <= p_CalcDate
                              AND ppv.DateTo > p_CalcDate
+                             AND s.AD_CLIENT_ID = v_Client_ID
                              AND (p_ProcessPlan IS NULL OR ppv.MA_ProcessPlan_ID = p_ProcessPlan)
                              AND EXISTS (SELECT 1 FROM MA_SEQUENCEPRODUCT
                                          WHERE PRODUCTIONTYPE = '+'
@@ -104,6 +110,7 @@
       AND ppv.DateFrom <= p_CalcDate
       AND ppv.DateTo > p_CalcDate
       AND s.calculated = 'N'
+      AND s.AD_CLIENT_ID = v_Client_ID
       AND (p_ProcessPlan IS NULL OR ppv.MA_ProcessPlan_ID = p_ProcessPlan)
       AND EXISTS (SELECT 1 FROM MA_SEQUENCEPRODUCT
                   WHERE PRODUCTIONTYPE = '+'
--- a/src-db/database/model/functions/MRP_PURCHASEORDER.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/MRP_PURCHASEORDER.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -16,7 +16,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-2016 Openbravo SLU
+* All portions are Copyright (C) 2001-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -55,7 +55,6 @@
   v_LineNetAmt NUMBER:=0;
   v_gross_unit_price NUMBER:=0;
   v_stdprecision NUMBER:=0;
-  v_priceprecision NUMBER:=0;
   v_line_gross_amount NUMBER:=0;
   v_gross_price_std NUMBER:=0;
   v_gross_price_list NUMBER:=0;
@@ -236,20 +235,20 @@
       v_TaxID := C_GetTax(Cur_workproposal.M_Product_ID, v_DateDoc, v_Org_ID, v_M_Warehouse_ID, v_BillTo_ID, v_BPartner_Location_ID, null, 'N');
       v_LineNetAmt:= v_PriceActual*Cur_workproposal.QTY;
       IF (v_istaxincluded = 'Y') THEN
-        SELECT PricePrecision, stdprecision
-            INTO v_priceprecision, v_stdprecision
-          FROM C_CURRENCY
-          WHERE C_CURRENCY_ID = Cur_workproposal.C_Currency_ID;
+        SELECT stdprecision
+        INTO v_stdprecision
+        FROM C_CURRENCY
+        WHERE C_CURRENCY_ID = Cur_workproposal.C_Currency_ID;
 
         v_gross_unit_price:= v_PriceActual;
         v_gross_price_std:= v_PriceStd;
         v_gross_price_list:= v_PriceList;
         v_line_gross_amount:= ROUND(v_gross_unit_price * Cur_workproposal.QTY, v_stdprecision);
-        v_PriceActual:= C_GET_NET_PRICE_FROM_GROSS(v_TaxID, v_PriceActual, 0, v_priceprecision, 1);
-        v_PriceStd:= C_GET_NET_PRICE_FROM_GROSS(v_TaxID, v_PriceStd, 0, v_priceprecision, 1);
-        v_PriceList:= C_GET_NET_PRICE_FROM_GROSS(v_TaxID, v_PriceList, 0, v_priceprecision, 1);
-        v_PriceLimit:= C_GET_NET_PRICE_FROM_GROSS(v_TaxID, v_PriceLimit, 0, v_priceprecision, 1);
-        v_LineNetAmt:= ROUND(v_PriceActual * Cur_workproposal.QTY, v_stdprecision);
+        v_PriceActual:= 0;
+        v_PriceStd:= 0;
+        v_PriceList:= 0;
+        v_PriceLimit:= 0;
+        v_LineNetAmt:= 0;
 
         UPDATE C_ORDER SET ISTAXINCLUDED='Y' WHERE C_ORDER_ID = v_COrder_ID;
 
--- a/src-db/database/model/functions/M_EXPLODEBOMNOTSTOCK.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/M_EXPLODEBOMNOTSTOCK.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -19,7 +19,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) 2013-2016 Openbravo SLU
+* All portions are Copyright (C) 2013-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -159,8 +159,8 @@
 					v_gross_unit_price:=M_Get_Offers_Price(CUR_BOM_Line.DateOrdered, v_CBPartner_ID, CUR_BOM.M_ProductBOM_ID, M_BOM_PriceStd(CUR_BOM.M_ProductBOM_ID, v_PriceList_Version_ID), CUR_BOM_Line.QtyInvoiced*CUR_BOM.BOMQty, v_PriceList_ID);
 					v_gross_price_list:=M_Get_Offers_Price(CUR_BOM_Line.DateOrdered, v_CBPartner_ID, CUR_BOM.M_ProductBOM_ID, M_BOM_PriceList(CUR_BOM.M_ProductBOM_ID, v_PriceList_Version_ID), CUR_BOM_Line.QtyInvoiced*CUR_BOM.BOMQty, v_PriceList_ID);
 					v_line_gross_amount:=ROUND(CUR_BOM_Line.QtyOrdered*CUR_BOM.BOMQty*v_gross_unit_price, v_Precision);
-					v_price_actual:=ROUND(C_GET_NET_PRICE_FROM_GROSS(V_C_Tax_Id,  M_Get_Offers_Price(CUR_BOM_Line.DateOrdered, v_CBPartner_ID, CUR_BOM.M_ProductBOM_ID, M_BOM_PriceStd(CUR_BOM.M_ProductBOM_ID, v_PriceList_Version_ID), CUR_BOM_Line.QtyInvoiced*CUR_BOM.BOMQty, v_PriceList_ID), 0, v_Precision, 1),v_Precision);
-					v_line_net_amt:=ROUND(CUR_BOM_Line.QtyOrdered*CUR_BOM.BOMQty*v_price_actual, v_Precision);
+					v_price_actual:=0;
+					v_line_net_amt:=0;
 				ELSE
 					v_gross_unit_price:=0;
 					v_line_gross_amount:=0;
--- a/src-db/database/model/functions/M_GET_PARETO_ABC.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/M_GET_PARETO_ABC.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -28,11 +28,17 @@
 * 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-2016 Openbravo SLU
+* All portions are Copyright (C) 2001-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
 
+/* 
+* This code has very important performance issues and it has been deprecated.
+* ReportParetoProduct_data.xsql, select method has been rewritten so it is not needed anymore.
+* @deprecated
+*/
+
   VARaCUM NUMBER:=0;
   VARaCUMB NUMBER:=0;
   v_limitA NUMBER:=80;
--- a/src-db/database/model/functions/M_INOUT_CREATEINVOICE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/M_INOUT_CREATEINVOICE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -19,7 +19,7 @@
   * parts created by ComPiere are Copyright (C) ComPiere, Inc.;
   * All Rights Reserved.
   * Contributor(s): Openbravo SLU
-  * Contributions are Copyright (C) 2001-2016 Openbravo, S.L.U.
+  * Contributions are Copyright (C) 2001-2017 Openbravo, S.L.U.
   *
   * Specifically, this derivative work is based upon the following Compiere
   * file and version.
@@ -113,7 +113,6 @@
       --
       v_taxBaseAmt NUMBER;
       v_LineNetAmt NUMBER;
-      v_TotalNet NUMBER;
       -- v_Offer_ID       varchar2(32);
     BEGIN
       FOR CUR_Shipment IN
@@ -265,7 +264,6 @@
             )
             ;
           -- Lines
-          v_TotalNet:=0;
           FOR CUR_ShipmentLines IN
             (SELECT *  FROM M_INOUTLINE  WHERE M_InOut_ID=v_Record_ID)
           LOOP
@@ -318,10 +316,10 @@
                 v_grosspricestd:= v_PriceActual;
                 v_grosspricelist:= v_PriceList;
                 v_line_gross_amount:= ROUND(v_gross_unit_price * CUR_ShipmentLines.MovementQty, v_stdprecision);
-                v_PriceActual:= C_GET_NET_PRICE_FROM_GROSS(v_C_Tax_ID, v_PriceActual, 0, v_priceprecision, 1);
-                v_PriceList:= C_GET_NET_PRICE_FROM_GROSS(v_C_Tax_ID, v_PriceList, 0, v_priceprecision, 1);
-                v_PriceLimit:= C_GET_NET_PRICE_FROM_GROSS(v_C_Tax_ID, v_PriceLimit, 0, v_priceprecision, 1);
-                v_LineNetAmt:= ROUND(v_PriceActual * CUR_ShipmentLines.MovementQty, v_stdprecision);
+                v_PriceActual:= 0;
+                v_PriceList:= 0;
+                v_PriceLimit:= 0;
+                v_LineNetAmt:= 0;
               ELSE
                 v_PriceActual:=M_Get_Offers_Price(now(), CUR_Shipment.C_BPartner_ID, CUR_ShipmentLines.M_Product_ID, v_PriceActual, CUR_ShipmentLines.MovementQty, v_M_PriceList_ID);
                 v_LineNetAmt:=ROUND(M_Get_Offers_Price(now(), CUR_Shipment.C_BPartner_ID, CUR_ShipmentLines.M_Product_ID, v_PriceActual, CUR_ShipmentLines.MovementQty, v_M_PriceList_ID) *CUR_ShipmentLines.MovementQty, v_stdprecision) ;
@@ -384,9 +382,7 @@
                 coalesce(CUR_ShipmentLines.c_costcenter_id, CUR_Shipment.c_costcenter_id),
                 coalesce(CUR_ShipmentLines.a_asset_id, CUR_Shipment.a_asset_id),
                 CUR_ShipmentLines.c_aum, CUR_ShipmentLines.aumqty
-              )
-              ;
-            v_TotalNet:=v_TotalNet + v_LineNetAmt;
+              );
           END LOOP; -- ShipLines
         END IF;
       END LOOP; -- All Shipments
--- a/src-db/database/model/functions/M_INOUT_POST.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/M_INOUT_POST.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -22,7 +22,7 @@
   * parts created by ComPiere are Copyright (C) ComPiere, Inc.;
   * All Rights Reserved.
   * Contributor(s): Openbravo SLU
-  * Contributions are Copyright (C) 2001-2016 Openbravo, S.L.U.
+  * Contributions are Copyright (C) 2001-2017 Openbravo, S.L.U.
   *
   * Specifically, this derivative work is based upon the following Compiere
   * file and version.
@@ -511,6 +511,28 @@
             -- For all active shipment lines
             v_ResultStr:='HeaderLoop-1';
             
+          -- Update the C_Order_Id of M_InOut accordingly
+          SELECT COUNT(A.c_order_id)
+            INTO v_Count
+          FROM (
+            SELECT ol.c_order_id FROM M_InOutLine iol
+              JOIN C_OrderLine ol on iol.C_OrderLine_Id = ol.C_OrderLine_Id
+            WHERE  iol.M_InOut_Id = Cur_InOut.M_InOut_ID
+            GROUP BY ol.c_order_id) A;   
+          IF v_Count = 1 THEN 
+            UPDATE M_InOut
+            SET C_Order_Id = (
+              SELECT ol.c_order_id FROM M_InOutLine iol
+               JOIN C_OrderLine ol on iol.C_OrderLine_Id = ol.C_OrderLine_Id
+              WHERE  iol.M_InOut_Id = Cur_InOut.M_InOut_ID
+              GROUP BY ol.c_order_id)
+            WHERE M_InOut_Id = Cur_InOut.M_InOut_ID;
+          ELSE
+            UPDATE M_InOut
+            SET C_Order_Id = NULL
+            WHERE M_InOut_Id = Cur_InOut.M_InOut_ID;
+          END IF;
+            
         IF v_Aux=0 THEN
         RAISE_APPLICATION_ERROR(-20000, '@ReceiptWithoutLines@');
         END IF;
--- a/src-db/database/model/functions/M_PROMOTION_ADJUSTMENT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/M_PROMOTION_ADJUSTMENT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -34,7 +34,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-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -97,8 +97,8 @@
     v_newGrossAmt := round(v_newUnitPrice * v_qty, p_stdprecision);
     v_totalPromotion := v_origGrossAmt - v_newGrossAmt;
 
-    v_newNetPrice := c_get_net_price_from_gross(v_tax, v_newGrossAmt, v_newGrossAmt, p_priceprecision, v_qty);
-    v_newNetAmt := round(v_newNetPrice * v_qty, p_stdprecision);
+    v_newNetPrice := 0;
+    v_newNetAmt := 0;
     v_basePrice := v_unitprice;
   else
     if (v_fixed is not null) then
--- a/src-db/database/model/functions/M_REQUISITION_CREATEPO.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/M_REQUISITION_CREATEPO.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -16,7 +16,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) 2008-2016 Openbravo SLU
+* All portions are Copyright (C) 2008-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -264,8 +264,8 @@
       IF (Cur_Lines.istaxincluded = 'Y') THEN
         v_gross_unit_price:= v_Gross;
         v_line_gross_amount:= ROUND(v_gross_unit_price * (Cur_Lines.QTY - Cur_Lines.ORDEREDQTY), v_stdPre);
-        v_PriceActual:= C_GET_NET_PRICE_FROM_GROSS(v_Tax_ID, v_line_gross_amount, v_line_gross_amount, v_priPre, (Cur_Lines.QTY - Cur_Lines.ORDEREDQTY));
-        v_LineNetAmt:= ROUND(v_PriceActual * (Cur_Lines.QTY - Cur_Lines.ORDEREDQTY), v_stdPre);
+        v_PriceActual:= 0;
+        v_LineNetAmt:= 0;
         IF (v_PriceList = 0) THEN
           v_Discount := 0 ;
         ELSE
--- a/src-db/database/model/functions/M_UPDATE_INVENTORY.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/functions/M_UPDATE_INVENTORY.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -52,7 +52,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-2014 Openbravo SLU
+* All portions are Copyright (C) 2001-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -111,7 +111,6 @@
       PREQTYONHAND=PREQTYONHAND + COALESCE(p_preqty, 0),
       PREQTYORDERONHAND=PREQTYORDERONHAND + v_preqtyorder,
       AD_CLIENT_ID=p_client,
-      AD_ORG_ID=p_org,
       UPDATED=now(),
       UPDATEDBY=p_user
     WHERE M_PRODUCT_ID=p_product
--- a/src-db/database/model/postscript-Oracle.sql	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/postscript-Oracle.sql	Wed Mar 15 18:56:27 2017 +0100
@@ -580,7 +580,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) 2009-2016 Openbravo SLU
+* All portions are Copyright (C) 2009-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -595,7 +595,7 @@
   cur_triggers RECORD;
   cur_tables RECORD;
   cur_cols RECORD;
-  triggerName varchar2(30);
+  targetTriggerName varchar2(30);
   recordIdName varchar2(30);
   datatype varchar2(30);
   clientinfo number;
@@ -603,6 +603,9 @@
   created number :=0;
   v_message varchar2(500);
   v_isObps number;
+  isavailablename number :=0;
+  suffixNumber number :=0;
+  numberCharsToRemove number;
   
   
   FUNCTION splitClob(code clob, splitcode out dbms_sql.varchar2s ) RETURN number AS 
@@ -644,7 +647,19 @@
                       and dataOriginType = 'Table'
                       order by tablename) loop
     dbms_output.put_line('Creating trigger for table '||cur_tables.tablename);
-    triggerName := 'AU_'||SUBSTR(cur_tables.tablename,1,23)||'_TRG';
+    targetTriggerName := 'AU_'||SUBSTR(cur_tables.tablename,1,23)||'_TRG';
+    LOOP
+        select count(*)
+          into isavailablename
+        from user_triggers
+        where upper(trigger_name) = upper(targetTriggerName);
+
+        EXIT WHEN isavailablename = 0;
+
+        suffixNumber := suffixNumber + 1;
+        numberCharsToRemove :=LENGTH(suffixNumber);
+        targetTriggerName := 'AU_'||SUBSTR(cur_tables.tablename,1,23-numberCharsToRemove)||''||suffixNumber||'_TRG';
+    END LOOP;
     
     select count(*) into clientinfo
       from dual
@@ -662,7 +677,7 @@
      where ad_table_id = cur_tables.ad_table_id
        and iskey='Y';
     
-      code := 'create or replace TRIGGER '||triggerName||' 
+      code := 'create or replace TRIGGER '||targetTriggerName||' 
 AFTER INSERT OR UPDATE OR DELETE
 ON '|| cur_tables.tablename||' FOR EACH ROW
 DECLARE
@@ -824,6 +839,7 @@
 DBMS_SQL.close_cursor(cursor_id);
 
     created := created + 1;
+    suffixNumber :=0;
   end loop;
   
   v_Message := '@Deleted@: '||deleted||' @Created@: '||created;
--- a/src-db/database/model/postscript-PostgreSql.sql	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/postscript-PostgreSql.sql	Wed Mar 15 18:56:27 2017 +0100
@@ -375,7 +375,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) 2009-2016 Openbravo SLU
+* All portions are Copyright (C) 2009-2017 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -383,7 +383,7 @@
   cur_triggers RECORD;
   cur_tables RECORD;
   cur_cols RECORD;
-  triggerName VARCHAR(30); 
+  targetTriggerName VARCHAR(30);
   recordIdName VARCHAR(30);
   datatype VARCHAR(30); 
   clientinfo NUMERIC;
@@ -391,6 +391,9 @@
   created NUMERIC :=0;
   v_message VARCHAR(500);
   v_isObps NUMERIC;
+  isavailablename NUMERIC :=0;
+  suffixNumber NUMERIC :=0;
+  numberCharsToRemove NUMERIC;
 BEGIN 
   select count(*) 
     into v_isObps
@@ -418,8 +421,21 @@
                       and dataOriginType = 'Table'
                       order by tablename) loop
     
-    triggerName := 'AU_'||SUBSTR(cur_tables.tablename,1,23)||'_TRG';
-    raise notice '%', triggerName;
+    targetTriggerName := 'AU_'||SUBSTR(cur_tables.tablename,1,23)||'_TRG';
+    LOOP
+        select count(*)
+         into isavailablename
+        from user_triggers u
+        where upper(trigger_name) = upper(targetTriggerName);
+
+        EXIT WHEN isavailablename = 0;
+
+	 suffixNumber := suffixNumber + 1;
+	 raise notice '%', targetTriggerName || ' is already exists. Renaming...';
+	 numberCharsToRemove :=LENGTH(CAST(suffixNumber AS VARCHAR));
+	 targetTriggerName := 'AU_'||SUBSTR(cur_tables.tablename,1,23-numberCharsToRemove)||''||suffixNumber||'_TRG';
+    END LOOP;
+    raise notice '%', targetTriggerName;
     
     select count(*) into clientinfo
       from dual
@@ -437,7 +453,7 @@
      where ad_table_id = cur_tables.ad_table_id
        and iskey='Y';
     
-      code := 'create or replace FUNCTION '||triggerName||'() 
+      code := 'create or replace FUNCTION '||targetTriggerName||'()
 RETURNS trigger AS
 $BODY$
 DECLARE
@@ -611,15 +627,15 @@
 EXECUTE(code);
 
  code := 
-    'CREATE TRIGGER '||triggerName||'
+    'CREATE TRIGGER '||targetTriggerName||'
       BEFORE INSERT OR UPDATE OR DELETE
       ON '||cur_cols.table_name||'
       FOR EACH ROW
-      EXECUTE PROCEDURE '||triggerName||'()';
+      EXECUTE PROCEDURE '||targetTriggerName||'()';
       execute(code);
       
     created := created + 1;
-
+    suffixNumber :=0;
   end loop;
   
   v_Message := '@Deleted@: '||deleted||' @Created@: '||created;
--- a/src-db/database/model/prescript-Oracle.sql	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/prescript-Oracle.sql	Wed Mar 15 18:56:27 2017 +0100
@@ -234,3 +234,38 @@
   RETURN p_date + p_hours/24 + p_minutes/1440 + p_seconds/86400;
 end ADD_HMS;
 /-- END
+
+create or replace
+FUNCTION OBEQUALS(p_number_a IN NUMBER, p_number_b IN NUMBER) RETURN CHAR DETERMINISTIC
+
+AS
+/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2017 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+/**
+* Returns 'Y' when both numbers are equals, else returns 'N'
+* This function is used as index in FIN_Payment table
+**/
+ v_dif NUMBER;
+begin
+    v_dif := coalesce(p_number_a, 0) - coalesce(p_number_b, 0);
+    IF (v_dif = 0) THEN
+     return 'Y';
+    ELSE
+     return 'N';
+    END IF;
+end OBEQUALS;
+/-- END
--- a/src-db/database/model/prescript-PostgreSql.sql	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/prescript-PostgreSql.sql	Wed Mar 15 18:56:27 2017 +0100
@@ -1184,6 +1184,7 @@
 RETURNS uuid
 AS '$libdir/uuid-ossp', 'uuid_generate_v4'
 VOLATILE STRICT LANGUAGE C;
+/-- END
 
 CREATE OR REPLACE FUNCTION get_uuid()
   RETURNS varchar AS
@@ -1531,3 +1532,44 @@
 END ; $BODY$
   LANGUAGE plpgsql IMMUTABLE
 /-- END
+
+-- INSTALL PG_TRGM EXTENSION
+CREATE EXTENSION IF NOT EXISTS "pg_trgm"
+/-- END
+
+CREATE OR REPLACE FUNCTION obequals(
+    p_number_a numeric,
+    p_number_b numeric)
+  RETURNS char AS
+$BODY$ DECLARE
+/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2017 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+/**
+* Returns 'Y' when both numbers are equals, else returns 'N'
+* This function is used as index in FIN_Payment table
+**/
+ v_dif NUMERIC;
+BEGIN
+    v_dif := coalesce(p_number_a, 0) - coalesce(p_number_b, 0);
+    IF (v_dif = 0) THEN
+     return 'Y';
+    ELSE
+     return 'N';
+    END IF;
+END; $BODY$
+  LANGUAGE plpgsql IMMUTABLE
+/-- END
--- a/src-db/database/model/tables/AD_COLUMN.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/AD_COLUMN.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -256,6 +256,7 @@
       </index>
       <index name="AD_COLUMN_PROCESS" unique="false">
         <index-column name="AD_PROCESS_ID"/>
+        <whereClause><![CDATA[AD_PROCESS_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="AD_COLUMN_TABLE" unique="false">
         <index-column name="AD_TABLE_ID"/>
--- a/src-db/database/model/tables/AD_MODEL_OBJECT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/AD_MODEL_OBJECT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -111,15 +111,19 @@
       </foreign-key>
       <index name="AD_MODELOBJECT_CALLOUT_IDX" unique="false">
         <index-column name="AD_CALLOUT_ID"/>
+        <whereClause><![CDATA[AD_CALLOUT_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="AD_MODELOBJECT_FORM_IDX" unique="false">
         <index-column name="AD_FORM_ID"/>
+        <whereClause><![CDATA[AD_FORM_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="AD_MODELOBJECT_PROCESS_IDX" unique="false">
         <index-column name="AD_PROCESS_ID"/>
+        <whereClause><![CDATA[AD_PROCESS_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="AD_MODELOBJECT_REFERENCE_IDX" unique="false">
         <index-column name="AD_REFERENCE_ID"/>
+        <whereClause><![CDATA[AD_REFERENCE_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="AD_MODEL_OBJECT_ISACTIVE_CHK"><![CDATA[ISACTIVE IN ('Y', 'N')]]></check>
       <check name="AD_MODEL_OBJECT_ISDEFAULT_CHK"><![CDATA[ISDEFAULT IN ('Y', 'N')]]></check>
--- a/src-db/database/model/tables/AD_PROCESS_RUN.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/AD_PROCESS_RUN.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -86,6 +86,7 @@
       </index>
       <index name="AD_PROCESS_RUN_ADPRGROUP_ID" unique="false">
         <index-column name="AD_PROCESS_RUN_GROUP_ID"/>
+        <whereClause><![CDATA[AD_PROCESS_RUN_GROUP_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="AD_PROCESS_RUN_STATUS" unique="false">
         <index-column name="STATUS"/>
--- a/src-db/database/model/tables/AD_TAB.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/AD_TAB.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -237,6 +237,7 @@
       </index>
       <index name="AD_TAB_TABLETREE_FK" unique="false">
         <index-column name="AD_TABLE_TREE_ID"/>
+        <whereClause><![CDATA[AD_TABLE_TREE_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="AD_TAB_WINDOW" unique="false">
         <index-column name="AD_WINDOW_ID"/>
--- a/src-db/database/model/tables/AD_USER.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/AD_USER.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -206,6 +206,7 @@
       </foreign-key>
       <index name="AD_USER_EMAIL" unique="false">
         <index-column name="EMAIL"/>
+        <whereClause><![CDATA[EMAIL IS NOT NULL]]></whereClause>
       </index>
       <index name="AD_USER_NAME" unique="false">
         <index-column name="AD_CLIENT_ID"/>
--- a/src-db/database/model/tables/A_AMORTIZATIONLINE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/A_AMORTIZATIONLINE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -109,6 +109,7 @@
       </index>
       <index name="A_AMORTIZATIONLINE_ASSET_IDX" unique="false">
         <index-column name="A_ASSET_ID"/>
+        <whereClause><![CDATA[A_ASSET_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="A_AMORTIZATIONL_ISACTIVE_CHECK"><![CDATA[ISACTIVE IN ('Y', 'N')]]></check>
     </table>
--- a/src-db/database/model/tables/A_ASSET.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/A_ASSET.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -291,6 +291,7 @@
       </foreign-key>
       <index name="A_ASSET_BPARTNER_IDX" unique="false">
         <index-column name="C_BPARTNER_ID"/>
+        <whereClause><![CDATA[C_BPARTNER_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="A_ASSET_IS30DAYMONTH_CHK"><![CDATA[IS30DAYMONTH IN ('Y', 'N')]]></check>
       <check name="A_ASSET_ISACTIVE_CHK"><![CDATA[ISACTIVE IN ('Y', 'N')]]></check>
--- a/src-db/database/model/tables/C_ACCTSCHEMA_PROCESS.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_ACCTSCHEMA_PROCESS.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -63,6 +63,7 @@
       </foreign-key>
       <index name="C_ACCTSCHEMAPRC_ACCTSCHEMA_IDX" unique="false">
         <index-column name="C_ACCTSCHEMA_ID"/>
+        <whereClause><![CDATA[C_ACCTSCHEMA_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="C_ACCTSCHEMA_PROCESS_ISACT_CHK"><![CDATA[ISACTIVE IN ('Y', 'N')]]></check>
       <check name="C_ACCTSCHEMA_PROCESS_ISDAT_CHK"><![CDATA[ISDATASET IN ('Y', 'N')]]></check>
--- a/src-db/database/model/tables/C_BPARTNER.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_BPARTNER.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -471,6 +471,7 @@
       <index name="C_BPARTNER_REFNO_ID" unique="false">
         <index-column name="REFERENCENO"/>
         <index-column name="C_BPARTNER_ID"/>
+        <whereClause><![CDATA[REFERENCENO IS NOT NULL]]></whereClause>
       </index>
       <index name="C_BPARTNER_VALUE_ID" unique="false">
         <index-column name="VALUE"/>
--- a/src-db/database/model/tables/C_CITY.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_CITY.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -75,6 +75,7 @@
       </foreign-key>
       <index name="C_CITY_REGION_IDX" unique="false">
         <index-column name="C_REGION_ID"/>
+        <whereClause><![CDATA[C_REGION_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="C_CITY_ISACTIVE_CHECK"><![CDATA[ISACTIVE IN ('Y', 'N')]]></check>
     </table>
--- a/src-db/database/model/tables/C_CONVERSION_RATE_DOCUMENT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_CONVERSION_RATE_DOCUMENT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -98,9 +98,14 @@
       </foreign-key>
       <index name="C_CONVRATEDOC_FINACCTRX_IDX" unique="false">
         <index-column name="FIN_FINACC_TRANSACTION_ID"/>
+        <whereClause><![CDATA[FIN_FINACC_TRANSACTION_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="C_CONVRATEDOC_GLJOURNAL_IDX" unique="false">
         <index-column name="GL_JOURNAL_ID"/>
+        <whereClause><![CDATA[GL_JOURNAL_ID IS NOT NULL]]></whereClause>
+      </index>
+      <index name="C_CONVRATEDOC_INVOICE_IDX" unique="false">
+        <index-column name="C_INVOICE_ID"/>
       </index>
       <index name="C_CONVRATEDOC_PAYMENT_IDX" unique="false">
         <index-column name="FIN_PAYMENT_ID"/>
--- a/src-db/database/model/tables/C_INVOICE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_INVOICE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -363,6 +363,7 @@
       </index>
       <index name="C_INVOICE_ORDER" unique="false">
         <index-column name="C_ORDER_ID"/>
+        <whereClause><![CDATA[C_ORDER_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="C_INVOICE_PAID" unique="false">
         <index-column name="ISPAID"/>
--- a/src-db/database/model/tables/C_INVOICELINE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_INVOICELINE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -306,12 +306,14 @@
       </foreign-key>
       <index name="C_INVOICELINE_INOUTLINE" unique="false">
         <index-column name="M_INOUTLINE_ID"/>
+        <whereClause><![CDATA[M_INOUTLINE_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="C_INVOICELINE_INVOICE" unique="false">
         <index-column name="C_INVOICE_ID"/>
       </index>
       <index name="C_INVOICELINE_ORDERLINE" unique="false">
         <index-column name="C_ORDERLINE_ID"/>
+        <whereClause><![CDATA[C_ORDERLINE_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="C_INVOICELINE_PRODUCT" unique="false">
         <index-column name="M_PRODUCT_ID"/>
--- a/src-db/database/model/tables/C_ORDER.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_ORDER.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -478,6 +478,7 @@
       </index>
       <index name="C_ORDER_C_RETURN_REASON" unique="false">
         <index-column name="C_RETURN_REASON_ID"/>
+        <whereClause><![CDATA[C_RETURN_REASON_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="C_ORDER_CANCELLEDORDER_ID" unique="false">
         <index-column name="CANCELLEDORDER_ID"/>
--- a/src-db/database/model/tables/C_ORDERLINE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_ORDERLINE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -385,9 +385,11 @@
       </foreign-key>
       <index name="C_ORDERLINE_C_RETURN_REASON" unique="false">
         <index-column name="C_RETURN_REASON_ID"/>
+        <whereClause><![CDATA[C_RETURN_REASON_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="C_ORDERLINE_INOUTLINE" unique="false">
         <index-column name="M_INOUTLINE_ID"/>
+        <whereClause><![CDATA[M_INOUTLINE_ID IS NOT NULL]]></whereClause>
       </index>
       <index name="C_ORDERLINE_ORDER" unique="false">
         <index-column name="C_ORDER_ID"/>
--- a/src-db/database/model/tables/C_ORDERLINETAX.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_ORDERLINETAX.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -72,6 +72,9 @@
       <foreign-key foreignTable="C_TAX" name="C_ORDERLINETAX_C_TAX">
         <reference local="C_TAX_ID" foreign="C_TAX_ID"/>
       </foreign-key>
+      <index name="C_ORDERLINETAX_ORDERID" unique="false">
+        <index-column name="C_ORDER_ID"/>
+      </index>
       <index name="C_ORDERLINETAX_ORDERLINE" unique="false">
         <index-column name="C_ORDERLINE_ID"/>
       </index>
--- a/src-db/database/model/tables/C_ORDERTAX.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_ORDERTAX.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -65,6 +65,9 @@
       <foreign-key foreignTable="C_TAX" name="C_ORDERTAX_C_TAX">
         <reference local="C_TAX_ID" foreign="C_TAX_ID"/>
       </foreign-key>
+      <index name="C_ORDERTAX_ORDERID" unique="false">
+        <index-column name="C_ORDER_ID"/>
+      </index>
       <unique name="C_ORDERTAX_ORDER_TAX_UN">
         <unique-column name="C_ORDER_ID"/>
         <unique-column name="C_TAX_ID"/>
--- a/src-db/database/model/tables/C_POC_DOCTYPE_TEMPLATE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_POC_DOCTYPE_TEMPLATE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -80,6 +80,7 @@
       </foreign-key>
       <index name="C_POC_DOCTYPE_TEMP_DOCTYPE_IDX" unique="false">
         <index-column name="C_DOCTYPE_ID"/>
+        <whereClause><![CDATA[C_DOCTYPE_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="C_POC_DOCTYPETEMP_SHOWCOMP_CHK"><![CDATA[SHOWCOMPANYDATA IN ('Y', 'N')]]></check>
       <check name="C_POC_DOCTYPETEMP_SHOWLOGO_CHK"><![CDATA[SHOWLOGO IN ('Y', 'N')]]></check>
--- a/src-db/database/model/tables/C_POC_EMAILDEFINITION.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_POC_EMAILDEFINITION.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -67,6 +67,7 @@
       </foreign-key>
       <index name="C_POCEMAILDEF_DOCTYPETEMPL_IDX" unique="false">
         <index-column name="C_POC_DOCTYPE_TEMPLATE_ID"/>
+        <whereClause><![CDATA[C_POC_DOCTYPE_TEMPLATE_ID IS NOT NULL]]></whereClause>
       </index>
     </table>
   </database>
--- a/src-db/database/model/tables/C_TAXREGISTER.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_TAXREGISTER.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -71,6 +71,7 @@
       </foreign-key>
       <index name="C_TAXREGISTER_TAXPAYMENT_IDX" unique="false">
         <index-column name="C_TAXPAYMENT_ID"/>
+        <whereClause><![CDATA[C_TAXPAYMENT_ID IS NOT NULL]]></whereClause>
       </index>
     </table>
   </database>
--- a/src-db/database/model/tables/C_TAXREGISTERLINE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_TAXREGISTERLINE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -98,6 +98,7 @@
       </foreign-key>
       <index name="C_TAXREGISTERLINE_TAXREGIS_IDX" unique="false">
         <index-column name="C_TAXREGISTER_ID"/>
+        <whereClause><![CDATA[C_TAXREGISTER_ID IS NOT NULL]]></whereClause>
       </index>
     </table>
   </database>
--- a/src-db/database/model/tables/C_TAXREGISTER_TYPE_LINES.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/C_TAXREGISTER_TYPE_LINES.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -62,6 +62,7 @@
       </foreign-key>
       <index name="C_TAXREGTYPELIN_TAXREGTYPE_IDX" unique="false">
         <index-column name="C_TAXREGISTER_TYPE_ID"/>
+        <whereClause><![CDATA[C_TAXREGISTER_TYPE_ID IS NOT NULL]]></whereClause>
       </index>
     </table>
   </database>
--- a/src-db/database/model/tables/FACT_ACCT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/FACT_ACCT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -302,6 +302,10 @@
       <index name="FACT_ACCT_GROUP" unique="false">
         <index-column name="FACT_ACCT_GROUP_ID"/>
       </index>
+      <index name="FACT_ACCT_LINE_ID" unique="false">
+        <index-column name="LINE_ID"/>
+        <whereClause><![CDATA[LINE_ID IS NOT NULL]]></whereClause>
+      </index>
       <index name="FACT_ACCT_RECORD_ID2" unique="false">
         <index-column name="RECORD_ID2"/>
       </index>
--- a/src-db/database/model/tables/FIN_DOUBTFUL_DEBT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/FIN_DOUBTFUL_DEBT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -161,6 +161,10 @@
       <index name="FIN_DOUBTDBT_DOUBTDBTRUN_IDX" unique="false">
         <index-column name="FIN_DOUBTFUL_DEBT_RUN_ID"/>
       </index>
+      <index name="FIN_DOUBTDBT_PAYSCHED_IDX" unique="false">
+        <index-column name="FIN_PAYMENT_SCHEDULE_ID"/>
+        <whereClause><![CDATA[FIN_PAYMENT_SCHEDULE_ID IS NOT NULL]]></whereClause>
+      </index>
       <index name="FIN_DOUBTFUL_DEBT_POSTED" unique="false">
         <index-column name="POSTED"/>
       </index>
--- a/src-db/database/model/tables/FIN_ORIG_PAYMENT_SCHEDULE.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/FIN_ORIG_PAYMENT_SCHEDULE.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -88,6 +88,7 @@
       </foreign-key>
       <index name="FIN_ORIG_PAYM_SCHED_IND" unique="false">
         <index-column name="C_INVOICE_ID"/>
+        <whereClause><![CDATA[C_INVOICE_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="FIN_PAYORIGSCHED_ISAC_CHK"><![CDATA[ISACTIVE IN ('Y', 'N')]]></check>
       <check name="FIN_PAYORIGSCHED_UPP_CHK"><![CDATA[UPDATE_PAYMENT_PLAN IN ('Y', 'N')]]></check>
--- a/src-db/database/model/tables/FIN_ORIG_PAYM_SCHEDDETAIL.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/FIN_ORIG_PAYM_SCHEDDETAIL.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -67,6 +67,7 @@
       </foreign-key>
       <index name="FIN_ORIG_PAYM_SCHDET_IND" unique="false">
         <index-column name="FIN_ORIG_PAYMENT_SCHEDULE_ID"/>
+        <whereClause><![CDATA[FIN_ORIG_PAYMENT_SCHEDULE_ID IS NOT NULL]]></whereClause>
       </index>
       <check name="FIN_ORIG_PAY_SCHDET_ISCANC_CHK"><![CDATA[ISCANCELED IN ('Y', 'N')]]></check>
       <check name="FIN_ORIG_PAYM_SCHDET_ACT_CHK"><![CDATA[ISACTIVE IN ('Y', 'N')]]></check>
--- a/src-db/database/model/tables/FIN_PAYMENT.xml	Thu Mar 16 08:47:42 2017 +0100
+++ b/src-db/database/model/tables/FIN_PAYMENT.xml	Wed Mar 15 18:56:27 2017 +0100
@@ -187,6 +187,10 @@
       <foreign-key foreignTable="USER2" name="FIN_PAYMENT_USER2">
         <reference local="USER2_ID" foreign="USER2_ID"/>
       </foreign-key>
+      <index name="FIN_PAYMENT_BPARTNER_CREDIT" unique="false">
+        <index-column name="C_BPARTNER_ID"/>
+        <index-column name="functionBasedColumn" functionExpression="OBEQUALS(GENERATED_CREDIT,USED_CREDIT)"/>
+      </index>