69 lines
2.1 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
customer = Customer.where(user_id: current_user.id)
customer_ids = customer.map { |c| c.id } if customer
subscription_ids = Subscription.where("customer_id in (?)", customer_ids).pluck(:external_id) if customer_ids
subscriptions = []
if subscription_ids
plans = ::Stripe::Price.list(
expand: ['data.product'],
limit: 100
)
customers = ::Stripe::Customer.list(
email: current_user.email,
expand: ['data.subscriptions']
)
2019-11-01 13:43:09 +11:00
subscriptions = customers[:data].map do |sub_customer|
sub_customer[:subscriptions][:data]
end.flatten(1)
2019-11-01 13:43:09 +11:00
subscriptions = subscriptions.select { |sub| subscription_ids.include?(sub[:id]) }
subscriptions.map! do |subscription|
plan = plans[:data].find { |p| p[:id] == subscription[:items][:data][0][:price][:id] }
subscription.to_h.except!(:plan)
subscription.to_h.merge(plan: plan, product: plan[:product].to_h.slice(:id, :name))
end
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
# we cancel but don't remove until the end of the period
# full removal is done via webhooks
2019-11-04 16:37:21 +11:00
begin
2020-08-19 15:10:47 -05:00
subscription = ::Stripe::Subscription.update(params[:id], { cancel_at_period_end: true, })
2019-11-04 16:37:21 +11:00
if subscription
render_json_dump subscription
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