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

https://github.com/joshnuss/spree-1 · Ruby · 68 lines · 56 code · 12 blank · 0 comment · 4 complexity · 87834d83497d2d49e764844307fb8ff2 MD5 · raw file

  1. module Spree
  2. module Api
  3. class StockItemsController < Spree::Api::BaseController
  4. before_filter :stock_location, except: [:update, :destroy]
  5. def index
  6. @stock_items = scope.ransack(params[:q]).result.page(params[:page]).per(params[:per_page])
  7. respond_with(@stock_items)
  8. end
  9. def show
  10. @stock_item = scope.find(params[:id])
  11. respond_with(@stock_item)
  12. end
  13. def create
  14. authorize! :create, StockItem
  15. count_on_hand = 0
  16. if params[:stock_item].has_key?(:count_on_hand)
  17. count_on_hand = params[:stock_item][:count_on_hand].to_i
  18. params[:stock_item].delete(:count_on_hand)
  19. end
  20. @stock_item = scope.new(params[:stock_item])
  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. if @stock_item.adjust_count_on_hand(count_on_hand)
  36. respond_with(@stock_item, status: 200, default_template: :show)
  37. else
  38. invalid_resource!(@stock_item)
  39. end
  40. end
  41. def destroy
  42. @stock_item = StockItem.accessible_by(current_ability, :destroy).find(params[:id])
  43. @stock_item.destroy
  44. respond_with(@stock_item, status: 204)
  45. end
  46. private
  47. def stock_location
  48. render 'spree/api/shared/stock_location_required', status: 422 and return unless params[:stock_location_id]
  49. @stock_location ||= StockLocation.accessible_by(current_ability, :read).find(params[:stock_location_id])
  50. end
  51. def scope
  52. @stock_location.stock_items.accessible_by(current_ability, :read).includes(:variant => :product)
  53. end
  54. end
  55. end
  56. end