fix: order for canned response (#6400)

* feat: order canned response

Order canned responses by short_code match first and then with content

* Added specs

---------

Co-authored-by: Pranav Raj S <pranav@chatwoot.com>
This commit is contained in:
Shivam Mishra
2023-02-07 02:23:48 +05:30
committed by GitHub
parent d672aa357b
commit f8aa544aae
3 changed files with 24 additions and 6 deletions

View File

@@ -33,7 +33,10 @@ class Api::V1::Accounts::CannedResponsesController < Api::V1::Accounts::BaseCont
def canned_responses
if params[:search]
Current.account.canned_responses.where('short_code ILIKE :search OR content ILIKE :search', search: "%#{params[:search]}%")
Current.account.canned_responses
.where('short_code ILIKE :search OR content ILIKE :search', search: "%#{params[:search]}%")
.order_by_search(params[:search])
else
Current.account.canned_responses
end

View File

@@ -17,4 +17,14 @@ class CannedResponse < ApplicationRecord
validates_uniqueness_of :short_code, scope: :account_id
belongs_to :account
scope :order_by_search, lambda { |search|
short_code_starts_with = sanitize_sql_array(['WHEN short_code ILIKE ? THEN 1', "#{search}%"])
short_code_like = sanitize_sql_array(['WHEN short_code ILIKE ? THEN 0.5', "%#{search}%"])
content_like = sanitize_sql_array(['WHEN content ILIKE ? THEN 0.2', "%#{search}%"])
order_clause = "CASE #{short_code_starts_with} #{short_code_like} #{content_like} ELSE 0 END"
order(Arel.sql(order_clause) => :desc)
}
end