[pi-expired-password] Merge with latest pi
authorNaroa Iriarte <naroa.iriarte@openbravo.com>
Tue, 19 Apr 2016 09:28:13 +0200
changeset 29411 2e25388a866d
parent 29410 5de1f0f07bc7 (current diff)
parent 29401 de209c96bd10 (diff)
child 29412 46b75b28bc64
[pi-expired-password] Merge with latest pi
src-db/database/sourcedata/AD_COLUMN.xml
src-db/database/sourcedata/AD_ELEMENT.xml
src-db/database/sourcedata/AD_FIELD.xml
--- a/src-db/database/model/functions/C_GET_SERVICE_AMOUNT.xml	Tue Apr 19 09:26:13 2016 +0200
+++ b/src-db/database/model/functions/C_GET_SERVICE_AMOUNT.xml	Tue Apr 19 09:28:13 2016 +0200
@@ -33,64 +33,59 @@
   Cur_Rule RECORD;
   Cur_Range RECORD;
   BEGIN
-  
-    
-  
-		SELECT SUM(AMOUNT), SUM(QUANTITY), ISPRICERULEBASED, M_PRODUCT.M_PRODUCT_ID, C_ORDER.DATEORDERED, STDPRECISION, C_ORDER.M_PRICELIST_ID
-		INTO v_TotalAmount, v_TotalQantity, v_IsPriceRuleBased, v_M_Product_ID,  v_Dateordered, v_stdPrecision, 	v_OrderPricelist
-		FROM C_ORDERLINE_SERVICERELATION, C_ORDERLINE, M_PRODUCT, C_ORDER, C_CURRENCY
-		WHERE C_ORDERLINE_SERVICERELATION.C_ORDERLINE_ID = C_ORDERLINE.C_ORDERLINE_ID
-		AND C_ORDER.C_ORDER_ID = C_ORDERLINE.C_ORDER_ID
-		AND C_ORDER.C_CURRENCY_ID =  C_CURRENCY.C_CURRENCY_ID
-		AND C_ORDERLINE.M_PRODUCT_id =  M_PRODUCT.M_PRODUCT_ID
-		AND C_ORDERLINE.C_ORDERLINE_ID =  v_c_orderline_id
-		GROUP BY ISPRICERULEBASED, M_PRODUCT.M_PRODUCT_ID, C_ORDER.DATEORDERED, STDPRECISION, C_ORDER.M_PRICELIST_ID;
+    SELECT SUM(AMOUNT), SUM(QUANTITY), ISPRICERULEBASED, M_PRODUCT.M_PRODUCT_ID, C_ORDER.DATEORDERED, STDPRECISION, C_ORDER.M_PRICELIST_ID
+      INTO v_TotalAmount, v_TotalQantity, v_IsPriceRuleBased, v_M_Product_ID,  v_Dateordered, v_stdPrecision, v_OrderPricelist
+    FROM C_ORDERLINE_SERVICERELATION, C_ORDERLINE, M_PRODUCT, C_ORDER, C_CURRENCY
+    WHERE C_ORDERLINE_SERVICERELATION.C_ORDERLINE_ID = C_ORDERLINE.C_ORDERLINE_ID
+    AND C_ORDER.C_ORDER_ID = C_ORDERLINE.C_ORDER_ID
+    AND C_ORDER.C_CURRENCY_ID =  C_CURRENCY.C_CURRENCY_ID
+    AND C_ORDERLINE.M_PRODUCT_id =  M_PRODUCT.M_PRODUCT_ID
+    AND C_ORDERLINE.C_ORDERLINE_ID =  v_c_orderline_id
+    GROUP BY ISPRICERULEBASED, M_PRODUCT.M_PRODUCT_ID, C_ORDER.DATEORDERED, STDPRECISION, C_ORDER.M_PRICELIST_ID;
 		
     IF(v_IsPriceRuleBased = 'Y') THEN
-          FOR Cur_Rule IN
-			      (
-						SELECT  RULETYPE, AFTERDISCOUNTS, PERCENTAGE, M_SERVICEPRICERULE.M_SERVICEPRICERULE_ID
-						FROM M_SERVICEPRICERULE_VERSION, M_SERVICEPRICERULE
-						WHERE M_SERVICEPRICERULE_VERSION.M_SERVICEPRICERULE_ID =  M_SERVICEPRICERULE.M_SERVICEPRICERULE_ID
-						AND M_PRODUCT_ID = v_M_Product_ID
-						AND VALIDFROM <=  v_Dateordered
-						ORDER BY VALIDFROM DESC
-			      )
-			    LOOP
-            IF(Cur_Rule.RULETYPE = 'P') THEN
-              RETURN  round(v_TotalAmount * Cur_Rule.percentage / 100, v_stdPrecision);
-            ELSE
-			          FOR Cur_Range IN
-						      (
-									SELECT  RULETYPE, AFTERDISCOUNTS, PERCENTAGE, M_PRICELIST_ID
-									FROM m_servicepricerule_range
-									WHERE m_servicepricerule_ID  = Cur_Rule.M_SERVICEPRICERULE_ID
-									AND coalesce(amountupto, v_TotalAmount)  >=  v_TotalAmount
-									ORDER BY amountupto
-						      )
-						    LOOP
-			            IF(Cur_Range.RULETYPE = 'P') THEN
-			              RETURN  ROUND(v_TotalAmount * Cur_Range.percentage / 100, v_stdPrecision);
-			            ELSE
-			              SELECT PRICELIST 
-			              INTO v_PriceList
-			              FROM M_PRODUCTPRICE
-			              WHERE M_PRICELIST_VERSION_ID = M_GET_PRICELIST_VERSION(Cur_Range.M_PRICELIST_ID, v_Dateordered)
-			              AND M_PRODUCT_ID = v_M_Product_ID;
-                    RETURN ROUND(v_PriceList * v_TotalQantity, v_stdPrecision);
-			            END IF;
-						    END LOOP;
-						    RAISE_APPLICATION_ERROR(-20000, '@NoMatchingRange@');
-            END IF;
-			    END LOOP;
-			    RAISE_APPLICATION_ERROR(-20000, '@NoMatchingPriceRule@');
-		ELSE
-			SELECT PRICELIST 
-			INTO v_PriceList
-			FROM M_PRODUCTPRICE
-			WHERE M_PRICELIST_VERSION_ID = M_GET_PRICELIST_VERSION(v_OrderPricelist, v_Dateordered)
-			AND M_PRODUCT_ID = v_M_Product_ID;
-			RETURN ROUND(v_PriceList * v_TotalQantity, v_stdPrecision);
+      FOR Cur_Rule IN
+	(SELECT  RULETYPE, AFTERDISCOUNTS, PERCENTAGE, M_SERVICEPRICERULE.M_SERVICEPRICERULE_ID
+	 FROM M_SERVICEPRICERULE_VERSION, M_SERVICEPRICERULE
+	 WHERE M_SERVICEPRICERULE_VERSION.M_SERVICEPRICERULE_ID =  M_SERVICEPRICERULE.M_SERVICEPRICERULE_ID
+	 AND M_PRODUCT_ID = v_M_Product_ID
+	 AND VALIDFROM <=  v_Dateordered
+	 ORDER BY VALIDFROM DESC
+	)
+      LOOP
+        IF(Cur_Rule.RULETYPE = 'P') THEN
+          RETURN  round(v_TotalAmount * Cur_Rule.percentage / 100, v_stdPrecision);
+        ELSE
+	  FOR Cur_Range IN
+            (SELECT  RULETYPE, AFTERDISCOUNTS, PERCENTAGE, M_PRICELIST_ID
+	     FROM m_servicepricerule_range
+	     WHERE m_servicepricerule_ID  = Cur_Rule.M_SERVICEPRICERULE_ID
+	     AND coalesce(amountupto, v_TotalAmount)  >=  v_TotalAmount
+	     ORDER BY amountupto
+	    )
+	  LOOP
+	    IF(Cur_Range.RULETYPE = 'P') THEN
+	      RETURN  ROUND(v_TotalAmount * Cur_Range.percentage / 100, v_stdPrecision);
+	    ELSE
+	      SELECT PRICELIST 
+		INTO v_PriceList
+	      FROM M_PRODUCTPRICE
+	      WHERE M_PRICELIST_VERSION_ID = M_GET_PRICELIST_VERSION(Cur_Range.M_PRICELIST_ID, v_Dateordered)
+	      AND M_PRODUCT_ID = v_M_Product_ID;
+              RETURN ROUND(v_PriceList * v_TotalQantity, v_stdPrecision);
+	    END IF;
+	  END LOOP;
+	  RAISE_APPLICATION_ERROR(-20000, '@NoMatchingRange@');
+        END IF;
+      END LOOP;
+      RAISE_APPLICATION_ERROR(-20000, '@NoMatchingPriceRule@');
+    ELSE
+      SELECT PRICELIST 
+        INTO v_PriceList
+      FROM M_PRODUCTPRICE
+      WHERE M_PRICELIST_VERSION_ID = M_GET_PRICELIST_VERSION(v_OrderPricelist, v_Dateordered)
+      AND M_PRODUCT_ID = v_M_Product_ID;
+      RETURN ROUND(v_PriceList * v_TotalQantity, v_stdPrecision);
     END IF;
 END C_GET_SERVICE_AMOUNT
 ]]></body>
--- a/src-db/database/model/functions/C_ORDER_POST1.xml	Tue Apr 19 09:26:13 2016 +0200
+++ b/src-db/database/model/functions/C_ORDER_POST1.xml	Tue Apr 19 09:28:13 2016 +0200
@@ -181,17 +181,16 @@
     END LOOP;
   ELSE
      IF (v_DocAction IN ('CO', 'PR')) THEN
-				SELECT COUNT(1) 
-				INTO v_Count
-				FROM DUAL 
-				WHERE EXISTS(
-											SELECT 1
-											FROM C_ORDERLINE, M_PRODUCT
-											WHERE C_ORDERLINE.M_PRODUCT_ID = M_PRODUCT.M_PRODUCT_ID 
-											AND ISLINKEDTOPRODUCT = 'Y'
-											AND C_ORDER_ID = v_Record_ID
-											AND NOT EXISTS (SELECT 1 FROM C_ORDERLINE_SERVICERELATION WHERE C_ORDERLINE_SERVICERELATION.C_ORDERLINE_ID = C_ORDERLINE.C_ORDERLINE_ID));
-			 IF (v_Count <> 0) THEN
+       SELECT COUNT(1) 
+         INTO v_Count
+       FROM DUAL 
+       WHERE EXISTS(SELECT 1
+		      FROM C_ORDERLINE, M_PRODUCT
+		      WHERE C_ORDERLINE.M_PRODUCT_ID = M_PRODUCT.M_PRODUCT_ID 
+		      AND ISLINKEDTOPRODUCT = 'Y'
+		      AND C_ORDER_ID = v_Record_ID
+		      AND NOT EXISTS (SELECT 1 FROM C_ORDERLINE_SERVICERELATION WHERE C_ORDERLINE_SERVICERELATION.C_ORDERLINE_ID = C_ORDERLINE.C_ORDERLINE_ID));
+       IF (v_Count <> 0) THEN
          v_Message:='@MissingServiceRelation@';
          RAISE_APPLICATION_ERROR(-20000, '@MissingServiceRelation@') ;
        END IF;
--- a/src-db/database/sourcedata/AD_COLUMN.xml	Tue Apr 19 09:26:13 2016 +0200
+++ b/src-db/database/sourcedata/AD_COLUMN.xml	Tue Apr 19 09:28:13 2016 +0200
@@ -263588,6 +263588,8 @@
 <!--481DD00275E04E569EC34D3E634249A3-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--481DD00275E04E569EC34D3E634249A3-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
 <!--481DD00275E04E569EC34D3E634249A3-->  <NAME><![CDATA[linkedToProduct]]></NAME>
+<!--481DD00275E04E569EC34D3E634249A3-->  <DESCRIPTION><![CDATA[The service can be linked to a Product]]></DESCRIPTION>
+<!--481DD00275E04E569EC34D3E634249A3-->  <HELP><![CDATA[The service can be linked to a Product. If so, when adding the product to a Sales Order, the related service product could be added to the Sales Order also, following special rules to set the quantity to be added and the price of the service, both of them based on the product.]]></HELP>
 <!--481DD00275E04E569EC34D3E634249A3-->  <COLUMNNAME><![CDATA[Islinkedtoproduct]]></COLUMNNAME>
 <!--481DD00275E04E569EC34D3E634249A3-->  <AD_TABLE_ID><![CDATA[208]]></AD_TABLE_ID>
 <!--481DD00275E04E569EC34D3E634249A3-->  <AD_REFERENCE_ID><![CDATA[20]]></AD_REFERENCE_ID>
--- a/src-db/database/sourcedata/AD_ELEMENT.xml	Tue Apr 19 09:26:13 2016 +0200
+++ b/src-db/database/sourcedata/AD_ELEMENT.xml	Tue Apr 19 09:28:13 2016 +0200
@@ -26245,6 +26245,8 @@
 <!--680E69F4E5C8492BA0897166B5C54926-->  <COLUMNNAME><![CDATA[Islinkedtoproduct]]></COLUMNNAME>
 <!--680E69F4E5C8492BA0897166B5C54926-->  <NAME><![CDATA[Linked To Product]]></NAME>
 <!--680E69F4E5C8492BA0897166B5C54926-->  <PRINTNAME><![CDATA[Linked To Product]]></PRINTNAME>
+<!--680E69F4E5C8492BA0897166B5C54926-->  <DESCRIPTION><![CDATA[The service can be linked to a Product]]></DESCRIPTION>
+<!--680E69F4E5C8492BA0897166B5C54926-->  <HELP><![CDATA[The service can be linked to a Product. If so, when adding the product to a Sales Order, the related service product could be added to the Sales Order also, following special rules to set the quantity to be added and the price of the service, both of them based on the product.]]></HELP>
 <!--680E69F4E5C8492BA0897166B5C54926-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
 <!--680E69F4E5C8492BA0897166B5C54926-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
 <!--680E69F4E5C8492BA0897166B5C54926--></AD_ELEMENT>
--- a/src-db/database/sourcedata/AD_FIELD.xml	Tue Apr 19 09:26:13 2016 +0200
+++ b/src-db/database/sourcedata/AD_FIELD.xml	Tue Apr 19 09:28:13 2016 +0200
@@ -237127,6 +237127,8 @@
 <!--7A007009BDAE4E8290430EEC81CB434C-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--7A007009BDAE4E8290430EEC81CB434C-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
 <!--7A007009BDAE4E8290430EEC81CB434C-->  <NAME><![CDATA[Linked To Product]]></NAME>
+<!--7A007009BDAE4E8290430EEC81CB434C-->  <DESCRIPTION><![CDATA[The service can be linked to a Product]]></DESCRIPTION>
+<!--7A007009BDAE4E8290430EEC81CB434C-->  <HELP><![CDATA[The service can be linked to a Product. If so, when adding the product to a Sales Order, the related service product could be added to the Sales Order also, following special rules to set the quantity to be added and the price of the service, both of them based on the product.]]></HELP>
 <!--7A007009BDAE4E8290430EEC81CB434C-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
 <!--7A007009BDAE4E8290430EEC81CB434C-->  <AD_TAB_ID><![CDATA[180]]></AD_TAB_ID>
 <!--7A007009BDAE4E8290430EEC81CB434C-->  <AD_COLUMN_ID><![CDATA[481DD00275E04E569EC34D3E634249A3]]></AD_COLUMN_ID>
--- a/src-db/database/sourcedata/AD_TAB.xml	Tue Apr 19 09:26:13 2016 +0200
+++ b/src-db/database/sourcedata/AD_TAB.xml	Tue Apr 19 09:28:13 2016 +0200
@@ -15878,6 +15878,8 @@
 <!--652123A308954FE8AA072DE90EE7C988-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--652123A308954FE8AA072DE90EE7C988-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
 <!--652123A308954FE8AA072DE90EE7C988-->  <NAME><![CDATA[Related Services]]></NAME>
+<!--652123A308954FE8AA072DE90EE7C988-->  <DESCRIPTION><![CDATA[In this table the 'Service' type product Order Lines related to an Order Line are displayed]]></DESCRIPTION>
+<!--652123A308954FE8AA072DE90EE7C988-->  <HELP><![CDATA[In this table the 'Service' type product Order Lines related to an Order Line are displayed]]></HELP>
 <!--652123A308954FE8AA072DE90EE7C988-->  <AD_TABLE_ID><![CDATA[15EAF61631484A11B6921AB05A342E8B]]></AD_TABLE_ID>
 <!--652123A308954FE8AA072DE90EE7C988-->  <AD_WINDOW_ID><![CDATA[143]]></AD_WINDOW_ID>
 <!--652123A308954FE8AA072DE90EE7C988-->  <SEQNO><![CDATA[29]]></SEQNO>
--- a/src-db/database/sourcedata/AD_TABLE.xml	Tue Apr 19 09:26:13 2016 +0200
+++ b/src-db/database/sourcedata/AD_TABLE.xml	Tue Apr 19 09:28:13 2016 +0200
@@ -9159,6 +9159,8 @@
 <!--15EAF61631484A11B6921AB05A342E8B-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
 <!--15EAF61631484A11B6921AB05A342E8B-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
 <!--15EAF61631484A11B6921AB05A342E8B-->  <NAME><![CDATA[C_Orderline_Productrelation]]></NAME>
+<!--15EAF61631484A11B6921AB05A342E8B-->  <DESCRIPTION><![CDATA[In this table the 'Service' type product Order Lines related to an Order Line are displayed]]></DESCRIPTION>
+<!--15EAF61631484A11B6921AB05A342E8B-->  <HELP><![CDATA[In this table the 'Service' type product Order Lines related to an Order Line are displayed]]></HELP>
 <!--15EAF61631484A11B6921AB05A342E8B-->  <TABLENAME><![CDATA[C_Orderline_Productrelation]]></TABLENAME>
 <!--15EAF61631484A11B6921AB05A342E8B-->  <ISVIEW><![CDATA[N]]></ISVIEW>
 <!--15EAF61631484A11B6921AB05A342E8B-->  <ACCESSLEVEL><![CDATA[1]]></ACCESSLEVEL>
--- a/src-test/src/org/openbravo/test/services/ServicesTest.java	Tue Apr 19 09:26:13 2016 +0200
+++ b/src-test/src/org/openbravo/test/services/ServicesTest.java	Tue Apr 19 09:28:13 2016 +0200
@@ -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-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -222,6 +222,7 @@
       OBDal.getInstance().remove(orls);
       OBDal.getInstance().flush();
     }
+    olsrScroller.close();
   }
 
   private void updateServiceRelationAmounts(OrderLine serviceOrderLine, BigDecimal amount,
@@ -242,6 +243,7 @@
       OBDal.getInstance().save(orls);
       OBDal.getInstance().flush();
     }
+    olsrScroller.close();
   }
 
   private OrderLine insertLine(Order sampleOrder, Order testOrder, String productId,
--- a/src/org/openbravo/common/actionhandler/ServiceOrderLineRelate.java	Tue Apr 19 09:26:13 2016 +0200
+++ b/src/org/openbravo/common/actionhandler/ServiceOrderLineRelate.java	Tue Apr 19 09:28:13 2016 +0200
@@ -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-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -57,6 +57,7 @@
     JSONObject jsonRequest = null;
     OBContext.setAdminMode(true);
     JSONObject errorMessage = new JSONObject();
+    ScrollableResults scroller = null;
     try {
       jsonRequest = new JSONObject(content);
       log.debug("{}", jsonRequest);
@@ -107,7 +108,7 @@
       rol.setNamedParameter("orderLineId", mainOrderLine.getId());
       rol.setMaxResult(1000);
 
-      final ScrollableResults scroller = rol.scroll(ScrollMode.FORWARD_ONLY);
+      scroller = rol.scroll(ScrollMode.FORWARD_ONLY);
       while (scroller.next()) {
         final OrderlineServiceRelation or = (OrderlineServiceRelation) scroller.get()[0];
         OBDal.getInstance().remove(or);
@@ -320,6 +321,9 @@
         log.error(e.getMessage(), e2);
       }
     } finally {
+      if (scroller != null) {
+        scroller.close();
+      }
       OBContext.restorePreviousMode();
     }
     return jsonRequest;
--- a/src/org/openbravo/erpCommon/info/ServiceProductPricePrecisionFilterExpression.java	Tue Apr 19 09:26:13 2016 +0200
+++ b/src/org/openbravo/erpCommon/info/ServiceProductPricePrecisionFilterExpression.java	Tue Apr 19 09:28:13 2016 +0200
@@ -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-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -41,7 +41,6 @@
           context.getString("inpcOrderlineId"));
       return orderLine.getSalesOrder().getCurrency().getPricePrecision().toString();
     } catch (JSONException e) {
-      // TODO Auto-generated catch block
       log.error("Error trying to get default value of " + strCurrentParam + " " + e.getMessage(), e);
       return null;
     }
--- a/src/org/openbravo/event/ServiceOrderLineEventHandler.java	Tue Apr 19 09:26:13 2016 +0200
+++ b/src/org/openbravo/event/ServiceOrderLineEventHandler.java	Tue Apr 19 09:28:13 2016 +0200
@@ -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-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -25,6 +25,7 @@
 import org.apache.log4j.Logger;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
+import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.model.Property;
@@ -91,49 +92,57 @@
         OBQuery<OrderlineServiceRelation> rol = relatedServices(thisLine);
         rol.setMaxResult(1000);
         final ScrollableResults scroller = rol.scroll(ScrollMode.FORWARD_ONLY);
-        while (scroller.next()) {
-          boolean changed = false;
-          final OrderlineServiceRelation or = (OrderlineServiceRelation) scroller.get()[0];
-          // Order Quantity has changed from positive to negative or backwards
-          if (currentOrderedQty.signum() != 0 && oldOrderedQty.signum() != 0
-              && currentOrderedQty.signum() != oldOrderedQty.signum()) {
-            // Create new order line
-            if (lineNo == null) {
-              lineNo = ServicePriceUtils.getNewLineNo(thisLine.getSalesOrder().getId());
+        try {
+          while (scroller.next()) {
+            boolean changed = false;
+            final OrderlineServiceRelation or = (OrderlineServiceRelation) scroller.get()[0];
+            // Order Quantity has changed from positive to negative or backwards
+            if (currentOrderedQty.signum() != 0 && oldOrderedQty.signum() != 0
+                && currentOrderedQty.signum() != oldOrderedQty.signum()) {
+              // Create new order line
+              if (lineNo == null) {
+                lineNo = ServicePriceUtils.getNewLineNo(thisLine.getSalesOrder().getId());
+              } else {
+                lineNo = lineNo + 10L;
+              }
+              OrderLine secondOrderline = (OrderLine) DalUtil.copy(or.getSalesOrderLine(), false);
+              secondOrderline.setLineNo(lineNo);
+              secondOrderline.setId(SequenceIdData.getUUID());
+              secondOrderline.setNewOBObject(true);
+              OBDal.getInstance().save(secondOrderline);
+
+              // Delete relation line
+              OBDal.getInstance().remove(or);
+
+              // Create new relation line and relate to the new orderline
+              OrderlineServiceRelation olsr = OBProvider.getInstance().get(
+                  OrderlineServiceRelation.class);
+              olsr.setClient(thisLine.getClient());
+              olsr.setOrganization(thisLine.getOrganization());
+              olsr.setOrderlineRelated(thisLine);
+              olsr.setSalesOrderLine(secondOrderline);
+              olsr.setAmount(currentAmount);
+              olsr.setQuantity(currentOrderedQty);
+              OBDal.getInstance().save(olsr);
             } else {
-              lineNo = lineNo + 10L;
+              if (or.getQuantity().compareTo(currentOrderedQty) != 0) {
+                or.setQuantity(currentOrderedQty);
+                changed = true;
+              }
+              if (currentAmount.compareTo(oldAmount) != 0) {
+                or.setAmount(currentAmount);
+                changed = true;
+              }
+              if (changed) {
+                OBDal.getInstance().save(or);
+              }
             }
-            OrderLine secondOrderline = (OrderLine) DalUtil.copy(or.getSalesOrderLine(), false);
-            secondOrderline.setLineNo(lineNo);
-            secondOrderline.setId(SequenceIdData.getUUID());
-            secondOrderline.setNewOBObject(true);
-            OBDal.getInstance().save(secondOrderline);
-
-            // Delete relation line
-            OBDal.getInstance().remove(or);
-
-            // Create new relation line and relate to the new orderline
-            OrderlineServiceRelation olsr = OBProvider.getInstance().get(
-                OrderlineServiceRelation.class);
-            olsr.setClient(thisLine.getClient());
-            olsr.setOrganization(thisLine.getOrganization());
-            olsr.setOrderlineRelated(thisLine);
-            olsr.setSalesOrderLine(secondOrderline);
-            olsr.setAmount(currentAmount);
-            olsr.setQuantity(currentOrderedQty);
-            OBDal.getInstance().save(olsr);
-          } else {
-            if (or.getQuantity().compareTo(currentOrderedQty) != 0) {
-              or.setQuantity(currentOrderedQty);
-              changed = true;
-            }
-            if (currentAmount.compareTo(oldAmount) != 0) {
-              or.setAmount(currentAmount);
-              changed = true;
-            }
-            if (changed) {
-              OBDal.getInstance().save(or);
-            }
+          }
+        } catch (Exception e) {
+          throw new OBException("Error in SalesOrderLineEventHandler" + e.getMessage());
+        } finally {
+          if (scroller != null) {
+            scroller.close();
           }
         }
       }
--- a/src/org/openbravo/materialmgmt/ServicePriceUtils.java	Tue Apr 19 09:26:13 2016 +0200
+++ b/src/org/openbravo/materialmgmt/ServicePriceUtils.java	Tue Apr 19 09:28:13 2016 +0200
@@ -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-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -68,86 +68,91 @@
       BigDecimal totalDiscounts, BigDecimal totalPrice, BigDecimal relatedQty,
       BigDecimal unitDiscountsAmt) {
     final Product serviceProduct = orderline.getProduct();
-    if (linesTotalAmount != null && linesTotalAmount.compareTo(BigDecimal.ZERO) == 0) {
-      return BigDecimal.ZERO;
-    }
-    BigDecimal serviceBasePrice = getProductPrice(orderline.getOrderDate(), orderline
-        .getSalesOrder().getPriceList(), serviceProduct);
-    if (serviceBasePrice == null) {
-      throw new OBException("@ServiceProductPriceListVersionNotFound@ "
-          + serviceProduct.getIdentifier() + ", @Date@: "
-          + OBDateUtils.formatDate(orderline.getOrderDate()));
-    }
-    BigDecimal serviceRelatedPrice = BigDecimal.ZERO;
-    boolean isPriceRuleBased = serviceProduct.isPricerulebased();
-    if (!isPriceRuleBased) {
-      return BigDecimal.ZERO;
-    } else {
-      ServicePriceRule servicePriceRule = getServicePriceRule(serviceProduct,
-          orderline.getOrderDate());
-      if (servicePriceRule == null) {
-        throw new OBException("@ServicePriceRuleVersionNotFound@ "
-            + orderline.getProduct().getIdentifier() + ", @Date@: "
+    OBContext.setAdminMode(true);
+    try {
+      if (linesTotalAmount != null && linesTotalAmount.compareTo(BigDecimal.ZERO) == 0) {
+        return BigDecimal.ZERO;
+      }
+      BigDecimal serviceBasePrice = getProductPrice(orderline.getOrderDate(), orderline
+          .getSalesOrder().getPriceList(), serviceProduct);
+      if (serviceBasePrice == null) {
+        throw new OBException("@ServiceProductPriceListVersionNotFound@ "
+            + serviceProduct.getIdentifier() + ", @Date@: "
             + OBDateUtils.formatDate(orderline.getOrderDate()));
       }
-      BigDecimal relatedAmount = BigDecimal.ZERO;
-      BigDecimal findRangeAmount = BigDecimal.ZERO;
-      if (linesTotalAmount != null) {
-        relatedAmount = linesTotalAmount;
+      BigDecimal serviceRelatedPrice = BigDecimal.ZERO;
+      boolean isPriceRuleBased = serviceProduct.isPricerulebased();
+      if (!isPriceRuleBased) {
+        return BigDecimal.ZERO;
       } else {
-        HashMap<String, BigDecimal> relatedAmountAndQuatity = getRelatedAmountAndQty(orderline);
-        relatedAmount = relatedAmountAndQuatity.get("amount");
-        // TODO: APPLY quantities
-        relatedQty = relatedAmountAndQuatity.get("quantity");
-      }
+        ServicePriceRule servicePriceRule = getServicePriceRule(serviceProduct,
+            orderline.getOrderDate());
+        if (servicePriceRule == null) {
+          throw new OBException("@ServicePriceRuleVersionNotFound@ "
+              + orderline.getProduct().getIdentifier() + ", @Date@: "
+              + OBDateUtils.formatDate(orderline.getOrderDate()));
+        }
+        BigDecimal relatedAmount = BigDecimal.ZERO;
+        BigDecimal findRangeAmount = BigDecimal.ZERO;
+        if (linesTotalAmount != null) {
+          relatedAmount = linesTotalAmount;
+        } else {
+          HashMap<String, BigDecimal> relatedAmountAndQuatity = getRelatedAmountAndQty(orderline);
+          relatedAmount = relatedAmountAndQuatity.get("amount");
+          // TODO: APPLY quantities
+          relatedQty = relatedAmountAndQuatity.get("quantity");
+        }
 
-      if (PERCENTAGE.equals(servicePriceRule.getRuletype())) {
-        if (!servicePriceRule.isAfterdiscounts() && totalDiscounts != null
-            && unitDiscountsAmt != null) {
-          relatedAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? relatedAmount
-              .add(totalDiscounts) : relatedAmount.add(unitDiscountsAmt);
-        }
-        serviceRelatedPrice = relatedAmount.multiply(new BigDecimal(servicePriceRule
-            .getPercentage()).divide(new BigDecimal("100.00")));
-      } else {
-        if (!servicePriceRule.isAfterdiscounts() && totalDiscounts != null
-            && unitDiscountsAmt != null) {
-          findRangeAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
-              .add(totalDiscounts) : totalPrice.add(unitDiscountsAmt);
+        if (PERCENTAGE.equals(servicePriceRule.getRuletype())) {
+          if (!servicePriceRule.isAfterdiscounts() && totalDiscounts != null
+              && unitDiscountsAmt != null) {
+            relatedAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? relatedAmount
+                .add(totalDiscounts) : relatedAmount.add(unitDiscountsAmt);
+          }
+          serviceRelatedPrice = relatedAmount.multiply(new BigDecimal(servicePriceRule
+              .getPercentage()).divide(new BigDecimal("100.00")));
         } else {
-          findRangeAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
-              : totalPrice;
-        }
-        ServicePriceRuleRange range = getRange(servicePriceRule, findRangeAmount);
-        if (range == null) {
-          throw new OBException("@ServicePriceRuleRangeNotFound@. @ServicePriceRule@: "
-              + servicePriceRule.getIdentifier() + ", @AmountUpTo@: " + linesTotalAmount);
-        }
-        if (PERCENTAGE.equals(range.getRuleType())) {
-          if (!range.isAfterDiscounts() && totalDiscounts != null && unitDiscountsAmt != null) {
-            relatedAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
+          if (!servicePriceRule.isAfterdiscounts() && totalDiscounts != null
+              && unitDiscountsAmt != null) {
+            findRangeAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
                 .add(totalDiscounts) : totalPrice.add(unitDiscountsAmt);
           } else {
-            relatedAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
+            findRangeAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
                 : totalPrice;
           }
-          serviceRelatedPrice = relatedAmount.multiply(new BigDecimal(range.getPercentage())
-              .divide(new BigDecimal("100.00")));
-        } else {
-          serviceRelatedPrice = getProductPrice(orderline.getOrderDate(), range.getPriceList(),
-              serviceProduct);
-          if (serviceRelatedPrice == null) {
-            throw new OBException("@ServiceProductPriceListVersionNotFound@ "
-                + serviceProduct.getIdentifier() + ", @Date@: "
-                + OBDateUtils.formatDate(orderline.getOrderDate()));
+          ServicePriceRuleRange range = getRange(servicePriceRule, findRangeAmount);
+          if (range == null) {
+            throw new OBException("@ServicePriceRuleRangeNotFound@. @ServicePriceRule@: "
+                + servicePriceRule.getIdentifier() + ", @AmountUpTo@: " + linesTotalAmount);
+          }
+          if (PERCENTAGE.equals(range.getRuleType())) {
+            if (!range.isAfterDiscounts() && totalDiscounts != null && unitDiscountsAmt != null) {
+              relatedAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
+                  .add(totalDiscounts) : totalPrice.add(unitDiscountsAmt);
+            } else {
+              relatedAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
+                  : totalPrice;
+            }
+            serviceRelatedPrice = relatedAmount.multiply(new BigDecimal(range.getPercentage())
+                .divide(new BigDecimal("100.00")));
+          } else {
+            serviceRelatedPrice = getProductPrice(orderline.getOrderDate(), range.getPriceList(),
+                serviceProduct);
+            if (serviceRelatedPrice == null) {
+              throw new OBException("@ServiceProductPriceListVersionNotFound@ "
+                  + serviceProduct.getIdentifier() + ", @Date@: "
+                  + OBDateUtils.formatDate(orderline.getOrderDate()));
+            }
+          }
+          if (!UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule())) {
+            serviceRelatedPrice = serviceRelatedPrice.multiply(relatedQty);
           }
         }
-        if (!UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule())) {
-          serviceRelatedPrice = serviceRelatedPrice.multiply(relatedQty);
-        }
+        return serviceRelatedPrice.setScale(orderline.getCurrency().getPricePrecision().intValue(),
+            RoundingMode.HALF_UP);
       }
-      return serviceRelatedPrice.setScale(orderline.getCurrency().getPricePrecision().intValue(),
-          RoundingMode.HALF_UP);
+    } finally {
+      OBContext.restorePreviousMode();
     }
   }
 
@@ -162,40 +167,56 @@
    */
   private static ServicePriceRuleRange getRange(ServicePriceRule servicePriceRule,
       BigDecimal relatedAmount) {
-    StringBuffer where = new StringBuffer();
-    where.append("  as sprr");
-    where.append(" where " + ServicePriceRuleRange.PROPERTY_SERVICEPRICERULE
-        + ".id = :servicePriceRuleId");
-    where.append(" and (" + ServicePriceRuleRange.PROPERTY_AMOUNTUPTO + " >= :amount or "
-        + ServicePriceRuleRange.PROPERTY_AMOUNTUPTO + " is null)");
-    where.append(" order by " + ServicePriceRuleRange.PROPERTY_AMOUNTUPTO + ", "
-        + ServicePriceRuleVersion.PROPERTY_CREATIONDATE + " desc");
-    OBQuery<ServicePriceRuleRange> sprrQry = OBDal.getInstance().createQuery(
-        ServicePriceRuleRange.class, where.toString());
-    sprrQry.setNamedParameter("servicePriceRuleId", servicePriceRule.getId());
-    sprrQry.setNamedParameter("amount", relatedAmount);
-    sprrQry.setMaxResult(1);
-    return sprrQry.uniqueResult();
+    OBContext.setAdminMode(true);
+    try {
+      StringBuffer where = new StringBuffer();
+      where.append("  as sprr");
+      where.append(" where " + ServicePriceRuleRange.PROPERTY_SERVICEPRICERULE
+          + ".id = :servicePriceRuleId");
+      where.append(" and (" + ServicePriceRuleRange.PROPERTY_AMOUNTUPTO + " >= :amount or "
+          + ServicePriceRuleRange.PROPERTY_AMOUNTUPTO + " is null)");
+      where.append(" order by " + ServicePriceRuleRange.PROPERTY_AMOUNTUPTO + ", "
+          + ServicePriceRuleVersion.PROPERTY_CREATIONDATE + " desc");
+      OBQuery<ServicePriceRuleRange> sprrQry = OBDal.getInstance().createQuery(
+          ServicePriceRuleRange.class, where.toString());
+      sprrQry.setNamedParameter("servicePriceRuleId", servicePriceRule.getId());
+      sprrQry.setNamedParameter("amount", relatedAmount);
+      sprrQry.setMaxResult(1);
+      return sprrQry.uniqueResult();
+    } finally {
+      OBContext.restorePreviousMode();
+    }
   }
 
+  /**
+   * Method that returns the total amount, quantity and price of all lines related to the given line
+   * 
+   * @param orderLine
+   * @return
+   */
   public static HashMap<String, BigDecimal> getRelatedAmountAndQty(OrderLine orderLine) {
-    StringBuffer strQuery = new StringBuffer();
-    strQuery
-        .append("select coalesce(sum(e.amount),0), coalesce(sum(e.quantity),0), coalesce(sum(case when pl.priceIncludesTax = false then ol.unitPrice else ol.grossUnitPrice end), 0)");
-    strQuery.append(" from OrderlineServiceRelation as e");
-    strQuery.append(" join e.orderlineRelated as ol");
-    strQuery.append(" join ol.salesOrder as o");
-    strQuery.append(" join o.priceList as pl");
-    strQuery.append(" where e.salesOrderLine.id = :orderLineId");
-    Query query = OBDal.getInstance().getSession().createQuery(strQuery.toString());
-    query.setParameter("orderLineId", orderLine.getId());
-    query.setMaxResults(1);
-    HashMap<String, BigDecimal> result = new HashMap<String, BigDecimal>();
-    Object[] values = (Object[]) query.uniqueResult();
-    result.put("amount", (BigDecimal) values[0]);
-    result.put("quantity", (BigDecimal) values[1]);
-    result.put("price", (BigDecimal) values[2]);
-    return result;
+    OBContext.setAdminMode(true);
+    try {
+      StringBuffer strQuery = new StringBuffer();
+      strQuery
+          .append("select coalesce(sum(e.amount),0), coalesce(sum(e.quantity),0), coalesce(sum(case when pl.priceIncludesTax = false then ol.unitPrice else ol.grossUnitPrice end), 0)");
+      strQuery.append(" from OrderlineServiceRelation as e");
+      strQuery.append(" join e.orderlineRelated as ol");
+      strQuery.append(" join ol.salesOrder as o");
+      strQuery.append(" join o.priceList as pl");
+      strQuery.append(" where e.salesOrderLine.id = :orderLineId");
+      Query query = OBDal.getInstance().getSession().createQuery(strQuery.toString());
+      query.setParameter("orderLineId", orderLine.getId());
+      query.setMaxResults(1);
+      HashMap<String, BigDecimal> result = new HashMap<String, BigDecimal>();
+      Object[] values = (Object[]) query.uniqueResult();
+      result.put("amount", (BigDecimal) values[0]);
+      result.put("quantity", (BigDecimal) values[1]);
+      result.put("price", (BigDecimal) values[2]);
+      return result;
+    } finally {
+      OBContext.restorePreviousMode();
+    }
   }
 
   /**
@@ -211,28 +232,32 @@
    */
   public static BigDecimal getProductPrice(Date date, PriceList priceList, Product product)
       throws OBException {
+    OBContext.setAdminMode(true);
+    try {
+      StringBuffer where = new StringBuffer();
+      where.append(" select pp." + ProductPrice.PROPERTY_LISTPRICE + " as listPrice");
+      where.append(" from " + ProductPrice.ENTITY_NAME + " as pp");
+      where.append("   join pp." + ProductPrice.PROPERTY_PRICELISTVERSION + " as plv");
+      where.append("   join plv." + PriceListVersion.PROPERTY_PRICELIST + " as pl");
+      where.append(" where pp." + ProductPrice.PROPERTY_PRODUCT + ".id = :productId");
+      where.append("   and plv." + PriceListVersion.PROPERTY_VALIDFROMDATE + " <= :date");
+      where.append("   and pl.id = :pricelistId");
+      where.append("   and pl." + PriceList.PROPERTY_ACTIVE + " = true");
+      where.append("   and pp." + ProductPrice.PROPERTY_ACTIVE + " = true");
+      where.append("   and plv." + PriceListVersion.PROPERTY_ACTIVE + " = true");
+      where.append(" order by pl." + PriceList.PROPERTY_DEFAULT + " desc, plv."
+          + PriceListVersion.PROPERTY_VALIDFROMDATE + " desc");
 
-    StringBuffer where = new StringBuffer();
-    where.append(" select pp." + ProductPrice.PROPERTY_LISTPRICE + " as listPrice");
-    where.append(" from " + ProductPrice.ENTITY_NAME + " as pp");
-    where.append("   join pp." + ProductPrice.PROPERTY_PRICELISTVERSION + " as plv");
-    where.append("   join plv." + PriceListVersion.PROPERTY_PRICELIST + " as pl");
-    where.append(" where pp." + ProductPrice.PROPERTY_PRODUCT + ".id = :productId");
-    where.append("   and plv." + PriceListVersion.PROPERTY_VALIDFROMDATE + " <= :date");
-    where.append("   and pl.id = :pricelistId");
-    where.append("   and pl." + PriceList.PROPERTY_ACTIVE + " = true");
-    where.append("   and pp." + ProductPrice.PROPERTY_ACTIVE + " = true");
-    where.append("   and plv." + PriceListVersion.PROPERTY_ACTIVE + " = true");
-    where.append(" order by pl." + PriceList.PROPERTY_DEFAULT + " desc, plv."
-        + PriceListVersion.PROPERTY_VALIDFROMDATE + " desc");
+      Query ppQry = OBDal.getInstance().getSession().createQuery(where.toString());
+      ppQry.setParameter("productId", product.getId());
+      ppQry.setParameter("date", date);
+      ppQry.setParameter("pricelistId", priceList.getId());
 
-    Query ppQry = OBDal.getInstance().getSession().createQuery(where.toString());
-    ppQry.setParameter("productId", product.getId());
-    ppQry.setParameter("date", date);
-    ppQry.setParameter("pricelistId", priceList.getId());
-
-    ppQry.setMaxResults(1);
-    return (BigDecimal) ppQry.uniqueResult();
+      ppQry.setMaxResults(1);
+      return (BigDecimal) ppQry.uniqueResult();
+    } finally {
+      OBContext.restorePreviousMode();
+    }
   }
 
   /**
@@ -246,21 +271,26 @@
    * @return
    */
   public static ServicePriceRule getServicePriceRule(Product serviceProduct, Date orderDate) {
-
-    StringBuffer where = new StringBuffer();
-    where.append(" select " + ServicePriceRuleVersion.PROPERTY_SERVICEPRICERULE);
-    where.append(" from " + ServicePriceRuleVersion.ENTITY_NAME + " as sprv");
-    where.append(" where sprv." + ServicePriceRuleVersion.PROPERTY_PRODUCT
-        + ".id = :serviceProductId");
-    where.append(" and sprv." + ServicePriceRuleVersion.PROPERTY_VALIDFROMDATE + " <= :orderDate");
-    where.append("   and sprv." + ServicePriceRuleVersion.PROPERTY_ACTIVE + " = true");
-    where.append(" order by sprv." + ServicePriceRuleVersion.PROPERTY_VALIDFROMDATE
-        + " desc, sprv." + ServicePriceRuleVersion.PROPERTY_CREATIONDATE + " desc");
-    Query sprvQry = OBDal.getInstance().getSession().createQuery(where.toString());
-    sprvQry.setParameter("serviceProductId", serviceProduct.getId());
-    sprvQry.setParameter("orderDate", orderDate);
-    sprvQry.setMaxResults(1);
-    return (ServicePriceRule) sprvQry.uniqueResult();
+    OBContext.setAdminMode(true);
+    try {
+      StringBuffer where = new StringBuffer();
+      where.append(" select " + ServicePriceRuleVersion.PROPERTY_SERVICEPRICERULE);
+      where.append(" from " + ServicePriceRuleVersion.ENTITY_NAME + " as sprv");
+      where.append(" where sprv." + ServicePriceRuleVersion.PROPERTY_PRODUCT
+          + ".id = :serviceProductId");
+      where
+          .append(" and sprv." + ServicePriceRuleVersion.PROPERTY_VALIDFROMDATE + " <= :orderDate");
+      where.append("   and sprv." + ServicePriceRuleVersion.PROPERTY_ACTIVE + " = true");
+      where.append(" order by sprv." + ServicePriceRuleVersion.PROPERTY_VALIDFROMDATE
+          + " desc, sprv." + ServicePriceRuleVersion.PROPERTY_CREATIONDATE + " desc");
+      Query sprvQry = OBDal.getInstance().getSession().createQuery(where.toString());
+      sprvQry.setParameter("serviceProductId", serviceProduct.getId());
+      sprvQry.setParameter("orderDate", orderDate);
+      sprvQry.setMaxResults(1);
+      return (ServicePriceRule) sprvQry.uniqueResult();
+    } finally {
+      OBContext.restorePreviousMode();
+    }
   }
 
   /**
@@ -270,17 +300,23 @@
    *          Order
    */
   public static Long getNewLineNo(String orderId) {
-    StringBuffer where = new StringBuffer();
-    where.append(" as ol");
-    where.append(" where ol." + OrderLine.PROPERTY_SALESORDER + ".id = :orderId");
-    where.append(" order by ol." + OrderLine.PROPERTY_LINENO + " desc");
-    OBQuery<OrderLine> olQry = OBDal.getInstance().createQuery(OrderLine.class, where.toString());
-    olQry.setNamedParameter("orderId", orderId);
-    if (olQry.count() > 0) {
-      OrderLine ol = olQry.list().get(0);
-      return ol.getLineNo() + 10L;
+    OBContext.setAdminMode(true);
+    try {
+      StringBuffer where = new StringBuffer();
+      where.append(" as ol");
+      where.append(" where ol." + OrderLine.PROPERTY_SALESORDER + ".id = :orderId");
+      where.append(" order by ol." + OrderLine.PROPERTY_LINENO + " desc");
+      OBQuery<OrderLine> olQry = OBDal.getInstance().createQuery(OrderLine.class, where.toString());
+      olQry.setNamedParameter("orderId", orderId);
+      olQry.setMaxResult(1);
+      if (olQry.count() > 0) {
+        OrderLine ol = olQry.list().get(0);
+        return ol.getLineNo() + 10L;
+      }
+      return 10L;
+    } finally {
+      OBContext.restorePreviousMode();
     }
-    return 10L;
   }
 
   /**
@@ -297,47 +333,55 @@
   public static JSONObject deferredSaleAllowed(OrderLine orderline, OrderLine orderLineToRelate) {
     JSONObject result = null;
     final Product serviceProduct = orderline.getProduct();
-    if (orderLineToRelate != null
-        && !orderline.getSalesOrder().getId().equals(orderLineToRelate.getSalesOrder().getId())) {
-      if (!serviceProduct.isAllowDeferredSell()) {
-        throw new OBException("@DeferredSaleNotAllowed@: " + serviceProduct.getIdentifier());
-      } else {
-        try {
-          Date deferredSaleDate = OBDateUtils.getDate(OBDateUtils.formatDate(orderLineToRelate
-              .getSalesOrder().getOrderDate()));
-          Date orderDate = OBDateUtils.getDate(OBDateUtils.formatDate(orderline.getSalesOrder()
-              .getOrderDate()));
-          if (orderline.getProduct().getDeferredSellMaxDays() != null) {
-            deferredSaleDate = DateUtils.addDays(deferredSaleDate, serviceProduct
-                .getDeferredSellMaxDays().intValue());
-            if (orderDate.after(deferredSaleDate)) {
-              String message = OBMessageUtils.parseTranslation(new DalConnectionProvider(false),
-                  RequestContext.get().getVariablesSecureApp(), OBContext.getOBContext()
-                      .getLanguage().getLanguage(),
-                  "@DeferredSaleExpired@: (" + OBDateUtils.formatDate(deferredSaleDate)
-                      + ") @ForService@ '" + serviceProduct.getIdentifier()
-                      + "' @relatingTo@ @line@ " + orderLineToRelate.getLineNo()
-                      + " @of@ @SalesOrderDocumentno@ "
-                      + orderLineToRelate.getSalesOrder().getDocumentNo());
-              result = new JSONObject();
-              result.put("severity", "warning");
-              result.put("title", "Warning");
-              result.put("text", message);
+    OBContext.setAdminMode(true);
+    try {
+      if (orderLineToRelate != null
+          && !orderline.getSalesOrder().getId().equals(orderLineToRelate.getSalesOrder().getId())) {
+        if (!serviceProduct.isAllowDeferredSell()) {
+          throw new OBException("@DeferredSaleNotAllowed@: " + serviceProduct.getIdentifier());
+        } else {
+          try {
+            Date deferredSaleDate = OBDateUtils.getDate(OBDateUtils.formatDate(orderLineToRelate
+                .getSalesOrder().getOrderDate()));
+            Date orderDate = OBDateUtils.getDate(OBDateUtils.formatDate(orderline.getSalesOrder()
+                .getOrderDate()));
+            if (orderline.getProduct().getDeferredSellMaxDays() != null) {
+              deferredSaleDate = DateUtils.addDays(deferredSaleDate, serviceProduct
+                  .getDeferredSellMaxDays().intValue());
+              if (orderDate.after(deferredSaleDate)) {
+                String message = OBMessageUtils.parseTranslation(new DalConnectionProvider(false),
+                    RequestContext.get().getVariablesSecureApp(), OBContext.getOBContext()
+                        .getLanguage().getLanguage(),
+                    "@DeferredSaleExpired@: (" + OBDateUtils.formatDate(deferredSaleDate)
+                        + ") @ForService@ '" + serviceProduct.getIdentifier()
+                        + "' @relatingTo@ @line@ " + orderLineToRelate.getLineNo()
+                        + " @of@ @SalesOrderDocumentno@ "
+                        + orderLineToRelate.getSalesOrder().getDocumentNo());
+                result = new JSONObject();
+                result.put("severity", "warning");
+                result.put("title", "Warning");
+                result.put("text", message);
+              }
             }
+          } catch (ParseException e) {
+            // TODO Auto-generated catch block
+            log.error(e.getMessage(), e);
+          } catch (JSONException e) {
+            // TODO Auto-generated catch block
+            log.error(e.getMessage(), e);
           }
-        } catch (ParseException e) {
-          // TODO Auto-generated catch block
-          log.error(e.getMessage(), e);
-        } catch (JSONException e) {
-          // TODO Auto-generated catch block
-          log.error(e.getMessage(), e);
         }
       }
+      return result;
+    } finally {
+      OBContext.restorePreviousMode();
     }
-    return result;
   }
 
   /**
+   * Method that returns a warning message if a service of a Return From Customer is not Returnable
+   * of the return period is expired.
+   * 
    * @param shipmentLine
    * @param serviceProduct
    * @param rfcOrderDate
@@ -346,47 +390,52 @@
   public static JSONObject serviceReturnAllowedRFC(ShipmentInOutLine shipmentLine,
       Product serviceProduct, Date rfcOrderDate) {
     JSONObject result = null;
-    if (SERVICEPRODUCT.equals(serviceProduct.getProductType())) {
-      if (!serviceProduct.isReturnable()) {
-        throw new OBException("@Service@ '" + serviceProduct.getIdentifier()
-            + "' @ServiceIsNotReturnable@");
-      } else {
-        try {
-          final Date orderDate = shipmentLine != null && shipmentLine.getSalesOrderLine() != null ? OBDateUtils
-              .getDate(OBDateUtils.formatDate(shipmentLine.getSalesOrderLine().getOrderDate()))
-              : null;
-          Date returnDate = null;
-          String message = null;
-          if (orderDate != null && serviceProduct.getOverdueReturnDays() != null) {
-            returnDate = DateUtils.addDays(orderDate, serviceProduct.getOverdueReturnDays()
-                .intValue());
+    OBContext.setAdminMode(true);
+    try {
+      if (SERVICEPRODUCT.equals(serviceProduct.getProductType())) {
+        if (!serviceProduct.isReturnable()) {
+          throw new OBException("@Service@ '" + serviceProduct.getIdentifier()
+              + "' @ServiceIsNotReturnable@");
+        } else {
+          try {
+            final Date orderDate = shipmentLine != null && shipmentLine.getSalesOrderLine() != null ? OBDateUtils
+                .getDate(OBDateUtils.formatDate(shipmentLine.getSalesOrderLine().getOrderDate()))
+                : null;
+            Date returnDate = null;
+            String message = null;
+            if (orderDate != null && serviceProduct.getOverdueReturnDays() != null) {
+              returnDate = DateUtils.addDays(orderDate, serviceProduct.getOverdueReturnDays()
+                  .intValue());
+            }
+            if (serviceProduct.getOverdueReturnDays() != null && returnDate != null
+                && rfcOrderDate.after(returnDate)) {
+              message = "@Service@ '" + serviceProduct.getIdentifier()
+                  + "' @ServiceReturnExpired@: " + OBDateUtils.formatDate(returnDate);
+            }
+            if (serviceProduct.getOverdueReturnDays() != null && returnDate == null) {
+              message = "@Service@ '" + serviceProduct.getIdentifier()
+                  + "' @ServiceMissingReturnDate@";
+            }
+            if (message != null) {
+              message = OBMessageUtils.parseTranslation(new DalConnectionProvider(false),
+                  RequestContext.get().getVariablesSecureApp(), OBContext.getOBContext()
+                      .getLanguage().getLanguage(), message);
+              result = new JSONObject();
+              result.put("severity", "warning");
+              result.put("title", "Warning");
+              result.put("text", message);
+            }
+          } catch (ParseException e) {
+            log.error(e.getMessage(), e);
+          } catch (JSONException e) {
+            log.error(e.getMessage(), e);
           }
-          if (serviceProduct.getOverdueReturnDays() != null && returnDate != null
-              && rfcOrderDate.after(returnDate)) {
-            message = "@Service@ '" + serviceProduct.getIdentifier() + "' @ServiceReturnExpired@: "
-                + OBDateUtils.formatDate(returnDate);
-          }
-          if (serviceProduct.getOverdueReturnDays() != null && returnDate == null) {
-            message = "@Service@ '" + serviceProduct.getIdentifier()
-                + "' @ServiceMissingReturnDate@";
-          }
-          if (message != null) {
-            message = OBMessageUtils.parseTranslation(new DalConnectionProvider(false),
-                RequestContext.get().getVariablesSecureApp(), OBContext.getOBContext()
-                    .getLanguage().getLanguage(), message);
-            result = new JSONObject();
-            result.put("severity", "warning");
-            result.put("title", "Warning");
-            result.put("text", message);
-          }
-        } catch (ParseException e) {
-          log.error(e.getMessage(), e);
-        } catch (JSONException e) {
-          log.error(e.getMessage(), e);
         }
       }
+      return result;
+    } finally {
+      OBContext.restorePreviousMode();
     }
-    return result;
   }
 
   /**
@@ -401,64 +450,69 @@
       BigDecimal linesTotalAmount, BigDecimal totalPrice, BigDecimal totalDiscounts,
       BigDecimal unitDiscountsAmt) {
 
-    final Product serviceProduct = orderline.getProduct();
-    if (linesTotalAmount != null && linesTotalAmount.compareTo(BigDecimal.ZERO) == 0) {
-      return true;
-    }
-    BigDecimal serviceBasePrice = getProductPrice(orderline.getOrderDate(), orderline
-        .getSalesOrder().getPriceList(), serviceProduct);
-    if (serviceBasePrice == null) {
-      throw new OBException("@ServiceProductPriceListVersionNotFound@ "
-          + serviceProduct.getIdentifier() + ", @Date@: "
-          + OBDateUtils.formatDate(orderline.getOrderDate()));
-    }
-    BigDecimal serviceRelatedPrice = BigDecimal.ZERO;
-    boolean isPriceRuleBased = serviceProduct.isPricerulebased();
-    if (!isPriceRuleBased) {
-      return false;
-    } else {
-      ServicePriceRule servicePriceRule = getServicePriceRule(serviceProduct,
-          orderline.getOrderDate());
-      if (servicePriceRule == null) {
-        throw new OBException("@ServicePriceRuleVersionNotFound@ "
-            + orderline.getProduct().getIdentifier() + ", @Date@: "
+    OBContext.setAdminMode(true);
+    try {
+      final Product serviceProduct = orderline.getProduct();
+      if (linesTotalAmount != null && linesTotalAmount.compareTo(BigDecimal.ZERO) == 0) {
+        return true;
+      }
+      BigDecimal serviceBasePrice = getProductPrice(orderline.getOrderDate(), orderline
+          .getSalesOrder().getPriceList(), serviceProduct);
+      if (serviceBasePrice == null) {
+        throw new OBException("@ServiceProductPriceListVersionNotFound@ "
+            + serviceProduct.getIdentifier() + ", @Date@: "
             + OBDateUtils.formatDate(orderline.getOrderDate()));
       }
-      BigDecimal findRangeAmount = BigDecimal.ZERO;
+      BigDecimal serviceRelatedPrice = BigDecimal.ZERO;
+      boolean isPriceRuleBased = serviceProduct.isPricerulebased();
+      if (!isPriceRuleBased) {
+        return false;
+      } else {
+        ServicePriceRule servicePriceRule = getServicePriceRule(serviceProduct,
+            orderline.getOrderDate());
+        if (servicePriceRule == null) {
+          throw new OBException("@ServicePriceRuleVersionNotFound@ "
+              + orderline.getProduct().getIdentifier() + ", @Date@: "
+              + OBDateUtils.formatDate(orderline.getOrderDate()));
+        }
+        BigDecimal findRangeAmount = BigDecimal.ZERO;
 
-      if (PERCENTAGE.equals(servicePriceRule.getRuletype())) {
-        if (servicePriceRule.isAfterdiscounts()) {
-          return true;
-        }
-      } else {
-        if (!servicePriceRule.isAfterdiscounts() && totalDiscounts != null
-            && unitDiscountsAmt != null) {
-          findRangeAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
-              .add(totalDiscounts) : totalPrice.add(unitDiscountsAmt);
-        } else {
-          findRangeAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
-              : totalPrice;
-        }
-        ServicePriceRuleRange range = getRange(servicePriceRule, findRangeAmount);
-        if (range == null) {
-          throw new OBException("@ServicePriceRuleRangeNotFound@. @ServicePriceRule@: "
-              + servicePriceRule.getIdentifier() + ", @AmountUpTo@: " + linesTotalAmount);
-        }
-        if (PERCENTAGE.equals(range.getRuleType())) {
+        if (PERCENTAGE.equals(servicePriceRule.getRuletype())) {
           if (servicePriceRule.isAfterdiscounts()) {
             return true;
           }
         } else {
-          serviceRelatedPrice = getProductPrice(orderline.getOrderDate(), range.getPriceList(),
-              serviceProduct);
-          if (serviceRelatedPrice == null) {
-            throw new OBException("@ServiceProductPriceListVersionNotFound@ "
-                + serviceProduct.getIdentifier() + ", @Date@: "
-                + OBDateUtils.formatDate(orderline.getOrderDate()));
+          if (!servicePriceRule.isAfterdiscounts() && totalDiscounts != null
+              && unitDiscountsAmt != null) {
+            findRangeAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
+                .add(totalDiscounts) : totalPrice.add(unitDiscountsAmt);
+          } else {
+            findRangeAmount = UNIQUE_QUANTITY.equals(serviceProduct.getQuantityRule()) ? linesTotalAmount
+                : totalPrice;
+          }
+          ServicePriceRuleRange range = getRange(servicePriceRule, findRangeAmount);
+          if (range == null) {
+            throw new OBException("@ServicePriceRuleRangeNotFound@. @ServicePriceRule@: "
+                + servicePriceRule.getIdentifier() + ", @AmountUpTo@: " + linesTotalAmount);
+          }
+          if (PERCENTAGE.equals(range.getRuleType())) {
+            if (servicePriceRule.isAfterdiscounts()) {
+              return true;
+            }
+          } else {
+            serviceRelatedPrice = getProductPrice(orderline.getOrderDate(), range.getPriceList(),
+                serviceProduct);
+            if (serviceRelatedPrice == null) {
+              throw new OBException("@ServiceProductPriceListVersionNotFound@ "
+                  + serviceProduct.getIdentifier() + ", @Date@: "
+                  + OBDateUtils.formatDate(orderline.getOrderDate()));
+            }
           }
         }
+        return false;
       }
-      return false;
+    } finally {
+      OBContext.restorePreviousMode();
     }
   }
 }