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

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

https://github.com/slavix/spree
Ruby | 75 lines | 61 code | 14 blank | 0 comment | 4 complexity | ba1dd4d12006946c0577c223b38423aa MD5 | raw file
Possible License(s): BSD-3-Clause
  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. end
  19. @stock_item = scope.new(stock_item_params)
  20. if @stock_item.save
  21. @stock_item.adjust_count_on_hand(count_on_hand)
  22. respond_with(@stock_item, status: 201, default_template: :show)
  23. else
  24. invalid_resource!(@stock_item)
  25. end
  26. end
  27. def update
  28. @stock_item = StockItem.accessible_by(current_ability, :update).find(params[:id])
  29. count_on_hand = 0
  30. if params[:stock_item].has_key?(:count_on_hand)
  31. count_on_hand = params[:stock_item][:count_on_hand].to_i
  32. params[:stock_item].delete(:count_on_hand)
  33. end
  34. updated = params[:stock_item][:force] ? @stock_item.set_count_on_hand(count_on_hand)
  35. : @stock_item.adjust_count_on_hand(count_on_hand)
  36. if updated
  37. respond_with(@stock_item, status: 200, default_template: :show)
  38. else
  39. invalid_resource!(@stock_item)
  40. end
  41. end
  42. def destroy
  43. @stock_item = StockItem.accessible_by(current_ability, :destroy).find(params[:id])
  44. @stock_item.destroy
  45. respond_with(@stock_item, status: 204)
  46. end
  47. private
  48. def stock_location
  49. render 'spree/api/shared/stock_location_required', status: 422 and return unless params[:stock_location_id]
  50. @stock_location ||= StockLocation.accessible_by(current_ability, :read).find(params[:stock_location_id])
  51. end
  52. def scope
  53. includes = {:variant => [{ :option_values => :option_type }, :product] }
  54. @stock_location.stock_items.accessible_by(current_ability, :read).includes(includes)
  55. end
  56. def stock_item_params
  57. params.require(:stock_item).permit(permitted_stock_item_attributes)
  58. end
  59. end
  60. end
  61. end