discourse-subscriptions/app/controllers/user/payments_controller.rb
Justin DiRose fb4fac197b
REFACTOR: Use models to store data (#11)
* REFACTOR: Use api to add subscribe link

* FIX: I18n subscribe link

* REFACTOR: Use models to store some data

This enables the plugin to show only subscription information which was
generated on Discourse. Subscription data storage is limited to the
external identifiers Stripe generates so we can interact with the API.

* DEV: Test/linting fixes/rake task
2020-05-22 11:20:05 -05:00

36 lines
1.3 KiB
Ruby

# frozen_string_literal: true
module DiscourseSubscriptions
module User
class PaymentsController < ::ApplicationController
include DiscourseSubscriptions::Stripe
before_action :set_api_key
requires_login
def index
begin
customer = Customer.find_by(user_id: current_user.id)
product_ids = Product.all.pluck(:external_id)
data = []
if customer.present? && product_ids.present?
# lots of matching because the Stripe API doesn't make it easy to match products => payments except from invoices
all_invoices = ::Stripe::Invoice.list(customer: customer[:customer_id])
invoices_with_products = all_invoices[:data].select { |invoice| product_ids.include?(invoice.dig(:lines, :data, 0, :plan, :product)) }
invoice_ids = invoices_with_products.map { |invoice| invoice[:id] }
payments = ::Stripe::PaymentIntent.list(customer: customer[:customer_id])
payments_from_invoices = payments[:data].select { |payment| invoice_ids.include?(payment[:invoice]) }
data = payments_from_invoices
end
render_json_dump data
rescue ::Stripe::InvalidRequestError => e
render_json_error e.message
end
end
end
end
end