From dda483ebdc4d59b9803766dbd8eb60c6072d27d8 Mon Sep 17 00:00:00 2001
From: Kevin Thorne <kevin@enhancesoft.com>
Date: Wed, 17 Jul 2019 10:44:53 -0500
Subject: [PATCH] issue: Advanced Search Default Sorting

This addresses an issue where conducting an Advanced Search will show the
results in ASC order (from oldest to most recent) by default. If there are
no keywords the search is supposed to show the results in DESC order (from
most recent to oldest) by default. If there are keywords the search is
supposed to show the results sorted by `relevance`. This adds additional
`select` options to the search criteria for keyword searches so that we can
use `relevance` in the outer query. This also adds an `order_by` to the
tickets to order them by the `relevance` in `DESC` order. In addition this
adds a new `order_by` to sort the results by `created` in DESC if there are
no keywords.
---
 include/class.queue.php                        | 3 +++
 include/staff/templates/queue-tickets.tmpl.php | 2 ++
 2 files changed, 5 insertions(+)

diff --git a/include/class.queue.php b/include/class.queue.php
index 8a39e0f55..ed07a8f7c 100644
--- a/include/class.queue.php
+++ b/include/class.queue.php
@@ -969,6 +969,9 @@ class CustomQueue extends VerySimpleModel {
                 if (list(,$field) = $searchable[$name])
                     if ($q = $field->getSearchQ($method, $value, $name))
                         $qs = $qs->filter($q);
+
+                // Add default sorting to non-keyword searches
+                $qs->order_by(array('-created'));
             }
         }
 
diff --git a/include/staff/templates/queue-tickets.tmpl.php b/include/staff/templates/queue-tickets.tmpl.php
index 49a8eb246..3afaa410b 100644
--- a/include/staff/templates/queue-tickets.tmpl.php
+++ b/include/staff/templates/queue-tickets.tmpl.php
@@ -90,8 +90,10 @@ if (isset($tickets->extra['tables'])) {
     $criteria->annotations = $criteria->related = $criteria->aggregated =
         $criteria->annotations = $criteria->ordering = [];
     $tickets->constraints = $tickets->extra = [];
+    $criteria->extra(array('select' => array('relevance' => 'Z1.relevance')));
     $tickets = $tickets->filter(['ticket_id__in' =>
             $criteria->values_flat('ticket_id')]);
+    $tickets->order_by(new SqlCode('relevance'), QuerySet::DESC);
     # Index hint should be used on the $criteria query only
     $tickets->clearOption(QuerySet::OPT_INDEX_HINT);
 }
-- 
GitLab