summaryrefslogtreecommitdiff
path: root/app/queries/searches/scope_filters/product_scope_filter.rb
blob: d6f254d0c4965bc1a7f845607c62c531a57c37fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true

module Searches
  module ScopeFilters
    # ProductScopeFilter
    class ProductScopeFilter
      def initialize(scope, params)
        @scope = scope
        @params = params
      end

      def query_result
        @scope
      end

      def order_by_price
        return self unless invalid_order_by_param(:price)

        @scope = @scope.order(unitary_price: @params[:price].to_sym)
        self
      end

      def order_by_bulk_price
        return self unless invalid_order_by_param(:bulk_price)

        @scope = @scope.order(bulk_price: @params[:bulk_price].to_sym)
        self
      end

      def by_category
        return self unless @params[:category].present?

        @scope = @scope.where("'categories' LIKE ?", "%#{@params[:category]}%")
        self
      end

      def order_by_available_quantity
        return self unless invalid_order_by_param(:quantity)

        @scope = @scope.order(available_quantity: @params[:quantity].to_sym)
        self
      end

      def by_company
        return self unless @params[:company].present?

        @scope = @scope.where('companies.short_name = ?', "#{@params[:company]}")
        self
      end

      def by_name
        return self unless @params[:name].present?

        @scope = @scope.where('LOWER(products.name) LIKE ?', "%#{@params[:name]}%")
        self
      end

      private

      def invalid_order_by_param(param_symbol)
        @params[param_symbol].present? || %w[asc desc].include?(@params[param_symbol])
      end
    end
  end
end