summaryrefslogtreecommitdiff
path: root/app/controllers/api/products_controller.rb
blob: 59019d01fb926b4e4210df117f0c08791e95d803 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# frozen_string_literal: true

module Api
  # ProductsController
  class ProductsController < MasterController
    def show
      render status: :not_found and return unless Product.exists?(public_id: params[:id])

      render json: serialized_object(params[:id]).serializable_hash, status: :ok
    end

    def index
      @search = Searches::ProductSearch.new(scope, search_params)
      @products = @search.call

      render json: serialized_collection.serializable_hash, status: :ok
    end

    def create
      @product = Product.new(object_params)

      if @product.save
        render json: serialized_object(@product.public_id).serializable_hash, status: :ok
      else
        render json: { errors: @product.errors.as_json }, status: :unprocessable_entity
      end
    end

    def update
      @product = Product.find_by(public_id: params[:id])

      render status: :not_found and return if @product.nil?

      if @product.update(object_params)
        render json: serialized_object(@product.public_id).serializable_hash, status: :ok
      else
        render json: { errors: @product.errors.as_json }, status: :unprocessable_entity
      end
    end

    def destroy
      @product = Product.find_by(public_id: params[:id])

      render status: :not_found and return if @product.nil?

      @product.destroy
      render status: :no_content
    end

    private

    def scope
      Product.joins(:company)
             .select('products.*', 'companies.name as company_name', 'companies.short_name as company_short_name')
             .includes(picture_attachment: :blob)
    end

    def serialized_object(public_id)
      ProductSerializer.new(scope.find_by(public_id:))
    end

    def serialized_collection
      ProductSerializer.new(@products.page(params[:page]))
    end

    def permitted_params
      params.permit(:name, :unitary_price, :bulk_price, :picture, :available_quantity, :categories, :company_id)
    end

    def object_params
      categories = permitted_params[:categories].split(',')
      public_id = SecureRandom.hex(12)
      public_id = SecureRandom.hex(12) while Product.exists?(public_id:)
      permitted_params.merge(categories:, public_id:)
    end

    def search_params
      params.permit(:name, :company, :category, :quantity, :bulk_price, :price)
    end
  end
end