DEV: use existing customer id instead of creating. (#92)

DEV: use existing customer id instead of creating. (#92)

Previosuly, new customer record is created in Stripe for each subscription in Discourse.

diff --git a/app/controllers/discourse_subscriptions/subscribe_controller.rb b/app/controllers/discourse_subscriptions/subscribe_controller.rb
index 6c3624e..c38805e 100644
--- a/app/controllers/discourse_subscriptions/subscribe_controller.rb
+++ b/app/controllers/discourse_subscriptions/subscribe_controller.rb
@@ -63,7 +63,7 @@ module DiscourseSubscriptions
     def create
       params.require([:source, :plan])
       begin
-        customer = create_customer(params[:source])
+        customer = find_or_create_customer(params[:source])
         plan = ::Stripe::Price.retrieve(params[:plan])
 
         if params[:promo].present?
@@ -173,11 +173,17 @@ module DiscourseSubscriptions
       end.sort_by { |plan| plan[:amount] }
     end
 
-    def create_customer(source)
-      ::Stripe::Customer.create(
-        email: current_user.email,
-        source: source
-      )
+    def find_or_create_customer(source)
+      customer = Customer.find_by_user_id(current_user.id)
+
+      if customer.present?
+        ::Stripe::Customer.retrieve(customer.customer_id)
+      else
+        ::Stripe::Customer.create(
+          email: current_user.email,
+          source: source
+        )
+      end
     end
 
     def retrieve_payment_intent(invoice_id)
diff --git a/spec/requests/subscribe_controller_spec.rb b/spec/requests/subscribe_controller_spec.rb
index b06b5a2..7f4e34b 100644
--- a/spec/requests/subscribe_controller_spec.rb
+++ b/spec/requests/subscribe_controller_spec.rb
@@ -210,12 +210,18 @@ module DiscourseSubscriptions
           end
 
           it "creates a customer model" do
-            ::Stripe::Price.expects(:retrieve).returns(type: 'recurring', metadata: {})
+            ::Stripe::Price.expects(:retrieve).returns(type: 'recurring', metadata: {}).twice
             ::Stripe::Subscription.expects(:create).returns(status: 'active', customer: 'cus_1234')
 
             expect {
               post "/s/create.json", params: { plan: 'plan_1234', source: 'tok_1234' }
             }.to change { DiscourseSubscriptions::Customer.count }
+
+            ::Stripe::Customer.expects(:retrieve).with('cus_1234')
+
+            expect {
+              post "/s/create.json", params: { plan: 'plan_5678', source: 'tok_5678' }
+            }.not_to change { DiscourseSubscriptions::Customer.count }
           end
 
           context "with promo code" do

GitHub sha: 33008b0b47d7da3f98f2b2363662d9c907522baf

This commit appears in #92 which was approved by techAPJ. It was merged by vinothkannans.