# HG changeset patch
# User Shankar Balachandran <shankar.balachandran@openbravo.com>
# Date 1354251982 -19800
# Node ID 001ddac72ca26209ec0a3281166984fe14ce53e1
# Parent  6bae9e346d78cce09294e5b3cf050badb7f37a52
Fixes Issue 0022292: Order PK column in DESC when other columns are DESC

In Grid, ordering primary key column in descending when all other order by columns are in descending.
This is done to use the index for sorting.

diff --git a/modules/org.openbravo.service.json/src/org/openbravo/service/json/AdvancedQueryBuilder.java b/modules/org.openbravo.service.json/src/org/openbravo/service/json/AdvancedQueryBuilder.java
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/AdvancedQueryBuilder.java
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/AdvancedQueryBuilder.java
@@ -28,6 +28,7 @@
 import java.util.Map;
 import java.util.Set;
 
+import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
@@ -1085,7 +1086,17 @@
     }
     final StringBuilder sb = new StringBuilder();
     boolean firstElement = true;
+    int columnsInDescending = StringUtils.countMatches(orderBy, "-");
+    int totalColumnSeperators = StringUtils.countMatches(orderBy, ",");
+    boolean orderPrimaryKeyInDesc = false;
+    if (columnsInDescending == totalColumnSeperators) {
+      orderPrimaryKeyInDesc = true;
+    }
+
     for (String localOrderBy : orderBy.split(",")) {
+      if (orderPrimaryKeyInDesc && localOrderBy.equals("id")) {
+        localOrderBy = "-".concat(localOrderBy);
+      }
       if (!firstElement) {
         sb.append(",");
       }
