mollie_pay 0.10.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.
Files changed (74) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +426 -0
  4. data/Rakefile +6 -0
  5. data/app/controllers/mollie_pay/application_controller.rb +4 -0
  6. data/app/controllers/mollie_pay/webhook_events_controller.rb +53 -0
  7. data/app/controllers/mollie_pay/webhooks_controller.rb +20 -0
  8. data/app/jobs/mollie_pay/application_job.rb +24 -0
  9. data/app/jobs/mollie_pay/delete_mollie_customer_job.rb +16 -0
  10. data/app/jobs/mollie_pay/notify_billable_job.rb +17 -0
  11. data/app/jobs/mollie_pay/process_webhook_event_job.rb +39 -0
  12. data/app/jobs/mollie_pay/process_webhook_job.rb +56 -0
  13. data/app/jobs/mollie_pay/refresh_pending_mandate_job.rb +22 -0
  14. data/app/jobs/mollie_pay/sync_chargebacks_job.rb +19 -0
  15. data/app/jobs/mollie_pay/sync_subscription_job.rb +18 -0
  16. data/app/jobs/mollie_pay/sync_subscriptions_job.rb +16 -0
  17. data/app/models/concerns/mollie_pay/has_uuid.rb +19 -0
  18. data/app/models/concerns/mollie_pay/syncable.rb +208 -0
  19. data/app/models/mollie_pay/application_record.rb +45 -0
  20. data/app/models/mollie_pay/billable.rb +445 -0
  21. data/app/models/mollie_pay/chargeback.rb +103 -0
  22. data/app/models/mollie_pay/customer.rb +32 -0
  23. data/app/models/mollie_pay/mandate.rb +113 -0
  24. data/app/models/mollie_pay/payment.rb +241 -0
  25. data/app/models/mollie_pay/refund.rb +61 -0
  26. data/app/models/mollie_pay/sales_invoice.rb +131 -0
  27. data/app/models/mollie_pay/subscription.rb +215 -0
  28. data/config/routes.rb +4 -0
  29. data/db/migrate/20260315142959_create_mollie_pay_customers.rb +9 -0
  30. data/db/migrate/20260315143008_create_mollie_pay_mandates.rb +13 -0
  31. data/db/migrate/20260315143014_create_mollie_pay_subscriptions.rb +15 -0
  32. data/db/migrate/20260315143020_create_mollie_pay_payments.rb +20 -0
  33. data/db/migrate/20260315143026_create_mollie_pay_refunds.rb +14 -0
  34. data/db/migrate/20260315143032_create_mollie_pay_webhook_events.rb +12 -0
  35. data/db/migrate/20260315143040_add_status_indexes_to_mollie_pay.rb +8 -0
  36. data/db/migrate/20260315143050_add_checkout_url_to_mollie_pay_payments.rb +5 -0
  37. data/db/migrate/20260316120000_make_mollie_id_nullable_on_mollie_pay_payments.rb +5 -0
  38. data/db/migrate/20260317100000_make_webhook_event_mollie_id_unique.rb +6 -0
  39. data/db/migrate/20260317194500_add_authorized_at_to_mollie_pay_payments.rb +5 -0
  40. data/db/migrate/20260317194501_add_amount_tracking_to_mollie_pay_payments.rb +9 -0
  41. data/db/migrate/20260318100000_add_name_to_mollie_pay_subscriptions.rb +12 -0
  42. data/db/migrate/20260318110000_drop_mollie_pay_webhook_events.rb +19 -0
  43. data/db/migrate/20260321000001_create_mollie_pay_chargebacks.rb +15 -0
  44. data/db/migrate/20260326000002_create_mollie_pay_sales_invoices.rb +19 -0
  45. data/db/migrate/20261115000001_change_mollie_pay_money_to_decimal.rb +38 -0
  46. data/db/migrate/20261202000001_add_sync_version_to_mollie_pay_tables.rb +13 -0
  47. data/db/migrate/20261202000002_add_created_at_mollie_to_mollie_pay_payments.rb +5 -0
  48. data/db/migrate/20261203000001_add_mandate_to_mollie_pay_payments.rb +6 -0
  49. data/docs/api.md +359 -0
  50. data/docs/mandates.md +340 -0
  51. data/docs/request-signing.md +178 -0
  52. data/docs/testing.md +177 -0
  53. data/docs/tutorial.md +1340 -0
  54. data/docs/webhooks.md +231 -0
  55. data/lib/generators/mollie_pay/install/install_generator.rb +44 -0
  56. data/lib/generators/mollie_pay/install/templates/initializer.rb.tt +12 -0
  57. data/lib/mollie/sales_invoice.rb +124 -0
  58. data/lib/mollie_pay/configuration.rb +101 -0
  59. data/lib/mollie_pay/engine.rb +31 -0
  60. data/lib/mollie_pay/errors.rb +12 -0
  61. data/lib/mollie_pay/request_signature.rb +160 -0
  62. data/lib/mollie_pay/test_fixtures/customer.json +36 -0
  63. data/lib/mollie_pay/test_fixtures/payment.json +40 -0
  64. data/lib/mollie_pay/test_fixtures/payment_billink.json +79 -0
  65. data/lib/mollie_pay/test_fixtures/payment_with_chargebacks.json +72 -0
  66. data/lib/mollie_pay/test_fixtures/refund.json +32 -0
  67. data/lib/mollie_pay/test_fixtures/sales_invoice.json +72 -0
  68. data/lib/mollie_pay/test_fixtures/subscription.json +48 -0
  69. data/lib/mollie_pay/test_helper.rb +576 -0
  70. data/lib/mollie_pay/version.rb +3 -0
  71. data/lib/mollie_pay/webhook_signature.rb +21 -0
  72. data/lib/mollie_pay.rb +182 -0
  73. data/lib/tasks/mollie_pay_tasks.rake +43 -0
  74. metadata +148 -0
@@ -0,0 +1,241 @@
1
+ module MolliePay
2
+ class Payment < ApplicationRecord
3
+ include MolliePay::Syncable
4
+
5
+ STATUSES = %w[ open pending authorized paid failed canceled expired ].freeze
6
+ SEQUENCE_TYPES = %w[ oneoff first recurring ].freeze
7
+ ALLOWED_FROM = {
8
+ "open" => [].freeze,
9
+ "pending" => %w[ open ].freeze,
10
+ "authorized" => %w[ open pending ].freeze,
11
+ "paid" => %w[ open pending authorized ].freeze,
12
+ "failed" => %w[ open pending authorized ].freeze,
13
+ "canceled" => %w[ open pending authorized ].freeze,
14
+ "expired" => %w[ open pending authorized ].freeze
15
+ }.freeze
16
+ TIMESTAMP_COLUMNS = {
17
+ "paid" => :paid_at,
18
+ "authorized" => :authorized_at,
19
+ "failed" => :failed_at,
20
+ "canceled" => :canceled_at,
21
+ "expired" => :expired_at
22
+ }.freeze
23
+ TRACKED_AMOUNT_FIELDS = %i[
24
+ amount_refunded
25
+ amount_remaining
26
+ amount_captured
27
+ amount_charged_back
28
+ ].freeze
29
+
30
+ belongs_to :customer
31
+ belongs_to :subscription, optional: true
32
+ belongs_to :mandate, optional: true
33
+ has_many :refunds, dependent: :destroy
34
+ has_many :chargebacks, dependent: :destroy
35
+
36
+ # amount_remaining uses nil-semantics: nil = "never fetched from Mollie",
37
+ # 0 = "fully captured/refunded". Only populated when Mollie includes the field.
38
+
39
+ validates :mollie_id, uniqueness: true, allow_nil: true
40
+ validates :status, inclusion: { in: STATUSES }
41
+ validates :sequence_type, inclusion: { in: SEQUENCE_TYPES }
42
+ validates :amount, presence: true
43
+ validates :amount, numericality: { greater_than_or_equal_to: 0 }, if: :first_payment?
44
+ validates :amount, numericality: { greater_than: 0 }, unless: :first_payment?
45
+ validate :amount_within_precision
46
+ validates :currency, presence: true
47
+
48
+ scope :paid, -> { where(status: "paid") }
49
+ scope :failed, -> { where(status: "failed") }
50
+ scope :open, -> { where(status: "open") }
51
+ scope :authorized, -> { where(status: "authorized") }
52
+ scope :recurring, -> { where(sequence_type: "recurring") }
53
+ scope :first_payments, -> { where(sequence_type: "first") }
54
+
55
+ def self.record_from_mollie(mp, expected_version: UNTRACKED)
56
+ customer = Customer.includes(:owner).find_by!(mollie_id: mp.customer_id)
57
+ payment = find_or_initialize_by(mollie_id: mp.id)
58
+ previous_amount_charged_back = nil
59
+
60
+ payment, outcome = sync_from_mollie(
61
+ payment,
62
+ target_status: mp.status,
63
+ attributes: mollie_attributes(mp, customer),
64
+ coalesce_attributes: ->(record) {
65
+ mollie_coalesce_attributes(
66
+ mp,
67
+ customer: customer,
68
+ existing_subscription_id: record.subscription_id,
69
+ existing_mandate_id: record.mandate_id
70
+ )
71
+ },
72
+ insert_attributes: -> { insert_redirect_id_attributes(mp) },
73
+ association_attributes: { customer: customer },
74
+ expected_version: expected_version
75
+ ) do |existing|
76
+ previous_amount_charged_back = existing.amount_charged_back
77
+ end
78
+
79
+ case outcome
80
+ when :inserted
81
+ payment.notify_billable(mp, status: mp.status) if mp.status != "open"
82
+ SyncChargebacksJob.perform_later(payment) if payment.amount_charged_back != 0
83
+ when :transitioned
84
+ payment.notify_billable(mp, status: mp.status)
85
+ SyncChargebacksJob.perform_later(payment) if payment.amount_charged_back != previous_amount_charged_back
86
+ when :updated
87
+ Mandate.refresh_pending_from_mollie_payment(payment, mp) if mp.status == "paid" && payment.first_payment?
88
+ SyncChargebacksJob.perform_later(payment) if payment.amount_charged_back != previous_amount_charged_back
89
+ end
90
+
91
+ payment
92
+ end
93
+
94
+ def self.synced_with_mollie?(payment, mp, customer:)
95
+ return false unless STATUSES.include?(mp.status)
96
+ return true if strictly_stale?(payment.status, mp.status)
97
+ return false if payment.status != mp.status
98
+ return false if mp.status == "paid" && payment.first_payment?
99
+
100
+ coalesce = mollie_coalesce_attributes(
101
+ mp,
102
+ customer: customer,
103
+ existing_subscription_id: payment.subscription_id,
104
+ existing_mandate_id: payment.mandate_id
105
+ )
106
+
107
+ attributes_match?(payment, mollie_attributes(mp, customer)) &&
108
+ coalesce_attributes_settled?(payment, coalesce)
109
+ end
110
+
111
+ def notify_billable(mollie_payment = nil, status: self.status)
112
+ billable = customer.owner
113
+
114
+ hook = case status
115
+ when "paid"
116
+ if first_payment?
117
+ Mandate.record_from_mollie_payment(self, mollie_payment)
118
+ :on_mollie_first_payment_paid
119
+ elsif recurring?
120
+ :on_mollie_subscription_charged
121
+ else
122
+ :on_mollie_payment_paid
123
+ end
124
+ when "authorized" then :on_mollie_payment_authorized
125
+ when "failed" then :on_mollie_payment_failed
126
+ when "canceled" then :on_mollie_payment_canceled
127
+ when "expired" then :on_mollie_payment_expired
128
+ end
129
+
130
+ NotifyBillableJob.perform_later(billable, hook, self) if hook
131
+ end
132
+
133
+ def mark_canceled!
134
+ conditional_sync_update!(
135
+ from_status: ALLOWED_FROM.fetch("canceled"),
136
+ attributes: { status: "canceled" },
137
+ coalesce_attributes: { canceled_at: Time.current }
138
+ )
139
+ self
140
+ end
141
+
142
+ def attach_checkout_url!(checkout_url)
143
+ return self if checkout_url.blank?
144
+
145
+ conditional_sync_update!(
146
+ scope: self.class.where(id: id, checkout_url: nil),
147
+ coalesce_attributes: { checkout_url: checkout_url }
148
+ )
149
+ self
150
+ end
151
+
152
+ def attach_mandate!(mandate)
153
+ return self if mandate.nil?
154
+ raise MolliePay::Error, "Mandate must be persisted" unless mandate.persisted?
155
+ raise MolliePay::Error, "Mandate does not belong to this customer" unless mandate.customer_id == customer_id
156
+ return self if mandate_id_in_database == mandate.id
157
+
158
+ conditional_sync_update!(
159
+ scope: self.class.where(id: id, mandate_id: nil),
160
+ coalesce_attributes: { mandate_id: mandate.id }
161
+ )
162
+ self
163
+ end
164
+
165
+ def mollie_record
166
+ Mollie::Payment.get(mollie_id)
167
+ end
168
+
169
+ def paid?
170
+ status == "paid"
171
+ end
172
+
173
+ def failed?
174
+ status == "failed"
175
+ end
176
+
177
+ def first_payment?
178
+ sequence_type == "first"
179
+ end
180
+
181
+ def recurring?
182
+ sequence_type == "recurring"
183
+ end
184
+
185
+ # Mollie expects amount as { currency: "EUR", value: "10.00" }
186
+ def mollie_amount
187
+ MolliePay.mollie_amount(amount, currency: currency)
188
+ end
189
+
190
+ private_class_method def self.mollie_attributes(mp, customer)
191
+ attrs = {
192
+ customer_id: customer.id,
193
+ amount: mollie_value_to_decimal(mp.amount),
194
+ currency: mp.amount.currency,
195
+ sequence_type: mp.sequence_type.presence || "oneoff"
196
+ }
197
+
198
+ TRACKED_AMOUNT_FIELDS.each do |field|
199
+ value = mp.public_send(field)
200
+ attrs[field] = mollie_value_to_decimal(value) if value
201
+ end
202
+
203
+ attrs
204
+ end
205
+
206
+ private_class_method def self.mollie_coalesce_attributes(mp, customer:, existing_subscription_id:, existing_mandate_id:)
207
+ coalesce = {}
208
+
209
+ timestamp_column = TIMESTAMP_COLUMNS[mp.status]
210
+ coalesce[timestamp_column] = Time.current if timestamp_column
211
+
212
+ created_at_mollie = mp.try(:created_at)
213
+ coalesce[:created_at_mollie] = created_at_mollie if created_at_mollie.present?
214
+
215
+ if mp.subscription_id.present? && existing_subscription_id.nil?
216
+ subscription_id = Subscription.where(mollie_id: mp.subscription_id).pick(:id)
217
+ coalesce[:subscription_id] = subscription_id if subscription_id
218
+ end
219
+
220
+ mollie_mandate_id = mp.try(:mandate_id)
221
+ if mollie_mandate_id.present? && existing_mandate_id.nil?
222
+ mandate_id = Mandate.where(customer_id: customer.id, mollie_id: mollie_mandate_id).pick(:id)
223
+ coalesce[:mandate_id] = mandate_id if mandate_id
224
+ end
225
+
226
+ coalesce
227
+ end
228
+
229
+ # Reuse the UUIDv7 Billable#create_mollie_payment embedded in
230
+ # default_redirect_path when a fast webhook inserts the payment first,
231
+ # so checkout returns to the persisted payment's ID.
232
+ private_class_method def self.insert_redirect_id_attributes(mp)
233
+ redirect_payment_id = MolliePay.configuration.payment_id_from_redirect_url(mp.try(:redirect_url))
234
+ if redirect_payment_id && !exists?(id: redirect_payment_id)
235
+ { id: redirect_payment_id }
236
+ else
237
+ {}
238
+ end
239
+ end
240
+ end
241
+ end
@@ -0,0 +1,61 @@
1
+ module MolliePay
2
+ class Refund < ApplicationRecord
3
+ include MolliePay::Syncable
4
+
5
+ STATUSES = %w[ queued pending processing refunded failed canceled ].freeze
6
+ ALLOWED_FROM = {
7
+ "queued" => [].freeze,
8
+ "pending" => %w[ queued ].freeze,
9
+ "processing" => %w[ queued pending ].freeze,
10
+ "refunded" => %w[ queued pending processing ].freeze,
11
+ "failed" => %w[ queued pending processing ].freeze,
12
+ "canceled" => %w[ queued pending processing ].freeze
13
+ }.freeze
14
+
15
+ belongs_to :payment
16
+
17
+ validates :mollie_id, presence: true, uniqueness: true
18
+ validates :status, inclusion: { in: STATUSES }
19
+ validates :amount, presence: true, numericality: { greater_than: 0 }
20
+ validate :amount_within_precision
21
+ validates :currency, presence: true
22
+
23
+ scope :refunded, -> { where(status: "refunded") }
24
+ scope :processing, -> { where(status: "processing") }
25
+
26
+ def self.record_from_mollie(mr)
27
+ payment = Payment.includes(customer: :owner).find_by!(mollie_id: mr.payment_id)
28
+ refund = find_or_initialize_by(mollie_id: mr.id)
29
+
30
+ refund, outcome = sync_from_mollie(
31
+ refund,
32
+ target_status: mr.status,
33
+ attributes: {
34
+ payment_id: payment.id,
35
+ amount: mollie_value_to_decimal(mr.amount),
36
+ currency: mr.amount.currency
37
+ },
38
+ coalesce_attributes: mr.status == "refunded" ? { refunded_at: Time.current } : {},
39
+ association_attributes: { payment: payment }
40
+ )
41
+
42
+ if %i[ inserted transitioned ].include?(outcome) && mr.status == "refunded"
43
+ NotifyBillableJob.perform_later(payment.customer.owner, :on_mollie_refund_processed, refund)
44
+ end
45
+
46
+ refund
47
+ end
48
+
49
+ def mollie_record
50
+ Mollie::Payment::Refund.get(mollie_id, payment_id: payment.mollie_id)
51
+ end
52
+
53
+ def refunded?
54
+ status == "refunded"
55
+ end
56
+
57
+ def mollie_amount
58
+ MolliePay.mollie_amount(amount, currency: currency)
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,131 @@
1
+ module MolliePay
2
+ class SalesInvoice < ApplicationRecord
3
+ include MolliePay::Syncable
4
+
5
+ STATUS_DRAFT = "draft"
6
+ STATUS_ISSUED = "issued"
7
+ STATUS_PAID = "paid"
8
+ STATUS_CANCELED = "cancelled" # Mollie's spelling
9
+
10
+ STATUSES = [
11
+ STATUS_DRAFT, "issuing", STATUS_ISSUED, "pending-payment", STATUS_PAID,
12
+ "overdue", "payment-reversed", STATUS_CANCELED, "expired", "failed"
13
+ ].freeze
14
+
15
+ ISSUED_HOOK_FROM = [ STATUS_DRAFT, "issuing" ].freeze
16
+
17
+ ALLOWED_FROM = {
18
+ STATUS_DRAFT => [].freeze,
19
+ "issuing" => [ STATUS_DRAFT ].freeze,
20
+ STATUS_ISSUED => [ STATUS_DRAFT, "issuing", "pending-payment", "overdue", STATUS_PAID, "payment-reversed" ].freeze,
21
+ "pending-payment" => [ STATUS_DRAFT, "issuing", STATUS_ISSUED, "overdue", STATUS_PAID, "payment-reversed" ].freeze,
22
+ "overdue" => [ STATUS_DRAFT, "issuing", STATUS_ISSUED, "pending-payment", STATUS_PAID, "payment-reversed" ].freeze,
23
+ STATUS_PAID => [ STATUS_DRAFT, "issuing", STATUS_ISSUED, "pending-payment", "overdue", "payment-reversed" ].freeze,
24
+ "payment-reversed" => [ STATUS_DRAFT, "issuing", STATUS_ISSUED, "pending-payment", "overdue", STATUS_PAID ].freeze,
25
+ STATUS_CANCELED => [ STATUS_DRAFT, "issuing", STATUS_ISSUED, "pending-payment", "overdue", STATUS_PAID, "payment-reversed" ].freeze,
26
+ "expired" => [ STATUS_DRAFT, "issuing", STATUS_ISSUED, "pending-payment", "overdue", STATUS_PAID, "payment-reversed" ].freeze,
27
+ "failed" => [ STATUS_DRAFT, "issuing" ].freeze
28
+ }.freeze
29
+
30
+ belongs_to :customer
31
+
32
+ validates :mollie_id, presence: true, uniqueness: true
33
+ validates :status, inclusion: { in: STATUSES }
34
+ validates :amount, numericality: { greater_than: 0 }, allow_nil: true
35
+ validate :amount_within_precision
36
+ validates :currency, presence: true, allow_nil: true
37
+
38
+ scope :draft, -> { where(status: STATUS_DRAFT) }
39
+ scope :issued, -> { where(status: STATUS_ISSUED) }
40
+ scope :paid, -> { where(status: STATUS_PAID) }
41
+ scope :overdue, -> { where(status: STATUS_ISSUED).where("due_at < ?", Time.current) }
42
+
43
+ def self.record_from_mollie(mollie_si, customer, expected_version: UNTRACKED)
44
+ invoice = find_or_initialize_by(mollie_id: mollie_si.id)
45
+ amount = mollie_si.total_amount ? mollie_value_to_decimal(mollie_si.total_amount) : nil
46
+ currency = mollie_si.total_amount&.currency
47
+
48
+ invoice, outcome = sync_from_mollie(
49
+ invoice,
50
+ target_status: mollie_si.status,
51
+ attributes: {
52
+ customer_id: customer.id,
53
+ invoice_number: mollie_si.invoice_number,
54
+ amount: amount,
55
+ currency: currency,
56
+ recipient_identifier: mollie_si.recipient_identifier,
57
+ memo: mollie_si.memo,
58
+ due_at: mollie_si.due_at
59
+ },
60
+ coalesce_attributes: {
61
+ issued_at: mollie_si.issued_at,
62
+ paid_at: mollie_si.paid_at
63
+ },
64
+ association_attributes: { customer: customer },
65
+ expected_version: expected_version,
66
+ transition_groups: transition_groups_for(mollie_si.status)
67
+ )
68
+
69
+ notify_billable(invoice, customer, status: mollie_si.status) if %i[ inserted transitioned ].include?(outcome)
70
+ invoice
71
+ end
72
+
73
+ def mollie_record
74
+ Mollie::SalesInvoice.get(mollie_id)
75
+ end
76
+
77
+ def mark_paid!
78
+ now = Time.current
79
+ updated = conditional_sync_update!(
80
+ from_status: STATUS_ISSUED,
81
+ attributes: { status: STATUS_PAID },
82
+ coalesce_attributes: { paid_at: now },
83
+ now: now
84
+ )
85
+ yield self if updated && block_given?
86
+ self
87
+ end
88
+
89
+ def draft?
90
+ status == STATUS_DRAFT
91
+ end
92
+
93
+ def issued?
94
+ status == STATUS_ISSUED
95
+ end
96
+
97
+ def paid?
98
+ status == STATUS_PAID
99
+ end
100
+
101
+ def canceled?
102
+ status == STATUS_CANCELED
103
+ end
104
+
105
+ # Nil for an invoice that has no amount yet, such as a draft.
106
+ def mollie_amount
107
+ return if amount.nil? || currency.nil?
108
+
109
+ MolliePay.mollie_amount(amount, currency: currency)
110
+ end
111
+
112
+ private_class_method def self.transition_groups_for(status)
113
+ if status == STATUS_ISSUED
114
+ [
115
+ { from: ISSUED_HOOK_FROM, outcome: :transitioned },
116
+ { from: ALLOWED_FROM.fetch(STATUS_ISSUED) - ISSUED_HOOK_FROM, outcome: :transitioned_silently }
117
+ ]
118
+ end
119
+ end
120
+
121
+ private_class_method def self.notify_billable(invoice, customer, status: invoice.status)
122
+ billable = customer.owner
123
+
124
+ if status == STATUS_ISSUED
125
+ NotifyBillableJob.perform_later(billable, :on_mollie_sales_invoice_issued, invoice)
126
+ elsif status == STATUS_PAID
127
+ NotifyBillableJob.perform_later(billable, :on_mollie_sales_invoice_paid, invoice)
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,215 @@
1
+ module MolliePay
2
+ class Subscription < ApplicationRecord
3
+ include MolliePay::Syncable
4
+
5
+ STATUSES = %w[ pending active suspended canceled completed ].freeze
6
+ ACTIVE_STATUSES = %w[ pending active ].freeze
7
+ PAYMENT_PAGE_LIMIT = 250
8
+ MAX_PAYMENT_SYNC_ATTEMPTS = 3
9
+ ALLOWED_FROM = {
10
+ "pending" => [].freeze,
11
+ "active" => %w[ pending suspended ].freeze,
12
+ "suspended" => %w[ pending active ].freeze,
13
+ "canceled" => %w[ pending active suspended ].freeze,
14
+ "completed" => %w[ pending active suspended ].freeze
15
+ }.freeze
16
+
17
+ belongs_to :customer
18
+ has_many :payments, dependent: :nullify
19
+
20
+ validates :mollie_id, presence: true, uniqueness: true
21
+ validates :status, inclusion: { in: STATUSES }
22
+ validates :amount, presence: true, numericality: { greater_than: 0 }
23
+ validate :amount_within_precision
24
+ validates :currency, presence: true
25
+ validates :interval, presence: true
26
+ validates :name, presence: true
27
+
28
+ scope :active, -> { where(status: "active") }
29
+ scope :pending, -> { where(status: "pending") }
30
+ scope :suspended, -> { where(status: "suspended") }
31
+ scope :canceled, -> { where(status: "canceled") }
32
+ scope :completed, -> { where(status: "completed") }
33
+ scope :named, ->(name) { where(name: name) }
34
+
35
+ def self.record_from_mollie(ms, expected_version: UNTRACKED)
36
+ customer = Customer.includes(:owner).find_by!(mollie_id: ms.customer_id)
37
+ subscription = find_or_initialize_by(mollie_id: ms.id)
38
+
39
+ subscription, outcome = sync_from_mollie(
40
+ subscription,
41
+ target_status: ms.status,
42
+ attributes: mollie_attributes(ms, customer),
43
+ coalesce_attributes: mollie_coalesce_attributes(ms),
44
+ insert_attributes: { name: ms.metadata&.dig("mollie_pay_name") || "default" },
45
+ association_attributes: { customer: customer },
46
+ expected_version: expected_version
47
+ )
48
+
49
+ if (outcome == :inserted && ms.status != "pending") || outcome == :transitioned
50
+ subscription.notify_billable(status: ms.status)
51
+ end
52
+
53
+ subscription
54
+ end
55
+
56
+ def self.synced_with_mollie?(subscription, ms, customer:)
57
+ return false unless STATUSES.include?(ms.status)
58
+ return false if ms.customer_id != customer.mollie_id
59
+ return true if strictly_stale?(subscription.status, ms.status)
60
+ return false if subscription.status != ms.status
61
+
62
+ attributes_match?(subscription, mollie_attributes(ms, customer)) &&
63
+ coalesce_attributes_settled?(subscription, mollie_coalesce_attributes(ms))
64
+ end
65
+
66
+ def notify_billable(status: self.status)
67
+ billable = customer.owner
68
+
69
+ hook = case status
70
+ when "canceled" then :on_mollie_subscription_canceled
71
+ when "suspended" then :on_mollie_subscription_suspended
72
+ when "completed" then :on_mollie_subscription_completed
73
+ end
74
+
75
+ NotifyBillableJob.perform_later(billable, hook, self) if hook
76
+ end
77
+
78
+ def mark_canceled!
79
+ updated = conditional_sync_update!(
80
+ from_status: ALLOWED_FROM.fetch("canceled"),
81
+ attributes: { status: "canceled" },
82
+ coalesce_attributes: { canceled_at: Time.current }
83
+ )
84
+ yield self if updated && block_given?
85
+ self
86
+ end
87
+
88
+ def record_swap!(amount:, interval:)
89
+ assign_attributes(amount: amount, interval: interval)
90
+ validate!
91
+
92
+ updated = conditional_sync_update!(
93
+ from_status: ACTIVE_STATUSES,
94
+ attributes: { amount: amount, interval: interval }
95
+ )
96
+ yield self if updated && block_given?
97
+ self
98
+ end
99
+
100
+ def sync_with_mollie(expected_version: Syncable::UNTRACKED)
101
+ version = resolve_sync_version(expected_version)
102
+ ms = fetch_mollie_subscription
103
+
104
+ if ms.nil?
105
+ Rails.logger.warn("[MolliePay] Subscription #{mollie_id} returned 404 from Mollie — marking canceled locally")
106
+ mark_canceled! { notify_billable(status: "canceled") }
107
+ else
108
+ local_customer = customer
109
+ ensure_persisted_for_sync!
110
+ sync_payments_from_mollie(ms)
111
+ reload
112
+
113
+ unless self.class.synced_with_mollie?(self, ms, customer: local_customer)
114
+ self.class.record_from_mollie(ms, expected_version: version)
115
+ reload
116
+ end
117
+
118
+ self
119
+ end
120
+ end
121
+
122
+ def mollie_record
123
+ Mollie::Customer::Subscription.get(mollie_id, customer_id: customer.mollie_id)
124
+ end
125
+
126
+ def active?
127
+ status == "active"
128
+ end
129
+
130
+ def canceled?
131
+ status == "canceled"
132
+ end
133
+
134
+ private
135
+
136
+ def resolve_sync_version(expected_version)
137
+ return expected_version unless expected_version.equal?(Syncable::UNTRACKED)
138
+
139
+ version = self.class.uncached { self.class.where(id: id).pick(:sync_version) }
140
+ if version.nil?
141
+ raise ActiveRecord::RecordNotFound, "MolliePay::Subscription##{id} was deleted during sync"
142
+ else
143
+ version
144
+ end
145
+ end
146
+
147
+ def fetch_mollie_subscription
148
+ mollie_record
149
+ rescue Mollie::ResourceNotFoundError
150
+ nil
151
+ end
152
+
153
+ def ensure_persisted_for_sync!
154
+ unless self.class.uncached { self.class.exists?(id: id) }
155
+ raise ActiveRecord::RecordNotFound, "MolliePay::Subscription##{id} was deleted during sync"
156
+ end
157
+ end
158
+
159
+ def sync_payments_from_mollie(ms)
160
+ local_payments = self.class.uncached { Payment.where(subscription_id: id).index_by(&:mollie_id) }
161
+ page = ms.payments(limit: PAYMENT_PAGE_LIMIT)
162
+
163
+ while page
164
+ ensure_persisted_for_sync!
165
+
166
+ page.each do |mp|
167
+ record_subscription_payment(mp, local_payments[mp.id])
168
+ end
169
+
170
+ page = page.links&.dig("next", "href").present? ? page.next : nil
171
+ end
172
+ end
173
+
174
+ def record_subscription_payment(mp, local_payment)
175
+ unless local_payment && Payment.synced_with_mollie?(local_payment, mp, customer: customer)
176
+ Payment.record_from_mollie(mp, expected_version: local_payment&.sync_version)
177
+ end
178
+ rescue MolliePay::StaleSyncError
179
+ refetch_subscription_payment(mp.id)
180
+ end
181
+
182
+ def refetch_subscription_payment(payment_mollie_id)
183
+ attempts = 0
184
+
185
+ MolliePay::ApplicationRecord.uncached do
186
+ begin
187
+ attempts += 1
188
+ expected_version = Payment.where(mollie_id: payment_mollie_id).pick(:sync_version)
189
+ mp = Mollie::Payment.get(payment_mollie_id)
190
+ ensure_persisted_for_sync!
191
+ Payment.record_from_mollie(mp, expected_version: expected_version)
192
+ rescue MolliePay::StaleSyncError
193
+ if attempts < MAX_PAYMENT_SYNC_ATTEMPTS
194
+ retry
195
+ else
196
+ raise
197
+ end
198
+ end
199
+ end
200
+ end
201
+
202
+ private_class_method def self.mollie_attributes(ms, customer)
203
+ {
204
+ customer_id: customer.id,
205
+ amount: mollie_value_to_decimal(ms.amount),
206
+ currency: ms.amount.currency,
207
+ interval: ms.interval
208
+ }
209
+ end
210
+
211
+ private_class_method def self.mollie_coalesce_attributes(ms)
212
+ ms.status == "canceled" ? { canceled_at: Time.current } : {}
213
+ end
214
+ end
215
+ end
data/config/routes.rb ADDED
@@ -0,0 +1,4 @@
1
+ MolliePay::Engine.routes.draw do
2
+ resources :webhooks, only: :create
3
+ resources :webhook_events, only: :create
4
+ end
@@ -0,0 +1,9 @@
1
+ class CreateMolliePayCustomers < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :mollie_pay_customers, id: :string do |t|
4
+ t.references :owner, polymorphic: true, null: false, index: { unique: true }, type: :string
5
+ t.string :mollie_id, null: false, index: { unique: true }
6
+ t.timestamps
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,13 @@
1
+ class CreateMolliePayMandates < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :mollie_pay_mandates, id: :string do |t|
4
+ t.references :customer, null: false, type: :string,
5
+ foreign_key: { to_table: :mollie_pay_customers }
6
+ t.string :mollie_id, null: false, index: { unique: true }
7
+ t.string :method, null: false
8
+ t.string :status, null: false, default: "pending"
9
+ t.datetime :mandated_at
10
+ t.timestamps
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,15 @@
1
+ class CreateMolliePaySubscriptions < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :mollie_pay_subscriptions, id: :string do |t|
4
+ t.references :customer, null: false, type: :string,
5
+ foreign_key: { to_table: :mollie_pay_customers }
6
+ t.string :mollie_id, null: false, index: { unique: true }
7
+ t.string :status, null: false, default: "pending"
8
+ t.string :amount, null: false, default: "0" # money as text until ChangeMolliePayMoneyToDecimal makes it decimal(15,4)
9
+ t.string :currency, null: false, default: "EUR"
10
+ t.string :interval, null: false
11
+ t.datetime :canceled_at
12
+ t.timestamps
13
+ end
14
+ end
15
+ end