1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2024-12-04 15:24:23 +01:00
fab-manager/app/controllers/api/subscriptions_controller.rb

78 lines
2.2 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
# API Controller for resources of type Subscription
2016-03-23 18:39:41 +01:00
class API::SubscriptionsController < API::ApiController
include FablabConfiguration
before_action :set_subscription, only: %i[show edit update destroy]
2016-03-23 18:39:41 +01:00
before_action :authenticate_user!
def show
authorize @subscription
end
def create
if fablab_plans_deactivated?
head 403
else
method = current_user.admin? ? :local : :stripe
user_id = current_user.admin? ? subscription_params[:user_id] : current_user.id
@subscription = Subscription.new(subscription_params)
2019-03-18 11:11:09 +01:00
is_subscribe = Subscriptions::Subscribe.new(user_id, current_user.id)
2018-12-10 17:20:23 +01:00
.pay_and_save(@subscription, method, coupon_params[:coupon_code], true)
2016-03-23 18:39:41 +01:00
if is_subscribe
render :show, status: :created, location: @subscription
else
render json: @subscription.errors, status: :unprocessable_entity
2016-03-23 18:39:41 +01:00
end
end
end
def update
authorize @subscription
free_days = params[:subscription][:free] || false
2016-03-23 18:39:41 +01:00
2019-03-18 11:11:09 +01:00
res = Subscriptions::Subscribe.new(@subscription.user_id, current_user.id)
2018-12-11 17:27:25 +01:00
.extend_subscription(@subscription, subscription_update_params[:expired_at], free_days)
if res.is_a?(Subscription)
@subscription = res
render status: :created
elsif res
2016-03-23 18:39:41 +01:00
render status: :ok
else
render status: :unprocessable_entity
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_subscription
@subscription = Subscription.find(params[:id])
end
2016-03-23 18:39:41 +01:00
# Never trust parameters from the scary internet, only allow the white list through.
def subscription_params
params.require(:subscription).permit(:plan_id, :user_id, :card_token)
end
2016-08-11 18:17:28 +02:00
def coupon_params
params.permit(:coupon_code)
end
def subscription_update_params
params.require(:subscription).permit(:expired_at)
end
# TODO, refactor subscriptions logic and move this in model/validator
def valid_card_token?(token)
Stripe::Token.retrieve(token)
rescue Stripe::InvalidRequestError => e
@subscription.errors[:card_token] << e.message
false
end
2016-03-23 18:39:41 +01:00
end