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
Implement payment methods management UI in Admin SPA (#14036)
Damian Legawiec48058ae8fae1
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0598661069..48e0f43a94 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -41,6 +41,7 @@ Current plans:- `5.4-metafield-translations.md` — Translate MetafieldDefinition names + Metafield text values (ShortText, LongText, RichText) via Mobility translation tables- `5.5-admin-auth-cookie-refresh.md` — Move admin SPA refresh token to httpOnly cookie, access token in memory, double-submit CSRF, server-side logout that destroys RefreshToken row. Breaking change shipped as a single coordinated bump (admin-sdk is unreleased)- `5.5-admin-spa-csv-export.md` — Reuse existing `Spree::Export` infra; add Admin API CRUD + `client.exports` SDK + toolbar button/modal + polling flow on Products/Orders/Customers index pages. Filters round-trip via Ransack JSON; download via short-lived signed Blob URL+- `5.5-6.0-display-on-to-boolean.md` — Collapse `display_on` tri-state on PaymentMethod + ShippingMethod/DeliveryMethod to a single `storefront_visible` boolean. 5.5 ships `alias_attribute` + dual serializer fields; 6.0 drops the column and the `Spree::DisplayOn` concern. Mirrors the custom-fields rename pattern.Completed plans:- `5.4-store-api-bridges.md` — Bridge 6.0 naming into 5.4 Store API (implemented, PR #13782)diff --git a/docs/plans/5.5-6.0-display-on-to-boolean.md b/docs/plans/5.5-6.0-display-on-to-boolean.mdnew file mode 100644index 0000000000..ef05b0a584--- /dev/null+++ b/docs/plans/5.5-6.0-display-on-to-boolean.md@@ -0,0 +1,230 @@+# `display_on` → `storefront_visible` (PaymentMethod, ShippingMethod / DeliveryMethod)++**Status:** Draft+**Target:** 5.5 (API alias + `alias_attribute` shim) + 6.0 (schema rename, drop the `Spree::DisplayOn` tri-state concern)+**Depends on:** `5.5-6.0-custom-fields-rename.md` (same bridge pattern, already in flight). `6.0-fulfillment-and-delivery.md` (drives the `ShippingMethod → DeliveryMethod` rename — this plan piggybacks on that wave).+**Author:** Damian + Claude+**Last updated:** 2026-05-15++## Summary++Collapse the tri-state `display_on` enum (`both` / `front_end` / `back_end`) on `Spree::PaymentMethod` and `Spree::ShippingMethod` to a single boolean `storefront_visible`, mirroring what `5.5-6.0-custom-fields-rename.md` does for `MetafieldDefinition`. The `front_end`-only state (visible to customers but hidden from admin) doesn't map to any real workflow — staff need to see every payment / shipping option to look up past transactions, process refunds, edit orders, etc. The remaining two states (`both`, `back_end`) collapse cleanly to a boolean.++Ships in two phases:++1. **5.5** — Add `storefront_visible` accessor (read + write) on both models that proxies to the existing `display_on` column. Admin API v3 speaks `storefront_visible` only on both reads and writes. The legacy Rails admin engine (`spree/admin`) keeps writing `display_on` via its form helpers — that path stays on the model layer until 6.0. SDK ships `storefront_visible` only. Admin SPA uses `<StorefrontVisibleSwitch>`. **No schema changes.**+2. **6.0** — Replace the `display_on` string column with `storefront_visible` boolean on both tables. Remove the `Spree::DisplayOn` concern. Drop the `display_on` API alias.++## Key Decisions (do not deviate without discussion)++- **Boolean, not tri-state.** `front_end`-only doesn't reflect a real workflow — admin staff need visibility into every payment/shipping option for support, refunds, reconciliation, and manual order entry. Same reasoning as the custom-fields plan.+- **`storefront_visible` not `available_on_storefront`.** Matches the custom-fields plan exactly; one term for the same concept across the whole product.+- **Default `true`.** Most payment/shipping methods are customer-facing. `back_end` is the exception (manual check entry, internal wire-transfer methods, refund-only methods).+- **5.5 reads expose `storefront_visible` only; writes still accept both names.** The Admin API is the only consumer of `display_on` today (the admin SPA, which is `next`-tagged and pre-1.0); migrating the wire shape now is cheaper than carrying two read paths for six months. Writes stay permissive so any out-of-tree integration that sends `display_on` keeps working through the 5.5 cycle.+- **Drop `Spree::DisplayOn` concern in 6.0.** The concern only had three callers (`PaymentMethod`, `ShippingMethod`, `MetafieldDefinition`); custom fields are already migrating off via `5.5-6.0-custom-fields-rename.md`, so removing the concern entirely in 6.0 is a clean sweep.+- **Migration is non-destructive in 5.5.** No data migration, no removed columns. Anyone reading `display_on` keeps working; anyone reading `storefront_visible` gets the boolean.+- **The `front_end`-only edge case (if any merchant set it) maps to `storefront_visible: true`.** Same as the custom-fields plan's data migration.++## Design Details++### Current model (5.4)++`Spree::PaymentMethod` and `Spree::ShippingMethod` both:+- Have a `display_on` string column (values: `'both' | 'front_end' | 'back_end'`).+- `include Spree::DisplayOn` (concern at `spree/core/app/models/concerns/spree/display_on.rb`).+- Expose `display_on` in their Admin API serializers (and Store API where applicable).++`Spree::DisplayOn` concern provides:+- `scope :available` (only `both`)+- `scope :available_on_front_end` (`front_end` + `both`)+- `scope :available_on_back_end` (`back_end` + `both`)+- `validates :display_on, presence: true, inclusion: { in: DISPLAY.map(&:to_s) }`+- `available_on_front_end?` instance predicate++### Target model (6.0)++- `display_on:string` column → `storefront_visible:boolean` (default `true`, `null: false`).+- Concern goes away. Scopes/predicates inline on each model (or a smaller `Spree::StorefrontVisible` concern if more models want it later — defer until a third caller exists).+- Serializers expose `storefront_visible:boolean`. The `display_on` field is removed from the wire.++### Phase 1: 5.5 API Bridge + `alias_attribute` shim++Mirrors `5.5-6.0-custom-fields-rename.md` exactly. No schema changes.++#### Shared accessor + scopes inside `Spree::DisplayOn`++`Spree::PaymentMethod`, `Spree::ShippingMethod`, and `Spree::MetafieldDefinition` all `include Spree::DisplayOn` today. We extend the existing concern with the new vocabulary so all three callers pick it up automatically — no per-model copy:++```ruby+# spree/core/app/models/concerns/spree/display_on.rb (5.5)+module Spree+ module DisplayOn+ extend ActiveSupport::Concern++ DISPLAY = [:both, :front_end, :back_end]++ included do+ scope :available, -> { where(display_on: [:both]) }+ scope :available_on_front_end, -> { where(display_on: [:front_end, :both]) }+ scope :available_on_back_end, -> { where(display_on: [:back_end, :both]) }++ # New canonical scopes (5.5 → 6.0).+ scope :storefront_visible, -> { where.not(display_on: 'back_end') }+ scope :admin_only, -> { where(display_on: 'back_end') }++ validates :display_on, presence: true, inclusion: { in: DISPLAY.map(&:to_s) }++ def available_on_front_end?+ display_on == 'front_end' || display_on == 'both'+ end++ # 5.5 bridge — `storefront_visible` is the canonical wire field.+ # `back_end` → false; everything else → true.+ def storefront_visible+ display_on != 'back_end'+ end++ def storefront_visible=(value)+ self.display_on = ActiveModel::Type::Boolean.new.cast(value) ? 'both' : 'back_end'+ end+ end+ end+end+```++Reads: `back_end` → `false`, anything else (`both` or the legacy `front_end`) → `true`. Writes: `true` → `both`, `false` → `back_end`. Round-trip works.++`Spree::MetafieldDefinition` already defines `storefront_visible` accessors per `5.5-6.0-custom-fields-rename.md` — those become redundant once the concern provides them and can be deleted. Coordinate via that plan's checklist.++In 6.0, the entire concern goes away — `storefront_visible` becomes a real column accessor on each model, scopes inline where needed (or, if a third caller wants it post-6.0, a smaller `Spree::StorefrontVisible` concern can be extracted).++#### Serializer changes++`Admin::PaymentMethodSerializer` (and any future `Admin::ShippingMethodSerializer`):++```ruby+# Before+typelize display_on: :string+attributes :display_on++# After (5.5) — wire field is the boolean only+typelize storefront_visible: :boolean+attributes :storefront_visible+```++`display_on` is dropped from the wire response. Reads-side consumers (admin SPA, SDK) must use `storefront_visible`. The DB column lives on under the hood — only the API surface changes.++#### Permitted params++`Spree::PermittedAttributes.payment_method_attributes` and `.shipping_method_attributes` keep **both** `:display_on` and `:storefront_visible` for the 5.5 cycle so out-of-tree integrations that still submit the legacy field on writes keep working. The accessor on the concern collapses both to the same underlying column. **Clients should submit one or the other, not both** — sending both is undefined behavior and depends on JSON key order in the request body. Document `storefront_visible` as the canonical name; treat `display_on` writes as a back-compat shim that disappears in 6.0.++#### SDK / TypeScript++```ts+// Before+export type DisplayOnValue = 'both' | 'front_end' | 'back_end'++export interface PaymentMethod {+ display_on: DisplayOnValue+ // …+}++// After (5.5) — boolean only; legacy types removed+export interface PaymentMethod {+ storefront_visible: boolean+ // …+}+```++`DisplayOnValue` / `PaymentMethodDisplayOn` types are removed entirely. The admin SDK is still `next`-tagged (per `5.5-admin-auth-cookie-refresh.md`), so out-of-tree TypeScript consumers are minimal — deleting beats deprecating.++Param shapes (`PaymentMethodCreateParams`, `PaymentMethodUpdateParams`, future shipping equivalents) expose `storefront_visible?: boolean` only. The server still accepts `display_on` on writes (see Permitted params above), but the SDK doesn't type it. TS callers who need to send the legacy field can cast.++#### Admin SPA++- `<StorefrontVisibleSwitch>` — a labelled `Switch` ("Visible on storefront" / "Admin only" hint text). Used on every payment/shipping form.+- Table cells render via `<ActiveBadge active={pm.storefront_visible} activeLabel="Visible" inactiveLabel="Admin only" />` so the visibility column matches the visual treatment of the existing Active column.++The switch wires up like the rest: `<StorefrontVisibleSwitch control={form.control} name="storefront_visible" />`. No tri-state `<DisplayOnSelect>` exists — it was deleted in the same change that introduced the switch.++### Phase 2: 6.0 Schema Change++Part of the 6.0 model rename wave (alongside `Shipment → Fulfillment`, `ShippingMethod → DeliveryMethod`, `Metafield → CustomField`).++#### Migrations++```ruby+class AddStorefrontVisibleToPaymentMethods < ActiveRecord::Migration[7.2]+ def change+ add_column :spree_payment_methods, :storefront_visible, :boolean, default: true, null: false+ # backfill via rake task before deploying the model change:+ # UPDATE spree_payment_methods SET storefront_visible = (display_on != 'back_end')+ remove_column :spree_payment_methods, :display_on, :string+ end+end+```++Same shape for `spree_shipping_methods` (or `spree_delivery_methods` if the 6.0 table rename ships first — coordinate with `6.0-fulfillment-and-delivery.md`).++Data migration in a rake task (not the migration itself, per CLAUDE.md: "Data transformations go in rake tasks, never in migrations"):++```ruby+namespace :spree do+ namespace :upgrade do+ task display_on_to_storefront_visible: :environment do+ Spree::PaymentMethod.unscoped.where(display_on: 'back_end').update_all(storefront_visible: false)+ Spree::ShippingMethod.unscoped.where(display_on: 'back_end').update_all(storefront_visible: false)+ # everything else (both, front_end, NULL) keeps the default true+ end+ end+end+```++#### Model cleanup++- Remove `include Spree::DisplayOn` from `PaymentMethod` and `ShippingMethod` / `DeliveryMethod`.+- Remove the `storefront_visible` getter/setter shims (they become the actual column accessors).+- Remove the `display_on` API alias from serializers.+- Delete the `Spree::DisplayOn` concern file entirely (no more callers).++#### SDK cleanup++- Remove `DisplayOnValue` type alias.+- Remove `display_on` from `PaymentMethod`, `ShippingMethod`/`DeliveryMethod` interfaces.+- Remove `display_on?` from all create/update param shapes.+- Delete the `<DisplayOnSelect>` component and `DISPLAY_ON_LABELS` constant in the admin SPA.++## Migration Path++### For Spree merchants / hosters (5.5 → 6.0)+1. Update Spree to 5.5 — no action required. `display_on` keeps working; `storefront_visible` becomes available.+2. Update Spree to 6.0 — run `bin/rails spree:upgrade:display_on_to_storefront_visible` against the production database before deploying the 6.0 code.++### For integrations consuming the Admin / Store API+1. **5.5:** start reading `storefront_visible` (boolean) instead of `display_on` (string). Both ship side-by-side.+2. **5.5:** start writing `storefront_visible` in create/update calls. The server prefers it over `display_on` when both are provided.+3. **6.0:** `display_on` disappears from responses and param shapes. Drop any code that reads or writes it.++### For extension / plugin developers+1. **5.5:** if your extension reads `payment_method.display_on` directly, switch to `payment_method.storefront_visible`.+2. **5.5:** if your extension queries `where(display_on: 'back_end')`, use the new `admin_only` scope or `where(storefront_visible: false)`.+3. **6.0:** any remaining `display_on` references stop compiling — the column is gone.++## Constraints on Current Work++- **All new Spree code (5.5+) should use `storefront_visible`** in serializers, controllers, models, specs, and the Admin SPA. `display_on` is in soft-deprecation as of this plan's adoption.+- **The `<DisplayOnSelect>` component shipped in [PR adding payment-method UX] stays callable for one minor cycle**, but new forms should use the new `<StorefrontVisibleSwitch>` once it lands. The existing component is not deleted in 5.5 — it just has no new callers.+- **Custom Fields (`MetafieldDefinition`) — handled by `5.5-6.0-custom-fields-rename.md`**. Don't try to consolidate the two plans; the custom-fields one is further along and renames more than just the visibility field.+- **The `Spree::DisplayOn` concern is frozen.** No new models should `include Spree::DisplayOn`; new resources that need storefront/admin visibility should add a `storefront_visible:boolean` column directly.++## Open Questions++- **Should we also rename `available_on_front_end` (the instance predicate from `Spree::DisplayOn`) in 5.5?** Leaning yes — alias it to `storefront_visible` and add a deprecation warning when called. Removed in 6.0.+- **Does the Store API expose `display_on` on `ShippingMethod`?** Need to audit — if yes, the bridge needs to handle the Store API surface too, not just Admin.+- **Naming for the 6.0 concern (if any):** if a third caller wants storefront/admin visibility post-6.0, do we extract a `Spree::StorefrontVisible` concern, or just keep inline columns + scopes per model? Defer until a third caller appears.++## References++- `5.5-6.0-custom-fields-rename.md` — same bridge pattern, further along; the canonical reference for how to do this kind of rename.+- `6.0-fulfillment-and-delivery.md` — `ShippingMethod → DeliveryMethod` rename context. This plan touches the same model; coordinate the 6.0 migration order so the column rename and the table rename happen in the right order.+- `decisions.md` — visibility-system simplification decisions live here once this plan is finalized.diff --git a/docs/plans/6.0-admin-spa.md b/docs/plans/6.0-admin-spa.mdindex 20c9111cda..5f861fd0e1 100644--- a/docs/plans/6.0-admin-spa.md+++ b/docs/plans/6.0-admin-spa.md@@ -333,7 +333,17 @@ Resources covered (matches the Rails struct): `admin_users`, `coupon_codes`, `cu**Form pages (settings):**- `store.form` — store edit form sections.-- `payment_method.form`, `shipping_method.form` — form bodies for those resources.+- `shipping_method.form` — form body for shipping methods.++**Payment method editors (per-provider):**++Mirror the `promotion.rule_form.<type>` / `promotion.action_form.<type>` pattern — slot keys end in the provider's STI shorthand (`bogus`, `stripe`, …):++- `payment_method.guide.<type>` — banner above the form (install instructions, "Connect via OAuth" CTAs, docs links).+- `payment_method.form.<type>` — replaces the generic `<PreferencesForm>` for that provider. Use when a gateway needs more than a key/value form (Stripe OAuth Connect, PayPal Onboarding, Adyen API-key wizard).+- `payment_method.actions.<type>` — footer actions (Test webhook, View webhook URL, Disconnect).++All three receive `PaymentMethodEditorContext` from `packages/admin/src/components/spree/payment-method-editors/types.ts`: `{ mode: 'create' | 'edit', type, paymentMethod, preferenceSchema, preferences, onPreferencesChange, form }`. Spree core registers nothing by default — `<PreferencesForm>` is the generic fallback for `payment_method.form`.**Sub-nav (was `content_for(:page_tabs)` plus `_*_nav.html.erb`):**- `nav.tax`, `nav.shipping`, `nav.stock`, `nav.returns_and_refunds`, `nav.team` — consumed by `<PageTabs>` on settings pages where these existed in Rails.diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.tsindex 62faaa3caf..b781d543b3 100644--- a/packages/admin-sdk/src/index.ts+++ b/packages/admin-sdk/src/index.ts@@ -18,6 +18,8 @@ export { createAdminClient } from './client'// Param types (request bodies)export type * from './params'+// Runtime helpers exported from params.ts alongside their related types.+export { isMaskedSecret, PREFERENCE_MASK_TOKEN } from './params'// All entity typesexport * from './types'diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 3f33fc3eba..cdca98a601 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -494,6 +494,26 @@ export interface PreferenceField {default: unknown}+/**+ * Mask token the server applies to `:password`-typed preferences before+ * returning them. The value `••••` followed by the original secret's+ * last four characters — Stripe's "stored, last 4 shown" pattern.+ *+ * Mirrors `Spree::Preferences::Masking::TOKEN` on the backend. The+ * backend's write-side guard skips updating a `:password` preference+ * whose submitted value starts with this token, so clients can+ * round-trip a fetched payload without overwriting the real secret.+ */+export const PREFERENCE_MASK_TOKEN = '••••'++/**+ * @param value Anything that might be a masked secret returned from the API.+ * @returns true when the value carries the leading mask token.+ */+export function isMaskedSecret(value: unknown): value is string {+ return typeof value === 'string' && value.startsWith(PREFERENCE_MASK_TOKEN)+}+/*** The shape returned by `/<resource>/types` endpoints — one entry per* registered subclass with its preference schema. Used to build "Add@@ -506,20 +526,14 @@ export interface ResourceTypeDefinition {preference_schema: PreferenceField[]}-/**- * Where the merchant exposes a payment method — `front_end` shows it on the- * storefront, `back_end` only in the admin (e.g. manual check capture),- * `both` everywhere.- */-export type PaymentMethodDisplayOn = 'both' | 'front_end' | 'back_end'-export interface PaymentMethodCreateParams {/** Fully-qualified STI subclass name, e.g. 'Spree::PaymentMethod::Check'. */type: stringname: stringdescription?: string | nullactive?: boolean- display_on?: PaymentMethodDisplayOn+ /** `false` → admin-only; `true` → also on the storefront. */+ storefront_visible?: booleanauto_capture?: boolean | nullposition?: numbermetadata?: Record<string, unknown>@@ -531,7 +545,8 @@ export interface PaymentMethodUpdateParams {name?: stringdescription?: string | nullactive?: boolean- display_on?: PaymentMethodDisplayOn+ /** `false` → admin-only; `true` → also on the storefront. */+ storefront_visible?: booleanauto_capture?: boolean | nullposition?: numbermetadata?: Record<string, unknown>diff --git a/packages/admin-sdk/src/types/generated/OptionType.ts b/packages/admin-sdk/src/types/generated/OptionType.tsindex 38164807e4..62a58b393c 100644--- a/packages/admin-sdk/src/types/generated/OptionType.ts+++ b/packages/admin-sdk/src/types/generated/OptionType.ts@@ -1,4 +1,4 @@-// Typelizer digest aafd25e420f86988b84c09e7c92a5b80+// Typelizer digest 4277db9a34a5e4f9e919ebdb57bd7e79//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {OptionValue} from '@/types'@@ -10,6 +10,7 @@ interface OptionType {position: number;kind: string;metadata: Record<string, unknown>;+ filterable: boolean;created_at: string;updated_at: string;option_values: Array<OptionValue>;diff --git a/packages/admin-sdk/src/types/generated/PaymentMethod.ts b/packages/admin-sdk/src/types/generated/PaymentMethod.tsindex 351c79a238..7bbbed1b6c 100644--- a/packages/admin-sdk/src/types/generated/PaymentMethod.ts+++ b/packages/admin-sdk/src/types/generated/PaymentMethod.ts@@ -1,4 +1,4 @@-// Typelizer digest cc3438e4b853754508739b48538ce6d9+// Typelizer digest fd47b56abdaf5f30ee85c0f108b4a6c0//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -12,7 +12,7 @@ interface PaymentMethod {metadata: Record<string, unknown>;active: boolean;auto_capture: boolean | null;- display_on: string;+ storefront_visible: boolean;position: number;created_at: string;updated_at: string;diff --git a/packages/admin/src/components/spree/drag-handle.tsx b/packages/admin/src/components/spree/drag-handle.tsxnew file mode 100644index 0000000000..46717eb78c--- /dev/null+++ b/packages/admin/src/components/spree/drag-handle.tsx@@ -0,0 +1,49 @@+import type { DraggableAttributes, DraggableSyntheticListeners } from '@dnd-kit/core'+import { GripVerticalIcon } from 'lucide-react'+import type { ComponentProps } from 'react'+import { cn } from '@/lib/utils'++interface DragHandleProps extends Omit<ComponentProps<'button'>, 'type'> {+ /** `attributes` from `useSortable` / `useDraggable`. */+ attributes: DraggableAttributes+ /** `listeners` from `useSortable` / `useDraggable`. */+ listeners: DraggableSyntheticListeners+}++/**+ * Standard drag handle for `useSortable` rows. Pair with a `useSortable` row+ * by spreading its `attributes` + `listeners` onto this component:+ *+ * ```tsx+ * const { attributes, listeners, setNodeRef, ... } = useSortable({ id })+ * return (+ * <tr ref={setNodeRef}>+ * <td className="w-8 touch-none p-0">+ * <DragHandle attributes={attributes} listeners={listeners} />+ * </td>+ * ...+ * </tr>+ * )+ * ```+ *+ * The handle owns its own cursor styling (`cursor-grab` / `active:cursor-grabbing`),+ * hover affordance, and accessible label — the caller only needs to size the+ * surrounding cell (typically `w-8 touch-none p-0`).+ */+export function DragHandle({ attributes, listeners, className, ...props }: DragHandleProps) {+ return (+ <button+ type="button"+ aria-label="Drag to reorder"+ className={cn(+ 'flex h-full w-full items-center justify-center rounded-lg p-3 text-muted-foreground cursor-grab active:cursor-grabbing hover:bg-accent',+ className,+ )}+ {...attributes}+ {...listeners}+ {...props}+ >+ <GripVerticalIcon className="size-4" />+ </button>+ )+}diff --git a/packages/admin/src/components/spree/payment-method-editors/payment-method-form.tsx b/packages/admin/src/components/spree/payment-method-editors/payment-method-form.tsxnew file mode 100644index 0000000000..f7ca4ac9a1--- /dev/null+++ b/packages/admin/src/components/spree/payment-method-editors/payment-method-form.tsx@@ -0,0 +1,227 @@+import type { PaymentMethod, PreferenceField } from '@spree/admin-sdk'+import { Controller, type UseFormReturn } from 'react-hook-form'+import { PreferencesForm } from '@/components/spree/preferences-form'+import { Slot } from '@/components/spree/slot'+import { StorefrontVisibleSwitch } from '@/components/spree/storefront-visible-switch'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { Input } from '@/components/ui/input'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { Switch } from '@/components/ui/switch'+import { Textarea } from '@/components/ui/textarea'+import { useSlotEntries } from '@/lib/slot-registry'+import {+ type PaymentMethodEditorContext,+ type PaymentMethodFormMode,+ type PaymentMethodFormValues,+ paymentMethodActionsSlot,+ paymentMethodFormSlot,+ paymentMethodGuideSlot,+} from './types'++interface ProviderOption {+ type: string+ label: string+ preference_schema: PreferenceField[]+}++interface PaymentMethodFormProps {+ mode: PaymentMethodFormMode+ form: UseFormReturn<PaymentMethodFormValues>+ /** Available provider types — only consulted in `create` mode for the dropdown. */+ providerTypes?: ProviderOption[]+ loadingTypes?: boolean+ /**+ * The provider's preference schema. In create mode, look it up from+ * `providerTypes` against the selected `type` (the parent does this so+ * it can also seed `preferences` with defaults on type change).+ */+ preferenceSchema: PreferenceField[]+ /** Current provider's STI shorthand — drives slot lookups. */+ providerType: string+ /** Loaded server record in edit mode; null while creating. */+ paymentMethod: PaymentMethod | null+ preferences: Record<string, unknown>+ onPreferencesChange: (next: Record<string, unknown>) => void+ /** Called when the user picks a different provider in the create dropdown. */+ onProviderTypeChange?: (next: string) => void+}++export function PaymentMethodForm({+ mode,+ form,+ providerTypes = [],+ loadingTypes,+ preferenceSchema,+ providerType,+ paymentMethod,+ preferences,+ onPreferencesChange,+ onProviderTypeChange,+}: PaymentMethodFormProps) {+ // Per-provider slot lookups. If a plugin has registered a `form` slot+ // for this provider (e.g. Stripe OAuth Connect), we render that+ // instead of the generic `<PreferencesForm>`. Guide/actions slots are+ // always additive.+ const formSlotEntries = useSlotEntries(paymentMethodFormSlot(providerType))+ const customFormRegistered = formSlotEntries.length > 0++ const slotContext: PaymentMethodEditorContext = {+ mode,+ type: providerType,+ paymentMethod,+ preferenceSchema,+ preferences,+ onPreferencesChange,+ form,+ }++ return (+ <div className="flex flex-1 flex-col gap-4">+ {mode === 'create' && (+ <Field>+ <FieldLabel htmlFor="type">Provider</FieldLabel>+ <Controller+ name="type"+ control={form.control}+ render={({ field }) => (+ <Select+ value={field.value ?? ''}+ onValueChange={(next) => {+ field.onChange(next)+ onProviderTypeChange?.(next)+ // Prefill the Name field with the provider's label —+ // but only if the admin hasn't typed something+ // themselves yet.+ const label = providerTypes.find((t) => t.type === next)?.label+ if (label && !form.formState.dirtyFields.name) {+ form.setValue('name', label, { shouldDirty: false })+ }+ }}+ >+ <SelectTrigger id="type" aria-invalid={!!form.formState.errors.type}>+ <SelectValue placeholder={loadingTypes ? 'Loading…' : 'Select a provider'}>+ {(value) =>+ providerTypes.find((t) => t.type === value)?.label ?? (value as string)+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {providerTypes.map((t) => (+ <SelectItem key={t.type} value={t.type}>+ {t.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ {form.formState.errors.type && (+ <p className="text-sm text-destructive">{form.formState.errors.type.message}</p>+ )}+ </Field>+ )}++ <PaymentMethodTopFields form={form} />++ {providerType && <Slot name={paymentMethodGuideSlot(providerType)} context={slotContext} />}++ {providerType && (customFormRegistered || preferenceSchema.length > 0) ? (+ <div className="rounded-md border bg-muted/30 p-3">+ <h3 className="mb-2 text-sm font-medium">Provider configuration</h3>+ {customFormRegistered ? (+ // A plugin has taken over — render the registered editor+ // instead of the generic preferences form. Plugin owns its+ // own dirty state and submission inside `onPreferencesChange`.+ <Slot name={paymentMethodFormSlot(providerType)} context={slotContext} />+ ) : (+ <PreferencesForm+ schema={preferenceSchema}+ values={preferences}+ onChange={onPreferencesChange}+ redactPasswords={mode === 'edit'}+ />+ )}+ </div>+ ) : null}++ {providerType && <Slot name={paymentMethodActionsSlot(providerType)} context={slotContext} />}+ </div>+ )+}++function PaymentMethodTopFields({ form }: { form: UseFormReturn<PaymentMethodFormValues> }) {+ return (+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="name">Name</FieldLabel>+ <Input+ id="name"+ placeholder="e.g. Credit card (Stripe)"+ {...form.register('name')}+ aria-invalid={!!form.formState.errors.name}+ />+ {form.formState.errors.name && (+ <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>+ )}+ </Field>++ <Field>+ <FieldLabel htmlFor="description">Description</FieldLabel>+ <Textarea+ id="description"+ rows={2}+ placeholder="Customer-facing description shown at checkout"+ {...form.register('description')}+ />+ </Field>++ <StorefrontVisibleSwitch control={form.control} name="storefront_visible" />++ <Field>+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col">+ <FieldLabel htmlFor="active" className="cursor-pointer">+ Active+ </FieldLabel>+ <span className="text-xs text-muted-foreground">+ Inactive methods are hidden from checkout.+ </span>+ </div>+ <Controller+ name="active"+ control={form.control}+ render={({ field }) => (+ <Switch id="active" checked={!!field.value} onCheckedChange={field.onChange} />+ )}+ />+ </div>+ </Field>++ <Field>+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col">+ <FieldLabel htmlFor="auto_capture" className="cursor-pointer">+ Auto-capture+ </FieldLabel>+ <span className="text-xs text-muted-foreground">+ Capture funds automatically on authorization. When off, you must capture manually.+ </span>+ </div>+ <Controller+ name="auto_capture"+ control={form.control}+ render={({ field }) => (+ <Switch id="auto_capture" checked={!!field.value} onCheckedChange={field.onChange} />+ )}+ />+ </div>+ </Field>+ </FieldGroup>+ )+}diff --git a/packages/admin/src/components/spree/payment-method-editors/types.ts b/packages/admin/src/components/spree/payment-method-editors/types.tsnew file mode 100644index 0000000000..3d14828e93--- /dev/null+++ b/packages/admin/src/components/spree/payment-method-editors/types.ts@@ -0,0 +1,64 @@+import type { PaymentMethod, PreferenceField } from '@spree/admin-sdk'+import type { UseFormReturn } from 'react-hook-form'++/**+ * Form-state row for a payment method — the in-flight values an editor+ * cares about whether the sheet is in `create` or `edit` mode.+ *+ * `create` mode has no server `id` and the provider type is still being+ * picked; `edit` mode carries the loaded record (id, original schema,+ * timestamps, etc.).+ */+export interface PaymentMethodFormValues {+ name: string+ description: string+ storefront_visible: boolean+ active: boolean+ auto_capture: boolean+ /** Provider STI shorthand (e.g. `stripe`). Only set in create mode. */+ type?: string+}++export type PaymentMethodFormMode = 'create' | 'edit'++/**+ * Slot context for a payment-method-editor slot. Editors mutate+ * `preferences` locally and bubble changes up via `onPreferencesChange`;+ * the parent sheet persists everything on submit. Slots may also use+ * `form` to read/write top-level fields (Active, Display on, …) or+ * register their own fields via `react-hook-form`.+ *+ * Slot keys follow the same per-type pattern as promotion editors:+ *+ * payment_method.guide.<provider_type> — banner above the form+ * payment_method.form.<provider_type> — replaces preferences form+ * payment_method.actions.<provider_type> — footer actions area+ */+export interface PaymentMethodEditorContext {+ mode: PaymentMethodFormMode+ /** The current provider's STI shorthand (`stripe`, `bogus`, …). */+ type: string+ /** Loaded server record in `edit` mode; `null` in `create` mode. */+ paymentMethod: PaymentMethod | null+ preferenceSchema: PreferenceField[]+ preferences: Record<string, unknown>+ onPreferencesChange: (next: Record<string, unknown>) => void+ /** react-hook-form instance for the top-level fields. */+ form: UseFormReturn<PaymentMethodFormValues>+}++const PAYMENT_METHOD_GUIDE_SLOT_PREFIX = 'payment_method.guide.'+const PAYMENT_METHOD_FORM_SLOT_PREFIX = 'payment_method.form.'+const PAYMENT_METHOD_ACTIONS_SLOT_PREFIX = 'payment_method.actions.'++export function paymentMethodGuideSlot(providerType: string): string {+ return `${PAYMENT_METHOD_GUIDE_SLOT_PREFIX}${providerType}`+}++export function paymentMethodFormSlot(providerType: string): string {+ return `${PAYMENT_METHOD_FORM_SLOT_PREFIX}${providerType}`+}++export function paymentMethodActionsSlot(providerType: string): string {+ return `${PAYMENT_METHOD_ACTIONS_SLOT_PREFIX}${providerType}`+}diff --git a/packages/admin/src/components/spree/preferences-form.tsx b/packages/admin/src/components/spree/preferences-form.tsxindex 2accbd8b8e..db153e0fbd 100644--- a/packages/admin/src/components/spree/preferences-form.tsx+++ b/packages/admin/src/components/spree/preferences-form.tsx@@ -2,12 +2,31 @@ import type { PreferenceField as PreferenceFieldDef } from '@spree/admin-sdk'import { PlusIcon, TrashIcon } from 'lucide-react'import { useId, useMemo, useState } from 'react'import { CurrencySelect } from '@/components/spree/currency-select'+import { SecretInput } from '@/components/spree/secret-input'import { Button } from '@/components/ui/button'import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'import { Input } from '@/components/ui/input'import { Switch } from '@/components/ui/switch'import { Textarea } from '@/components/ui/textarea'+/**+ * Hydrates a `preferences` hash with each field's default. Used to seed+ * create-mode forms when the user picks a provider/calculator so the+ * `<PreferencesForm>` shows sensible starting values instead of blanks.+ *+ * `:password` fields are always skipped — the server returns their+ * defaults as `null`, and even when it doesn't, autofilling a password+ * field is hostile UX.+ */+export function defaultPreferences(schema: PreferenceFieldDef[]): Record<string, unknown> {+ const out: Record<string, unknown> = {}+ for (const field of schema) {+ if (field.type === 'password') continue+ if (field.default !== null && field.default !== undefined) out[field.key] = field.default+ }+ return out+}+interface PreferencesFormProps {schema: PreferenceFieldDef[]values: Record<string, unknown>@@ -170,32 +189,14 @@ export function PreferenceField({)case 'password':- if (redactPasswords) {- return (- <Field>- <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>- <Input- id={id}- type="password"- autoComplete="new-password"- placeholder="Stored — leave blank to keep current"- value={(value as string) ?? ''}- onChange={(e) => onChange(e.target.value)}- />- </Field>- )- }return (- <Field>- <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>- <Input- id={id}- type="password"- autoComplete="new-password"- value={(value as string) ?? ''}- onChange={(e) => onChange(e.target.value)}- />- </Field>+ <SecretInput+ id={id}+ label={displayLabel}+ value={value}+ onChange={onChange}+ redactWhenMasked={!!redactPasswords}+ />)default:diff --git a/packages/admin/src/components/spree/promotion-editors/register.ts b/packages/admin/src/components/spree/promotion-editors/register.tsindex 2bac7c00fd..8b4124709c 100644--- a/packages/admin/src/components/spree/promotion-editors/register.ts+++ b/packages/admin/src/components/spree/promotion-editors/register.ts@@ -31,7 +31,7 @@ registerSlot(ruleFormSlot('category'), {component: CategoryRuleEditor,})-registerSlot(ruleFormSlot('user'), {+registerSlot(ruleFormSlot('customer'), {id: 'builtin',component: UserRuleEditor,})diff --git a/packages/admin/src/components/spree/promotion-editors/types.ts b/packages/admin/src/components/spree/promotion-editors/types.tsindex 58638417b8..532c46ef5b 100644--- a/packages/admin/src/components/spree/promotion-editors/types.ts+++ b/packages/admin/src/components/spree/promotion-editors/types.ts@@ -12,6 +12,7 @@ import type {PromotionRule,PromotionRuleDraft,} from '@spree/admin-sdk'+import { defaultPreferences } from '@/components/spree/preferences-form'/*** Form-state row for a promotion rule. Carries everything the editor@@ -203,14 +204,6 @@ function calculatorFromAction(}}-function defaultPreferences(schema: PreferenceField[]): Record<string, unknown> {- const out: Record<string, unknown> = {}- for (const f of schema) {- if (f.default !== null && f.default !== undefined) out[f.key] = f.default- }- return out-}-/** Strips display-only fields before sending to the API. */export function ruleDraftToPayload(draft: PromotionRuleFormDraft): PromotionRuleDraft {const {diff --git a/packages/admin/src/components/spree/resource-table.tsx b/packages/admin/src/components/spree/resource-table.tsxindex 771bd24afb..61d1a9380f 100644--- a/packages/admin/src/components/spree/resource-table.tsx+++ b/packages/admin/src/components/spree/resource-table.tsx@@ -17,7 +17,6 @@ import {import { CSS } from '@dnd-kit/utilities'import { useQuery } from '@tanstack/react-query'import { useNavigate } from '@tanstack/react-router'-import { GripVerticalIcon } from 'lucide-react'import {type CSSProperties,type ReactNode,@@ -27,6 +26,7 @@ import {useState,} from 'react'import { z } from 'zod/v4'+import { DragHandle } from '@/components/spree/drag-handle'import { EmptyState } from '@/components/spree/empty-state'import { TableToolbar } from '@/components/spree/table-toolbar'import { Card, CardContent } from '@/components/ui/card'@@ -468,16 +468,8 @@ function SortableRow<T extends Record<string, any>>({isDragging && 'relative z-10 opacity-70',)}>- <TableCell className="w-8 cursor-grab touch-none text-muted-foreground active:cursor-grabbing">- <button- type="button"- aria-label="Drag to reorder"- className="flex size-6 items-center justify-center rounded hover:bg-muted"- {...attributes}- {...listeners}- >- <GripVerticalIcon className="size-4" />- </button>+ <TableCell className="w-8 touch-none p-0">+ <DragHandle attributes={attributes} listeners={listeners} /></TableCell>{columns.map((col) => (<TableCell key={col.key} className={col.className}>diff --git a/packages/admin/src/components/spree/secret-input.tsx b/packages/admin/src/components/spree/secret-input.tsxnew file mode 100644index 0000000000..f85a7bd0ba--- /dev/null+++ b/packages/admin/src/components/spree/secret-input.tsx@@ -0,0 +1,125 @@+import { isMaskedSecret } from '@spree/admin-sdk'+import { EyeIcon, EyeOffIcon } from 'lucide-react'+import { useState } from 'react'+import { Button } from '@/components/ui/button'+import { Field, FieldLabel } from '@/components/ui/field'+import { Input } from '@/components/ui/input'++interface SecretInputProps {+ id: string+ label: string+ value: unknown+ onChange: (value: unknown) => void+ /**+ * When true, a value that arrives carrying the server's mask token+ * (`••••3K9z`) is treated as "already stored" — show the masked badge+ * with a Replace button instead of an editable input. Cancel restores+ * the original masked value so the backend's round-trip guard keeps+ * the existing secret.+ */+ redactWhenMasked?: boolean+ /** Replaces the default "Stored on the server. Click Replace to rotate." caption. */+ helpText?: string+ /** Placeholder for the editable input — only shown when not redacted. */+ placeholder?: string+}++/**+ * Stripe-style credential field. When the value comes back from the API+ * masked (`••••3K9z`), display it as a read-only badge with a "Replace"+ * button. Replace switches to a password input pre-filled empty so the+ * admin opts in to rotation; Cancel reverts to the masked badge so the+ * next save preserves the existing secret via the backend's masked+ * round-trip guard.+ *+ * Domain-agnostic — used by `<PreferencesForm>` for `:password`-typed+ * preferences, but also suitable for any other secret that round-trips+ * through the API (webhook signing keys, OAuth client secrets, etc).+ */+export function SecretInput({+ id,+ label,+ value,+ onChange,+ redactWhenMasked = false,+ helpText,+ placeholder,+}: SecretInputProps) {+ const storedMask = isMaskedSecret(value) ? value : null+ // Captured at click time so Cancel can restore the original mask even+ // after `onChange('')` has cleared the parent value.+ const [pendingMask, setPendingMask] = useState<string | null>(null)+ const [revealed, setRevealed] = useState(false)+ const replacing = pendingMask !== null++ if (redactWhenMasked && storedMask && !replacing) {+ return (+ <Field>+ <FieldLabel htmlFor={id}>{label}</FieldLabel>+ <div className="flex items-center gap-2">+ <div className="flex min-h-9 w-full min-w-0 items-center rounded-lg border border-border bg-muted/40 px-2.5 py-1.5 shadow-xs">+ <span className="font-mono text-sm tabular-nums text-muted-foreground" id={id}>+ {storedMask}+ </span>+ </div>+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => {+ setPendingMask(storedMask)+ onChange('')+ }}+ >+ Replace+ </Button>+ </div>+ <span className="text-xs text-muted-foreground">+ {helpText ?? 'Stored on the server. Click Replace to rotate.'}+ </span>+ </Field>+ )+ }++ return (+ <Field>+ <FieldLabel htmlFor={id}>{label}</FieldLabel>+ <div className="flex items-center gap-2">+ <div className="relative flex-1">+ <Input+ id={id}+ type={revealed ? 'text' : 'password'}+ autoComplete="new-password"+ placeholder={replacing ? 'New value' : placeholder}+ value={(value as string) ?? ''}+ onChange={(e) => onChange(e.target.value)}+ className="pr-9"+ />+ <button+ type="button"+ aria-label={revealed ? 'Hide value' : 'Show value'}+ aria-pressed={revealed}+ onClick={() => setRevealed((v) => !v)}+ className="absolute inset-y-0 right-0 flex items-center px-2.5 text-muted-foreground hover:text-foreground"+ >+ {revealed ? <EyeOffIcon className="size-4" /> : <EyeIcon className="size-4" />}+ </button>+ </div>+ {replacing && (+ <Button+ type="button"+ size="sm"+ variant="ghost"+ onClick={() => {+ onChange(pendingMask)+ setPendingMask(null)+ setRevealed(false)+ }}+ >+ Cancel+ </Button>+ )}+ </div>+ </Field>+ )+}diff --git a/packages/admin/src/components/spree/storefront-visible-switch.tsx b/packages/admin/src/components/spree/storefront-visible-switch.tsxnew file mode 100644index 0000000000..bf24a8f914--- /dev/null+++ b/packages/admin/src/components/spree/storefront-visible-switch.tsx@@ -0,0 +1,54 @@+import { type Control, Controller, type FieldPath, type FieldValues } from 'react-hook-form'+import { Field, FieldLabel } from '@/components/ui/field'+import { Switch } from '@/components/ui/switch'++interface StorefrontVisibleSwitchProps<TFieldValues extends FieldValues> {+ control: Control<TFieldValues>+ name: FieldPath<TFieldValues>+ /** Defaults to "Visible on storefront". */+ label?: string+ /** Helper text under the row. Defaults to the on/off explanation. */+ description?: string+ /** Switch id — defaults to the field name. */+ id?: string+}++/**+ * Canonical 5.5+ "Visible on storefront" control. Wraps a `Switch` with+ * a labelled row mirroring the Active / Auto-capture rows on the same+ * forms. Used by every resource that exposes `storefront_visible` on+ * the API (PaymentMethod today; ShippingMethod/DeliveryMethod when+ * those admin pages land — see `docs/plans/5.5-6.0-display-on-to-boolean.md`).+ *+ * For column-cell rendering use `<ActiveBadge active={…} activeLabel="Visible"+ * inactiveLabel="Admin only" />` so the visibility column matches the+ * Active column's visual treatment.+ */+export function StorefrontVisibleSwitch<TFieldValues extends FieldValues>({+ control,+ name,+ label = 'Visible on storefront',+ description = 'When off, only admin staff see this option (back-office orders, manual entry).',+ id,+}: StorefrontVisibleSwitchProps<TFieldValues>) {+ const fieldId = id ?? name+ return (+ <Field>+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col">+ <FieldLabel htmlFor={fieldId} className="cursor-pointer">+ {label}+ </FieldLabel>+ <span className="text-xs text-muted-foreground">{description}</span>+ </div>+ <Controller+ name={name}+ control={control}+ render={({ field }) => (+ <Switch id={fieldId} checked={!!field.value} onCheckedChange={field.onChange} />+ )}+ />+ </div>+ </Field>+ )+}diff --git a/packages/admin/src/components/spree/table-toolbar.tsx b/packages/admin/src/components/spree/table-toolbar.tsxindex d6e8a3717f..e3c9e4a178 100644--- a/packages/admin/src/components/spree/table-toolbar.tsx+++ b/packages/admin/src/components/spree/table-toolbar.tsx@@ -97,6 +97,11 @@ function getOperators(type: string) {const noValueOperators = ['present', 'blank']+const booleanItems = [+ { value: 'true', label: 'Yes' },+ { value: 'false', label: 'No' },+] as const+// ============================================================================// TableToolbar// ============================================================================@@ -427,6 +432,7 @@ function FilterPanel({return (<div key={filter.id} className="flex items-center gap-1.5"><Select+ items={columns.map((c) => ({ value: c.key, label: c.label }))}value={filter.field}onValueChange={(val) => {const newCol = columns.find((c) => c.key === val)@@ -451,6 +457,7 @@ function FilterPanel({</Select><Select+ items={ops}value={filter.operator}onValueChange={(val) => updateFilter(filter.id, { operator: val })}>@@ -469,6 +476,7 @@ function FilterPanel({{!noValueOperators.includes(filter.operator) &&(col?.filterType === 'status' && col.filterOptions ? (<Select+ items={col.filterOptions}value={filter.value || undefined}onValueChange={(val) => updateFilter(filter.id, { value: val })}>@@ -485,6 +493,7 @@ function FilterPanel({</Select>) : col?.filterType === 'boolean' ? (<Select+ items={booleanItems}value={filter.value || undefined}onValueChange={(val) => updateFilter(filter.id, { value: val })}>diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsxindex 47d289ce89..fe8fe55611 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx@@ -2,31 +2,24 @@ import { zodResolver } from '@hookform/resolvers/zod'import type {PaymentMethod,PaymentMethodCreateParams,- PaymentMethodDisplayOn,PaymentMethodUpdateParams,+ PreferenceField,} from '@spree/admin-sdk'import { useQueryClient } from '@tanstack/react-query'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { PlusIcon } from 'lucide-react'import { useEffect, useMemo, useRef, useState } from 'react'-import { Controller, useForm } from 'react-hook-form'+import { useForm } from 'react-hook-form'import { z } from 'zod/v4'import { adminClient } from '@/client'import { Can } from '@/components/spree/can'import { useConfirm } from '@/components/spree/confirm-dialog'-import { PreferencesForm } from '@/components/spree/preferences-form'+import { PaymentMethodForm } from '@/components/spree/payment-method-editors/payment-method-form'+import type { PaymentMethodFormValues } from '@/components/spree/payment-method-editors/types'+import { defaultPreferences } from '@/components/spree/preferences-form'import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'import { useRowClickBridge } from '@/components/spree/row-click-bridge'import { Button } from '@/components/ui/button'-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'-import { Input } from '@/components/ui/input'-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@/components/ui/select'import {Sheet,SheetContent,@@ -35,8 +28,6 @@ import {SheetHeader,SheetTitle,} from '@/components/ui/sheet'-import { Switch } from '@/components/ui/switch'-import { Textarea } from '@/components/ui/textarea'import {useCreatePaymentMethod,useDeletePaymentMethod,@@ -57,12 +48,6 @@ export const Route = createFileRoute('/_authenticated/$storeId/settings/payment-component: PaymentMethodsPage,})-const DISPLAY_ON_OPTIONS: { value: PaymentMethodDisplayOn; label: string }[] = [- { value: 'both', label: 'Storefront + Admin' },- { value: 'front_end', label: 'Storefront only' },- { value: 'back_end', label: 'Admin only' },-]-function PaymentMethodsPage() {const search = Route.useSearch() as z.infer<typeof paymentMethodsSearchSchema>const navigate = useNavigate()@@ -121,7 +106,7 @@ function PaymentMethodsPage() {const baseFormSchema = z.object({name: z.string().min(1, 'Name is required'),description: z.string().optional(),- display_on: z.enum(['both', 'front_end', 'back_end']),+ storefront_visible: z.boolean(),active: z.boolean(),auto_capture: z.boolean(),})@@ -130,37 +115,38 @@ const createFormSchema = baseFormSchema.extend({type: z.string().min(1, 'Pick a provider'),})-type BaseFormValues = z.infer<typeof baseFormSchema>-type CreateFormValues = z.infer<typeof createFormSchema>--const BASE_DEFAULTS: BaseFormValues = {+const BASE_DEFAULTS: PaymentMethodFormValues = {name: '',description: '',- display_on: 'both',+ storefront_visible: true,active: true,auto_capture: false,}-const CREATE_DEFAULTS: CreateFormValues = { ...BASE_DEFAULTS, type: '' }+const CREATE_DEFAULTS: PaymentMethodFormValues = { ...BASE_DEFAULTS, type: '' }-function valuesToCreateParams(v: CreateFormValues): PaymentMethodCreateParams {+function valuesToCreateParams(+ v: PaymentMethodFormValues,+ preferences: Record<string, unknown>,+): PaymentMethodCreateParams {return {- type: v.type,+ type: v.type ?? '',name: v.name,description: v.description?.length ? v.description : null,active: v.active,auto_capture: v.auto_capture,- display_on: v.display_on,+ storefront_visible: v.storefront_visible,+ ...(Object.keys(preferences).length > 0 ? { preferences } : {}),}}-function valuesToUpdateParams(v: BaseFormValues): PaymentMethodUpdateParams {+function valuesToUpdateParams(v: PaymentMethodFormValues): PaymentMethodUpdateParams {return {name: v.name,description: v.description?.length ? v.description : null,active: v.active,auto_capture: v.auto_capture,- display_on: v.display_on,+ storefront_visible: v.storefront_visible,}}@@ -173,17 +159,30 @@ function CreatePaymentMethodSheet({}) {const createMutation = useCreatePaymentMethod()const { data: typesResponse, isLoading: loadingTypes } = usePaymentMethodTypes()- const providerTypes = typesResponse?.data ?? []+ const providerTypes = useMemo(() => typesResponse?.data ?? [], [typesResponse])- const form = useForm<CreateFormValues>({+ const form = useForm<PaymentMethodFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(createFormSchema) as any,defaultValues: CREATE_DEFAULTS,})- async function onSubmit(values: CreateFormValues) {- await createMutation.mutateAsync(valuesToCreateParams(values))+ const [preferences, setPreferences] = useState<Record<string, unknown>>({})+ const providerType = form.watch('type') ?? ''+ const preferenceSchema: PreferenceField[] = useMemo(+ () => providerTypes.find((t) => t.type === providerType)?.preference_schema ?? [],+ [providerTypes, providerType],+ )++ function handleProviderTypeChange(next: string) {+ const nextSchema = providerTypes.find((t) => t.type === next)?.preference_schema ?? []+ setPreferences(defaultPreferences(nextSchema))+ }++ async function onSubmit(values: PaymentMethodFormValues) {+ await createMutation.mutateAsync(valuesToCreateParams(values, preferences))form.reset(CREATE_DEFAULTS)+ setPreferences({})onOpenChange(false)}@@ -191,64 +190,32 @@ function CreatePaymentMethodSheet({<Sheetopen={open}onOpenChange={(next) => {- if (!next) form.reset(CREATE_DEFAULTS)+ if (!next) {+ form.reset(CREATE_DEFAULTS)+ setPreferences({})+ }onOpenChange(next)}}><SheetContent><SheetHeader><SheetTitle>Add payment method</SheetTitle>- <SheetDescription>- Pick a provider to register a new payment method. Provider-specific configuration is- edited after the method is created.- </SheetDescription>+ <SheetDescription>Pick a provider and configure it in one step.</SheetDescription></SheetHeader><form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">- <Field>- <FieldLabel htmlFor="type">Provider</FieldLabel>- <Controller- name="type"- control={form.control}- render={({ field }) => (- <Select- value={field.value}- onValueChange={(next) => {- field.onChange(next)- // Prefill the Name field with the provider's label- // — but only if the admin hasn't typed something- // themselves yet. `dirtyFields.name` is true after- // any keystroke in the name input, so we leave it- // alone in that case.- const label = providerTypes.find((t) => t.type === next)?.label- if (label && !form.formState.dirtyFields.name) {- form.setValue('name', label, { shouldDirty: false })- }- }}- >- <SelectTrigger id="type" aria-invalid={!!form.formState.errors.type}>- <SelectValue placeholder={loadingTypes ? 'Loading…' : 'Select a provider'}>- {(value) =>- providerTypes.find((t) => t.type === value)?.label ?? (value as string)- }- </SelectValue>- </SelectTrigger>- <SelectContent>- {providerTypes.map((t) => (- <SelectItem key={t.type} value={t.type}>- {t.label}- </SelectItem>- ))}- </SelectContent>- </Select>- )}- />- {form.formState.errors.type && (- <p className="text-sm text-destructive">{form.formState.errors.type.message}</p>- )}- </Field>-- <PaymentMethodFormFields form={form} />+ <PaymentMethodForm+ mode="create"+ form={form}+ providerTypes={providerTypes}+ loadingTypes={loadingTypes}+ preferenceSchema={preferenceSchema}+ providerType={providerType}+ paymentMethod={null}+ preferences={preferences}+ onPreferencesChange={setPreferences}+ onProviderTypeChange={handleProviderTypeChange}+ /></div><SheetFooter><Button@@ -284,7 +251,7 @@ function EditPaymentMethodSheet({const deleteMutation = useDeletePaymentMethod()const confirm = useConfirm()- const form = useForm<BaseFormValues>({+ const form = useForm<PaymentMethodFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(baseFormSchema) as any,defaultValues: BASE_DEFAULTS,@@ -303,7 +270,7 @@ function EditPaymentMethodSheet({form.reset({name: paymentMethod.name,description: paymentMethod.description ?? '',- display_on: (paymentMethod.display_on as PaymentMethodDisplayOn) ?? 'both',+ storefront_visible: paymentMethod.storefront_visible ?? true,active: paymentMethod.active,auto_capture: paymentMethod.auto_capture ?? false,})@@ -318,7 +285,7 @@ function EditPaymentMethodSheet({[preferences],)- async function onSubmit(values: BaseFormValues) {+ async function onSubmit(values: PaymentMethodFormValues) {const params = valuesToUpdateParams(values)if (preferencesDirty) params.preferences = preferencesawait updateMutation.mutateAsync(params)@@ -339,8 +306,15 @@ function EditPaymentMethodSheet({onOpenChange(false)}- const providerLabel =- paymentMethod?.type?.replace(/^Spree::PaymentMethod::/, '') ?? paymentMethod?.type+ // STI shorthand for slot lookup, e.g. `bogus`, `stripe`. The API+ // returns it on the `type` attribute (see PaymentMethodSerializer).+ const providerType = paymentMethod?.type ?? ''+ // Title-case the shorthand for the sheet header — `stripe` → `Stripe`,+ // `store_credit` → `Store Credit`.+ const providerLabel = providerType+ .split('_')+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))+ .join(' ')return (<Sheet open={open} onOpenChange={onOpenChange}>@@ -356,19 +330,15 @@ function EditPaymentMethodSheet({) : (<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">- <PaymentMethodFormFields form={form} />-- {paymentMethod?.preference_schema?.length ? (- <div className="rounded-md border bg-muted/30 p-3">- <h3 className="mb-2 text-sm font-medium">Provider configuration</h3>- <PreferencesForm- schema={paymentMethod.preference_schema}- values={preferences}- onChange={setPreferences}- redactPasswords- />- </div>- ) : null}+ <PaymentMethodForm+ mode="edit"+ form={form}+ preferenceSchema={paymentMethod?.preference_schema ?? []}+ providerType={providerType}+ paymentMethod={paymentMethod ?? null}+ preferences={preferences}+ onPreferencesChange={setPreferences}+ /></div><SheetFooter><Can I="destroy" a={Subject.PaymentMethod}>@@ -408,99 +378,3 @@ function EditPaymentMethodSheet({</Sheet>)}--function PaymentMethodFormFields({- form,-}: {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- form: any-}) {- return (- <FieldGroup>- <Field>- <FieldLabel htmlFor="name">Name</FieldLabel>- <Input- id="name"- placeholder="e.g. Credit card (Stripe)"- {...form.register('name')}- aria-invalid={!!form.formState.errors.name}- />- {form.formState.errors.name && (- <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>- )}- </Field>-- <Field>- <FieldLabel htmlFor="description">Description</FieldLabel>- <Textarea- id="description"- rows={2}- placeholder="Customer-facing description shown at checkout"- {...form.register('description')}- />- </Field>-- <Field>- <FieldLabel htmlFor="display_on">Visible on</FieldLabel>- <Controller- name="display_on"- control={form.control}- render={({ field }) => (- <Select items={DISPLAY_ON_OPTIONS} value={field.value} onValueChange={field.onChange}>- <SelectTrigger id="display_on">- <SelectValue />- </SelectTrigger>- <SelectContent>- {DISPLAY_ON_OPTIONS.map((o) => (- <SelectItem key={o.value} value={o.value}>- {o.label}- </SelectItem>- ))}- </SelectContent>- </Select>- )}- />- </Field>-- <Field>- <div className="flex items-start justify-between gap-4">- <div className="flex flex-col">- <FieldLabel htmlFor="active" className="cursor-pointer">- Active- </FieldLabel>- <span className="text-xs text-muted-foreground">- Inactive methods are hidden from checkout.- </span>- </div>- <Controller- name="active"- control={form.control}- render={({ field }) => (- <Switch id="active" checked={!!field.value} onCheckedChange={field.onChange} />- )}- />- </div>- </Field>-- <Field>- <div className="flex items-start justify-between gap-4">- <div className="flex flex-col">- <FieldLabel htmlFor="auto_capture" className="cursor-pointer">- Auto-capture- </FieldLabel>- <span className="text-xs text-muted-foreground">- Capture funds automatically on authorization. When off, you must capture manually.- </span>- </div>- <Controller- name="auto_capture"- control={form.control}- render={({ field }) => (- <Switch id="auto_capture" checked={!!field.value} onCheckedChange={field.onChange} />- )}- />- </div>- </Field>- </FieldGroup>- )-}diff --git a/packages/admin/src/tables/payment-methods.tsx b/packages/admin/src/tables/payment-methods.tsxindex 0cd09e7289..261f881fcc 100644--- a/packages/admin/src/tables/payment-methods.tsx+++ b/packages/admin/src/tables/payment-methods.tsx@@ -1,14 +1,8 @@-import type { PaymentMethod, PaymentMethodDisplayOn } from '@spree/admin-sdk'+import type { PaymentMethod } from '@spree/admin-sdk'import { CreditCardIcon } from 'lucide-react'import { ActiveBadge } from '@/components/ui/badge'import { defineTable } from '@/lib/table-registry'-const DISPLAY_ON_LABELS: Record<PaymentMethodDisplayOn, string> = {- both: 'Storefront + Admin',- front_end: 'Storefront only',- back_end: 'Admin only',-}-defineTable<PaymentMethod>('payment-methods', {title: 'Payment Methods',searchParam: 'name_cont',@@ -44,16 +38,21 @@ defineTable<PaymentMethod>('payment-methods', {sortable: true,filterable: true,default: true,- // The STI subclass name is verbose ("Spree::PaymentMethod::Check"); strip- // the namespace + class prefix so the table reads "Check" / "BogusGateway".- render: (pm) => pm.type.replace(/^Spree::PaymentMethod::/, ''),+ render: (pm) => pm.type,},{- key: 'display_on',- label: 'Visible on',+ key: 'storefront_visible',+ label: 'Storefront',filterable: true,+ filterType: 'boolean',default: true,- render: (pm) => DISPLAY_ON_LABELS[pm.display_on as PaymentMethodDisplayOn] ?? pm.display_on,+ render: (pm) => (+ <ActiveBadge+ active={pm.storefront_visible}+ activeLabel="Visible"+ inactiveLabel="Admin only"+ />+ ),},{key: 'active',diff --git a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rbindex ae97c499b8..adbc58aea2 100644--- a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb@@ -50,6 +50,14 @@ module SpreeSpree.api.admin_payment_method_serializerend+ # Explicit allowlist per the v3 convention — flat params, no+ # reach into the global `Spree::PermittedAttributes` registry+ # (which is the legacy Rails admin's surface). `type` and+ # `preferences` are added by `SubclassedResource` on top.+ def permitted_params+ params.permit(:name, :description, :active, :storefront_visible, :auto_capture, :position, metadata: {}, preferences: {})+ end+private# New payment methods get scoped to the current store automatically.diff --git a/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rbindex cf56b147d4..e94e98ce55 100644--- a/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb@@ -5,13 +5,13 @@ module Spreeclass PaymentMethodSerializer < V3::PaymentMethodSerializertypelize active: :boolean,auto_capture: [:boolean, nullable: true],- display_on: :string,+ storefront_visible: :boolean,position: :number,metadata: 'Record<string, unknown>',preferences: 'Record<string, unknown>',preference_schema: "Array<{ key: string; type: string; default: unknown }>"- attributes :metadata, :active, :auto_capture, :display_on, :position,+ attributes :metadata, :active, :auto_capture, :storefront_visible, :position,created_at: :iso8601, updated_at: :iso8601attribute :preferences, &:serialized_preferencesdiff --git a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rbindex fb04879e9c..981b715868 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb@@ -28,6 +28,31 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlleexpect(json_response['data'].map { |pm| pm['id'] }).not_to include(other_payment_method.prefixed_id)endend++ context 'when filtering by storefront_visible' do+ let!(:storefront_visible_method) do+ create(:check_payment_method, stores: [store], display_on: 'both')+ end+ let!(:admin_only_method) do+ create(:check_payment_method, stores: [store], display_on: 'back_end')+ end++ it 'returns only storefront-visible methods when q[storefront_visible_eq]=true' do+ get :index, params: { q: { storefront_visible_eq: true } }, as: :json++ ids = json_response['data'].map { |pm| pm['id'] }+ expect(ids).to include(storefront_visible_method.prefixed_id)+ expect(ids).not_to include(admin_only_method.prefixed_id)+ end++ it 'returns only admin-only methods when q[storefront_visible_eq]=false' do+ get :index, params: { q: { storefront_visible_eq: false } }, as: :json++ ids = json_response['data'].map { |pm| pm['id'] }+ expect(ids).to include(admin_only_method.prefixed_id)+ expect(ids).not_to include(storefront_visible_method.prefixed_id)+ end+ endenddescribe 'GET #show' do@@ -79,7 +104,7 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controllename: 'Check on delivery',description: 'Pay by physical check',active: true,- display_on: 'back_end'+ storefront_visible: false}end@@ -163,6 +188,54 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlleendend+ # `storefront_visible` is the wire-level visibility flag. The+ # underlying `display_on` column lives on until 6.0 (see+ # docs/plans/5.5-6.0-display-on-to-boolean.md) but is no longer+ # exposed or accepted by the Admin API — clients read/write only the+ # boolean.+ describe 'storefront_visible' do+ context 'GET #show' do+ it 'returns storefront_visible: false when display_on is back_end' do+ payment_method.update!(display_on: 'back_end')++ get :show, params: { id: payment_method.prefixed_id }, as: :json++ expect(json_response['storefront_visible']).to be false+ expect(json_response).not_to have_key('display_on')+ end++ it 'returns storefront_visible: true when display_on is both' do+ payment_method.update!(display_on: 'both')++ get :show, params: { id: payment_method.prefixed_id }, as: :json++ expect(json_response['storefront_visible']).to be true+ end+ end++ context 'PATCH #update' do+ it 'maps storefront_visible: false to display_on: back_end' do+ patch :update,+ params: { id: payment_method.prefixed_id, storefront_visible: false },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(payment_method.reload.display_on).to eq('back_end')+ end++ it 'maps storefront_visible: true to display_on: both' do+ payment_method.update!(display_on: 'back_end')++ patch :update,+ params: { id: payment_method.prefixed_id, storefront_visible: true },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(payment_method.reload.display_on).to eq('both')+ end+ end+ end+describe 'DELETE #destroy' doit 'soft-deletes the payment method' doexpect { delete :destroy, params: { id: payment_method.prefixed_id }, as: :json }.diff --git a/spree/core/app/models/concerns/spree/display_on.rb b/spree/core/app/models/concerns/spree/display_on.rbindex e98845c366..f7b0202065 100644--- a/spree/core/app/models/concerns/spree/display_on.rb+++ b/spree/core/app/models/concerns/spree/display_on.rb@@ -9,11 +9,42 @@ module Spreescope :available_on_front_end, -> { where(display_on: [:front_end, :both]) }scope :available_on_back_end, -> { where(display_on: [:back_end, :both]) }+ # 5.5 → 6.0 bridge: see docs/plans/5.5-6.0-display-on-to-boolean.md.+ # The tri-state `display_on` enum collapses to a single+ # `storefront_visible` boolean in 6.0 — `back_end` becomes `false`,+ # everything else becomes `true`. The legacy `front_end`-only value+ # (visible to customers but hidden from staff) has no real use case+ # and folds into `storefront_visible: true` on migration.+ scope :storefront_visible, -> { where.not(display_on: 'back_end') }+ scope :admin_only, -> { where(display_on: 'back_end') }++ # Expose `storefront_visible` to Ransack so admin clients can filter+ # by it (e.g. `q[storefront_visible_eq]=true`) without knowing about+ # the underlying tri-state `display_on` column.+ ransacker :storefront_visible, type: :boolean do |parent|+ # Wrap in `Grouping` so Postgres sees `(display_on != 'back_end') = TRUE`+ # instead of the ambiguous `display_on != 'back_end' = TRUE`.+ Arel::Nodes::Grouping.new(+ Arel::Nodes::NotEqual.new(parent.table[:display_on], Arel::Nodes::Quoted.new('back_end'))+ )+ end++ self.whitelisted_ransackable_attributes =+ (whitelisted_ransackable_attributes || []) | %w[storefront_visible]+validates :display_on, presence: true, inclusion: { in: DISPLAY.map(&:to_s) }def available_on_front_end?display_on == 'front_end' || display_on == 'both'end++ def storefront_visible+ display_on != 'back_end'+ end++ def storefront_visible=(value)+ self.display_on = ActiveModel::Type::Boolean.new.cast(value) ? 'both' : 'back_end'+ endendendenddiff --git a/spree/core/app/models/spree/metafield_definition.rb b/spree/core/app/models/spree/metafield_definition.rbindex d774cc40c6..d696f6be1c 100644--- a/spree/core/app/models/spree/metafield_definition.rb+++ b/spree/core/app/models/spree/metafield_definition.rb@@ -52,10 +52,10 @@ module Spreeself.whitelisted_ransackable_attributes = %w[key namespace name resource_type display_on]self.whitelisted_ransackable_scopes = %w[search multi_search]- # API naming bridge — internal columns rename in 6.0.- # `label` matches OptionType/OptionValue conventions.- # `storefront_visible` maps the boolean API field to the- # `display_on: 'both'/'back_end'` string enum.+ # API naming bridge — internal columns rename in 6.0. `label` matches+ # OptionType/OptionValue conventions. (`storefront_visible` lives on+ # the `Spree::DisplayOn` concern, shared with PaymentMethod + ShippingMethod —+ # see docs/plans/5.5-6.0-display-on-to-boolean.md.)alias_attribute :label, :name# API-facing token for the STI subclass name stored in `metafield_type`.@@ -77,14 +77,6 @@ module Spreeself.metafield_type = mapped || valueend- def storefront_visible- available_on_front_end?- end-- def storefront_visible=(value)- self.display_on = ActiveModel::Type::Boolean.new.cast(value) ? 'both' : 'back_end'- end-# Returns the full key with namespace# @return [String] eg. custom.iddef full_keydiff --git a/spree/core/spec/models/spree/concerns/display_on_spec.rb b/spree/core/spec/models/spree/concerns/display_on_spec.rbnew file mode 100644index 0000000000..250c9cfbae--- /dev/null+++ b/spree/core/spec/models/spree/concerns/display_on_spec.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::DisplayOn do+ # PaymentMethod is the simplest factory-backed host; ShippingMethod+ # and MetafieldDefinition include the concern identically and inherit+ # this behaviour.+ let(:payment_method) { build(:check_payment_method) }++ describe '#storefront_visible' do+ it 'returns false when display_on is back_end' do+ payment_method.display_on = 'back_end'+ expect(payment_method.storefront_visible).to be false+ end++ it 'returns true when display_on is both' do+ payment_method.display_on = 'both'+ expect(payment_method.storefront_visible).to be true+ end++ it 'returns true for the legacy front_end-only value' do+ payment_method.display_on = 'front_end'+ expect(payment_method.storefront_visible).to be true+ end+ end++ describe '#storefront_visible=' do+ it 'maps true to display_on=both' do+ payment_method.storefront_visible = true+ expect(payment_method.display_on).to eq('both')+ end++ it 'maps false to display_on=back_end' do+ payment_method.storefront_visible = false+ expect(payment_method.display_on).to eq('back_end')+ end++ it 'coerces truthy strings to true (form payloads)' do+ payment_method.storefront_visible = '1'+ expect(payment_method.display_on).to eq('both')+ end++ it 'coerces falsy strings to false (form payloads)' do+ payment_method.storefront_visible = '0'+ expect(payment_method.display_on).to eq('back_end')+ end++ it 'round-trips: getter returns what setter set' do+ payment_method.storefront_visible = false+ expect(payment_method.storefront_visible).to be false++ payment_method.storefront_visible = true+ expect(payment_method.storefront_visible).to be true+ end+ end++ describe 'scopes' do+ let!(:storefront_method) { create(:check_payment_method, display_on: 'both') }+ let!(:admin_only_method) { create(:check_payment_method, display_on: 'back_end') }++ describe '.storefront_visible' do+ it 'returns methods where display_on != back_end' do+ expect(Spree::PaymentMethod.storefront_visible).to include(storefront_method)+ expect(Spree::PaymentMethod.storefront_visible).not_to include(admin_only_method)+ end+ end++ describe '.admin_only' do+ it 'returns methods where display_on == back_end' do+ expect(Spree::PaymentMethod.admin_only).to include(admin_only_method)+ expect(Spree::PaymentMethod.admin_only).not_to include(storefront_method)+ end+ end+ end+end