summaryrefslogtreecommitdiff
path: root/app/controllers/solidus_subscriptions/api/v1/subscriptions_controller.rb
blob: 8db616d9f7e5d7df7654e131d54d7732095fef8f (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
class SolidusSubscriptions::Api::V1::SubscriptionsController < Spree::Api::BaseController
  before_action :load_subscription, only: [:cancel, :update, :skip]

  protect_from_forgery unless: -> { request.format.json? }

  def update
    if @subscription.update(subscription_params)
      render json: @subscription.to_json(include: [:line_items, :shipping_address, :billing_address])
    else
      render json: @subscription.errors.to_json, status: 422
    end
  end

  def skip
    if @subscription.skip
      render json: @subscription.to_json
    else
      render json: @subscription.errors.to_json, status: 422
    end
  end

  def cancel
    if @subscription.cancel
      render json: @subscription.to_json
    else
      render json: @subscription.errors.to_json, status: 422
    end
  end

  private

  def load_subscription
    @subscription = current_api_user.subscriptions.find(params[:id])
  end

  def subscription_params
    params.require(:subscription).permit(
      :interval_units,
      :interval_length,
      :end_date,
      line_items_attributes: line_item_attributes,
      shipping_address_attributes: Spree::PermittedAttributes.address_attributes,
      billing_address_attributes: Spree::PermittedAttributes.address_attributes,
    )
  end

  def line_item_attributes
    SolidusSubscriptions::Config.subscription_line_item_attributes - [:subscribable_id] + [:id]
  end
end