From 8ea5a27ae942285ea1d51653d674840d3c68955c Mon Sep 17 00:00:00 2001 From: Oleg Hasjanov Date: Fri, 15 Sep 2023 12:50:15 +0300 Subject: [PATCH] fixed by total sort column --- app/models/invoice.rb | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/app/models/invoice.rb b/app/models/invoice.rb index f41fb387f..80abb4ffa 100644 --- a/app/models/invoice.rb +++ b/app/models/invoice.rb @@ -30,6 +30,8 @@ class Invoice < ApplicationRecord delegate :enable_deposit?, to: :enable_deposit? delegate :deposit, to: :deposit + attr_accessor :vat_rate + scope :with_search_scope, (lambda do |origin| if origin.present? if numeric?(origin) @@ -61,15 +63,6 @@ class Invoice < ApplicationRecord Time.zone.today + number_of_days, statuses[:issued]) } - def self.with_totals - select("invoices.*, - (CASE WHEN auctions.enable_deposit - THEN ROUND((invoices.cents / 100.0 * (1 + COALESCE(invoices.vat_rate, 0.0)) - auctions.requirement_deposit_in_cents / 100.0), 2) - ELSE ROUND((invoices.cents / 100.0 * (1 + COALESCE(invoices.vat_rate, 0.0))), 2) - END) AS total_value") - .joins(result: :auction) - end - def self.search(params = {}) sort_column = params[:sort].presence_in(%w[paid_through paid_amount @@ -90,9 +83,19 @@ def self.search(params = {}) .select("invoices.*, REPLACE(payment_orders.type, 'PaymentOrders::', '') AS payment_order_channel") .order(Arel.sql("payment_order_channel #{sort_direction} NULLS LAST")) when 'billing_profile_name' - query.left_outer_joins(:billing_profile).order("billing_profiles.name #{sort_direction}") + query.left_outer_joins(:billing_profile).order("billing_profiles.name #{sort_direction} NULLS LAST") when 'total' - query.with_totals.order("total_value #{sort_direction} NULLS LAST") + invoices_array = query.to_a + sorted_invoices = if sort_direction == 'asc' + invoices_array.sort_by(&:total) + else + invoices_array.sort_by(&:total).reverse + end + + ids_order = sorted_invoices.map(&:id) + ids_order_string = ids_order.join(',') + + query.where(id: ids_order).order(Arel.sql("position(id::text in '#{ids_order_string}')")) else query.order("#{sort_column} #{sort_direction} NULLS LAST") end