PageRenderTime 1060ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/api/app/controllers/spree/api/v1/stock_items_controller.rb

https://gitlab.com/shinvdu/spree
Ruby | 77 lines | 63 code | 14 blank | 0 comment | 4 complexity | d4173d22734678d44da5634f10c00968 MD5 | raw file
  1. module Spree
  2. module Api
  3. module V1
  4. class StockItemsController < Spree::Api::BaseController
  5. before_action :stock_location, except: [:update, :destroy]
  6. def index
  7. @stock_items = scope.ransack(params[:q]).result.page(params[:page]).per(params[:per_page])
  8. respond_with(@stock_items)
  9. end
  10. def show
  11. @stock_item = scope.find(params[:id])
  12. respond_with(@stock_item)
  13. end
  14. def create
  15. authorize! :create, StockItem
  16. count_on_hand = 0
  17. if params[:stock_item].has_key?(:count_on_hand)
  18. count_on_hand = params[:stock_item][:count_on_hand].to_i
  19. end
  20. @stock_item = scope.new(stock_item_params)
  21. if @stock_item.save
  22. @stock_item.adjust_count_on_hand(count_on_hand)
  23. respond_with(@stock_item, status: 201, default_template: :show)
  24. else
  25. invalid_resource!(@stock_item)
  26. end
  27. end
  28. def update
  29. @stock_item = StockItem.accessible_by(current_ability, :update).find(params[:id])
  30. count_on_hand = 0
  31. if params[:stock_item].has_key?(:count_on_hand)
  32. count_on_hand = params[:stock_item][:count_on_hand].to_i
  33. params[:stock_item].delete(:count_on_hand)
  34. end
  35. updated = params[:stock_item][:force] ? @stock_item.set_count_on_hand(count_on_hand)
  36. : @stock_item.adjust_count_on_hand(count_on_hand)
  37. if updated
  38. respond_with(@stock_item, status: 200, default_template: :show)
  39. else
  40. invalid_resource!(@stock_item)
  41. end
  42. end
  43. def destroy
  44. @stock_item = StockItem.accessible_by(current_ability, :destroy).find(params[:id])
  45. @stock_item.destroy
  46. respond_with(@stock_item, status: 204)
  47. end
  48. private
  49. def stock_location
  50. render 'spree/api/v1/shared/stock_location_required', status: 422 and return unless params[:stock_location_id]
  51. @stock_location ||= StockLocation.accessible_by(current_ability, :read).find(params[:stock_location_id])
  52. end
  53. def scope
  54. includes = { variant: [{ option_values: :option_type }, :product] }
  55. @stock_location.stock_items.accessible_by(current_ability, :read).includes(includes)
  56. end
  57. def stock_item_params
  58. params.require(:stock_item).permit(permitted_stock_item_attributes)
  59. end
  60. end
  61. end
  62. end
  63. end