thumbjive-koudoku 1.5.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (92) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +198 -0
  4. data/Rakefile +10 -0
  5. data/app/assets/javascripts/koudoku/application.js +15 -0
  6. data/app/assets/stylesheets/koudoku/application.css +13 -0
  7. data/app/assets/stylesheets/koudoku/pricing-table.scss +78 -0
  8. data/app/concerns/koudoku/coupon.rb +7 -0
  9. data/app/concerns/koudoku/plan.rb +14 -0
  10. data/app/concerns/koudoku/subscription.rb +255 -0
  11. data/app/controllers/koudoku/application_controller.rb +7 -0
  12. data/app/controllers/koudoku/subscriptions_controller.rb +181 -0
  13. data/app/helpers/koudoku/application_helper.rb +20 -0
  14. data/app/views/koudoku/subscriptions/_card.html.erb +99 -0
  15. data/app/views/koudoku/subscriptions/_pricing_table.html.erb +40 -0
  16. data/app/views/koudoku/subscriptions/_social_proof.html.erb +11 -0
  17. data/app/views/koudoku/subscriptions/_stripe_js.html.erb +0 -0
  18. data/app/views/koudoku/subscriptions/edit.html.erb +7 -0
  19. data/app/views/koudoku/subscriptions/index.html.erb +2 -0
  20. data/app/views/koudoku/subscriptions/new.html.erb +1 -0
  21. data/app/views/koudoku/subscriptions/show.html.erb +15 -0
  22. data/app/views/koudoku/subscriptions/unauthorized.html.erb +1 -0
  23. data/app/views/layouts/koudoku/application.html.erb +14 -0
  24. data/config/environment.rb +0 -0
  25. data/config/initializers/stripe_event.rb +27 -0
  26. data/config/locales/en.yml +58 -0
  27. data/config/locales/pt-BR.yml +57 -0
  28. data/config/routes.rb +14 -0
  29. data/lib/generators/koudoku/install_generator.rb +74 -0
  30. data/lib/generators/koudoku/templates/app/models/coupon.rb +5 -0
  31. data/lib/generators/koudoku/templates/app/models/plan.rb +6 -0
  32. data/lib/generators/koudoku/templates/app/models/subscription.rb +8 -0
  33. data/lib/generators/koudoku/templates/config/initializers/koudoku.rb +18 -0
  34. data/lib/generators/koudoku/views_generator.rb +31 -0
  35. data/lib/koudoku-tj.rb +0 -0
  36. data/lib/koudoku.rb +84 -0
  37. data/lib/koudoku/engine.rb +20 -0
  38. data/lib/koudoku/errors.rb +4 -0
  39. data/lib/koudoku/version.rb +3 -0
  40. data/lib/tasks/koudoku_tasks.rake +12 -0
  41. data/spec/concerns/koudoku/plan_spec.rb +39 -0
  42. data/spec/concerns/koudoku/subscription_spec.rb +0 -0
  43. data/spec/controllers/koudoku/subscriptions_controller.rb +21 -0
  44. data/spec/dummy/README.rdoc +261 -0
  45. data/spec/dummy/Rakefile +7 -0
  46. data/spec/dummy/app/assets/javascripts/application.js +15 -0
  47. data/spec/dummy/app/assets/stylesheets/application.css +13 -0
  48. data/spec/dummy/app/controllers/application_controller.rb +3 -0
  49. data/spec/dummy/app/helpers/application_helper.rb +2 -0
  50. data/spec/dummy/app/models/coupon.rb +3 -0
  51. data/spec/dummy/app/models/customer.rb +6 -0
  52. data/spec/dummy/app/models/plan.rb +8 -0
  53. data/spec/dummy/app/models/subscription.rb +7 -0
  54. data/spec/dummy/app/views/koudoku/subscriptions/_social_proof.html.erb +11 -0
  55. data/spec/dummy/app/views/layouts/application.html.erb +14 -0
  56. data/spec/dummy/config.ru +4 -0
  57. data/spec/dummy/config/application.rb +55 -0
  58. data/spec/dummy/config/boot.rb +10 -0
  59. data/spec/dummy/config/database.yml +25 -0
  60. data/spec/dummy/config/environment.rb +5 -0
  61. data/spec/dummy/config/environments/development.rb +32 -0
  62. data/spec/dummy/config/environments/production.rb +69 -0
  63. data/spec/dummy/config/environments/test.rb +36 -0
  64. data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
  65. data/spec/dummy/config/initializers/devise.rb +0 -0
  66. data/spec/dummy/config/initializers/inflections.rb +15 -0
  67. data/spec/dummy/config/initializers/koudoku.rb +7 -0
  68. data/spec/dummy/config/initializers/mime_types.rb +5 -0
  69. data/spec/dummy/config/initializers/secret_token.rb +7 -0
  70. data/spec/dummy/config/initializers/session_store.rb +8 -0
  71. data/spec/dummy/config/initializers/wrap_parameters.rb +14 -0
  72. data/spec/dummy/config/locales/devise.en.yml +59 -0
  73. data/spec/dummy/config/locales/en.yml +5 -0
  74. data/spec/dummy/config/routes.rb +6 -0
  75. data/spec/dummy/db/migrate/20130318201927_create_customers.rb +8 -0
  76. data/spec/dummy/db/migrate/20130318204455_create_subscriptions.rb +16 -0
  77. data/spec/dummy/db/migrate/20130318204458_create_plans.rb +14 -0
  78. data/spec/dummy/db/migrate/20130318204502_create_coupons.rb +10 -0
  79. data/spec/dummy/db/migrate/20130520163946_add_interval_to_plan.rb +5 -0
  80. data/spec/dummy/db/schema.rb +53 -0
  81. data/spec/dummy/db/test.sqlite3 +0 -0
  82. data/spec/dummy/log/test.log +80 -0
  83. data/spec/dummy/public/404.html +26 -0
  84. data/spec/dummy/public/422.html +26 -0
  85. data/spec/dummy/public/500.html +25 -0
  86. data/spec/dummy/public/favicon.ico +0 -0
  87. data/spec/dummy/script/rails +6 -0
  88. data/spec/dummy/test/fixtures/customers.yml +7 -0
  89. data/spec/dummy/test/unit/customer_test.rb +7 -0
  90. data/spec/helpers/koudoku/application_helper_spec.rb +29 -0
  91. data/spec/spec_helper.rb +30 -0
  92. metadata +332 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 50fbdceb853ea51b754ebeb8ade4a9feccec2563
4
+ data.tar.gz: 783bd44103f5e4bd053bf62dda3a7b8302f81afe
5
+ SHA512:
6
+ metadata.gz: 7f7b506a2e1828936b26d02c3029cd7b53444e6842557541c5f0495e9b6306f9f4e7617204872232e8360e6fb01933fe7047ba0ca394497e153ca174f7a36b57
7
+ data.tar.gz: da482feb71c1315e06a39e419bc56a12d8dbdc494d50fd2a033875040c3e6d2d16b0e1f91715ffc0c16dacc665da59b52a9b39da48ae689bdef5886947c8f42f
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2013 YOURNAME
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # Koudoku
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/koudoku.png)](https://rubygems.org/gems/koudoku) [![Code Climate](https://codeclimate.com/github/andrewculver/koudoku.png)](https://codeclimate.com/github/andrewculver/koudoku) [![Build Status](https://travis-ci.org/andrewculver/koudoku.png)](https://travis-ci.org/andrewculver/koudoku)
4
+
5
+ Robust subscription support for Ruby on Rails apps using [Stripe](https://stripe.com), including out-of-the-box pricing pages, payment pages, and subscription management for your customers. Also makes it easy to manage logic related to new subscriptions, upgrades, downgrades, cancellations, payment failures, and streamlines hooking up notifications, metrics logging, etc.
6
+
7
+ To see an example of Koudoku in action, please visit [Koudoku.org](http://koudoku.org/).
8
+
9
+ <small><a href="http://churnbuster.io"><img src="https://s3.amazonaws.com/andrew-culver-images/churn-buster/koudoku-readme.png" width="196" height="38" alt="Churn Buster" /></a><br>Koudoku is authored and maintained by [Andrew Culver](http://twitter.com/andrewculver) and [Christoph Engelhardt](https://twitter.com/itengelhardt). If you find it useful, consider checking out [Churn Buster](http://churnbuster.io). It's designed to help you handle the pain points you'll run into when doing payments at scale.</small>
10
+
11
+ ## Installation
12
+
13
+ Include the following in your `Gemfile`:
14
+
15
+ ```ruby
16
+ gem 'koudoku'
17
+ ```
18
+
19
+ After running `bundle install`, you can run a Rails generator to do the rest. Before installing, the model you'd like to have own subscriptions must already exist. (In many cases this will be `user`. It may also be something like `company`, etc.)
20
+
21
+ ```ruby
22
+ rails g koudoku:install user
23
+ rake db:migrate
24
+ ```
25
+
26
+ Add the following to `app/views/layouts/application.html.erb` before your `<head>` tag closes:
27
+
28
+ ```ruby
29
+ <%= yield :koudoku %>
30
+ ```
31
+
32
+ (This allows us to inject a Stripe `<script>` tag in the correct place. If you don't, the payment form will not work.)
33
+
34
+ After installing, you'll need to add some subscription plans. (You can see an explanation of each of the attributes in the table below.)
35
+
36
+ **Note:** You need to create the plans in your [Stripe Dashboard](https://dashboard.stripe.com) separately.
37
+
38
+ ```ruby
39
+ Plan.create({
40
+ name: 'Personal',
41
+ price: 10.00,
42
+ interval: 'month',
43
+ stripe_id: '1',
44
+ features: ['1 Project', '1 Page', '1 User', '1 Organization'].join("\n\n"),
45
+ display_order: 1
46
+ })
47
+
48
+ Plan.create({
49
+ name: 'Team',
50
+ highlight: true, # This highlights the plan on the pricing page.
51
+ price: 30.00,
52
+ interval: 'month',
53
+ stripe_id: '2',
54
+ features: ['3 Projects', '3 Pages', '3 Users', '3 Organizations'].join("\n\n"),
55
+ display_order: 2
56
+ })
57
+
58
+ Plan.create({
59
+ name: 'Enterprise',
60
+ price: 100.00,
61
+ interval: 'month',
62
+ stripe_id: '3',
63
+ features: ['10 Projects', '10 Pages', '10 Users', '10 Organizations'].join("\n\n"),
64
+ display_order: 3
65
+ })
66
+ ```
67
+
68
+ To help you understand the attributes:
69
+
70
+ | Attribute | Type | Function |
71
+ | --------------- | ------- | -------- |
72
+ | `name` | string | Name for the plan to be presented to customers. |
73
+ | `price` | float | Price per billing cycle. |
74
+ | `interval` | string | *Optional.* What is the billing cycle? Valid options are `month`, `year`, `week`, `3-month`, `6-month`. Defaults to `month`. |
75
+ | `stripe_id` | string | The Plan ID in Stripe. |
76
+ | `features` | string | A list of features. Supports Markdown syntax. |
77
+ | `display_order` | integer | Order in which to display plans. |
78
+ | `highlight` | boolean | *Optional.* Whether to highlight the plan on the pricing page. |
79
+
80
+ The only view installed locally into your app by default is the `koudoku/subscriptions/_social_proof.html.erb` partial which is displayed alongside the pricing table. It's designed as a placeholder where you can provide quotes about your product from customers that could positively influence your visitors.
81
+
82
+ ### Configuring Stripe API Keys
83
+
84
+ You can supply your publishable and secret API keys in `config/initializers/koudoku.rb`. However, by default it will use the `STRIPE_PUBLISHABLE_KEY` and `STRIPE_SECRET_KEY` shell environment variables. This encourages people to keep these API keys out of version control. You may want to rename these environment variables to be more application specific.
85
+
86
+ In a bash shell, you can set them in `~/.bash_profile` like so:
87
+
88
+ ```bash
89
+ export STRIPE_PUBLISHABLE_KEY=pk_0CJwDH9sdh98f79FDHDOjdiOxQob0
90
+ export STRIPE_SECRET_KEY=sk_0CJwFDIUshdfh97JDJOjZ5OIDjOCH
91
+ ```
92
+
93
+ (Reload your terminal for these settings to take effect.)
94
+
95
+ On Heroku you accomplish this same effect with [Config Vars](https://devcenter.heroku.com/articles/config-vars):
96
+
97
+ ```bash
98
+ heroku config:add STRIPE_PUBLISHABLE_KEY=pk_0CJwDH9sdh98f79FDHDOjdiOxQob0
99
+ heroku config:add STRIPE_SECRET_KEY=sk_0CJwFDIUshdfh97JDJOjZ5OIDjOCH
100
+ ```
101
+
102
+ ## User-Facing Subscription Management
103
+
104
+ By default a `pricing_path` route is defined which you can link to in order to show visitors a pricing table. If a user is signed in, this pricing table will take into account their current plan. For example, you can link to this page like so:
105
+
106
+ ```ruby
107
+ <%= link_to 'Pricing', main_app.pricing_path %>
108
+ ```
109
+
110
+ (Note: Koudoku uses the application layout, so it's important that application paths referenced in that layout are prefixed with "`main_app.`" like you see above or Rails will try to look the paths up in the Koudoku engine instead of your application.)
111
+
112
+ Existing users can view available plans, select a plan, enter credit card details, review their subscription, change plans, and cancel at the following route:
113
+
114
+ ```ruby
115
+ koudoku.owner_subscriptions_path(@user)
116
+ ```
117
+
118
+ In these paths, `owner` refers to `User` by default, or whatever model has been configured to be the owner of the `Subscription` model.
119
+
120
+ A number of views are provided by default. To customize the views, use the following generator:
121
+
122
+ ```ruby
123
+ rails g koudoku:views
124
+ ```
125
+
126
+ ### Pricing Table
127
+
128
+ Koudoku ships with a stock pricing table. By default it depends on Twitter Bootstrap, but also has some additional styles required. In order to import these styles, add the following to your `app/assets/stylesheets/application.css`:
129
+
130
+ ```css
131
+ *= require 'koudoku/pricing-table'
132
+ ```
133
+
134
+ Or, if you've replaced your `application.css` with an `application.scss` (like I always do):
135
+
136
+ ```css
137
+ @import "koudoku/pricing-table"
138
+ ```
139
+
140
+ ## Using Coupons
141
+
142
+ While more robust coupon support is expected in the future, the simple way to use a coupon is to first create it:
143
+
144
+ ```ruby
145
+ coupon = Coupon.create(code: '30-days-free', free_trial_length: 30)
146
+ ```
147
+
148
+ Then assign it to a _new_ subscription before saving:
149
+
150
+ ```ruby
151
+ subscription = Subscription.new(...)
152
+ subscription.coupon = coupon
153
+ subscription.save
154
+ ```
155
+
156
+ It should be noted that these coupons are different from the coupons provided natively by Stripe.
157
+
158
+ ## Implementing Logging, Notifications, etc.
159
+
160
+ The included module defines the following empty "template methods" which you're able to provide an implementation for in `Subscription`:
161
+
162
+ - `prepare_for_plan_change`
163
+ - `prepare_for_new_subscription`
164
+ - `prepare_for_upgrade`
165
+ - `prepare_for_downgrade`
166
+ - `prepare_for_cancelation`
167
+ - `prepare_for_card_update`
168
+ - `finalize_plan_change!`
169
+ - `finalize_new_subscription!`
170
+ - `finalize_upgrade!`
171
+ - `finalize_downgrade!`
172
+ - `finalize_cancelation!`
173
+ - `finalize_card_update!`
174
+ - `card_was_declined`
175
+
176
+ Be sure to include a call to `super` in each of your implementations, especially if you're using multiple concerns to break all this logic into smaller pieces.
177
+
178
+ Between `prepare_for_*` and `finalize_*`, so far I've used `finalize_*` almost exclusively. The difference is that `prepare_for_*` runs before we settle things with Stripe, and `finalize_*` runs after everything is settled in Stripe. For that reason, please be sure not to implement anything in `finalize_*` implementations that might cause issues with ActiveRecord saving the updated state of the subscription.
179
+
180
+ ### Webhooks
181
+
182
+ We use [stripe_event](https://github.com/integrallis/stripe_event) under the hood to support webhooks.
183
+ The default webhooks URL is `/koudoku/webhooks`.
184
+
185
+ You can add your own webhooks using the (reduced) stripe_event syntax in the `config/initializers/koudoku.rb` file:
186
+
187
+ ```
188
+ # /config/initializers/koudoku.rb
189
+ Koudoku.setup do |config|
190
+ config.subscriptions_owned_by = :user
191
+ config.stripe_publishable_key = ENV['STRIPE_PUBLISHABLE_KEY']
192
+ config.stripe_secret_key = ENV['STRIPE_SECRET_KEY']
193
+
194
+ # add webhooks
195
+ config.subscribe 'charge.failed', YourChargeFailed
196
+ end
197
+
198
+ ```
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
3
+
4
+ APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__)
5
+ load 'rails/tasks/engine.rake'
6
+
7
+ require 'rspec/core/rake_task'
8
+ RSpec::Core::RakeTask.new(spec: 'app:db:test:prepare')
9
+
10
+ task default: :spec
@@ -0,0 +1,15 @@
1
+ // This is a manifest file that'll be compiled into application.js, which will include all the files
2
+ // listed below.
3
+ //
4
+ // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5
+ // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
6
+ //
7
+ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8
+ // the compiled file.
9
+ //
10
+ // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
11
+ // GO AFTER THE REQUIRES BELOW.
12
+ //
13
+ //= require jquery
14
+ //= require jquery_ujs
15
+ //= require_tree .
@@ -0,0 +1,13 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the top of the
9
+ * compiled file, but it's generally better to create a new file per style scope.
10
+ *
11
+ *= require_self
12
+ *= require_tree .
13
+ */
@@ -0,0 +1,78 @@
1
+ ul.koudoku-pricing-table {
2
+
3
+ position: relative;
4
+ margin: 20px 0;
5
+ margin-left: 25px;
6
+
7
+
8
+ li.plan {
9
+
10
+ text-align: center;
11
+
12
+ background-color: #f5f5f5;
13
+ margin-top: 17px;
14
+
15
+ margin-left: 0;
16
+
17
+ position: relative;
18
+ z-index: 99;
19
+
20
+ &.plan-primary {
21
+ background-color: #f9f9f9;
22
+ margin-top: 0px;
23
+
24
+ margin-left: -5px;
25
+ margin-right: -5px;
26
+
27
+ z-index: 100;
28
+
29
+ h3 {
30
+ font-size: 32.5px;
31
+ line-height: 51px;
32
+ }
33
+ h4 {
34
+ line-height: 22px;
35
+ }
36
+ a, input[type=submit] {
37
+ font-size: 21.5px;
38
+ line-height: 26px;
39
+ }
40
+ ul.features {
41
+ margin-bottom: 12px;
42
+ li {
43
+ font-size: 12pt;
44
+ }
45
+ }
46
+ }
47
+
48
+ .call-to-action {
49
+ margin: 10px 0;
50
+ }
51
+
52
+ .features {
53
+ margin: 0;
54
+ li {
55
+ list-style: none;
56
+ padding: 8px;
57
+ line-height: 18px;
58
+ vertical-align: top;
59
+ border-top: 1px solid #dddddd;
60
+ }
61
+ li:first-child {
62
+ border-top: none;
63
+ }
64
+ }
65
+
66
+ }
67
+
68
+
69
+ .social-proof {
70
+ padding: 17px 0;
71
+ blockquote {
72
+ h2, h3, h4 {
73
+ padding: 5px 0;
74
+ }
75
+ }
76
+ }
77
+
78
+ }
@@ -0,0 +1,7 @@
1
+ module Koudoku::Coupon
2
+ extend ActiveSupport::Concern
3
+
4
+ included do
5
+ has_many :subscriptions
6
+ end
7
+ end
@@ -0,0 +1,14 @@
1
+ module Koudoku::Plan
2
+ extend ActiveSupport::Concern
3
+
4
+ # Todo: fix the unit tests so that the association can be defined here
5
+ #
6
+ # included do
7
+ # has_many :subscriptions
8
+ # end
9
+
10
+ def is_upgrade_from?(plan)
11
+ (price || 0) >= (plan.price || 0)
12
+ end
13
+
14
+ end
@@ -0,0 +1,255 @@
1
+ module Koudoku::Subscription
2
+ extend ActiveSupport::Concern
3
+
4
+ included do
5
+
6
+ # We don't store these one-time use tokens, but this is what Stripe provides
7
+ # client-side after storing the credit card information.
8
+ attr_accessor :credit_card_token
9
+
10
+ belongs_to :plan, optional: true
11
+ belongs_to :coupon, optional: true
12
+
13
+ belongs_to Koudoku.subscriptions_owned_by
14
+
15
+ # update details.
16
+ before_save :processing!
17
+ def processing!
18
+
19
+ # if their package level has changed ..
20
+ if changing_plans?
21
+
22
+ prepare_for_plan_change
23
+
24
+ # and a customer exists in stripe ..
25
+ if stripe_id.present?
26
+
27
+ # fetch the customer.
28
+ customer = Stripe::Customer.retrieve(self.stripe_id)
29
+
30
+ # if a new plan has been selected
31
+ if self.plan.present?
32
+
33
+ # Record the new plan pricing.
34
+ self.current_price = self.plan.price
35
+
36
+ prepare_for_downgrade if downgrading?
37
+ prepare_for_upgrade if upgrading?
38
+
39
+ # update the package level with stripe.
40
+ customer.update_subscription(:plan => self.plan.stripe_id, :prorate => Koudoku.prorate)
41
+
42
+ finalize_downgrade! if downgrading?
43
+ finalize_upgrade! if upgrading?
44
+
45
+ # if no plan has been selected.
46
+ else
47
+
48
+ prepare_for_cancelation
49
+
50
+ # Remove the current pricing.
51
+ self.current_price = nil
52
+
53
+ # delete the subscription.
54
+ customer.cancel_subscription
55
+
56
+ finalize_cancelation!
57
+
58
+ end
59
+
60
+ # when customer DOES NOT exist in stripe ..
61
+ else
62
+ # if a new plan has been selected
63
+ if self.plan.present?
64
+
65
+ # Record the new plan pricing.
66
+ self.current_price = self.plan.price
67
+
68
+ prepare_for_new_subscription
69
+ prepare_for_upgrade
70
+
71
+ begin
72
+ # raise Koudoku::NilCardToken, "Possible javascript error" if credit_card_token.blank?
73
+ raise "Possible javascript error" if credit_card_token.blank?
74
+ customer_attributes = {
75
+ description: subscription_owner_description,
76
+ email: subscription_owner_email,
77
+ card: credit_card_token # obtained with Stripe.js
78
+ }
79
+
80
+ # If the class we're being included in supports coupons ..
81
+ if respond_to? :coupon
82
+ if coupon.present? and coupon.free_trial?
83
+ customer_attributes[:trial_end] = coupon.free_trial_ends.to_i
84
+ end
85
+ end
86
+
87
+ customer_attributes[:coupon] = @coupon_code if @coupon_code
88
+
89
+ # create a customer at that package level.
90
+ customer = Stripe::Customer.create(customer_attributes)
91
+
92
+ finalize_new_customer!(customer.id, plan.price)
93
+ customer.update_subscription(:plan => self.plan.stripe_id, :prorate => Koudoku.prorate)
94
+
95
+ rescue Stripe::CardError => card_error
96
+ errors[:base] << card_error.message
97
+ card_was_declined
98
+ return false
99
+ end
100
+
101
+ # store the customer id.
102
+ self.stripe_id = customer.id
103
+ self.last_four = customer.cards.retrieve(customer.default_card).last4
104
+
105
+ finalize_new_subscription!
106
+ finalize_upgrade!
107
+
108
+ else
109
+
110
+ # This should never happen.
111
+
112
+ self.plan_id = nil
113
+
114
+ # Remove any plan pricing.
115
+ self.current_price = nil
116
+
117
+ end
118
+
119
+ end
120
+
121
+ finalize_plan_change!
122
+
123
+ # if they're updating their credit card details.
124
+ elsif self.credit_card_token.present?
125
+
126
+ prepare_for_card_update
127
+
128
+ # fetch the customer.
129
+ customer = Stripe::Customer.retrieve(self.stripe_id)
130
+ customer.card = self.credit_card_token
131
+ customer.save
132
+
133
+ # update the last four based on this new card.
134
+ self.last_four = customer.cards.retrieve(customer.default_card).last4
135
+ finalize_card_update!
136
+
137
+ end
138
+ end
139
+ end
140
+
141
+
142
+ def describe_difference(plan_to_describe)
143
+ if plan.nil?
144
+ if persisted?
145
+ I18n.t('koudoku.plan_difference.upgrade')
146
+ else
147
+ if Koudoku.free_trial?
148
+ I18n.t('koudoku.plan_difference.start_trial')
149
+ else
150
+ I18n.t('koudoku.plan_difference.upgrade')
151
+ end
152
+ end
153
+ else
154
+ if plan_to_describe.is_upgrade_from?(plan)
155
+ I18n.t('koudoku.plan_difference.upgrade')
156
+ else
157
+ I18n.t('koudoku.plan_difference.downgrade')
158
+ end
159
+ end
160
+ end
161
+
162
+ # Set a Stripe coupon code that will be used when a new Stripe customer (a.k.a. Koudoku subscription)
163
+ # is created
164
+ def coupon_code=(new_code)
165
+ @coupon_code = new_code
166
+ end
167
+
168
+ # Pretty sure this wouldn't conflict with anything someone would put in their model
169
+ def subscription_owner
170
+ # Return whatever we belong to.
171
+ # If this object doesn't respond to 'name', please update owner_description.
172
+ send Koudoku.subscriptions_owned_by
173
+ end
174
+
175
+ def subscription_owner=(owner)
176
+ # e.g. @subscription.user = @owner
177
+ send Koudoku.owner_assignment_sym, owner
178
+ end
179
+
180
+ def subscription_owner_description
181
+ # assuming owner responds to name.
182
+ # we should check for whether it responds to this or not.
183
+ "#{subscription_owner.try(:name) || subscription_owner.try(:id)}"
184
+ end
185
+
186
+ def subscription_owner_email
187
+ "#{subscription_owner.try(:email)}"
188
+ end
189
+
190
+ def changing_plans?
191
+ plan_id_changed?
192
+ end
193
+
194
+ def downgrading?
195
+ plan.present? and plan_id_was.present? and plan_id_was > self.plan_id
196
+ end
197
+
198
+ def upgrading?
199
+ (plan_id_was.present? and plan_id_was < plan_id) or plan_id_was.nil?
200
+ end
201
+
202
+ # Template methods.
203
+ def prepare_for_plan_change
204
+ end
205
+
206
+ def prepare_for_new_subscription
207
+ end
208
+
209
+ def prepare_for_upgrade
210
+ end
211
+
212
+ def prepare_for_downgrade
213
+ end
214
+
215
+ def prepare_for_cancelation
216
+ end
217
+
218
+ def prepare_for_card_update
219
+ end
220
+
221
+ def finalize_plan_change!
222
+ end
223
+
224
+ def finalize_new_subscription!
225
+ end
226
+
227
+ def finalize_new_customer!(customer_id, amount)
228
+ end
229
+
230
+ def finalize_upgrade!
231
+ end
232
+
233
+ def finalize_downgrade!
234
+ end
235
+
236
+ def finalize_cancelation!
237
+ end
238
+
239
+ def finalize_card_update!
240
+ end
241
+
242
+ def card_was_declined
243
+ end
244
+
245
+ # stripe web-hook callbacks.
246
+ def payment_succeeded(amount)
247
+ end
248
+
249
+ def charge_failed
250
+ end
251
+
252
+ def charge_disputed
253
+ end
254
+
255
+ end