spree-bank_payments 5.3.0 → 6.0.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 (67) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +136 -0
  3. data/README.md +188 -115
  4. data/Rakefile +39 -1
  5. data/app/controllers/concerns/spree/bank_payments/release_on_other_method.rb +56 -0
  6. data/app/controllers/spree/api/v3/admin/bank_payments/accounts_controller.rb +135 -0
  7. data/app/controllers/spree/api/v3/admin/bank_payments/health_controller.rb +44 -0
  8. data/app/controllers/spree/api/v3/admin/bank_payments/orders_controller.rb +44 -0
  9. data/app/controllers/spree/api/v3/admin/bank_payments/payment_methods_controller.rb +32 -0
  10. data/app/controllers/spree/api/v3/admin/bank_payments/resource_controller.rb +40 -0
  11. data/app/controllers/spree/api/v3/admin/bank_payments/transfers_controller.rb +179 -0
  12. data/app/jobs/spree/bank_payments/expire_sessions_job.rb +67 -57
  13. data/app/jobs/spree/bank_payments/send_reminders_job.rb +4 -1
  14. data/app/mailers/spree/bank_payments/instructions_mailer.rb +7 -4
  15. data/app/models/spree/bank_payments/adjusters/discount.rb +99 -0
  16. data/app/models/spree/bank_payments/bank_account.rb +3 -0
  17. data/app/models/spree/bank_payments/base.rb +8 -0
  18. data/app/models/spree/bank_payments/current.rb +10 -0
  19. data/app/models/spree/bank_payments/gateway.rb +204 -72
  20. data/app/models/spree/bank_payments/incoming_transfer.rb +5 -0
  21. data/app/models/spree/payment_sessions/bank_transfer.rb +80 -9
  22. data/app/serializers/spree/api/v3/admin/bank_payments/bank_account_serializer.rb +23 -0
  23. data/app/serializers/spree/api/v3/admin/bank_payments/incoming_transfer_serializer.rb +48 -0
  24. data/app/serializers/spree/api/v3/admin/bank_payments/payment_session_serializer.rb +21 -0
  25. data/app/serializers/spree/api/v3/admin/bank_payments/suggestion_serializer.rb +40 -0
  26. data/app/services/spree/bank_payments/apply_transfer.rb +74 -45
  27. data/app/services/spree/bank_payments/guard_capture.rb +17 -0
  28. data/app/services/spree/bank_payments/health_reporter.rb +8 -6
  29. data/app/services/spree/bank_payments/ignore_transfer.rb +37 -0
  30. data/app/services/spree/bank_payments/ingest_transfer.rb +16 -4
  31. data/app/services/spree/bank_payments/migrate_legacy_accounts.rb +5 -1
  32. data/app/services/spree/bank_payments/migrate_legacy_discounts.rb +82 -0
  33. data/app/services/spree/bank_payments/record_manual_transfer.rb +115 -0
  34. data/app/services/spree/bank_payments/release_selection.rb +58 -0
  35. data/app/services/spree/bank_payments/settle_at_completion.rb +35 -0
  36. data/app/services/spree/bank_payments/suggest_matches.rb +7 -3
  37. data/app/subscribers/spree/bank_payments/instructions_mailer_subscriber.rb +29 -0
  38. data/app/subscribers/spree/bank_payments/order_placed_subscriber.rb +31 -0
  39. data/app/views/spree/bank_payments/instructions_mailer/instructions.html.erb +5 -5
  40. data/app/views/spree/bank_payments/instructions_mailer/reminder.html.erb +6 -6
  41. data/config/initializers/spree.rb +50 -56
  42. data/config/locales/en.yml +22 -0
  43. data/config/routes.rb +23 -15
  44. data/lib/spree/bank_payments/api_fields.rb +39 -0
  45. data/lib/spree/bank_payments/events.rb +36 -0
  46. data/lib/spree/bank_payments/factories.rb +10 -5
  47. data/lib/spree/bank_payments/version.rb +2 -2
  48. data/lib/spree/bank_payments.rb +27 -57
  49. data/lib/tasks/spree_bank_payments.rake +9 -0
  50. metadata +30 -65
  51. data/app/controllers/spree/admin/bank_accounts_controller.rb +0 -134
  52. data/app/controllers/spree/admin/bank_transfers_controller.rb +0 -293
  53. data/app/models/spree/bank_payments/adjuster/discount.rb +0 -55
  54. data/app/models/spree/bank_payments/payment_decorator.rb +0 -22
  55. data/app/services/spree/bank_payments/apply_discount.rb +0 -154
  56. data/app/views/spree/admin/bank_accounts/_form.html.erb +0 -33
  57. data/app/views/spree/admin/bank_accounts/edit.html.erb +0 -3
  58. data/app/views/spree/admin/bank_accounts/index.html.erb +0 -84
  59. data/app/views/spree/admin/bank_accounts/new.html.erb +0 -3
  60. data/app/views/spree/admin/bank_transfers/index.html.erb +0 -91
  61. data/app/views/spree/admin/bank_transfers/new.html.erb +0 -46
  62. data/app/views/spree/admin/payment_methods/configuration_guides/_spree_bank_payments.html.erb +0 -52
  63. data/app/views/spree/admin/payment_methods/descriptions/_spree_bank_payments.html.erb +0 -4
  64. data/app/views/spree/bank_payments/_order_instructions.html.erb +0 -82
  65. data/app/views/spree/bank_payments/admin/_order_panel.html.erb +0 -55
  66. data/app/views/spree/checkout/payment/_spree_bank_payments.html.erb +0 -13
  67. data/lib/spree/bank_payments/subscribers.rb +0 -42
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6a51b19c1448a4d27b386e8e65276fb900e18528f4e7bfd4f539e33b559414fa
4
- data.tar.gz: 51ed0b549ce5d0bf543118430c45cd49cb6c5a66646a031ef94980c6d6c6035c
3
+ metadata.gz: 691381c2f0df4208b375a5d717b71965f00ce2151104ad709efa8ccc4267b3bc
4
+ data.tar.gz: 8e65b580952f031b481730037abcee943117eedc0e529716667e9791103aefa5
5
5
  SHA512:
6
- metadata.gz: 228b83f83281f96655f08ff8e9f0258f4a7031ac3c618643e5d962ecc5d999d9a4e4d4a0d1e4d952fca49d3e26649eaa766269d92a40551e806e3169aa0505f1
7
- data.tar.gz: 7c295fe395cd41e19d60fadefa0da4467d4873b12cd4658e7c13d4b1fb595b729d93490182fe6f23d85f8ef7104c87e097e30b441b6c5a9cdeb3d77c004fc16a
6
+ metadata.gz: 16c6e9ffe0a561e23da7d9a2c28a62f8738476f775b965a87cf73f2d4ea24413fcf5c0ec84c8d35d406080d912ef4df854161474c3986b1706d5983ff0aee20d
7
+ data.tar.gz: 8c1378d1095f1d0f826cf2772e5ce041a40df623d1980db99bda60a01c7843066176d0c535456f70cff9cd577aeeaadfc55d3491d99b81f49f66b91e44cb24f3
data/CHANGELOG.md CHANGED
@@ -2,6 +2,142 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 6.0.0
6
+
7
+ Spree 6 support. The major version tracks Spree's, so 6.x supports Spree 6.
8
+ Spree 5.6 stays on 5.3.x, on the `5-3-stable` branch. To upgrade, see
9
+ [docs/upgrading-5-to-6.md](docs/upgrading-5-to-6.md).
10
+
11
+ ### Requirements
12
+
13
+ - Spree `~> 6.0` and Ruby 3.3 or newer. The 5.x releases do not install on
14
+ Spree 6.
15
+ - The `spree_admin` dependency is gone: Spree 6 has no Rails admin.
16
+
17
+ ### Removed
18
+
19
+ - **The Rails admin screens**: the unmatched-transfers queue, the "record a
20
+ received transfer" form, the bank accounts screen, the sidebar entry, the
21
+ order panel partial and the payment method configuration guide. Spree 6's
22
+ dashboard plugin replaces them (see "The dashboard" below).
23
+ - **The Rails storefront partials** (the checkout payment partial and
24
+ `spree/bank_payments/_order_instructions`). A storefront reads the quote
25
+ from the Store API instead.
26
+ - `Gateway#bank_details` (deprecated in 5.2.0), `#method_type`,
27
+ `#description_partial_name`, `#configuration_guide_partial_name` and
28
+ `#auto_capture?`.
29
+ - `Spree::BankPayments.gateway_type_names` and `.gateway_scope`.
30
+
31
+ ### The dashboard
32
+
33
+ - **A Spree dashboard plugin**, `@aypex-io/spree-bank-payments-dashboard` on
34
+ npm, released with the gem at the same version. `pnpm add` it in the
35
+ dashboard app and the next build picks it up. It brings back the 5.x
36
+ screens: the unmatched-transfers queue under Orders, each transfer's
37
+ possible matches with Apply and Ignore, recording a received transfer, the
38
+ bank accounts screen, a Bank transfer card on the order page and the
39
+ payment method's setup guide.
40
+ - **Applying a transfer for a different amount asks first.** The Admin API
41
+ answers 422 `amount_mismatch`, with both amounts, until the request
42
+ confirms with `confirm_mismatch`.
43
+ - **Accounts can be added by hand** from the dashboard, for the `manual`
44
+ reconciler. Sync from provider is offered only for a provider's
45
+ reconciler, as in 5.x.
46
+ - **An Admin API** under `/api/v3/admin/bank_payments`: transfers (list,
47
+ show, suggestions, record, apply, ignore), the store's bank transfer
48
+ payment methods, each one's accounts (list, create, update, delete, sync
49
+ plan, sync) and reconciler health, and an order's bank transfer. Transfers and accounts have prefixed ids,
50
+ `btxfr_` and `bacct_`.
51
+ - **A Bank transfers permission** for staff roles (`read_bank_payments`,
52
+ `write_bank_payments`): read to see the queue, write to act on it.
53
+
54
+ ### Checkout
55
+
56
+ - **The gateway is session-based** and its API type is `bank_transfer`.
57
+ Creating a payment session quotes the cart: a fresh reference, the amount
58
+ due after the discount, the deadline and the bank details, under
59
+ `external_data.bank_transfer`, which a client cannot write. Completing the
60
+ session re-quotes, then leaves a pending payment carrying the reference, so
61
+ Spree places the order unpaid (`payment_status` `authorized`).
62
+ - **Changing the cart after choosing bank transfer** re-quotes it, up to the
63
+ moment the order is placed: completing the session re-quotes, and so does
64
+ completing the cart, under Spree's lock. The quote, the pending payment and
65
+ the order total are always equal.
66
+ - **A released, expired or completed session cannot be completed again**
67
+ (or updated): the Store API answers 422, so an order is never placed
68
+ against a reference nothing will match.
69
+ - **Switching to another payment method releases bank transfer first.**
70
+ Before the Store API creates another method's session or payment, or
71
+ updates or completes one created earlier, the bank transfer session is
72
+ cancelled, its payment voided and the discount recalculated away, so the
73
+ other method charges the full total. A request Spree refuses releases
74
+ nothing. A bank transfer session the buyer never completed is released when
75
+ the cart completes, so an order is never placed on a discount bank transfer
76
+ is not paying.
77
+ - **Spree holds dispatch of an unpaid bank transfer order** unless staff
78
+ force it: the gateway captures at checkout, so its pending payment does not
79
+ count as money staff have taken charge of collecting. `authorize` and
80
+ `purchase` refuse, and the dashboard offers no Capture: Spree's capture
81
+ workflow refuses a bank transfer payment unless a transfer is being applied
82
+ to it. Money moves only when a transfer is reconciled.
83
+ - **The Store API shows the quote**: a bank transfer payment, on the cart and
84
+ on the order, carries a `bank_transfer` field with the reference, amount,
85
+ deadline and bank details. The payment method carries
86
+ `bank_transfer.discount_percent` and `expiry_days`.
87
+
88
+ ### Discount
89
+
90
+ - Written as one `manual` `Spree::Discount` per line item, found by
91
+ `metadata.source = "spree_bank_payments"`, through an adjuster registered in
92
+ `Spree.adjusters`. The figures do not change: 3% off a 20% VAT-inclusive
93
+ 100.00 line records 16.17 VAT, and a 20% promotion plus 3% is 23%. Shares
94
+ round to the currency's own minor unit.
95
+
96
+ ### Reconciliation and expiry
97
+
98
+ - A transfer settles through `Spree.payment_capture_workflow`, so Spree
99
+ records the capture and publishes `payment.captured`. Under the order's
100
+ lock it re-checks that the session is still open and the order still
101
+ placed, so a second transfer racing the first queues rather than being
102
+ marked applied with nothing captured.
103
+ - **Only placed orders reconcile automatically.** A transfer quoting a
104
+ reference from a checkout that was never placed queues for a person, and is
105
+ never suggested; it is not used to place the cart.
106
+ - `parse_webhook_event` ingests the transfer and returns `nil`, so Spree's
107
+ webhook workflow has nothing to settle a second time.
108
+ - An unpaid placed order past its deadline is cancelled through
109
+ `Spree.order_cancel_workflow`, which releases its stock and voids the
110
+ payment, with a staff note. A cancel Spree refuses, or one that raises,
111
+ leaves the session open and reports `bank_transfer.expiry_failed`, and the
112
+ run carries on with the next session. A session whose checkout was never
113
+ placed is expired silently.
114
+ - An order counts as paid when its `payment_status` is `paid`, `overcharged`,
115
+ `partially_refunded` or `refunded`: it is never cancelled for an unpaid
116
+ transfer, and a transfer for it queues for a person.
117
+ - **Upgrading:** Spree's own upgrade writes each 5.x bank transfer discount as
118
+ a 0.00 surcharge. Run `bin/rails spree_bank_payments:upgrade:legacy_discounts`
119
+ after `spree:upgrade` to restore them as discounts; otherwise the next
120
+ re-sum of such an order raises its total by the discount.
121
+
122
+ ### Events and email
123
+
124
+ - **Instructions are sent when the order is placed**, not when the session is
125
+ created, and the payment window starts then. Reminders go only to placed
126
+ orders.
127
+ - Every event is declared. The operational ones
128
+ (`reconciler_unhealthy`, `expiry_failed`, `reconciler_health.*`) are
129
+ declared `webhook: false`: their payloads carry error text.
130
+ - Events are published under the gateway's store, so they reach webhook
131
+ endpoints from the background jobs too.
132
+ - **Payloads use string keys and prefixed ids** (`ps_...`, `pm_...`), and the
133
+ customer-facing payload adds `order_id`, `discount_percent` and
134
+ `bank_details`. A subscriber reading `payload[:payment_session_id]` must
135
+ read `payload['payment_session_id']`.
136
+ - The default mailer is `Spree::BankPayments::InstructionsMailerSubscriber`,
137
+ registered through `Spree.subscribers`. 5.x subscribed blocks from
138
+ `to_prepare`, which on Spree 6 stopped every one of Spree's own subscribers
139
+ from registering. `InstructionsMailer` takes the session's prefixed id.
140
+
5
141
  ## 5.3.0
6
142
 
7
143
  ### Upgrading from 5.2.0
data/README.md CHANGED
@@ -1,11 +1,16 @@
1
1
  # spree-bank_payments
2
2
 
3
- Bank transfer checkout for Spree 5.6+, with pluggable reconciliation of
3
+ Bank transfer checkout for Spree 6, with pluggable reconciliation of
4
4
  incoming payments.
5
5
 
6
+ The major version tracks Spree's: 6.x supports Spree 6. Spree 5.6 stays on
7
+ 5.3.x, on the `5-3-stable` branch. Upgrading from 5.3: see
8
+ [docs/upgrading-5-to-6.md](docs/upgrading-5-to-6.md).
9
+
6
10
  ## Requirements
7
11
 
8
- PostgreSQL. The gem uses `jsonb`, partial unique indexes, and `pg_trgm`.
12
+ - Spree `~> 6.0` and Ruby 3.3 or newer.
13
+ - PostgreSQL. The gem uses `jsonb`, partial unique indexes, and `pg_trgm`.
9
14
 
10
15
  ## Installation
11
16
 
@@ -15,7 +20,7 @@ gem 'spree-bank_payments'
15
20
 
16
21
  ```bash
17
22
  bundle install
18
- bin/rails g spree:bank_transfer:install
23
+ bin/rails g spree:bank_payments:install
19
24
  ```
20
25
 
21
26
  The generator copies the migrations and then asks whether to run them. Pass
@@ -23,16 +28,60 @@ The generator copies the migrations and then asks whether to run them. Pass
23
28
 
24
29
  ## Configuration
25
30
 
26
- Add a Bank Transfer payment method in the Spree admin and set:
31
+ Add a **Bank transfer** payment method in the Spree dashboard (its API type
32
+ is `bank_transfer`) and set:
27
33
 
28
34
  | Preference | Purpose |
29
35
  |---|---|
30
36
  | `reconciler` | `manual` by default; `revolut` with `spree-bank_payments_revolut` installed |
31
- | `reference_prefix` | Prefix on generated references, e.g. `TKF-` |
37
+ | `reference_prefix` | Prefix on generated references, e.g. `ACME-` |
32
38
  | `expiry_days` | Days before an unpaid order is cancelled and restocked |
33
39
  | `discount_percent` | Percentage off `item_total` for paying by transfer |
34
40
  | `poll_interval_minutes` | How often the reconciler polls; drives the health gate |
35
- | `account_*` | **Deprecated.** Pre-5.2 flat bank details. On upgrade these are folded automatically into one offered `BankAccount` for the store's default currency (see below) — do not set them on a fresh 5.2+ install; use the bank accounts screen instead. |
41
+
42
+ The pre-5.2 flat `account_*` preferences are hidden from the dashboard. A
43
+ store upgrading from 5.1 has them folded into one offered `BankAccount` for
44
+ the store's default currency by the 5.2 migration.
45
+
46
+ ## Checkout through the Store API
47
+
48
+ Spree 6 has no Rails storefront; the gem's checkout runs through the Store
49
+ API, as a payment session:
50
+
51
+ 1. **The buyer picks bank transfer.** The storefront creates a payment
52
+ session: `POST /api/v3/store/carts/:cart_id/payment_sessions` with the
53
+ payment method's id. The response's `external_data.bank_transfer` is the
54
+ quote: `reference`, `amount` (with the discount applied), `currency`,
55
+ `expires_at`, `discount_percent` and `bank_details`. The cart's totals now
56
+ include the discount. Creating another bank transfer session replaces the
57
+ previous one.
58
+ 2. **The buyer places the order.** The storefront completes the session
59
+ (`PATCH .../payment_sessions/:id/complete`), which re-quotes the cart and
60
+ leaves a pending payment carrying the reference, then completes the cart
61
+ (`POST /api/v3/store/carts/:cart_id/complete`). Completing the cart
62
+ re-quotes once more, under Spree's lock, so the quote, the payment and the
63
+ order total are equal however the cart changed. Spree places the order
64
+ unpaid: its `payment_status` is `authorized`. A session that was released
65
+ or has expired cannot be completed: the Store API answers 422 and the buyer
66
+ chooses bank transfer again.
67
+ 3. **The confirmation page shows how to pay.** Every bank transfer payment,
68
+ on the cart and on the order (`GET /api/v3/store/orders/:id`), carries a
69
+ `bank_transfer` field with the same quote. The payment method itself
70
+ carries `bank_transfer.discount_percent` and `expiry_days`, for the
71
+ checkout to advertise before the buyer chooses.
72
+
73
+ If the buyer switches to another payment method, bank transfer is released
74
+ before Spree sizes the other method's session or payment, or updates or
75
+ completes one created earlier: its session is cancelled and the discount
76
+ comes off, so the other method charges the full total. A bank transfer
77
+ session the buyer never completed is also released when the cart completes,
78
+ so the discount only reaches an order bank transfer is paying.
79
+
80
+ Spree holds dispatch of an unpaid bank transfer order (its "not paid for
81
+ yet" rule) unless staff force it. The payment is captured when a transfer is
82
+ applied to it, and never otherwise: not on dispatch, and not from the
83
+ dashboard's Capture action, which Spree's capture workflow refuses for a
84
+ bank transfer payment.
36
85
 
37
86
  ## Bank accounts and currencies
38
87
 
@@ -51,8 +100,9 @@ every order regardless of currency.
51
100
  wrong hides the details the customer actually needed, costing them a
52
101
  bounced transfer or a correspondent fee with no explanation. Let them
53
102
  choose; they know where they bank.
54
- - **Admin checklist:** the bank accounts screen under the payment method
55
- lets an admin toggle at most one *offered* account per currency. This is
103
+ - **Staff choose the offered account:** at most one account per currency
104
+ can be *offered*, and only a person sets it (the **Offer to customers**
105
+ switch on the dashboard's bank accounts screen). This is
56
106
  enforced by a partial unique database index
57
107
  (`index_bp_bank_accounts_on_pm_and_currency_offered`), not just a form
58
108
  validation — a second offered row for the same currency cannot exist,
@@ -71,11 +121,11 @@ every order regardless of currency.
71
121
  currency, in which case availability is kept so that order can still be
72
122
  paid. This is easy to reach by accident: **the first sync leaves every
73
123
  account unchecked**, so bank transfer is unavailable in every currency
74
- until an admin offers at least one account. The admin screen states this
75
- plainly.
124
+ until someone offers at least one account.
76
125
  - **Two sync triggers:**
77
- 1. A **"Sync from <provider>"** button in the payment method admin,
78
- which always shows a diff for confirmation before applying it.
126
+ 1. **A person asks for it.** `SyncAccounts.new(payment_method:).plan`
127
+ returns the diff to confirm, and `#apply!` applies it (the dashboard's
128
+ **Sync from provider** button, shown for any reconciler but `manual`).
79
129
  2. **Consent re-approval**, for providers whose credentials need periodic
80
130
  re-authorisation (e.g. an OAuth consent that expires every ~90 days).
81
131
  A provider gem can call `SyncAccounts.new(payment_method:).apply!(additive_only: true)`
@@ -90,7 +140,7 @@ every order regardless of currency.
90
140
  immutable, because changing what a customer was told after the fact
91
141
  makes a dispute unwinnable.
92
142
  - **Soft-deleted accounts are not resurrected by sync.** `BankAccount` is
93
- `acts_as_paranoid`; deleting one from the admin is a soft delete, so a
143
+ `acts_as_paranoid`; deleting one is a soft delete, so a
94
144
  session that already quoted it keeps rendering the coordinates. If a
95
145
  later sync reports the same provider account again, it is **not**
96
146
  silently recreated — it's surfaced as `skipped` in the sync diff, visible
@@ -103,7 +153,7 @@ every order regardless of currency.
103
153
  hand every customer the same IBAN and separate the payers by reference
104
154
  alone. A provider reports this through `AccountData#pooled` (default
105
155
  `false`, so a provider that never sets it behaves exactly as before) and
106
- it is shown as a **Pooled** badge on the bank accounts screen. It changes
156
+ it is recorded on the account as `pooled`. It changes
107
157
  nothing about auto-apply — that has always required an exact normalized
108
158
  reference match, on every account — but it changes how a human must read
109
159
  the unmatched queue. Suggestions there are ranked partly on fuzzy
@@ -167,54 +217,70 @@ is skipped too; both appear under `skipped` in the sync diff.
167
217
  See "Writing a reconciler" below for the full contract, including the shared
168
218
  example group that exercises this method's return type.
169
219
 
170
- ## The admin queue and the manual workflow
171
-
172
- The gem adds a **Bank transfers** entry to the Spree admin sidebar, pointing
173
- at `/admin/bank_transfers`. That screen is the operational heart of the gem:
174
-
175
- - **The unmatched queue** (`/admin/bank_transfers`) lists every observed
176
- transfer that hasn't been matched to an order, with suggested sessions
177
- ranked by exact amount first and fuzzy payer-name similarity second. Apply
178
- a suggestion in one click, or ignore the transfer with a reason.
179
- - **Record a received transfer** (`/admin/bank_transfers/new`) is how money
180
- gets into the system when you're not running a provider integration. This
181
- is **required reading if you use the default `manual` reconciler**: it has
182
- nothing to poll and no webhook, so this form is the only way a transfer can
183
- ever be recorded. You enter the payment method, amount, currency, payer
184
- name, the reference as the customer quoted it, and the date received; the
185
- entry then goes through exactly the same matching path as a
186
- provider-delivered transfer. An exact match (reference, amount, currency,
187
- against a single open session on an unpaid order) applies immediately and
188
- marks the order paid. Anything else lands in the queue above.
189
-
190
- Submitting the same form twice is safe: the transfer's identity is derived
191
- from what you typed, so a resubmission is recognised as the same transfer
192
- and nothing is credited twice.
193
-
194
- The same derivation has a flip side. Two genuinely separate transfers that
195
- match on every recorded field — payment method, amount, currency, reference,
196
- payer name and date received — are treated as one, and only the first is
197
- credited. If a customer really did send the same amount twice on the same day,
198
- record the second with something that distinguishes it (the payer name exactly
199
- as it appears on that transfer, for instance) so it is not collapsed into the
200
- first.
201
-
202
- - **Applying to a mismatched order** takes two deliberate steps. The first
203
- click is refused with both amounts spelled out; only then does an explicit
204
- "Yes — apply … anyway" control appear for that specific pairing, behind a
205
- confirmation dialog. A mismatch is credited for the amount that actually
206
- arrived, so the order lands in `balance_due`/`credit_owed` rather than a
207
- false `paid`.
208
-
209
- ### The order panel partial
210
-
211
- `spree/bank_payments/admin/_order_panel` renders the bank-transfer state for
212
- a single order — reference, amount, status, expiry, and the matched transfer
213
- if there is one. The gem does **not** inject it anywhere; render it from your
214
- admin order view where it makes sense for your store:
215
-
216
- ```erb
217
- <%= render 'spree/bank_payments/admin/order_panel', order: @order %>
220
+ ## The dashboard
221
+
222
+ A transfer that matches exactly (reference, amount and currency, against a
223
+ single open session on a placed, unpaid order) is applied automatically and
224
+ the order reads `paid`. Anything else is kept as an unmatched
225
+ `Spree::BankPayments::IncomingTransfer` for a person to decide. They decide
226
+ in Spree's dashboard, through a plugin released with the gem at the same
227
+ version, [`@aypex-io/spree-bank-payments-dashboard`](dashboard/README.md):
228
+
229
+ ```bash
230
+ # in the dashboard app (the one built with Spree's dashboard-starter)
231
+ pnpm add @aypex-io/spree-bank-payments-dashboard
232
+ ```
233
+
234
+ The dashboard discovers the plugin on its next build. It adds:
235
+
236
+ - **Bank transfers**, under Orders: the queue, which opens on unmatched
237
+ transfers ("any status" lists every one). A transfer's page ranks the
238
+ open sessions it could belong to, with **Apply** and **Ignore** (with a
239
+ reason). Applying a transfer for a different amount asks first, and the
240
+ order is credited for what arrived, so it reads `partially_paid` or
241
+ `overcharged`, never a false `paid`.
242
+ - **Record a transfer**: enter one seen on the bank statement. With the
243
+ default `manual` reconciler this is how transfers are recorded. An exact
244
+ match is applied at once; anything else joins the queue.
245
+ - **Bank accounts**, linked from the bank transfer payment method: offer one
246
+ account per currency, deactivate one, add one by hand, or, with a
247
+ provider's reconciler, sync from the provider after previewing the
248
+ changes.
249
+ - A **Bank transfer** card on the order page (the reference, the amount, the
250
+ deadline and the transfer applied) and a **setup guide** on the payment
251
+ method (reconciler health, the webhook URL to give the provider, and a
252
+ warning when no account is offered).
253
+
254
+ Give staff roles the **Bank transfers** permission: read to see the queue,
255
+ write to apply, ignore, record and manage accounts. The plugin talks to the
256
+ gem's Admin API under `/api/v3/admin/bank_payments`, which any other admin
257
+ client can use too.
258
+
259
+ Recording the same transfer twice is safe: a transfer's identity is its
260
+ provider and provider transaction id, so a second record is the same row and
261
+ nothing is credited twice.
262
+
263
+ ### Without the dashboard
264
+
265
+ The same decisions from a console:
266
+
267
+ ```ruby
268
+ # Record a transfer received outside any provider integration.
269
+ data = Spree::BankPayments::TransferData.new(
270
+ provider: 'manual', provider_transaction_id: 'bank-statement-2026-11-02-1',
271
+ amount: BigDecimal('97.00'), currency: 'GBP', reference: 'ACME-7Q4X2',
272
+ payer_name: 'Jane Doe', occurred_at: Time.current, raw: {}
273
+ )
274
+ Spree::BankPayments::IngestTransfer.new(payment_method: gateway, transfer_data: data).call
275
+
276
+ # Rank the open sessions an unmatched transfer could belong to.
277
+ Spree::BankPayments::SuggestMatches.new(transfer: transfer).call
278
+
279
+ # Apply it.
280
+ Spree::BankPayments::ApplyTransfer.call(transfer: transfer, payment_session: session, applied_by: admin)
281
+
282
+ # Offer an account.
283
+ account.update!(offered: true)
218
284
  ```
219
285
 
220
286
  ## Scheduling
@@ -267,75 +333,82 @@ decision, not a reconciliation.
267
333
 
268
334
  ## Events
269
335
 
270
- The gem never sends notifications directly — it publishes to
271
- `Spree::Events`, and subscribers decide what to do:
336
+ The gem never sends notifications directly. It publishes Spree events, and
337
+ subscribers decide what to do. Every event is declared, as Spree 6 requires.
272
338
 
273
- | Event | Fired when |
274
- |---|---|
275
- | `bank_transfer.instructions_ready` | A payment session is created and the customer needs the reference/bank details |
276
- | `bank_transfer.reminder_due` | An unpaid session is approaching its expiry deadline |
277
- | `bank_transfer.expired` | `ExpireSessionsJob` cancels an unpaid order |
278
- | `bank_transfer.session_superseded` | An open session is closed because its order was already paid another way — the order is left alone |
279
- | `bank_transfer.reconciler_unhealthy` | The [health gate](#the-health-gate) trips — `ExpireSessionsJob` declined to cancel anything because the reconciler is stale |
280
- | `bank_transfer.reconciler_health.unhealthy` | `PollJob` reports a *transition* into `:transient` or `:consent_revoked` — and at most hourly while it persists. Carries `status`, `reason` and `consecutive_failures` (see [`#health`](#health)) |
281
- | `bank_transfer.reconciler_health.recovered` | The same reporter sees health return to `:ok` |
282
- | `bank_transfer.expiry_failed` | `ExpireSessionsJob` hits an error cancelling a specific session |
339
+ | Event | Fired when | Webhooks |
340
+ |---|---|---|
341
+ | `bank_transfer.instructions_ready` | The order is placed, and the buyer needs the reference and bank details | yes |
342
+ | `bank_transfer.reminder_due` | An open session on a placed order is approaching its deadline | yes |
343
+ | `bank_transfer.expired` | `ExpireSessionsJob` cancels an unpaid order | yes |
344
+ | `bank_transfer.session_superseded` | An open session is closed because its order was already paid another way; the order is left alone | yes |
345
+ | `bank_transfer.reconciler_unhealthy` | The [health gate](#the-health-gate) trips: `ExpireSessionsJob` declined to cancel anything because the reconciler is stale | never |
346
+ | `bank_transfer.reconciler_health.unhealthy` | `PollJob` reports a *transition* into `:transient` or `:consent_revoked`, and at most hourly while it persists. Carries `status`, `reason` and `consecutive_failures` (see [`#health`](#health)) | never |
347
+ | `bank_transfer.reconciler_health.recovered` | The same reporter sees health return to `:ok` | never |
348
+ | `bank_transfer.expiry_failed` | `ExpireSessionsJob` hits an error for a payment method or a session, or Spree refuses to cancel a specific order | never |
349
+
350
+ The four operational events carry reconciler error text, so they are
351
+ declared `webhook: false`: no webhook endpoint receives them, not even one
352
+ subscribed to `*`. Subscribe to them in the application and route them
353
+ somewhere a person will see them.
283
354
 
284
355
  The two `reconciler` events are not the same signal:
285
356
  `reconciler_unhealthy` says the expiry job stood down, while the
286
357
  `reconciler_health.*` pair reports the reconciler's own state and is what
287
358
  decides whether checkout offers bank transfer at all.
288
359
 
289
- Payloads contain serializable primitives only — never AR objects — because
290
- subscribers may run async via ActiveJob. See
291
- `Spree::PaymentSessions::BankTransfer#notification_payload` for the exact
292
- shape. Subscribe with `Spree::Events.subscribe('bank_transfer.*', MyHandler)`
293
- or to individual event names.
360
+ The customer-facing payload (`Spree::PaymentSessions::BankTransfer#notification_payload`)
361
+ has string keys and prefixed ids, like Spree's own: `payment_session_id`,
362
+ `order_id`, `order_number`, `order_email`, `reference`, `amount`, `currency`,
363
+ `expires_at`, `discount_percent` and `bank_details`. A store that emails from
364
+ webhooks has everything it needs without another API call.
365
+
366
+ Subscribe with a `Spree::Subscriber` added to `Spree.subscribers` in an
367
+ `after_initialize` block. Do not call `Spree::Events.subscribe` from
368
+ `to_prepare`: Spree activates `Spree.subscribers` only while its registry is
369
+ empty, so a block subscribed first leaves every one of Spree's own
370
+ subscribers unregistered.
294
371
 
295
- A bundled mailer subscribes to `instructions_ready` and `reminder_due` as one
296
- optional subscriber among possibly several. Disable it with:
372
+ A bundled mailer, `Spree::BankPayments::InstructionsMailerSubscriber`, emails
373
+ the buyer on `instructions_ready` and `reminder_due`. Disable it with:
297
374
 
298
375
  ```ruby
299
376
  Spree::BankPayments::Config.disable_default_mailer = true
300
377
  ```
301
378
 
302
- Stores that deliver mail another way — for example a storefront webhook
303
- handler that calls out to Postmark/Resend/etc. rather than using
304
- ActionMailer — should disable the default mailer and subscribe to the events
305
- directly instead of fighting the bundled one.
379
+ Stores that deliver mail another way, for example a storefront webhook
380
+ handler that sends through an email API, should disable the default mailer
381
+ and handle the events instead.
306
382
 
307
383
  ## Tax, and stacking with promotions
308
384
 
309
- The discount is applied as one `Spree::Adjustment` per **line item** (sourced
310
- from the payment method, not a promotion action), allocated proportionally to
311
- each line's amount and reconciled with largest-remainder rounding so the parts
312
- sum to exactly `-(item_total * discount_percent / 100)` — to the cent.
313
-
314
- Because they are line-item adjustments, they reach Spree's
315
- `taxable_adjustment_total`, so **recorded tax falls with the discount**. On a
316
- tax-inclusive (VAT) store a 3% discount on a £100 line reduces recorded VAT
317
- from £16.67 to £16.17. The pre-5.1 order-level adjustment did not do this — the
318
- customer paid less while the order still recorded tax on the undiscounted
319
- price. That is fixed.
320
-
321
- **The discount stacks with promotions.** It is deliberately not a competing
322
- promotion: Spree picks a single winner among competing promo adjustments, but
323
- this is a separate concession for paying by transfer, so it is never marked
324
- ineligible and never makes a promotion ineligible. A 20% promotion plus a 3%
325
- transfer discount is 23% off. Set `discount_percent` with that in mind.
326
-
327
- Base is always `item_total`, never `order.total` — the discount never applies
328
- to shipping or tax.
329
-
330
- ## The instructions partial ships no CSS
331
-
332
- `spree/bank_payments/_order_instructions` renders the payment reference and
333
- bank details with no styling of its own. Making the reference visually
334
- prominent — the single most impactful thing you can do for match rates — is
335
- the host store's responsibility. Customers who don't notice or don't copy
336
- the reference correctly produce transfers reconciliation can't match
337
- automatically, which means manual admin work. Style it like the most
338
- important line on the page, because for a bank-transfer checkout, it is.
385
+ The discount is written as one `manual` `Spree::Discount` per **line item**,
386
+ tagged `metadata.source = "spree_bank_payments"`, while bank transfer is the
387
+ cart's selected payment. Shares are allocated in proportion to each line's
388
+ amount with Spree's largest-remainder apportionment, in the currency's minor
389
+ units, so they sum to exactly `-(item_total * discount_percent / 100)` and a
390
+ yen discount stays in whole yen.
391
+
392
+ Spree counts every discount row into a line's taxable basis, so **recorded
393
+ tax falls with the discount**: on a tax-inclusive market a 3% discount on a
394
+ £100 line reduces recorded VAT from £16.67 to £16.17.
395
+
396
+ **The discount stacks with promotions.** It is deliberately not a promotion:
397
+ Spree keeps one winning promotion per group, but this is a separate
398
+ concession for paying by transfer. A 20% promotion plus a 3% transfer
399
+ discount is 23% off. Set `discount_percent` with that in mind.
400
+
401
+ The base is always `item_total`, never the order total: the discount never
402
+ applies to delivery or tax. Once the order is placed its money is frozen, and
403
+ the rows are copied onto it.
404
+
405
+ ## Showing the instructions
406
+
407
+ The storefront renders the payment reference and bank details from
408
+ `payments[].bank_transfer`. Making the reference visually prominent is the
409
+ single most effective thing a store can do for match rates: a buyer who does
410
+ not notice or copy it produces a transfer reconciliation cannot match
411
+ automatically, which means work for a person.
339
412
 
340
413
  ## Writing a reconciler
341
414
 
data/Rakefile CHANGED
@@ -11,6 +11,7 @@ task :default do
11
11
  Rake::Task[:test_app].invoke
12
12
  Dir.chdir('../../')
13
13
  end
14
+ Rake::Task['dummy:verify_schema'].invoke
14
15
  Rake::Task[:spec].invoke
15
16
  end
16
17
 
@@ -32,5 +33,42 @@ task :test_app do
32
33
  # migrations (scoped via `rake spree_bank_payments:install:migrations`, not the
33
34
  # unscoped `railties:install:migrations`) and runs db:migrate, so a fresh
34
35
  # `rake test_app` needs no manual migration step.
35
- Rake::Task['extension:test_app'].execute(install_storefront: true, install_admin: true)
36
+ # Spree 6's extension:test_app takes no install_admin or install_storefront
37
+ # option: there is no Rails admin or storefront to install.
38
+ Rake::Task['extension:test_app'].execute
39
+ end
40
+
41
+ namespace :dummy do
42
+ # Spree's test_app task runs `db:migrate` in the generator's own process with
43
+ # output redirected to /dev/null and its exit status ignored. If a migration
44
+ # fails partway (Spree's preferences conversion eager loads the whole app, so
45
+ # any class that fails to load stops it), the dummy database is left
46
+ # half-built and the suite errors with "Could not find table 'spree_*'" and
47
+ # no hint of the cause. Rebuild it from the migration files, in a fresh
48
+ # process and visibly, and fail fast with the real error.
49
+ desc 'Ensure the dummy app database schema is fully migrated'
50
+ task :verify_schema do
51
+ dummy_path = File.expand_path('spec/dummy', __dir__)
52
+ next unless File.directory?(dummy_path)
53
+
54
+ # Keep using the gem's bundle after the chdir below.
55
+ ENV['BUNDLE_GEMFILE'] = File.expand_path(ENV['BUNDLE_GEMFILE'], __dir__) if ENV['BUNDLE_GEMFILE']
56
+ ENV['RAILS_ENV'] = 'test'
57
+
58
+ Dir.chdir(dummy_path) do
59
+ puts 'Rebuilding dummy app database schema...'
60
+
61
+ # A possibly truncated dump must not stand in for the migration files.
62
+ schema = File.join(dummy_path, 'db', 'schema.rb')
63
+ File.delete(schema) if File.exist?(schema)
64
+
65
+ # Separate invocations on purpose: chaining db:create and db:migrate in
66
+ # one `rails` call can leave migrate reading a stale schema state.
67
+ system('bundle exec rails db:drop db:create')
68
+ next if system('bundle exec rails db:migrate')
69
+
70
+ abort 'Dummy app database setup failed; aborting before running specs. ' \
71
+ 'See the migration output above for the underlying error.'
72
+ end
73
+ end
36
74
  end