2022-08-19 19:59:13 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# API Controller for manage user's cart
|
|
|
|
class API::CartController < API::ApiController
|
2022-08-21 19:08:10 +02:00
|
|
|
include API::OrderConcern
|
|
|
|
|
2022-08-20 20:49:51 +02:00
|
|
|
before_action :current_order, except: %i[create]
|
2022-08-19 19:59:13 +02:00
|
|
|
before_action :ensure_order, except: %i[create]
|
|
|
|
|
|
|
|
def create
|
|
|
|
authorize :cart, :create?
|
2022-08-26 10:46:30 +02:00
|
|
|
@order = Order.find_by(token: order_token, state: 'cart')
|
2022-08-25 16:23:00 +02:00
|
|
|
if @order.nil?
|
|
|
|
if current_user&.member?
|
|
|
|
@order = Order.where(statistic_profile_id: current_user.statistic_profile.id,
|
|
|
|
state: 'cart').last
|
|
|
|
end
|
|
|
|
if current_user&.privileged?
|
2022-08-26 11:55:35 +02:00
|
|
|
@order = Order.where(operator_profile_id: current_user.invoicing_profile.id,
|
2022-08-25 16:23:00 +02:00
|
|
|
state: 'cart').last
|
|
|
|
end
|
2022-08-25 08:52:17 +02:00
|
|
|
end
|
2022-08-21 15:34:23 +02:00
|
|
|
if @order
|
|
|
|
@order.update(statistic_profile_id: current_user.statistic_profile.id) if @order.statistic_profile_id.nil? && current_user&.member?
|
2022-08-26 11:55:35 +02:00
|
|
|
@order.update(operator_profile_id: current_user.invoicing_profile.id) if @order.operator_profile_id.nil? && current_user&.privileged?
|
2022-08-20 20:49:51 +02:00
|
|
|
end
|
2022-08-19 19:59:13 +02:00
|
|
|
@order ||= Cart::CreateService.new.call(current_user)
|
|
|
|
render 'api/orders/show'
|
|
|
|
end
|
|
|
|
|
|
|
|
def add_item
|
|
|
|
authorize @current_order, policy_class: CartPolicy
|
|
|
|
@order = Cart::AddItemService.new.call(@current_order, orderable, cart_params[:quantity])
|
|
|
|
render 'api/orders/show'
|
|
|
|
end
|
|
|
|
|
|
|
|
def remove_item
|
2022-08-20 20:49:51 +02:00
|
|
|
authorize @current_order, policy_class: CartPolicy
|
2022-08-19 19:59:13 +02:00
|
|
|
@order = Cart::RemoveItemService.new.call(@current_order, orderable)
|
|
|
|
render 'api/orders/show'
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_quantity
|
2022-08-20 20:49:51 +02:00
|
|
|
authorize @current_order, policy_class: CartPolicy
|
2022-08-19 19:59:13 +02:00
|
|
|
@order = Cart::SetQuantityService.new.call(@current_order, orderable, cart_params[:quantity])
|
|
|
|
render 'api/orders/show'
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def orderable
|
|
|
|
Product.find(cart_params[:orderable_id])
|
|
|
|
end
|
|
|
|
end
|