discourse-subscriptions/app/controllers/user/subscriptions_controller.rb

67 lines
1.8 KiB
Ruby
Raw Normal View History

2019-11-01 13:43:09 +11:00
# frozen_string_literal: true
2019-12-04 11:23:45 +11:00
module DiscourseSubscriptions
2019-11-01 13:43:09 +11:00
module User
class SubscriptionsController < ::ApplicationController
2019-12-04 11:23:45 +11:00
include DiscourseSubscriptions::Stripe
include DiscourseSubscriptions::Group
2019-11-01 13:43:09 +11:00
before_action :set_api_key
requires_login
def index
begin
plans = ::Stripe::Plan.list(
expand: ['data.product']
)
2019-11-01 13:43:09 +11:00
customers = ::Stripe::Customer.list(
email: current_user.email,
expand: ['data.subscriptions']
)
subscriptions = customers[:data].map do |customer|
customer[:subscriptions][:data]
end.flatten(1)
subscriptions.map! do |subscription|
plan = plans[:data].find { |p| p[:id] == subscription[:plan][:id] }
subscription.to_h.merge(product: plan[:product].to_h.slice(:id, :name))
end
2019-11-01 13:43:09 +11:00
render_json_dump subscriptions
rescue ::Stripe::InvalidRequestError => e
2019-12-12 09:59:38 +11:00
render_json_error e.message
2019-11-01 13:43:09 +11:00
end
end
2019-11-04 16:37:21 +11:00
def destroy
begin
2019-11-26 11:09:54 +11:00
subscription = ::Stripe::Subscription.retrieve(params[:id])
2019-11-04 16:37:21 +11:00
2019-11-26 11:09:54 +11:00
customer = Customer.find_by(
user_id: current_user.id,
2019-11-29 08:15:46 +11:00
customer_id: subscription[:customer],
product_id: subscription[:plan][:product]
2019-11-26 11:09:54 +11:00
)
2019-11-12 12:43:23 +11:00
2019-11-26 11:09:54 +11:00
if customer.present?
deleted = ::Stripe::Subscription.delete(params[:id])
customer.delete
group = plan_group(subscription[:plan])
group.remove(current_user) if group
2019-11-26 11:09:54 +11:00
render_json_dump deleted
else
2019-12-04 09:33:39 +11:00
render_json_error I18n.t('discourse_subscriptions.customer_not_found')
2019-11-12 12:43:23 +11:00
end
2019-11-04 16:37:21 +11:00
rescue ::Stripe::InvalidRequestError => e
2019-12-12 09:59:38 +11:00
render_json_error e.message
2019-11-04 16:37:21 +11:00
end
end
2019-11-01 13:43:09 +11:00
end
end
end