2019-10-25 08:18:16 +11:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-12-04 11:23:45 +11:00
|
|
|
module DiscourseSubscriptions
|
2019-10-25 08:18:16 +11:00
|
|
|
class ProductsController < ::ApplicationController
|
2019-12-04 11:23:45 +11:00
|
|
|
include DiscourseSubscriptions::Stripe
|
2019-10-25 08:18:16 +11:00
|
|
|
|
|
|
|
before_action :set_api_key
|
|
|
|
|
|
|
|
def index
|
|
|
|
begin
|
2019-11-04 16:37:21 +11:00
|
|
|
response = ::Stripe::Product.list(active: true)
|
2019-10-25 08:18:16 +11:00
|
|
|
|
2019-11-04 16:37:21 +11:00
|
|
|
products = response[:data].map do |p|
|
|
|
|
serialize(p)
|
|
|
|
end
|
|
|
|
|
|
|
|
render_json_dump products
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
def show
|
|
|
|
begin
|
|
|
|
product = ::Stripe::Product.retrieve(params[:id])
|
|
|
|
|
|
|
|
render_json_dump serialize(product)
|
2019-10-25 08:18:16 +11:00
|
|
|
|
|
|
|
rescue ::Stripe::InvalidRequestError => e
|
2019-12-12 09:59:38 +11:00
|
|
|
render_json_error e.message
|
2019-10-25 08:18:16 +11:00
|
|
|
end
|
|
|
|
end
|
2019-11-04 16:37:21 +11:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def serialize(product)
|
|
|
|
{
|
|
|
|
id: product[:id],
|
|
|
|
name: product[:name],
|
2019-11-28 17:43:03 +11:00
|
|
|
description: product[:metadata][:description],
|
|
|
|
subscribed: current_user_products.include?(product[:id])
|
2019-11-04 16:37:21 +11:00
|
|
|
}
|
|
|
|
end
|
2019-11-28 17:43:03 +11:00
|
|
|
|
|
|
|
def current_user_products
|
2019-12-03 14:31:15 +11:00
|
|
|
return [] if current_user.nil?
|
|
|
|
|
2019-12-04 11:23:45 +11:00
|
|
|
::DiscourseSubscriptions::Customer
|
2019-11-28 17:43:03 +11:00
|
|
|
.select(:product_id)
|
|
|
|
.where(user_id: current_user.id)
|
|
|
|
.map { |c| c.product_id }.compact
|
|
|
|
end
|
2019-10-25 08:18:16 +11:00
|
|
|
end
|
|
|
|
end
|