Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add Spree 5.7 plans
Damian Legawieccffcb0ca1c27
diff --git a/CLAUDE.md b/CLAUDE.mdindex 45e4fd1afc..764f91d09e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -44,6 +44,8 @@ Multi-version plans (some phases shipped, some pending):- `5.6-dashboard-typed-plugin-routes.md` — Plugin file routes compiled into the host's TanStack route tree: `spree.dashboard.routes` marker + virtual-route-config composition in `@spree/dashboard/vite`, `createDashboardRouter` + `<Dashboard router>` ownership inversion, typed cast-free links, cross-package collision pre-flight with package-named errors. Runtime route registry stays for dynamic/in-app cases (catch-all is lowest priority). Implemented; published-tarball spike passed.Pending design work (drafts, no implementation yet):+- `5.7-payment-method-rules.md` — `Spree::PaymentMethodRule` STI on PaymentMethod (Channel / Market / OrderTotal / CustomerGroup rules), mirroring the PromotionRule/PriceRule/OrderRoutingRule pattern. Enforced solely through `Order#collect_frontend_payment_methods` (listing + `Payments::Create` + payment sessions all flow through it); admin/backoffice bypasses; no rules = available everywhere. Dashboard-only management (nested Admin API CRUD + `/payment_method_rules/types` discovery). Supersedes the "no distribution concept" rationale in `5.6-6.0-single-store-promotions-payment-methods.md`; per-channel provider credentials (multiple Stripe accounts, Shopify-style multi-entity) explicitly deferred for grooming — see decisions.md 2026-07-23.+- `5.7-channel-markets.md` — Optional Channel→Markets allowlist (`spree_channel_markets` join, empty = all markets). Enforced in market resolution (`set_market_from_country` + channel-aware `Spree::Current.market` fallback), channel-filtered Store API `/store/markets`, and order-level `market must be served by channel` validation. Composes with `MarketRule` from the payment-method-rules plan.- `5.6-admin-spa-csv-import.md` — Universal dashboard CSV import over the existing `Spree::Import` pipeline (implemented). Admin API v3 surface (create via direct-upload signed blob, `complete_mapping`, `retry_failed_rows`, nested failed-rows index, write-scope gating), `client.imports` SDK resource, dashboard-core `ImportButton` (per-context `<Can>` gating, upload Sheet) + full-window wizard dialog driven by an `?import=` search param, with history under `/settings/imports` (new `audit` settings-nav group). Status via API polling — explicitly no ActionCable/Turbo Streams in the SPA; legacy per-row live feed replaced by polled counters + paginated failed-rows table.- `5.5-6.0-resource-translations-api.md` — Admin API v3 translation management + React dashboard for all `Spree.translatable_resources`. Hybrid: embedded `translations` object on resource update + generic dedicated `…/:id/translations` endpoint (one registry-driven controller), self-describing field discovery, advisory server-side staleness. Canonical `{ locale → { field → value } }` shape (consistent with metafield-translations). Cross-record bulk = CSV import/export generalized across the registry (NOT a JSON bulk endpoint — no competitor ships one). Phase 1 (5.5) API; Phase 2 (6.0) coverage read + CSV generalization + staleness + centralized SPA page; Phase 3 folds in metafields.- `5.4-centralized-translations-admin.md` — Centralized Translations admin page under Products, overview grid + bulk CSV import/exportdiff --git a/docs/plans/5.6-6.0-single-store-promotions-payment-methods.md b/docs/plans/5.6-6.0-single-store-promotions-payment-methods.mdindex 9f1e7f6c12..ebee807aa6 100644--- a/docs/plans/5.6-6.0-single-store-promotions-payment-methods.md+++ b/docs/plans/5.6-6.0-single-store-promotions-payment-methods.md@@ -22,7 +22,7 @@ This plan removes the need for that branch.## Key Decisions (do not deviate without discussion)- **Single owner via FK.** Both models gain a `store_id` column and `belongs_to :store`. No new join model is introduced (unlike Product, which needed `ProductPublication` for channel distribution — promotions and payment methods have no equivalent distribution concept, so the FK is the whole story).-- **No `Channel`/`Publication` layer.** Products needed publications because a catalog item is *distributed* to multiple channels. A promotion or payment method belongs to exactly one store; there is nothing to publish. Keep it simple — just the FK.+- **No `Channel`/`Publication` layer.** Products needed publications because a catalog item is *distributed* to multiple channels. A promotion or payment method belongs to exactly one store; there is nothing to publish. Keep it simple — just the FK. **Amended 2026-07-23:** the single-owner FK stands, but "no distribution concept" is superseded for payment methods — per-channel/market/total/customer-group *eligibility* is layered on via `Spree::PaymentMethodRule` (see `5.7-payment-method-rules.md`), not via scoping columns or join tables.- **Multi-store behaviour moves to `spree_multi_store`.** The `has_many :stores` / `store_ids` accessors are preserved as **deprecation bridges** in core (returning `Array(store)`), and the real multi-store association is restored by the `spree_multi_store` extension on top of the untouched join tables. Same split as Product.- **Join tables survive 5.6, drop in 6.0.** `spree_promotions_stores` and `spree_payment_methods_stores` are left intact in the 5.6 migration so the extension can overlay the old relationship and so the backfill is re-runnable. The 6.0 cleanup migration drops them.- **`store_id` stays nullable in 5.6, `null: false` in 6.0.** Matching the Product migration (which left `store_id` nullable in 5.5), the 5.6 columns are nullable so installs that haven't run the backfill don't fail validations. The 6.0 cleanup migration enforces `null: false` once the data is known-clean.diff --git a/docs/plans/5.7-channel-markets.md b/docs/plans/5.7-channel-markets.mdnew file mode 100644index 0000000000..ea0cfd489b--- /dev/null+++ b/docs/plans/5.7-channel-markets.md@@ -0,0 +1,133 @@+# Channel → Markets Allowlist++**Status:** Draft+**Target:** Spree 5.7+**Depends on:** `6.0-channels-catalogs-b2b.md` (Channel, shipped 5.5), `5.6-store-channel-context-and-key-binding.md` (channel binding + `/store/channel`), Markets (existing)+**Author:** Damian + Claude+**Last updated:** 2026-07-23++## Summary++Let a Channel be limited to a subset of the store's Markets. Today Channel (where you sell) and Market (where your customers are) are fully orthogonal request axes — `Spree::Current.channel` comes from key binding / `X-Spree-Channel`, `Spree::Current.market` from `x-spree-country` — and nothing can express "the wholesale channel only serves EU markets" or "the POS channel is domestic-only". This plan adds an optional allowlist: a join table between Channel and Market, empty meaning "all markets" (today's behavior). The industry validates the link from both directions: Vendure and Saleor merge channel and market into one primitive (per-channel currencies/zones), Shopify bridges its separate primitives with *channel markets* (a market conditioned on a sales channel) and since May 2026 routes per-market Shopify Payments entities through it; Medusa alone leaves the axes unlinked. Spree keeps its two first-class models and adds the constraint — which also composes with `5.7-payment-method-rules.md` (`MarketRule` on a channel-restricted market set) into "wholesale channel → EU markets → invoice payment".++## Key Decisions (do not deviate without discussion)++- **A join table (`spree_channel_markets`), not a preference array.** Unlike rule config, this is a first-class admin-managed relationship that needs eager loading (`channel.markets`), serializer expansion, and Ransack — the same reasoning that made `ProductPublication` a table. `has_many :markets, through: :channel_markets`.+- **Empty allowlist = channel serves all store markets.** Matches the "empty = unrestricted" convention used by every rule preference. No backfill, zero behavior change on upgrade, and a single-market store never has to touch this.+- **Resolution degrades gracefully — no 422 for browsing.** A visitor whose country resolves to a market the channel doesn't serve gets the channel's default market experience (currency/locale/prices), exactly like a visitor from a country with no market at all. Hard ship-to enforcement at checkout is a separate concern, out of scope here (see Open Questions).+- **`Channel#default_market`** = the store's default market when allowed, else the first allowed market by position. `Spree::Current.market`'s fallback becomes channel-aware.+- **The Store API markets reference endpoints are the public surface of the restriction.** `/api/v3/store/markets` (and nested countries) return only the current channel's allowed markets. No `markets` embedding on the `/store/channel` serializer — the filtered reference endpoint already answers "which markets does this storefront serve" without creating a second source, and the no-enumeration rule (never leak other channels' config) stays intact.+- **Order-level integrity:** when both FKs are present, the order's market must be served by its channel — validated on market/channel assignment, and `resolve_market_from_currency` only considers allowed markets. Guards against clients forcing an off-channel `market_id` through the API.+- **Markets must belong to the channel's store** (validation on the join model), mirroring every cross-store guard in the codebase.+- **Deleting a market removes it from allowlists; a channel left with an empty allowlist reverts to "all markets".** Documented behavior + dashboard confirmation copy — not a deletion blocker (Market already blocks deleting the default/last market; further guards would make market cleanup miserable).+- **Management is dashboard-only** (markets multi-select in the channel sheet + Admin API), consistent with the 2026-07-21 decision — no legacy Rails admin surface.++## Design Details++### Models++```ruby+# app/models/spree/channel_market.rb+module Spree+ class ChannelMarket < Spree.base_class+ belongs_to :channel, class_name: 'Spree::Channel', touch: true+ belongs_to :market, class_name: 'Spree::Market'++ validates :channel, :market, presence: true+ validates :market_id, uniqueness: { scope: [:channel_id, *spree_base_uniqueness_scope] }+ validate :market_belongs_to_channel_store+ end+end+```++Table: `spree_channel_markets` — `channel_id` (null: false), `market_id` (null: false), timestamps, unique index on `(channel_id, market_id)`.++```ruby+# Spree::Channel additions+has_many :channel_markets, class_name: 'Spree::ChannelMarket', dependent: :destroy+has_many :markets, through: :channel_markets, class_name: 'Spree::Market'++# @return [ActiveRecord::Relation<Spree::Market>] markets this channel serves;+# an empty allowlist means every market in the store.+def allowed_markets+ channel_markets.exists? ? markets.order(:position) : store.markets.order(:position)+end++# @param market [Spree::Market]+# @return [Boolean]+def serves_market?(market)+ return false if market.nil?+ !channel_markets.exists? || markets.exists?(market.id)+end++# @return [Spree::Market, nil] the store default when served, else first allowed+def default_market+ store_default = store.default_market+ return store_default if serves_market?(store_default)+ allowed_markets.first+end+```++`Spree::Market` gains the inverse (`has_many :channel_markets, dependent: :destroy` + `has_many :channels, through:`) so market deletion cleans allowlist rows.++### Request resolution++Two touch points, both already centralized:++1. **`Spree::Api::V3::LocaleAndCurrency#set_market_from_country`** — after resolving `store.market_for_country(country)`, discard the market unless `current_channel.serves_market?(market)` (visitor falls through to the channel default, same as an unmatched country today).+2. **`Spree::Current#market` fallback** — becomes channel-aware: `super || channel&.default_market || store&.default_market` (the channel branch only diverges when an allowlist exists).++Derived effect: since Market drives currency/locale/tax-zone fallbacks, a restricted channel automatically constrains its sellable currency set to its allowed markets' currencies — converging on Vendure's `availableCurrencyCodes` / Saleor's per-channel currency without a second mechanism.++### Order integrity++- `Spree::Order#ensure_market_presence` resolves through `channel&.default_market` when the channel restricts markets.+- Validation: `market must be served by the order's channel` when both are set (skipped when either is nil — jobs/imports without channel context keep working).+- `resolve_market_from_currency` (currency-change hook) picks from `channel&.allowed_markets || store.markets`.++### Store API++- `Store::MarketsController` (+ `Markets::CountriesController`) scope through `current_channel.allowed_markets` instead of `current_store.markets`. These endpoints are guest-accessible reference data (`allow_guest_storefront_access!`) — filtering them is the entire public contract; nothing else changes shape.+- `GET /store/channel` (from `5.6-store-channel-context-and-key-binding.md`) is unchanged.++### Admin API v3++- Channel create/update accepts `market_ids: []` (prefixed `mkt_…` IDs, normalized + store-scope-validated on write; empty array clears the allowlist → all markets).+- Admin channel serializer exposes `market_ids` (prefixed) and `many :markets` via `expand=markets`.+- No new endpoints — the allowlist is part of the channel aggregate, matching how publications are managed through channel action endpoints rather than join-table CRUD.++### SDK & Dashboard++- `@spree/admin-sdk`: `market_ids` on the channel resource types; typelizer regeneration.+- Dashboard: a "Markets" multi-select (Combobox) in the channel edit sheet, defaulting to "All markets" when the allowlist is empty; confirmation copy when clearing the last entry ("this channel will serve all markets"). Translation keys in all dashboard locale files.+- `@spree/sdk` (Store): no changes — clients keep consuming `/store/markets`, which is now channel-scoped transparently.++## Migration Path++Additive only:++1. Migration creates `spree_channel_markets`. No backfill — every channel starts unrestricted.+2. Models + resolution changes ship together (behavior only diverges once an admin restricts a channel).+3. Admin API + dashboard UI.++The 5.6 wholesale seed channel stays unrestricted by default; the sample-data story ("wholesale serves EU markets only") is optional polish once `5.7-payment-method-rules.md` lands its seed changes.++## Constraints on Current Work++- **New market-dependent features must resolve through `channel.allowed_markets` / `Channel#serves_market?`** when a channel context exists — don't reach for `store.markets` directly in request-path code.+- **Don't expose other channels' market allowlists through any Store API surface** — the no-enumeration rule from `5.6-store-channel-context-and-key-binding.md` extends to this relationship.+- **Don't add market columns to `spree_channels`** (e.g. a `default_market_id`) — `Channel#default_market` is derived; a persisted override is a future decision.++## Open Questions++- **Hard checkout enforcement for unserved geographies** (reject ship-to addresses outside the channel's markets) — likely wants to compose with delivery-zone work (`6.0-delivery-rate-provider.md`) rather than live here.+- **Per-channel market *defaults*** (a persisted `default_market_id` override on Channel, à la Shopify's per-market primary) — deferred until a merchant needs a default other than "store default, else first by position".++## References++- Sibling plan: `docs/plans/5.7-payment-method-rules.md` (`MarketRule` composes with the allowlist)+- Channel infrastructure: `docs/plans/6.0-channels-catalogs-b2b.md`, `docs/plans/5.6-store-channel-context-and-key-binding.md`+- Market model: `spree/core/app/models/spree/market.rb`; resolution: `spree/api/app/controllers/concerns/spree/api/v3/locale_and_currency.rb` (`set_market_from_country`), `spree/core/app/models/spree/current.rb`+- Order market wiring: `spree/core/app/models/spree/order.rb` (`ensure_market_presence`, `resolve_market_from_currency`)+- Decision log: `docs/plans/decisions.md` 2026-07-23+- Competitive research (2026-07-23 session): Shopify channel markets (help.shopify.com/en/manual/online-sales-channels/channel-markets) + market types/precedence (help.shopify.com/en/manual/markets/getting-started/market-types) + multi-entity payments routed by market (help.shopify.com/en/manual/payments/shopify-payments/onboarding/selling-with-multiple-entities) · Vendure per-channel currencies/zones (docs.vendure.io/guides/core-concepts/channels/) · Saleor one-currency channels (docs.saleor.io/developer/channels/overview) · Medusa's unlinked axes as the cautionary contrast (docs.medusajs.com/resources/commerce-modules/region)diff --git a/docs/plans/5.7-payment-method-rules.md b/docs/plans/5.7-payment-method-rules.mdnew file mode 100644index 0000000000..848cc3899c--- /dev/null+++ b/docs/plans/5.7-payment-method-rules.md@@ -0,0 +1,210 @@+# Payment Method Rules++**Status:** Draft+**Target:** Spree 5.7+**Depends on:** `6.0-channels-catalogs-b2b.md` (Channel, shipped 5.5), `5.6-6.0-single-store-promotions-payment-methods.md` (single-store PaymentMethod, 5.6), Markets (existing), `5.7-channel-markets.md` (composes, not required)+**Author:** Damian + Claude+**Last updated:** 2026-07-23++## Summary++Add conditional availability rules to `Spree::PaymentMethod`: STI rule records (`Spree::PaymentMethodRule`) attached to a payment method that gate whether it is offered for a given order — by channel, market, order total, or customer group. This closes the gap surfaced by merchant asks ("wholesale channel gets net payment while DTC gets Stripe", "orders over 5k qualify for installments", "market-bound payment methods") and confirmed by the 2026-07-23 competitive review: Vendure gates payment methods per channel + a `PaymentMethodEligibilityChecker` (their canonical example is an order-total minimum), Medusa scopes payment providers per Region, Saleor resolves payment apps per channel, and Shopify covers the same ground with Payment Customization Functions (cart total, market, B2B company inputs) plus, since May 2026, per-market business entities on Shopify Payments (Plus-gated).++This **supersedes half of a key decision** in `5.6-6.0-single-store-promotions-payment-methods.md` ("promotions and payment methods have no distribution concept, so the FK is the whole story"): the single-store FK stays correct, but payment methods do have an *eligibility* dimension within a store. Rules are that dimension — mirroring how promotions already solve the identical problem (`Spree::Promotion::Rules::Channel/Market/CustomerGroup/ItemTotal`), rather than adding scoping columns or join tables to `PaymentMethod`.++## Problem++1. **No channel dimension.** Checkout availability is `store.payment_methods.active.available_on_front_end.select { |pm| pm.available_for_order?(order) }` — every active payment method appears on every channel. A store running a B2C channel and a gated wholesale channel (seeded by default since 5.6) cannot offer invoice/manual payment to wholesale buyers without also showing it at B2C checkout.+2. **No market dimension.** Payment methods that only make sense for certain geographies (local methods, region-specific providers) can't be bound to a Market, even though Markets already drive currency/locale/tax-zone per request.+3. **No conditional rules.** "Installments only above 5k", "invoice only for the Wholesale customer group" have no home. The only seam is the per-gateway `available_for_order?` override — code, not configuration, and invisible to admins.+4. **Blocks the per-channel credentials story.** Running two records of the same gateway with different API keys (groomed separately — see Open Questions) is only meaningful once each record can be confined to a channel or market.++## Key Decisions (do not deviate without discussion)++- **Mirror `Spree::PromotionRule`, don't invent a framework.** STI base `Spree::PaymentMethodRule` on a new `spree_payment_method_rules` table, subclasses under `app/models/spree/payment_method_rules/`, preference-schema-driven config (same `preference … parse_on_set: normalize_id_preference(…)` idiom as promotion/price rules), registry-validated `type`. This is the fourth instance of an established house pattern (PromotionRule, PriceRule, OrderRoutingRule) — deviating from it needs a reason.+- **No rules = available everywhere.** A payment method with zero rules behaves exactly as today. No backfill, no behavior change on upgrade.+- **AND semantics.** All active rules on a payment method must pass. No `match_policy` — "any" composition is a future addition if a real merchant needs it (none of the surveyed platforms offer OR at this layer).+- **Empty preference within a rule = unrestricted** (`ChannelRule` with no channels selected passes) — matching the PriceRule/PromotionRule convention so admin half-configured rules fail open per-rule, not per-method.+- **One enforcement seam: `PaymentMethod#eligible_for_order?(order)`** = existing `available_for_order?(order)` gateway hook `&&` all active rules pass. `Order#collect_frontend_payment_methods` switches to it. Because `Spree::Payments::Create` (and via it the Store API payments + payment-sessions controllers) already resolves the payment method through `collect_frontend_payment_methods`, listing and creation are enforced server-side by the same change — a storefront cannot attach an ineligible method by ID.+- **Admin/backoffice bypasses rules.** `collect_backend_payment_methods` and the `Spree::Payment` model validation keep checking only `available_for_order?` + `available_for_store?`. An admin taking a phone order can use any active method — matching Shopify, where Payment Customization Functions run at checkout only. Rules are a *storefront checkout* concept.+- **Rules evaluate the order's persisted context** (`order.channel_id`, `order.market_id`, `order.total`, `order.user`), never `Spree::Current` — webhook/job/admin evaluation must not depend on request state.+- **Rules belong to the payment method only** — `belongs_to :payment_method`, store delegated (`payment_method.store`). No `store_id` column (unlike `OrderRoutingRule`, which needs it for its own scoping); ID-preference normalization scopes lookups to the owning store (`rule.payment_method.store.channels`, `.markets`, `.customer_groups`) so cross-store IDs can't sneak in.+- **Initial rule set:** `ChannelRule`, `MarketRule`, `OrderTotalRule` (min/max), `CustomerGroupRule`. `CompanyRule`/`CompanyLocationRule` wait for the 6.1 Company tree. No Zone rule — Market is the geographic axis going forward (`6.0-tax-provider.md` drops Zone).+- **Registry:** `Spree.payment_method_rules` (array of class names, defaulted in the engine, extensible by plugins) — same shape as `Spree.order_routing.rules`; `type_must_be_registered` validation on the base class.+- **Management is dashboard-only** (Admin API v3 + React dashboard). No legacy Rails admin UI, per the 2026-07-21 order-routing-rules decision — the legacy admin is in maintenance mode.+- **Net-terms is out of scope.** The wholesale demo is served by an existing manual-style method (e.g. `Check`) + a `ChannelRule` on the wholesale channel. First-class net terms (due dates, credit limits, deposits) belongs on Company/CompanyLocation per the Shopify model and is deferred to the post-6.1 B2B plan.+- **`display_on` is orthogonal and untouched.** Rules filter *within* the storefront-visible set; the `5.5-6.0-display-on-to-boolean.md` migration proceeds independently.++## Design Details++### Base class++```ruby+# app/models/spree/payment_method_rule.rb+module Spree+ class PaymentMethodRule < Spree.base_class+ has_prefix_id :pmrule++ belongs_to :payment_method, class_name: 'Spree::PaymentMethod',+ inverse_of: :payment_method_rules, touch: true++ delegate :store, to: :payment_method++ attribute :active, :boolean, default: true++ validates :type, :payment_method, presence: true+ # One instance of each rule kind per payment method — duplicates would+ # either be a no-op or contradict themselves under AND semantics.+ validates :type, uniqueness: { scope: [:payment_method_id, *spree_base_uniqueness_scope] }+ validate :type_must_be_registered++ scope :active, -> { where(active: true) }++ # @param order [Spree::Order]+ # @return [Boolean] whether the payment method may be offered for this order+ def eligible?(order)+ raise NotImplementedError, "#{self.class.name} must implement #eligible?"+ end++ def self.human_name+ Spree.t("payment_method_rule_types.#{api_type}.name", default: api_type.titleize)+ end++ def self.human_description+ Spree.t("payment_method_rule_types.#{api_type}.description", default: '')+ end++ def self.registered_subclasses+ Array(Spree.payment_method_rules)+ end+ end+end+```++Table: `spree_payment_method_rules` — `type` (string, null: false), `payment_method_id` (reference, null: false), `active` (boolean, null: false), `preferences` (text), timestamps. Index on `payment_method_id`; unique index on `(payment_method_id, type)`.++### Rules++```ruby+# app/models/spree/payment_method_rules/channel_rule.rb+module Spree+ module PaymentMethodRules+ class ChannelRule < Spree::PaymentMethodRule+ preference :channel_ids, :array, default: [],+ parse_on_set: normalize_id_preference(+ klass: Spree::Channel,+ scope: ->(rule) { rule.payment_method&.store&.channels || Spree::Channel.none }+ )++ def eligible?(order)+ return true if preferred_channel_ids.empty?+ preferred_channel_ids.map(&:to_s).include?(order.channel_id.to_s)+ end+ end+ end+end+```++`MarketRule` is identical over `market_ids` / `order.market_id`. `CustomerGroupRule` matches when `order.user` belongs to any preferred group (guest orders fail a configured group rule — an invoice method restricted to "Wholesale" must never surface to guests). `OrderTotalRule`:++```ruby+# app/models/spree/payment_method_rules/order_total_rule.rb+module Spree+ module PaymentMethodRules+ class OrderTotalRule < Spree::PaymentMethodRule+ preference :min_total, :decimal, default: nil+ preference :max_total, :decimal, default: nil++ # Thresholds are interpreted in the order's currency (see Open Questions+ # for multi-currency refinement).+ def eligible?(order)+ total = order.total+ return false if preferred_min_total.present? && total < preferred_min_total+ return false if preferred_max_total.present? && total > preferred_max_total+ true+ end+ end+ end+end+```++### Enforcement++```ruby+# Spree::PaymentMethod+has_many :payment_method_rules, class_name: 'Spree::PaymentMethodRule',+ inverse_of: :payment_method, dependent: :destroy++# Storefront checkout eligibility: the gateway hook AND every active rule.+def eligible_for_order?(order)+ available_for_order?(order) && payment_method_rules.active.all? { |rule| rule.eligible?(order) }+end+```++```ruby+# Spree::Order#collect_frontend_payment_methods+store.payment_methods.active.available_on_front_end+ .includes(:payment_method_rules)+ .select { |pm| pm.eligible_for_order?(self) }+```++`collect_backend_payment_methods`, `Spree::Payment` validation, and `available_for_store?` are unchanged. The Store API cart payment-methods listing, `Payments::Create`, and payment-session creation all flow through `collect_frontend_payment_methods` already — no additional controller changes.++### Admin API v3++Mirrors the order-routing-rules surface (nested CRUD + type discovery):++```+GET /api/v3/admin/payment_methods/:payment_method_id/rules+POST /api/v3/admin/payment_methods/:payment_method_id/rules+PATCH /api/v3/admin/payment_method_rules/:id+DELETE /api/v3/admin/payment_method_rules/:id+GET /api/v3/admin/payment_method_rules/types # discovery: type, label, description, preference_schema+```++- Serializer: `id`, `type`, `active`, `preferences` (prefixed IDs in array prefs — the `normalize_id_preference` write path accepts them; the read path serializes back to prefixed), timestamps.+- Scope gating: `read_payment_methods` / `write_payment_methods` (rules are part of the payment-method aggregate — no new scope).+- Admin payment-method serializer gains `many :payment_method_rules` via `expand=payment_method_rules`.++### Store API++No new surface. The cart's payment-method listing is simply filtered; rules are never serialized to the storefront. (Same posture as channel gating: enforcement in the API, configuration invisible to clients.)++### SDK & Dashboard++- `@spree/admin-sdk`: `client.paymentMethods.rules.{list,create,update,delete}` + `client.paymentMethodRules.types()`; typelizer types.+- Dashboard: rules editor inside the payment-method edit form — same schema-driven `PreferencesForm` composition as the channel sheet's routing-rules editor (add-rule picker fed by the `types` endpoint, active toggles). Translation keys under `payment_method_rule_types.*` (Ruby) and `admin.paymentMethodRules.*` (dashboard locales, all languages).++### Seeds / sample data++Extend the 5.6 wholesale demo: sample data attaches a `ChannelRule` (wholesale channel) to the seeded manual/Check payment method and leaves Stripe/card methods unrestricted — a fresh install then demos differentiated checkout payment options per channel out of the box.++## Migration Path++Additive only:++1. Migration creates `spree_payment_method_rules`. No changes to existing tables, no backfill — zero-rule methods behave exactly as before.+2. Ship models + enforcement + Admin API + dashboard together (the feature is invisible until a rule is created).+3. Sample-data/seed changes last.++## Constraints on Current Work++- **Don't add ad-hoc `channel_id`/`market_id` columns or join tables to `Spree::PaymentMethod`** — channel/market confinement is a rule.+- **New checkout code must resolve payment methods through `collect_frontend_payment_methods`** (or `eligible_for_order?`), never by re-querying `store.payment_methods` and filtering manually — the single seam is what makes enforcement airtight.+- **The Stripe-gateway pull-in (`decisions.md` 2026-07-15) must not bake in "one payment method per provider per store"** assumptions beyond the existing admin `types` filter — the multi-credentials grooming (below) may relax it.+- **Per-gateway `available_for_order?` overrides remain valid** (StoreCredit's coverage check, custom gateways) — rules layer on top, they don't replace the hook.++## Open Questions++- **Multi-currency thresholds on `OrderTotalRule`.** v1 interprets min/max in the order's currency. Options for later: per-currency amounts (Vendure stores minor units in channel currency), or normalizing through the store default currency. Revisit when a multi-market merchant hits it.+- **Per-channel/per-market provider credentials ("multiple Stripe accounts", Shopify's multi-entity model).** Explicitly parked for grooming (2026-07-23): candidate shapes are separate PaymentMethod records per channel/market (Vendure/Medusa style — needs the admin `types` "already installed" filter relaxed) vs. per-channel credential sets on one record (Saleor style). Also carries the legal-entity attribution question (payouts/compliance per entity). Do not implement under this plan.+- **Backend enforcement toggle.** If merchants ask for rules to bind admin-created orders too, add an explicit store preference rather than changing the default.++## References++- Sibling plan: `docs/plans/5.7-channel-markets.md` (Channel→Markets allowlist; `MarketRule` + a restricted channel compose into "this channel's markets pay this way")+- Superseded rationale: `docs/plans/5.6-6.0-single-store-promotions-payment-methods.md` (Key Decisions — "No Channel/Publication layer")+- Pattern references: `spree/core/app/models/spree/promotion_rule.rb`, `spree/core/app/models/spree/promotion/rules/channel.rb`, `spree/core/app/models/spree/price_rules/channel_rule.rb`, `spree/core/app/models/spree/order_routing_rule.rb`+- Enforcement seam: `spree/core/app/models/spree/order.rb` (`collect_frontend_payment_methods`), `spree/core/app/services/spree/payments/create.rb`+- Decision log: `docs/plans/decisions.md` 2026-07-23 (this plan + multi-credentials grooming deferral), 2026-07-21 (dashboard-only rule management precedent)+- Competitive research (2026-07-23 session): Vendure `PaymentMethodEligibilityChecker` (docs.vendure.io/reference/typescript-api/payment/payment-method-eligibility-checker) · Medusa Region↔PaymentProvider link (docs.medusajs.com/resources/commerce-modules/payment/links-to-other-modules) · Saleor per-channel payment apps (docs.saleor.io/developer/payments/payment-apps) · Shopify Payment Customization Functions (shopify.dev/docs/api/functions/latest/payment-customization) + multi-entity Shopify Payments (help.shopify.com/en/manual/payments/shopify-payments/onboarding/selling-with-multiple-entities)diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 2b9a2fdaca..2cf42b4a1b 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,33 @@+## 2026-07-23: Payment-method eligibility rules + Channel→Markets allowlist target 5.7; multi-credential grooming deferred++Merchant asks (wholesale net payment vs DTC Stripe, installments above an+order-total threshold, market-bound payment methods, channels limited to+certain markets) plus a four-platform review (Vendure channel-scoped+PaymentMethods + `PaymentMethodEligibilityChecker`, Medusa region-scoped+payment providers, Saleor per-channel payment apps, Shopify Payment+Customization Functions + the May-2026 per-market multi-entity Shopify+Payments) settled three things:++1. **`5.7-payment-method-rules.md`** — `Spree::PaymentMethodRule` STI+ (Channel / Market / OrderTotal / CustomerGroup rules), mirroring the+ PromotionRule/PriceRule/OrderRoutingRule house pattern; enforced through+ the single `Order#collect_frontend_payment_methods` seam; storefront-only+ (admin/backoffice bypasses). Supersedes the "payment methods have no+ distribution concept" rationale in+ `5.6-6.0-single-store-promotions-payment-methods.md` — the single-store FK+ stands, eligibility is layered on via rules.+2. **`5.7-channel-markets.md`** — optional Channel→Markets allowlist+ (`spree_channel_markets`, empty = all markets), enforced in market+ resolution, the Store API markets reference endpoints, and order+ validation. Composes with `MarketRule` above.+3. **Deferred for grooming: multiple provider credentials / legal entities+ in one store** (two Stripe accounts split by channel or market, Shopify's+ multi-entity model). Candidate shapes — separate PaymentMethod records per+ channel/market (Vendure/Medusa style; needs the Admin API `types`+ "already installed" filter relaxed) vs per-channel credential mapping on+ one record (Saleor style) — plus the legal-entity attribution question+ (per-entity payouts, compliance, reporting). No plan yet; do not implement.+## 2026-07-21: Order routing rules get admin management in the React dashboard onlyPer-channel `Spree::OrderRoutingRule` management (the Phase 2 "Admin API + SPA