subscriptions_pulse 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0a4f14b9517eeecac1f59f1f209cc156c28c3c971900778d8464c9286c0b36c2
4
+ data.tar.gz: b4443c9113f17abf610f760d81259b0643e44fdadb8522c43ed4fcafda901cb4
5
+ SHA512:
6
+ metadata.gz: 2031e133efaba1cb175501d59a8f9c18af034e5d099b68cab4f4f78d009996fd33efd1247e0ed1eabcaca3015b9c2cc6d8a898609d00447728459b4a72c451f1
7
+ data.tar.gz: 33a822bc7054626359b327cebd111817c32188ae93c4cbfdcd5e308e5c9a581eddba694cb18d2ff72fe4b47fee245d216cce338b355cf117f3156d376f40163c
data/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ ## [0.1.0] - 2026-11-28
2
+
3
+ - Add `SubscriptionsPulse.calculate`, which calculates the new, expanded, reactivated, churned, and contracted revenue and customers
4
+ of a Stripe account for the current and previous months.
5
+ Revenue is grouped by currency, in each currency's smallest unit (e.g. cents).
6
+ - Declare `stripe` as a runtime dependency so it's installed with the gem.
7
+ - Add PayPal: `SubscriptionsPulse.calculate(paypal: { client_id: "...", client_secret: "...", sandbox: false })` calculates the same statistics
8
+ from PayPal subscriptions and their payments
9
+ (`sandbox: true` for sandbox credentials; optional, live by default).
10
+ - Declare `paypal-server-sdk` and `base64` (which the PayPal SDK needs on Ruby 4.0) as runtime dependencies.
11
+ - Count only billed Stripe revenue: draft invoices and pending (not yet invoiced) prorations are no longer counted.
12
+ - Return PayPal HUF and TWD revenue in hundredths, like Stripe's, instead of whole units.
13
+ - Raise `SubscriptionsPulse::Error` when `SubscriptionsPulse.calculate` gets no payment processor, instead of returning `{}`.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mário Marroquim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # Subscriptions Pulse
2
+
3
+ This Ruby gem calculates monthly statistics for your Stripe and PayPal subscriptions. This is a work in progress.
4
+
5
+ ## Instructions
6
+
7
+ Requires Ruby 4.0 or later. The `stripe` and `paypal-server-sdk` gems are installed as dependencies.
8
+
9
+ **1 - Add the gem to your Rails application's Gemfile:**
10
+
11
+ ```bash
12
+ bundle add subscriptions_pulse
13
+ ```
14
+
15
+ **2 - Install the gem by running:**
16
+
17
+ ```bash
18
+ bundle install
19
+ ```
20
+
21
+ ## Usage examples
22
+
23
+ ```ruby
24
+ SubscriptionsPulse.calculate(
25
+ stripe: { api_key: "sk_live_..." },
26
+ paypal: { client_id: "...", client_secret: "...", sandbox: false }
27
+ )
28
+ # => {
29
+ # stripe: {
30
+ # current_month: {
31
+ # revenue: {
32
+ # usd: { new: 1000, expanded: 2000, reactivated: 0, churned: 1000, contracted: 0 }
33
+ # },
34
+ # customers: { new: 1, expanded: 1, reactivated: 0, churned: 1, contracted: 0 }
35
+ # },
36
+ # previous_month: { ... }
37
+ # },
38
+ # paypal: { current_month: { ... }, previous_month: { ... } }
39
+ # }
40
+ ```
41
+
42
+ Pass only the payment processors you use (at least one); the result has only those.
43
+ Revenue is grouped by currency and comes in the currency's smallest unit, like Stripe's amounts:
44
+ `usd: { new: 1000 }` means $10.00 of new monthly recurring revenue.
45
+ Only revenue that was billed counts, paid or not: free trials and subscriptions that were never billed don't show up.
46
+
47
+ - **Stripe:** a restricted API key with read access is enough.
48
+ - **PayPal:** use the client ID and secret of a REST app from the PayPal Developer Dashboard.
49
+ Set `sandbox: true` for sandbox credentials; it's optional and defaults to `false` (live).
50
+
51
+ ## Support
52
+
53
+ You can contact me at [mariomarroquim@gmail.com](mailto:mariomarroquim@gmail.com).
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SubscriptionsPulse
4
+ # Classifies monthly recurring revenue (MRR) movements for a period, independently of the payment processor.
5
+ #
6
+ # Input is a list of Segments, which add (or, when negative, remove) MRR to a customer during a time interval.
7
+ #
8
+ # Revenue is grouped by currency (lowercase symbols, e.g. :usd) and rounded to whole units. Amounts in
9
+ # different currencies can't be compared, so a customer is classified separately in each of its currencies;
10
+ # customer counts add those up.
11
+ #
12
+ # For each customer, the MRR at the start of the period is compared with the MRR at its end:
13
+ # - new: no MRR at the start, MRR at the end, and no MRR ever before the period.
14
+ # - reactivated: no MRR at the start, MRR at the end, and some MRR before the period.
15
+ # - expanded / contracted: MRR at both ends, higher / lower at the end.
16
+ # - churned: MRR at the start, none at the end.
17
+ class Movements
18
+ TYPES = %i[new expanded reactivated churned contracted].freeze
19
+
20
+ def initialize(segments)
21
+ @segments_by_customer = segments.group_by { [it.customer, it.currency.to_s.downcase.to_sym] }
22
+ @currencies = @segments_by_customer.keys.map(&:last).uniq.sort
23
+ end
24
+
25
+ # Statistics for the month containing `now` (until `now`) and for the month before it, in UTC.
26
+ def by_month(now)
27
+ current_month = Time.utc(now.year, now.month)
28
+ previous_month = (current_month - 1).then { Time.utc(it.year, it.month) }
29
+
30
+ {
31
+ current_month: for_period(current_month.to_i, now.to_i),
32
+ previous_month: for_period(previous_month.to_i, current_month.to_i)
33
+ }
34
+ end
35
+
36
+ private
37
+
38
+ def for_period(from, to)
39
+ revenue = @currencies.to_h { [it, TYPES.to_h { [it, 0r] }] }
40
+ customers = TYPES.to_h { [it, 0] }
41
+
42
+ @segments_by_customer.each do |(_customer, currency), segments|
43
+ type, amount = classify(segments, from, mrr_at(segments, from), mrr_at(segments, to))
44
+ next unless type
45
+
46
+ revenue[currency][type] += amount
47
+ customers[type] += 1
48
+ end
49
+
50
+ { revenue: revenue.transform_values { it.transform_values(&:round) }, customers: customers }
51
+ end
52
+
53
+ def classify(segments, from, before, after)
54
+ if before.zero?
55
+ return unless after.positive?
56
+
57
+ [earlier_revenue?(segments, from) ? :reactivated : :new, after]
58
+ elsif after.zero?
59
+ [:churned, before]
60
+ elsif after > before
61
+ [:expanded, after - before]
62
+ elsif after < before
63
+ [:contracted, before - after]
64
+ end
65
+ end
66
+
67
+ def mrr_at(segments, time)
68
+ total = segments.sum(0r) { it.starts_at <= time && time < it.ends_at ? it.mrr : 0 }
69
+ total.positive? ? total : 0r
70
+ end
71
+
72
+ def earlier_revenue?(segments, time)
73
+ segments.any? { it.mrr.positive? && it.starts_at < time }
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,279 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64" # Needed by paypal-server-sdk, but no longer a default gem since Ruby 3.4.
4
+ require "date"
5
+ require "time"
6
+ require "paypal_server_sdk"
7
+
8
+ module SubscriptionsPulse
9
+ module Processors
10
+ # Everything specific to PayPal: turns a PayPal account into MRR Segments.
11
+ #
12
+ # MRR history is rebuilt from each subscription's payments (only what was billed counts):
13
+ # - Each payment that wasn't declined adds its amount, without taxes, shipping, or the setup fee, to the
14
+ # subscriber during the billing cycle it paid for, following the plan's billing cycles (free trials included).
15
+ # - Changes (quantity or plan) apply from the next billing cycle on, as PayPal bills them.
16
+ # - Everything a subscription contributes stops when it's cancelled, suspended, or expired.
17
+ module Paypal
18
+ MAX_RETRIES = 5
19
+
20
+ # Runs a PayPal request, retrying with exponential backoff when PayPal rate-limits it, fails on its side
21
+ # (5xx), or the connection fails.
22
+ def self.with_retries
23
+ attempts = 0
24
+ begin
25
+ yield
26
+ rescue PaypalServerSdk::APIException, Faraday::ConnectionFailed, Faraday::TimeoutError => e
27
+ attempts += 1
28
+ raise if attempts > MAX_RETRIES || !retryable?(e)
29
+
30
+ sleep((2**(attempts - 1)) + rand)
31
+ retry
32
+ end
33
+ end
34
+
35
+ def self.retryable?(error)
36
+ return true unless error.is_a?(PaypalServerSdk::APIException)
37
+
38
+ error.response_code == 429 || error.response_code.to_i >= 500
39
+ end
40
+ private_class_method :retryable?
41
+
42
+ # Fetches the account's subscriptions, their plans, and their payments.
43
+ class Processor
44
+ PAGE_SIZE = 20 # The most PayPal accepts for subscriptions.
45
+ # Every status the subscription list accepts. Subscriptions waiting for the buyer's approval are never
46
+ # listed, and never billed.
47
+ LISTED_STATUSES = "ACTIVE,SUSPENDED,CANCELLED,EXPIRED"
48
+ UNBILLED_STATUSES = %w[APPROVAL_PENDING APPROVED].freeze
49
+ DAY = 86_400
50
+
51
+ # client_id, client_secret: credentials of a REST app; sandbox: true for sandbox credentials.
52
+ def initialize(client_id:, client_secret:, sandbox: false)
53
+ raise Error, "Missing PayPal client ID or secret" if client_id.to_s.empty? || client_secret.to_s.empty?
54
+
55
+ @client = PaypalServerSdk::Client.new(
56
+ client_credentials_auth_credentials: PaypalServerSdk::ClientCredentialsAuthCredentials.new(
57
+ o_auth_client_id: client_id, o_auth_client_secret: client_secret
58
+ ),
59
+ environment: sandbox ? PaypalServerSdk::Environment::SANDBOX : PaypalServerSdk::Environment::PRODUCTION
60
+ )
61
+ end
62
+
63
+ def segments
64
+ now = Time.now.utc
65
+ subscriptions = list_subscriptions
66
+ plans = subscriptions.map(&:plan_id).uniq.to_h { [it, plan(it)] }
67
+
68
+ subscriptions.flat_map do |subscription|
69
+ next [] if UNBILLED_STATUSES.include?(subscription.status)
70
+
71
+ Segments.new(subscription, plans.fetch(subscription.plan_id)).build(payments(subscription, now))
72
+ end
73
+ end
74
+
75
+ private
76
+
77
+ def list_subscriptions
78
+ (1..).each_with_object([]) do |page, results|
79
+ batch = request do
80
+ @client.subscriptions.list_subscriptions(
81
+ "statuses" => LISTED_STATUSES, "page_size" => PAGE_SIZE, "page" => page
82
+ )
83
+ end.subscriptions || []
84
+ results.concat(batch)
85
+ break results if batch.size < PAGE_SIZE
86
+ end
87
+ end
88
+
89
+ def plan(id)
90
+ request { @client.subscriptions.get_billing_plan(id) }
91
+ end
92
+
93
+ # Every payment of the subscription, from a day before it was created until now.
94
+ def payments(subscription, now)
95
+ created_at = Time.iso8601(subscription.create_time || subscription.start_time)
96
+ transactions(subscription.id, created_at - DAY, now).uniq(&:id)
97
+ end
98
+
99
+ # Transactions can't be paged, so a range with more than one page is split in two.
100
+ def transactions(id, from, to)
101
+ list = transactions_page(id, from, to)
102
+ return list.transactions || [] if (list.total_pages || 1) <= 1 || to - from < 2
103
+
104
+ middle = from + ((to - from) / 2).floor
105
+ transactions(id, from, middle) + transactions(id, middle, to)
106
+ end
107
+
108
+ def transactions_page(id, from, to)
109
+ request do
110
+ @client.subscriptions.list_subscription_transactions(
111
+ "id" => id, "start_time" => from.utc.iso8601, "end_time" => to.utc.iso8601
112
+ )
113
+ end
114
+ end
115
+
116
+ def request(&) = Paypal.with_retries(&).data
117
+ end
118
+
119
+ # Converts a subscription's payments into Segments, one per billing cycle paid for.
120
+ class Segments
121
+ # Months in one billing interval of each unit, to normalize amounts to a month.
122
+ MONTHS_PER_INTERVAL = {
123
+ "DAY" => Rational(12, 365), "WEEK" => Rational(12, 52), "MONTH" => 1r, "YEAR" => 12r
124
+ }.freeze
125
+ # Currencies without a smallest unit below the main one, like Stripe's; all others are in hundredths.
126
+ # PayPal formats HUF and TWD without decimals, but Stripe counts them in hundredths, so they are here too.
127
+ ZERO_DECIMAL_CURRENCIES = %w[JPY].freeze
128
+ # Statuses that stop a subscription's MRR at its last status change.
129
+ ENDED_STATUSES = %w[CANCELLED SUSPENDED EXPIRED].freeze
130
+
131
+ def self.time(iso8601) = Time.iso8601(iso8601).to_i
132
+
133
+ def initialize(subscription, plan)
134
+ @customer = customer_id(subscription)
135
+ @ended_at = Segments.time(subscription.status_update_time) if ENDED_STATUSES.include?(subscription.status)
136
+ @schedule = Schedule.new(plan, Segments.time(subscription.start_time || subscription.create_time))
137
+ @setup_fee = plan.payment_preferences&.setup_fee
138
+ end
139
+
140
+ # Payments are matched with the plan's paid billing cycles in order, starting when the subscription started.
141
+ def build(transactions)
142
+ segments = billed(transactions).each_with_object([]) do |payment, result|
143
+ amount = recurring_amount(payment)
144
+ next unless amount.positive?
145
+
146
+ period = @schedule.next_period(Segments.time(payment.time))
147
+ break result unless period # Every cycle of the plan was paid for already.
148
+
149
+ result << segment(payment, amount, *period)
150
+ end
151
+ segments.compact
152
+ end
153
+
154
+ private
155
+
156
+ # The payer's PayPal account, or else their email, or else the subscription (e.g. paid with a card).
157
+ def customer_id(subscription)
158
+ subscriber = subscription.subscriber
159
+ subscriber&.payer_id || subscriber&.email_address || subscription.id
160
+ end
161
+
162
+ def billed(transactions)
163
+ transactions.reject { it.status == "DECLINED" }.sort_by { Segments.time(it.time) }
164
+ end
165
+
166
+ # The amount paid for the subscription itself: without taxes and shipping, and without the setup fee, which
167
+ # comes with the first payment (or alone, leaving nothing).
168
+ def recurring_amount(payment)
169
+ breakdown = payment.amount_with_breakdown
170
+ amount = minor_units(breakdown.gross_amount) - minor_units(breakdown.tax_amount) -
171
+ minor_units(breakdown.shipping_amount)
172
+ setup_fee = @setup_fee
173
+ @setup_fee = nil
174
+ setup_fee&.currency_code&.downcase == currency(payment) ? amount - minor_units(setup_fee) : amount
175
+ end
176
+
177
+ def segment(payment, amount, starts_at, ends_at, frequency)
178
+ ends_at = [ends_at, @ended_at].compact.min
179
+ months = MONTHS_PER_INTERVAL[frequency.interval_unit]
180
+ return unless months && ends_at > starts_at
181
+
182
+ Segment.new(
183
+ customer: @customer, currency: currency(payment), starts_at: starts_at, ends_at: ends_at,
184
+ mrr: amount / (months * Schedule.count(frequency))
185
+ )
186
+ end
187
+
188
+ def currency(payment)
189
+ payment.amount_with_breakdown.gross_amount.currency_code.downcase
190
+ end
191
+
192
+ def minor_units(money)
193
+ return 0r unless money
194
+
195
+ money.value.to_r * (ZERO_DECIMAL_CURRENCIES.include?(money.currency_code.upcase) ? 1 : 100)
196
+ end
197
+ end
198
+
199
+ # Walks a plan's billing cycles from when a subscription started, to tell which period each payment paid for.
200
+ class Schedule
201
+ def self.count(frequency) = frequency.interval_count.to_i.clamp(1..)
202
+
203
+ DAY = 86_400
204
+
205
+ # The time one billing interval after `from`; months and years follow the calendar.
206
+ def self.advance(from, frequency)
207
+ count = count(frequency)
208
+ case frequency.interval_unit
209
+ when "DAY" then from + (count * DAY)
210
+ when "WEEK" then from + (count * 7 * DAY)
211
+ when "YEAR" then add_months(from, 12 * count)
212
+ else add_months(from, count)
213
+ end
214
+ end
215
+
216
+ # Date#>> keeps the day of the month, or uses the month's last day when it's shorter.
217
+ def self.add_months(from, months)
218
+ date = Time.at(from).utc.to_date
219
+ from + (((date >> months) - date).to_i * DAY)
220
+ end
221
+
222
+ def initialize(plan, starts_at)
223
+ @cycles = cycles(plan.billing_cycles.sort_by(&:sequence))
224
+ @cursor = starts_at
225
+ end
226
+
227
+ # [starts_at, ends_at, frequency] of the next cycle with a price, after skipping free cycles (trials); nil
228
+ # after the plan's last cycle. When billing resumed later than scheduled (e.g. reactivated after a
229
+ # suspension), the cycle starts with the payment instead.
230
+ def next_period(paid_at)
231
+ while (cycle = following)
232
+ frequency = cycle.frequency
233
+ return period(paid_at, frequency) unless free?(cycle)
234
+
235
+ @cursor = Schedule.advance(@cursor, frequency)
236
+ end
237
+ end
238
+
239
+ private
240
+
241
+ def period(paid_at, frequency)
242
+ @cursor = paid_at if paid_at >= Schedule.advance(@cursor, frequency)
243
+ starts_at = @cursor
244
+ @cursor = Schedule.advance(starts_at, frequency)
245
+ [starts_at, @cursor, frequency]
246
+ end
247
+
248
+ # Each cycle repeated as many times as it runs (regular cycles without a limit repeat forever).
249
+ def cycles(billing_cycles)
250
+ Enumerator.new do |yielder|
251
+ billing_cycles.each do |cycle|
252
+ if cycle.total_cycles.to_i.zero?
253
+ loop { yielder << cycle }
254
+ else
255
+ cycle.total_cycles.times { yielder << cycle }
256
+ end
257
+ end
258
+ end
259
+ end
260
+
261
+ # Kernel#loop would swallow the end of the cycles, so this returns nil instead.
262
+ def following
263
+ @cycles.next
264
+ rescue StopIteration
265
+ nil
266
+ end
267
+
268
+ # Free trials have no pricing scheme or a zero fixed price; tiered and volume prices have tiers instead.
269
+ def free?(cycle)
270
+ scheme = cycle.pricing_scheme
271
+ return true unless scheme
272
+ return scheme.fixed_price.value.to_r.zero? if scheme.fixed_price
273
+
274
+ Array(scheme.tiers).empty?
275
+ end
276
+ end
277
+ end
278
+ end
279
+ end
@@ -0,0 +1,172 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "stripe"
4
+
5
+ module SubscriptionsPulse
6
+ module Processors
7
+ # Everything specific to Stripe: turns a Stripe account into MRR Segments.
8
+ #
9
+ # MRR history is rebuilt from billed invoices (finalized: open, paid, or uncollectible), which Stripe keeps for good
10
+ # (events expire after 30 days):
11
+ # - Each subscription invoice line adds its price's monthly amount to the customer during the line's period.
12
+ # - Invoiced proration lines add or remove the prorated price from the time of the change, so upgrades and
13
+ # downgrades count once they're billed.
14
+ # - Everything a subscription contributes stops when the subscription ends.
15
+ module Stripe
16
+ MAX_RETRIES = 5
17
+
18
+ # Runs a Stripe request, retrying with exponential backoff when Stripe rate-limits it or the connection fails.
19
+ def self.with_retries
20
+ attempts = 0
21
+ begin
22
+ yield
23
+ rescue ::Stripe::RateLimitError, ::Stripe::APIConnectionError
24
+ attempts += 1
25
+ raise if attempts > MAX_RETRIES
26
+
27
+ sleep((2**(attempts - 1)) + rand)
28
+ retry
29
+ end
30
+ end
31
+
32
+ # Fetches the account's prices, subscriptions, and billed invoices.
33
+ class Processor
34
+ PAGE_SIZE = 100
35
+ # Invoices that weren't billed: drafts aren't finalized yet, and void ones were cancelled.
36
+ UNBILLED_STATUSES = %w[draft void].freeze
37
+
38
+ # api_key: secret or restricted (read-only) key.
39
+ def initialize(api_key:)
40
+ raise Error, "Missing Stripe API key" if api_key.to_s.empty?
41
+
42
+ @client = ::Stripe::StripeClient.new(api_key)
43
+ end
44
+
45
+ def segments
46
+ entries = invoice_entries
47
+ converter = Segments.new(
48
+ prices: prices(entries.map { it[2] }),
49
+ subscriptions: list_all(@client.v1.subscriptions, status: "all")
50
+ )
51
+
52
+ entries.filter_map { converter.segment(*it) }
53
+ end
54
+
55
+ private
56
+
57
+ # Recurring prices, plus the ones of the items missing from the list: inline prices (created with
58
+ # `price_data`) are archived and hidden from it.
59
+ def prices(items)
60
+ listed = list_all(@client.v1.prices, type: "recurring")
61
+ missing = items.filter_map { Segments.price_id(it) }.uniq - listed.map(&:id)
62
+ listed + missing.map { |id| Stripe.with_retries { @client.v1.prices.retrieve(id) } }
63
+ end
64
+
65
+ # [customer, subscription, line, proration?] for subscription lines and proration lines of billed invoices.
66
+ def invoice_entries
67
+ list_all(@client.v1.invoices, {}).reject { UNBILLED_STATUSES.include?(it.status) }.flat_map do |invoice|
68
+ invoice_lines(invoice).filter_map do |line|
69
+ details = Segments.subscription_details(line)
70
+ [invoice.customer, details.subscription, line, details.proration] if details
71
+ end
72
+ end
73
+ end
74
+
75
+ def invoice_lines(invoice)
76
+ return invoice.lines.data unless invoice.lines.has_more
77
+
78
+ list_all(@client.v1.invoices.line_items, {}, invoice.id)
79
+ end
80
+
81
+ def list_all(service, params, *)
82
+ results = []
83
+ starting_after = nil
84
+
85
+ loop do
86
+ page_params = params.merge(limit: PAGE_SIZE, starting_after: starting_after).compact
87
+ page = Stripe.with_retries { service.list(*, page_params) }
88
+ results.concat(page.data)
89
+ break unless page.has_more && page.data.any?
90
+
91
+ starting_after = page.data.last.id
92
+ end
93
+
94
+ results
95
+ end
96
+ end
97
+
98
+ # Converts invoice lines into Segments.
99
+ class Segments
100
+ # Months in one billing interval of each type, to normalize prices to a monthly amount.
101
+ MONTHS_PER_INTERVAL = {
102
+ "day" => Rational(12, 365), "week" => Rational(12, 52), "month" => 1r, "year" => 12r
103
+ }.freeze
104
+
105
+ # The subscription details of an invoice line that is a subscription charge or a subscription proration.
106
+ def self.subscription_details(line)
107
+ parent = line.parent
108
+ return unless parent
109
+
110
+ details = parent.subscription_item_details if parent.type == "subscription_item_details"
111
+ details ||= proration_details(parent)
112
+ details if details&.subscription
113
+ end
114
+
115
+ def self.proration_details(parent)
116
+ parent.invoice_item_details if parent.type == "invoice_item_details" && parent.invoice_item_details&.proration
117
+ end
118
+ private_class_method :proration_details
119
+
120
+ # The price of an invoice line.
121
+ def self.price_id(item)
122
+ item.pricing&.price_details&.price
123
+ end
124
+
125
+ def initialize(prices:, subscriptions:)
126
+ @prices = prices.to_h { [it.id, it] }
127
+ @ended_at = subscriptions.to_h { [it.id, it.ended_at] }
128
+ end
129
+
130
+ # item: an invoice line; a negative amount removes MRR (e.g. unused time after a change).
131
+ def segment(customer, subscription, item, proration)
132
+ price = recurring_price(item)
133
+ return if price.nil? || item.amount.zero?
134
+
135
+ amount = full_period_amount(item, proration, price)
136
+ period = active_period(item, subscription)
137
+ return unless amount && period
138
+
139
+ mrr = monthly(amount, price.recurring) * (item.amount <=> 0)
140
+ Segment.new(
141
+ customer: customer, currency: item.currency, starts_at: period.first, ends_at: period.last, mrr: mrr
142
+ )
143
+ end
144
+
145
+ private
146
+
147
+ def recurring_price(item)
148
+ price = @prices[self.class.price_id(item)]
149
+ price if price&.recurring
150
+ end
151
+
152
+ # The amount of a whole billing interval; prorated lines of prices without a unit amount (tiered) are skipped.
153
+ def full_period_amount(item, proration, price)
154
+ return price.unit_amount_decimal.to_r * (item.quantity || 1) if price.unit_amount_decimal
155
+
156
+ item.amount.abs.to_r unless proration
157
+ end
158
+
159
+ # The item's period, cut short when the subscription ended earlier.
160
+ def active_period(item, subscription)
161
+ starts_at = item.period.start
162
+ ends_at = [item.period.end, @ended_at[subscription]].compact.min
163
+ [starts_at, ends_at] if ends_at > starts_at
164
+ end
165
+
166
+ def monthly(amount, recurring)
167
+ amount / (MONTHS_PER_INTERVAL.fetch(recurring.interval) * recurring.interval_count)
168
+ end
169
+ end
170
+ end
171
+ end
172
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SubscriptionsPulse
4
+ # A piece of a customer's monthly recurring revenue (MRR): what payment processors produce and Movements reads.
5
+ #
6
+ # - customer: the customer's ID in the payment processor.
7
+ # - currency: ISO currency code, e.g. "usd" (any case).
8
+ # - starts_at, ends_at: Unix timestamps of the half-open interval [starts_at, ends_at) when the MRR applies.
9
+ # - mrr: Rational amount per month in the currency's smallest unit (e.g. cents); negative to remove MRR.
10
+ Segment = Data.define(:customer, :currency, :starts_at, :ends_at, :mrr)
11
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SubscriptionsPulse
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "subscriptions_pulse/version"
4
+ require_relative "subscriptions_pulse/segment"
5
+ require_relative "subscriptions_pulse/movements"
6
+ require_relative "subscriptions_pulse/processors/stripe"
7
+ require_relative "subscriptions_pulse/processors/paypal"
8
+
9
+ # Monthly statistics (new, expanded, reactivated, churned, and contracted revenue and customers) for
10
+ # subscriptions of payment processors.
11
+ module SubscriptionsPulse
12
+ class Error < StandardError; end
13
+ # Your code goes here...
14
+
15
+ # Each payment processor turns its options (e.g. API keys) into Segments: `Class.new(**options).segments`.
16
+ PROCESSORS = { stripe: Processors::Stripe::Processor, paypal: Processors::Paypal::Processor }.freeze
17
+
18
+ # Calculates the monthly statistics of each payment processor in the input, e.g.
19
+ # SubscriptionsPulse.calculate(
20
+ # stripe: { api_key: "sk_..." },
21
+ # paypal: { client_id: "...", client_secret: "...", sandbox: false }
22
+ # ). Only the payment processors in the input are calculated, and at least one is required.
23
+ def self.calculate(processors)
24
+ raise Error, "No payment processor given" if processors.nil? || processors.empty?
25
+
26
+ now = Time.now.utc
27
+
28
+ processors.to_h do |name, options|
29
+ processor = PROCESSORS.fetch(name) { raise Error, "Unsupported payment processor: #{name}" }
30
+ [name, Movements.new(processor.new(**options).segments).by_month(now)]
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,99 @@
1
+ module SubscriptionsPulse
2
+ VERSION: String
3
+
4
+ class Error < StandardError
5
+ end
6
+
7
+ # What every payment processor implements: built with its options (e.g. API keys), it returns MRR segments.
8
+ interface _Processor
9
+ def segments: () -> Array[Segment]
10
+ end
11
+
12
+ PROCESSORS: Hash[Symbol, untyped]
13
+
14
+ def self.calculate: (Hash[Symbol, Hash[Symbol, untyped]]? processors) -> Hash[Symbol, Hash[Symbol, untyped]]
15
+
16
+ class Segment
17
+ attr_reader customer: String
18
+ attr_reader currency: String
19
+ attr_reader starts_at: Integer
20
+ attr_reader ends_at: Integer
21
+ attr_reader mrr: Rational
22
+
23
+ def initialize: (customer: String, currency: String, starts_at: Integer, ends_at: Integer, mrr: Rational) -> void
24
+ end
25
+
26
+ class Movements
27
+ TYPES: Array[Symbol]
28
+
29
+ def initialize: (Array[Segment] segments) -> void
30
+ def by_month: (Time now) -> Hash[Symbol, untyped]
31
+ end
32
+
33
+ module Processors
34
+ module Stripe
35
+ MAX_RETRIES: Integer
36
+
37
+ def self.with_retries: [T] () { () -> T } -> T
38
+
39
+ class Processor
40
+ include _Processor
41
+
42
+ PAGE_SIZE: Integer
43
+ UNBILLED_STATUSES: Array[String]
44
+
45
+ def initialize: (api_key: String?) -> void
46
+ def segments: () -> Array[Segment]
47
+ end
48
+
49
+ class Segments
50
+ MONTHS_PER_INTERVAL: Hash[String, Rational]
51
+
52
+ def self.subscription_details: (untyped line) -> untyped
53
+ def self.price_id: (untyped item) -> String?
54
+ def initialize: (prices: Array[untyped], subscriptions: Array[untyped]) -> void
55
+ def segment: (String customer, String subscription, untyped item, bool proration) -> Segment?
56
+ end
57
+ end
58
+
59
+ module Paypal
60
+ MAX_RETRIES: Integer
61
+
62
+ def self.with_retries: [T] () { () -> T } -> T
63
+
64
+ class Processor
65
+ include _Processor
66
+
67
+ PAGE_SIZE: Integer
68
+ LISTED_STATUSES: String
69
+ UNBILLED_STATUSES: Array[String]
70
+ DAY: Integer
71
+
72
+ def initialize: (client_id: String?, client_secret: String?, ?sandbox: bool) -> void
73
+ def segments: () -> Array[Segment]
74
+ end
75
+
76
+ class Segments
77
+ MONTHS_PER_INTERVAL: Hash[String, Rational]
78
+ ZERO_DECIMAL_CURRENCIES: Array[String]
79
+ ENDED_STATUSES: Array[String]
80
+
81
+ def self.time: (String iso8601) -> Integer
82
+ def initialize: (untyped subscription, untyped plan) -> void
83
+ def build: (Array[untyped] transactions) -> Array[Segment]
84
+ end
85
+
86
+ class Schedule
87
+ DAY: Integer
88
+
89
+ def self.count: (untyped frequency) -> Integer
90
+ def self.advance: (Integer from, untyped frequency) -> Integer
91
+ def self.add_months: (Integer from, Integer months) -> Integer
92
+ def initialize: (untyped plan, Integer starts_at) -> void
93
+ def next_period: (Integer paid_at) -> [Integer, Integer, untyped]?
94
+ end
95
+ end
96
+ end
97
+
98
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
99
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: subscriptions_pulse
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mário Marroquim
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: base64
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ -
17
+ - ~>
18
+ - !ruby/object:Gem::Version
19
+ version: "0.3"
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ -
25
+ - ~>
26
+ - !ruby/object:Gem::Version
27
+ version: "0.3"
28
+ - !ruby/object:Gem::Dependency
29
+ name: paypal-server-sdk
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ -
33
+ - ~>
34
+ - !ruby/object:Gem::Version
35
+ version: "2.4"
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ -
41
+ - ~>
42
+ - !ruby/object:Gem::Version
43
+ version: "2.4"
44
+ - !ruby/object:Gem::Dependency
45
+ name: stripe
46
+ requirement: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ -
49
+ - ~>
50
+ - !ruby/object:Gem::Version
51
+ version: "21.1"
52
+ type: :runtime
53
+ prerelease: false
54
+ version_requirements: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ -
57
+ - ~>
58
+ - !ruby/object:Gem::Version
59
+ version: "21.1"
60
+ description: "Calculates monthly statistics for Stripe and PayPal subscriptions: new, expanded, reactivated, churned, and contracted revenue and customers, by payment processor for the current and previous months."
61
+ email:
62
+ - mariomarroquim@gmail.com
63
+ executables: []
64
+ extensions: []
65
+ extra_rdoc_files: []
66
+ files:
67
+ - CHANGELOG.md
68
+ - LICENSE.txt
69
+ - README.md
70
+ - lib/subscriptions_pulse.rb
71
+ - lib/subscriptions_pulse/movements.rb
72
+ - lib/subscriptions_pulse/processors/paypal.rb
73
+ - lib/subscriptions_pulse/processors/stripe.rb
74
+ - lib/subscriptions_pulse/segment.rb
75
+ - lib/subscriptions_pulse/version.rb
76
+ - sig/subscriptions_pulse.rbs
77
+ homepage: "https://github.com/mariomarroquim/subscriptions_pulse"
78
+ licenses:
79
+ - MIT
80
+ metadata:
81
+ allowed_push_host: "https://rubygems.org"
82
+ homepage_uri: "https://github.com/mariomarroquim/subscriptions_pulse"
83
+ changelog_uri: "https://github.com/mariomarroquim/subscriptions_pulse/blob/main/CHANGELOG.md"
84
+ rubygems_mfa_required: "true"
85
+ rdoc_options: []
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ -
91
+ - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: "4.0"
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ -
97
+ - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: "0"
100
+ requirements: []
101
+ rubygems_version: 4.1.0
102
+ specification_version: 4
103
+ summary: Monthly statistics for Stripe and PayPal subscriptions.
104
+ test_files: []