Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Added integrations gallery with payment providers, instant switches and setup guides (#14816)

Damian Legawiec06c53811174f
diff --git a/.changeset/admin-sdk-provider-listing.md b/.changeset/admin-sdk-provider-listing.md
new file mode 100644
index 0000000000..1adbba3995
--- /dev/null
+++ b/.changeset/admin-sdk-provider-listing.md
@@ -0,0 +1,5 @@
+---
+"@spree/admin-sdk": minor
+---
+
+Payment methods, payment method types and integration types now carry `logo_url` and `docs_url`, the provider's logo and setup guide. `PaymentMethodType` is its own interface rather than an alias of `ResourceTypeDefinition`.
diff --git a/.changeset/dashboard-integrations-gallery.md b/.changeset/dashboard-integrations-gallery.md
new file mode 100644
index 0000000000..c39eb3e037
--- /dev/null
+++ b/.changeset/dashboard-integrations-gallery.md
@@ -0,0 +1,5 @@
+---
+"@spree/dashboard": minor
+---
+
+Settings → Integrations is now a card gallery with tabs, and it lists payment providers next to service integrations. Each card switches its integration or payment method on and off straight away, opens its setup panel, and links to the provider's setup guide when one is declared.
diff --git a/docs/developer/how-to/custom-delivery-rate-provider.mdx b/docs/developer/how-to/custom-delivery-rate-provider.mdx
index cf7a7fd0d5..c291ba76b2 100644
--- a/docs/developer/how-to/custom-delivery-rate-provider.mdx
+++ b/docs/developer/how-to/custom-delivery-rate-provider.mdx
@@ -33,6 +33,8 @@ module SpreeAcmeCarrier
preference :test_mode, :boolean, default: true
def self.integration_group = 'shipping'
+ def self.logo_url = 'https://acme-carrier.example.com/logo.svg'
+ def self.docs_url = 'https://acme-carrier.example.com/docs/spree'
# Called when an admin activates the integration. Returning false blocks
# activation and shows your message in the dashboard.
@@ -51,6 +53,8 @@ module SpreeAcmeCarrier
end
```
+`logo_url` and `docs_url` are optional. They put your logo and a "Setup guide" link on the integration's card under **Settings > Integrations**. Payment methods declare them the same way.
+
Declare secrets as `:password` preferences. Spree masks them on read and guards the round-trip on write, so an API key never leaves the server in plain text.
## 2. Implement the provider
diff --git a/docs/developer/how-to/custom-payment-method.mdx b/docs/developer/how-to/custom-payment-method.mdx
index f20a72f6b9..0b450577c4 100644
--- a/docs/developer/how-to/custom-payment-method.mdx
+++ b/docs/developer/how-to/custom-payment-method.mdx
@@ -43,6 +43,24 @@ end
After restarting your server, you can select "MyGateway" when creating a new payment method in the admin panel under **Settings > Payments**.
+### Show a logo and setup guide (optional)
+
+Payment providers also appear in the admin dashboard under **Settings > Integrations**. Declare a logo and a link to your setup guide so merchants recognise the provider and know how to connect it:
+
+```ruby app/models/my_gateway.rb
+class MyGateway < Spree::PaymentMethod
+ def self.logo_url
+ 'https://my-gateway.example.com/logo.svg'
+ end
+
+ def self.docs_url
+ 'https://my-gateway.example.com/docs/spree'
+ end
+end
+```
+
+`logo_url` accepts anything an image tag accepts, including a `data:` URI if you don't want to host the file. Both are optional: without a logo the card shows the provider's first letter, and without a guide the link is hidden. Integrations declare the same two methods — see [custom delivery rate providers](/developer/how-to/custom-delivery-rate-provider).
+
## Step 3: Add Payment Session Support
Payment Sessions are the modern, PCI-compliant way to handle payments. Your gateway creates a session with the provider, the frontend collects payment details using the provider's SDK, and Spree records the result.
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index ad3fd91152..e1f5419284 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -2407,12 +2407,14 @@ export interface PaymentMethodUpdateParams {
/**
* One entry returned by `GET /payment_methods/types` — the registered list
* of available STI subclasses, with their per-provider preference schemas
- * for the universal configuration form.
- *
- * @deprecated Prefer `ResourceTypeDefinition`; this alias remains for
- * naming-symmetry with the controller. They are structurally identical.
+ * for the universal configuration form and their gallery listing.
*/
-export type PaymentMethodType = ResourceTypeDefinition
+export interface PaymentMethodType extends ResourceTypeDefinition {
+ /** Gallery logo: an absolute URL to hosted brand assets, or a `data:` URI. Render with a fallback. */
+ logo_url: string | null
+ /** Absolute URL of the provider's setup guide. */
+ docs_url: string | null
+}
/**
* One entry returned by `GET /integrations/types` — every registered
@@ -2433,6 +2435,8 @@ export interface IntegrationTypeDefinition {
description: string | null
/** Gallery logo: an absolute URL to hosted brand assets, or a `data:` URI for self-contained gems. Render with a fallback — hosted logos are a courtesy, not a guarantee. */
logo_url: string | null
+ /** Absolute URL of the integration's setup guide. */
+ docs_url: string | null
preference_schema: { key: string; type: string; default: unknown }[]
}
diff --git a/packages/admin-sdk/src/types/generated/PaymentMethod.ts b/packages/admin-sdk/src/types/generated/PaymentMethod.ts
index 86edafc9ed..a83fb9eed2 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 24af170a9383cb551f829e815a82231a
+// Typelizer digest 7cc02be62c6e93ce605d1ac420f2d252
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -21,6 +21,8 @@ interface PaymentMethod {
updated_at: string;
preferences: Record<string, unknown>;
preference_schema: Array<{ key: string; type: string; default: unknown; choices?: string[] }>;
+ logo_url: string | null;
+ docs_url: string | null;
}
export default PaymentMethod;
diff --git a/packages/admin-sdk/src/zod/generated/PaymentMethod.ts b/packages/admin-sdk/src/zod/generated/PaymentMethod.ts
index 08ff6d49e2..66edd6a831 100644
--- a/packages/admin-sdk/src/zod/generated/PaymentMethod.ts
+++ b/packages/admin-sdk/src/zod/generated/PaymentMethod.ts
@@ -19,6 +19,8 @@ export const PaymentMethodSchema = z.object({
updated_at: z.string(),
preferences: z.record(z.string(), z.unknown()),
preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown(), choices: z.array(z.string()).optional() })),
+ logo_url: z.string().nullable(),
+ docs_url: z.string().nullable(),
});
export type PaymentMethod = z.infer<typeof PaymentMethodSchema>;
diff --git a/packages/dashboard-core/src/pages/settings-index.tsx b/packages/dashboard-core/src/pages/settings-index.tsx
index 2f76b89271..557ffe4428 100644
--- a/packages/dashboard-core/src/pages/settings-index.tsx
+++ b/packages/dashboard-core/src/pages/settings-index.tsx
@@ -88,7 +88,7 @@ function SettingsCard({ entry, tenantId }: { entry: SettingsNavEntry; tenantId:
const description = resolveNavDescription(entry, t)
return (
- <Card className="p-0 transition-colors hover:bg-accent/80 hover:border-border">
+ <Card className="p-0 transition-colors border-border-subtle hover:bg-accent/80 hover:border-border">
{/* The whole card is the target — a small title-only link would fail the
44px minimum on touch and leaves most of the card dead to a click. */}
{/* Paths come from a runtime registry plugins extend, so they can't be
diff --git a/packages/dashboard-ui/src/styles.css b/packages/dashboard-ui/src/styles.css
index 94ceca6ace..ce3a08132e 100644
--- a/packages/dashboard-ui/src/styles.css
+++ b/packages/dashboard-ui/src/styles.css
@@ -153,7 +153,7 @@
sheet rather than a surface floating above it, so its edge only has to
suggest where the region ends. Used by `CardContent`'s frame; a dialog or
the sheet itself must keep --border, or the shell loses its outline. */
- --border-card: color-mix(in srgb, var(--border-base) 60%, transparent);
+ --border-card: color-mix(in srgb, var(--border-base) 70%, transparent);
/* Dividers *inside* a container — card header/footer splits, dialog and
sheet separators, table row rules.
@@ -224,11 +224,9 @@
--sidebar-foreground: oklch(26.8% 0.007 34.298);
--sidebar-primary: var(--primary);
--sidebar-primary-foreground: var(--primary-foreground);
- --sidebar-accent: var(--accent);
- --sidebar-accent-foreground: var(--accent-foreground);
- --sidebar-accent-strong: var(--accent-strong);
+ --sidebar-accent: oklch(92.3% 0.003 48.717);
+ --sidebar-accent-foreground: var(--accent-foreground);;
--sidebar-accent-hover: var(--accent-strong);
- --sidebar-accent-strong-hover: var(--accent-strong-hover);
/* Matches the rule the top bar draws, so every edge framing the shell —
the sidebar's, the top bar's, the settings header's — is one weight. */
--sidebar-border: color-mix(in srgb, var(--border) 75%, transparent);
@@ -327,7 +325,7 @@
hairline weight. */
--border-base: oklch(1 0 0 / 16%);
--border: var(--border-base);
- --border-card: color-mix(in srgb, var(--border-base) 50%, transparent);
+ --border-card: color-mix(in srgb, var(--border-base) 70%, transparent);
--border-subtle: color-mix(in srgb, var(--border-base) 50%, transparent);
/* Light mode darkens the control edge away from the card; dark mode lightens
it. Not the light value inverted — measured on this theme's own surfaces:
@@ -376,9 +374,7 @@
--sidebar-primary-foreground: var(--primary-foreground);
--sidebar-accent: var(--accent);
--sidebar-accent-foreground: var(--accent-foreground);
- --sidebar-accent-strong: var(--accent-strong);
--sidebar-accent-hover: var(--accent-hover);
- --sidebar-accent-strong-hover: var(--accent-strong-hover);
/* Matches the rule the top bar draws, so every edge framing the shell —
the sidebar's, the top bar's, the settings header's — is one weight. */
--sidebar-border: color-mix(in srgb, var(--border) 75%, transparent);
@@ -486,9 +482,7 @@
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
- --color-sidebar-accent-strong: var(--sidebar-accent-strong);
--color-sidebar-accent-hover: var(--sidebar-accent-hover);
- --color-sidebar-accent-strong-hover: var(--sidebar-accent-strong-hover);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
diff --git a/packages/dashboard-ui/src/ui/button.tsx b/packages/dashboard-ui/src/ui/button.tsx
index 84ed429059..ab1f1b039f 100644
--- a/packages/dashboard-ui/src/ui/button.tsx
+++ b/packages/dashboard-ui/src/ui/button.tsx
@@ -13,7 +13,7 @@ const buttonVariants = cva(
// and it was the only variant with no lift at all.
default: 'bg-primary text-primary-foreground shadow-xs hover:bg-primary/85',
outline:
- 'border-border bg-card shadow-xs text-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent',
+ 'border-border/80 bg-card shadow-xs text-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent',
// `group-hover/row:` — inside a hovered table row the row already wears
// --accent, so repeating it here leaves the button at 1.03:1 against its
// own background: invisible exactly when the pointer is on it. On a
diff --git a/packages/dashboard/e2e/integrations.spec.ts b/packages/dashboard/e2e/integrations.spec.ts
index 454d3d2b5b..31e39a0ced 100644
--- a/packages/dashboard/e2e/integrations.spec.ts
+++ b/packages/dashboard/e2e/integrations.spec.ts
@@ -1,17 +1,188 @@
-import { expect, test } from '@playwright/test'
+import { expect, type Page, test } from '@playwright/test'
import { login } from './helpers'
+const INTEGRATIONS_PATH = (storeId: string) => `/${storeId}/settings/integrations`
+
+// Seeds its own payment method rather than toggling a shared one. The custom
+// payment source type is hidden from the add-provider picker, so creating it
+// cannot starve payment-methods.spec.ts of a provider it installs.
+async function seedPaymentMethod(page: Page, storeId: string, accessToken: string, name: string) {
+ const res = await page.request.post('/api/v3/admin/payment_methods', {
+ headers: { 'X-Spree-Store-Id': storeId, Authorization: `Bearer ${accessToken}` },
+ data: { type: 'custom_payment_source_method', name, active: true },
+ })
+ if (!res.ok()) {
+ throw new Error(`Failed to seed payment method "${name}": ${res.status()} ${await res.text()}`)
+ }
+ return ((await res.json()) as { id: string }).id
+}
+
+async function deletePaymentMethod(page: Page, storeId: string, accessToken: string, id: string) {
+ await page.request.delete(`/api/v3/admin/payment_methods/${id}`, {
+ headers: { 'X-Spree-Store-Id': storeId, Authorization: `Bearer ${accessToken}` },
+ })
+}
+
+function paymentMethodCard(page: Page, name: string) {
+ const toggle = page.getByRole('switch', { name: `Turn ${name} on or off` })
+ return { toggle, card: page.locator('[data-slot="card"]').filter({ has: toggle }) }
+}
+
test.describe('integrations', () => {
- // Integrations come from provider gems, and the test app installs none —
- // so the page has to explain where they come from rather than sit blank.
- test('explains where integrations come from when none are installed', async ({ page }) => {
+ // The test app installs no provider gems, but payment providers ship with
+ // core — so the gallery always lists them next to any service integrations.
+ test('lists payment providers alongside integrations', async ({ page }) => {
const creds = await login(page)
- await page.goto(`/${creds.store_id}/settings/integrations`)
+ await page.goto(INTEGRATIONS_PATH(creds.store_id))
await expect(page.getByRole('heading', { name: /^integrations$/i })).toBeVisible({
timeout: 15_000,
})
- await expect(page.getByText(/no integrations installed/i)).toBeVisible()
- await expect(page.getByText(/install a provider gem/i)).toBeVisible()
+ await expect(page.getByRole('heading', { name: /^payments$/i })).toBeVisible()
+ await expect(page.getByRole('link', { name: /manage payment methods/i })).toBeVisible()
+ })
+
+ test('switches a payment method off and back on from its card', async ({ page }) => {
+ const creds = await login(page)
+ const name = `E2E Toggle PM ${Date.now()}`
+ const id = await seedPaymentMethod(page, creds.store_id, creds.accessToken, name)
+
+ try {
+ await page.goto(`${INTEGRATIONS_PATH(creds.store_id)}?tab=payments`)
+ const { toggle, card } = paymentMethodCard(page, name)
+ await expect(toggle).toBeChecked({ timeout: 15_000 })
+
+ await toggle.click()
+ await expect(toggle).not.toBeChecked()
+ await expect(card.getByText(/^disabled$/i)).toBeVisible()
+
+ // Survives a reload, so the change was saved rather than only shown.
+ await page.reload()
+ await expect(toggle).not.toBeChecked({ timeout: 15_000 })
+
+ await toggle.click()
+ await expect(toggle).toBeChecked()
+ await page.reload()
+ await expect(toggle).toBeChecked({ timeout: 15_000 })
+ await expect(card.getByText(/^active$/i)).toBeVisible()
+ } finally {
+ await deletePaymentMethod(page, creds.store_id, creds.accessToken, id)
+ }
+ })
+
+ // The switch is optimistic: it moves before the server answers, which a
+ // UI-only assertion cannot tell apart from a completed save. Holding the
+ // request open is what proves both halves — moved early, reverted on failure.
+ test('moves the switch at once and reverts it when the save fails', async ({ page }) => {
+ const creds = await login(page)
+ const name = `E2E Failing Toggle PM ${Date.now()}`
+ const id = await seedPaymentMethod(page, creds.store_id, creds.accessToken, name)
+
+ try {
+ await page.goto(`${INTEGRATIONS_PATH(creds.store_id)}?tab=payments`)
+ const { toggle, card } = paymentMethodCard(page, name)
+ await expect(toggle).toBeChecked({ timeout: 15_000 })
+
+ let releaseSave: () => void = () => {}
+ const saveHeld = new Promise<void>((resolve) => {
+ releaseSave = resolve
+ })
+ await page.route(`**/api/v3/admin/payment_methods/${id}`, async (route) => {
+ if (route.request().method() !== 'PATCH') return route.fallback()
+ await saveHeld
+ await route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: { code: 'internal_error', message: 'Server error' } }),
+ })
+ })
+
+ await toggle.click()
+ await expect(toggle).not.toBeChecked()
+ await expect(card.getByText(/^disabled$/i)).toBeVisible()
+
+ releaseSave()
+ await expect(toggle).toBeChecked({ timeout: 15_000 })
+ await expect(card.getByText(/^active$/i)).toBeVisible()
+ } finally {
+ await page.unrouteAll({ behavior: 'ignoreErrors' })
+ await deletePaymentMethod(page, creds.store_id, creds.accessToken, id)
+ }
+ })
+
+ // A second click while the first save is still open must win, even though
+ // the first save finishes later — otherwise the older value overwrites it.
+ test('saves the last choice when the switch is clicked again during a save', async ({ page }) => {
+ const creds = await login(page)
+ const name = `E2E Racing Toggle PM ${Date.now()}`
+ const id = await seedPaymentMethod(page, creds.store_id, creds.accessToken, name)
+
+ try {
+ await page.goto(`${INTEGRATIONS_PATH(creds.store_id)}?tab=payments`)
+ const { toggle } = paymentMethodCard(page, name)
+ await expect(toggle).toBeChecked({ timeout: 15_000 })
+
+ let releaseFirstSave: () => void = () => {}
+ const firstSaveHeld = new Promise<void>((resolve) => {
+ releaseFirstSave = resolve
+ })
+ let releaseSecondSave: () => void = () => {}
+ const secondSaveHeld = new Promise<void>((resolve) => {
+ releaseSecondSave = resolve
+ })
+ let saves = 0
+ await page.route(`**/api/v3/admin/payment_methods/${id}`, async (route) => {
+ if (route.request().method() !== 'PATCH') return route.fallback()
+ saves += 1
+ await (saves === 1 ? firstSaveHeld : secondSaveHeld)
+ await route.fallback()
+ })
+
+ await toggle.click()
+ await expect(toggle).not.toBeChecked()
+ await toggle.click()
+ await expect(toggle).toBeChecked()
+
+ // Once the first save lands the list is refetched holding its value
+ // (off). The switch must keep showing the latest choice regardless.
+ const listRefetched = page.waitForResponse(
+ (res) => res.request().method() === 'GET' && /\/payment_methods\?/.test(res.url()),
+ )
+ releaseFirstSave()
+ await expect.poll(() => saves, { timeout: 15_000 }).toBe(2)
+ // Let the refetched list reach the card before checking it; while the
+ // second save is held, a card that dropped the latest choice stays off.
+ await (await listRefetched).finished()
+ await page.evaluate(
+ () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
+ )
+ await expect(toggle).toBeChecked()
+
+ releaseSecondSave()
+
+ // The second save is forwarded, not awaited, by the route; wait for the
+ // server to hold the final choice before reloading to read it back.
+ await expect
+ .poll(
+ async () => {
+ const res = await page.request.get(`/api/v3/admin/payment_methods/${id}`, {
+ headers: {
+ 'X-Spree-Store-Id': creds.store_id,
+ Authorization: `Bearer ${creds.accessToken}`,
+ },
+ })
+ return ((await res.json()) as { active: boolean }).active
+ },
+ { timeout: 15_000 },
+ )
+ .toBe(true)
+
+ await page.unrouteAll({ behavior: 'wait' })
+ await page.reload()
+ await expect(toggle).toBeChecked({ timeout: 15_000 })
+ } finally {
+ await page.unrouteAll({ behavior: 'ignoreErrors' })
+ await deletePaymentMethod(page, creds.store_id, creds.accessToken, id)
+ }
})
})
diff --git a/packages/dashboard/src/components/spree/integrations/configure-integration-sheet.tsx b/packages/dashboard/src/components/spree/integrations/configure-integration-sheet.tsx
index 3d7b704c85..f4a922261c 100644
--- a/packages/dashboard/src/components/spree/integrations/configure-integration-sheet.tsx
+++ b/packages/dashboard/src/components/spree/integrations/configure-integration-sheet.tsx
@@ -29,11 +29,14 @@ import {
export function ConfigureIntegrationSheet({
type,
integration,
+ defaultActive = false,
open,
onOpenChange,
}: {
type: IntegrationTypeDefinition
integration?: Integration
+ /** Starting value of the Active switch when connecting a new integration. */
+ defaultActive?: boolean
open: boolean
onOpenChange: (open: boolean) => void
}) {
@@ -51,7 +54,7 @@ export function ConfigureIntegrationSheet({
? ((integration.preferences as Record<string, unknown>) ?? {})
: defaultPreferences(type.preference_schema),
)
- const [active, setActive] = useState(integration?.active ?? false)
+ const [active, setActive] = useState(integration?.active ?? defaultActive)
const [submitError, setSubmitError] = useState<string | null>(null)
const saving = createMutation.isPending || updateMutation.isPending
diff --git a/packages/dashboard/src/components/spree/integrations/integration-card.tsx b/packages/dashboard/src/components/spree/integrations/integration-card.tsx
new file mode 100644
index 0000000000..3bd0b44b68
--- /dev/null
+++ b/packages/dashboard/src/components/spree/integrations/integration-card.tsx
@@ -0,0 +1,185 @@
+import {
+ Avatar,
+ AvatarFallback,
+ AvatarImage,
+ Button,
+ Card,
+ CardContent,
+ CardFooter,
+ cn,
+ Switch,
+} from '@spree/dashboard-ui'
+import { ExternalLinkIcon } from '@spree/dashboard-ui/icons'
+import { type ReactNode, useEffect, useRef, useState } from 'react'
+
+export type IntegrationCardStatus = 'active' | 'inactive' | 'not_connected'
+
+/**
+ * One tile of the integrations gallery. Shared by connected services and
+ * payment providers so both read as the same kind of thing: a logo, its
+ * state, a switch to turn it on or off, and one action.
+ */
+export function IntegrationCard({
+ name,
+ logoUrl,
+ status,
+ statusLabels,
+ description,
+ tags,
+ toggle,
+ docsUrl,
+ docsLabel,
+ actionLabel,
+ onAction,
+}: {
+ name: string
+ logoUrl?: string | null
+ status: IntegrationCardStatus
+ /** Wording per state — the card picks one, following the switch while a save is in flight. */
+ statusLabels: Record<IntegrationCardStatus, string>
+ description?: string
+ tags?: ReactNode
+ toggle?: {
+ checked: boolean
+ disabled?: boolean
+ label: string
+ /**
+ * Return the save's promise, resolving to the value the server kept, and
+ * the switch moves at once and settles when it lands — flipping back if
+ * the save fails. Return nothing when the switch opens a form instead.
+ */
+ onCheckedChange: (checked: boolean) => Promise<boolean> | undefined
+ }
+ /** Setup guide, opened in a new tab. Only absolute http(s) URLs are linked. */
+ docsUrl?: string | null
+ docsLabel: string
+ actionLabel: string
+ onAction: () => void
+}) {
+ // The value the merchant just chose, shown until the saved record agrees.
+ const [optimisticChecked, setOptimisticChecked] = useState<boolean | null>(null)
+ // Mirrors `saveInFlight` for rendering: while a save is open the record can
+ // still hold the value from before it, which must not end the optimistic one.
+ const [saving, setSaving] = useState(false)
+ const savedChecked = toggle?.checked
+
+ useEffect(() => {
+ if (!saving && optimisticChecked !== null && savedChecked === optimisticChecked) {
+ setOptimisticChecked(null)
+ }
+ }, [saving, savedChecked, optimisticChecked])
+
+ const displayedStatus: IntegrationCardStatus =
+ optimisticChecked === null ? status : optimisticChecked ? 'active' : 'inactive'
+
+ // One save at a time, so saves cannot land out of order. Clicks made while
+ // one is in flight only move the switch; the latest of them is saved when
+ // it settles, unless the server already holds that value.
+ const saveInFlight = useRef(false)
+ const queuedChecked = useRef<boolean | null>(null)
+
+ function save(checked: boolean, request: Promise<boolean>) {
+ saveInFlight.current = true
+ setSaving(true)
+ request.then(
+ (kept) => settle(checked, kept),
+ () => settle(checked, null),
+ )
+ }
+
+ function settle(requested: boolean, kept: boolean | null) {
+ saveInFlight.current = false
+ setSaving(false)
+ const next = queuedChecked.current
+ queuedChecked.current = null
+ if (next !== null && next !== kept) {
+ const request = toggle?.onCheckedChange(next)
+ if (request) return save(next, request)
+ }
+ if (next === null && kept === requested) return
+ if (next === null || next !== kept) setOptimisticChecked(null)
+ }
+
+ function handleCheckedChange(checked: boolean) {
+ if (saveInFlight.current) {
+ queuedChecked.current = checked
+ setOptimisticChecked(checked)
+ return
+ }
+ const request = toggle?.onCheckedChange(checked)
+ if (!request) return
+ setOptimisticChecked(checked)
+ save(checked, request)
+ }
+
+ return (
+ <Card>
+ <CardContent className="flex flex-1 flex-col gap-3 p-4">
+ <div className="flex items-start gap-3">
+ <IntegrationLogo name={name} logoUrl={logoUrl ?? null} />
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate font-semibold text-sm">{name}</span>
+ <span className="flex items-center gap-1.5 text-muted-foreground text-xs">
+ <span
+ aria-hidden
+ className={cn(
+ 'size-1.5 shrink-0 rounded-full',
+ displayedStatus === 'active' && 'bg-success',
+ displayedStatus === 'inactive' && 'bg-warning',
+ displayedStatus === 'not_connected' && 'bg-muted-foreground/40',
+ )}
+ />
+ {statusLabels[displayedStatus]}
+ </span>
+ </div>
+ {toggle && (
+ <Switch
+ checked={optimisticChecked ?? toggle.checked}
+ disabled={toggle.disabled}
+ aria-label={toggle.label}
+ onCheckedChange={handleCheckedChange}
+ />
+ )}
+ </div>
+ {description && <p className="line-clamp-2 text-muted-foreground text-sm">{description}</p>}
+ {tags && <div className="mt-auto flex flex-wrap gap-1.5">{tags}</div>}
+ </CardContent>
+ <CardFooter className="justify-between gap-2 bg-muted/40 px-4 py-2">
+ {docsUrl && /^https?:\/\//.test(docsUrl) ? (
+ <a
+ href={docsUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="link inline-flex items-center gap-1 text-sm"
+ >
+ {docsLabel}
+ <ExternalLinkIcon className="size-3.5" />
+ </a>
+ ) : (
+ <span />
+ )}
+ <Button
+ size="sm"
+ variant={status === 'not_connected' ? 'default' : 'ghost'}
+ onClick={onAction}
+ >
+ {actionLabel}
+ </Button>
+ </CardFooter>
+ </Card>
+ )
+}
+
+// Gem-declared logo (hosted URL or data URI); the Avatar compound shows the
+// initial-letter fallback until the image loads, covering unset and
+// unreachable URLs alike — same pattern as the store switcher.
+function IntegrationLogo({ name, logoUrl }: { name: string; logoUrl: string | null }) {
+ return (
+ <Avatar className="size-10 shrink-0 rounded-lg bg-background p-1.5 after:rounded-lg after:border-border-subtle">
+ {logoUrl && <AvatarImage src={logoUrl} className="rounded-none object-contain" />}
+ <AvatarFallback className="rounded-md bg-transparent font-semibold">
+ {name.charAt(0).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/payment-method-editors/payment-method-sheets.tsx b/packages/dashboard/src/components/spree/payment-method-editors/payment-method-sheets.tsx
new file mode 100644
index 0000000000..1ebcc09c3d
--- /dev/null
+++ b/packages/dashboard/src/components/spree/payment-method-editors/payment-method-sheets.tsx
@@ -0,0 +1,278 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { PaymentMethodType, PreferenceField } from '@spree/admin-sdk'
+import { defaultPreferences, mapSpreeErrorsToForm, useStore } from '@spree/dashboard-core'
+import {
+ Button,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@spree/dashboard-ui'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import {
+ useCreatePaymentMethod,
+ usePaymentMethod,
+ usePaymentMethodTypes,
+ useUpdatePaymentMethod,
+} from '../../../hooks/use-payment-methods'
+import {
+ PAYMENT_METHOD_BASE_DEFAULTS,
+ PAYMENT_METHOD_CREATE_DEFAULTS,
+ paymentMethodBaseFormSchema,
+ paymentMethodCreateFormSchema,
+ paymentMethodValuesToCreateParams,
+ paymentMethodValuesToUpdateParams,
+} from '../../../schemas/payment-method'
+import { PaymentMethodForm } from './payment-method-form'
+import type { PaymentMethodFormValues } from './types'
+
+/** Readable provider name from its wire shorthand — `store_credit` → `Store Credit`. */
+export function paymentProviderLabel(type: string) {
+ return type
+ .split('_')
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(' ')
+}
+
+/**
+ * Add-payment-method sheet. Pass `initialType` to open it with that provider
+ * already chosen, as the integrations gallery does from a provider card.
+ */
+export function CreatePaymentMethodSheet({
+ open,
+ onOpenChange,
+ initialType,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ initialType?: PaymentMethodType
+}) {
+ const { t } = useTranslation()
+ const createMutation = useCreatePaymentMethod()
+ const { data: typesResponse, isLoading: loadingTypes } = usePaymentMethodTypes()
+ const providerTypes = useMemo(() => typesResponse?.data ?? [], [typesResponse])
+ // Seed `currency`-typed preferences with the store default so the merchant
+ // sees and submits a real value — `CurrencySelect` only displays the
+ // fallback now (it no longer commits via onChange).
+ const { defaultCurrency } = useStore()
+
+ const createDefaults: PaymentMethodFormValues = initialType
+ ? { ...PAYMENT_METHOD_CREATE_DEFAULTS, type: initialType.type, name: initialType.label }
+ : PAYMENT_METHOD_CREATE_DEFAULTS
+ const initialPreferences = () =>
+ initialType
+ ? defaultPreferences(initialType.preference_schema, { currency: defaultCurrency })
+ : {}
+
+ const form = useForm<PaymentMethodFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(paymentMethodCreateFormSchema) as any,
+ defaultValues: createDefaults,
+ })
+
+ const [preferences, setPreferences] = useState<Record<string, unknown>>(initialPreferences)
+ 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, { currency: defaultCurrency }))
+ }
+
+ async function onSubmit(values: PaymentMethodFormValues) {
+ try {
+ await createMutation.mutateAsync(paymentMethodValuesToCreateParams(values, preferences))
+ form.reset(createDefaults)
+ setPreferences(initialPreferences())
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Sheet
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) {
+ form.reset(createDefaults)
+ setPreferences(initialPreferences())
+ }
+ onOpenChange(next)
+ }}
+ >
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.pages.settings.payment_methods.add_sheet_title')}</SheetTitle>
+ <SheetDescription>{t('admin.payment_methods.create_description')}</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">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
+ <PaymentMethodForm
+ mode="create"
+ form={form}
+ providerTypes={providerTypes}
+ loadingTypes={loadingTypes}
+ preferenceSchema={preferenceSchema}
+ providerType={providerType}
+ paymentMethod={null}
+ preferences={preferences}
+ onPreferencesChange={setPreferences}
+ onProviderTypeChange={handleProviderTypeChange}
+ />
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting
+ ? t('admin.actions.creating')
+ : t('admin.payment_methods.create_label')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+export function EditPaymentMethodSheet({
+ id,
+ open,
+ onOpenChange,
+}: {
+ id: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { data: paymentMethod, isLoading } = usePaymentMethod(id)
+ const updateMutation = useUpdatePaymentMethod(id)
+
+ const form = useForm<PaymentMethodFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(paymentMethodBaseFormSchema) as any,
+ defaultValues: PAYMENT_METHOD_BASE_DEFAULTS,
+ })
+ const [preferences, setPreferences] = useState<Record<string, unknown>>({})
+ // Snapshot of the preferences last loaded from the server. Derive the
+ // dirty state by comparing JSON shape — avoids a separate flag that
+ // can drift out of sync with the actual values.
+ const originalPreferencesRef = useRef<string>('{}')
+ // Track the loaded record so we don't clobber in-flight edits when the
+ // cache invalidates after a save.
+ const loadedIdRef = useRef<string | undefined>(undefined)
+
+ useEffect(() => {
+ if (!paymentMethod || paymentMethod.id === loadedIdRef.current) return
+ form.reset({
+ name: paymentMethod.name,
+ description: paymentMethod.description ?? '',
+ storefront_visible: paymentMethod.storefront_visible ?? true,
+ active: paymentMethod.active,
+ capture_method: paymentMethod.capture_method ?? '',
+ })
+ const initialPreferences = (paymentMethod.preferences as Record<string, unknown>) ?? {}
+ setPreferences(initialPreferences)
+ originalPreferencesRef.current = JSON.stringify(initialPreferences)
+ loadedIdRef.current = paymentMethod.id
+ }, [paymentMethod, form])
+
+ const preferencesDirty = useMemo(
+ () => JSON.stringify(preferences) !== originalPreferencesRef.current,
+ [preferences],
+ )
+
+ async function onSubmit(values: PaymentMethodFormValues) {
+ const params = paymentMethodValuesToUpdateParams(values)
+ if (preferencesDirty) params.preferences = preferences
+ try {
+ await updateMutation.mutateAsync(params)
+ form.reset(values)
+ originalPreferencesRef.current = JSON.stringify(preferences)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ // STI shorthand for slot lookup, e.g. `bogus`, `stripe`. The API
+ // returns it on the `type` attribute (see PaymentMethodSerializer).
+ const providerType = paymentMethod?.type ?? ''
+ const providerLabel = paymentProviderLabel(providerType)
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>
+ {paymentMethod?.name ?? t('admin.pages.settings.payment_methods.edit_sheet_title')}
+ </SheetTitle>
+ <SheetDescription>
+ {providerLabel
+ ? t('admin.payment_methods.provider_description', { provider: providerLabel })
+ : t('admin.payment_methods.edit_description')}
+ </SheetDescription>
+ </SheetHeader>
+ {isLoading ? (
+ <div className="p-4 text-sm text-muted-foreground">{t('admin.common.loading')}</div>
+ ) : (
+ <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">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
+ <PaymentMethodForm
+ mode="edit"
+ form={form}
+ preferenceSchema={paymentMethod?.preference_schema ?? []}
+ providerType={providerType}
+ paymentMethod={paymentMethod ?? null}
+ preferences={preferences}
+ onPreferencesChange={setPreferences}
+ />
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button
+ type="submit"
+ disabled={
+ form.formState.isSubmitting || (!form.formState.isDirty && !preferencesDirty)
+ }
+ >
+ {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </SheetFooter>
+ </form>
+ )}
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/packages/dashboard/src/hooks/use-integrations.ts b/packages/dashboard/src/hooks/use-integrations.ts
index 27a4a04cbc..33e98c1a8e 100644
--- a/packages/dashboard/src/hooks/use-integrations.ts
+++ b/packages/dashboard/src/hooks/use-integrations.ts
@@ -41,9 +41,17 @@ export function useCreateIntegration() {
})
}
-/** Updates credentials or activation. Masked secrets round-trip safely. */
-export function useUpdateIntegration(id: string) {
+/**
+ * Updates credentials or activation. Masked secrets round-trip safely.
+ * `showValidationErrors` toasts a failed activation for callers with no form
+ * to show it in, such as the gallery card's switch.
+ */
+export function useUpdateIntegration(
+ id: string,
+ { showValidationErrors = false }: { showValidationErrors?: boolean } = {},
+) {
return useResourceMutation<Integration, Error, IntegrationUpdateParams>({
+ showValidationErrors,
mutationFn: (params) => adminClient.integrations.update(id, params),
invalidate: [['integrations'], ['delivery-methods']],
successMessage: i18n.t('admin.integrations.messages.updated'),
diff --git a/packages/dashboard/src/hooks/use-payment-methods.ts b/packages/dashboard/src/hooks/use-payment-methods.ts
index 31842b6a14..94677478fb 100644
--- a/packages/dashboard/src/hooks/use-payment-methods.ts
+++ b/packages/dashboard/src/hooks/use-payment-methods.ts
@@ -14,7 +14,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
import i18n from 'i18next'
import { filterPaymentMethodProviderTypes } from '../schemas/payment-method'
-export function usePaymentMethodTypes() {
+export function usePaymentMethodTypes({ enabled = true }: { enabled?: boolean } = {}) {
// Store-scoped because the server filters out providers already installed
// on the current store. Matches the +['payment-methods', 'types']+ shape
// that +useResourceMutation+ expands to +['payment-methods', storeId, 'types']+.
@@ -25,18 +25,25 @@ export function usePaymentMethodTypes() {
return { ...response, data: filterPaymentMethodProviderTypes(response.data) }
},
staleTime: Infinity,
+ enabled,
})
}
interface UsePaymentMethodsParams {
page?: number
limit?: number
+ enabled?: boolean
}
-export function usePaymentMethods({ page = 1, limit = 100 }: UsePaymentMethodsParams = {}) {
+export function usePaymentMethods({
+ page = 1,
+ limit = 100,
+ enabled = true,
+}: UsePaymentMethodsParams = {}) {
return useQuery({
queryKey: useResourceKey('payment-methods', { page, limit }),
queryFn: () => adminClient.paymentMethods.list({ page, limit }),
+ enabled,
})
}
@@ -60,8 +67,12 @@ export function useCreatePaymentMethod() {
})
}
-export function useUpdatePaymentMethod(id: string) {
+export function useUpdatePaymentMethod(
+ id: string,
+ { showValidationErrors = false }: { showValidationErrors?: boolean } = {},
+) {
return useResourceMutation<PaymentMethod, Error, PaymentMethodUpdateParams>({
+ showValidationErrors,
mutationFn: (params) => adminClient.paymentMethods.update(id, params),
invalidate: [['payment-methods'], ['payment-methods', id], [STORE_QUERY_RESOURCE]],
successMessage: i18n.t('admin.payment_methods.messages.updated'),
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index a721fc13e9..b0a5baeb9a 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2441,7 +2441,7 @@
"configure_cta": "إعداد",
"connect_cta": "اتصال",
"connect_description": "أدخل بيانات اعتماد هذا المزوّد. الحفظ يخزّنها؛ والتفعيل يتحقق من الاتصال.",
- "description": "اربط خدمات المزوّدين بهذا المتجر. تُخزَّن بيانات الاعتماد لكل متجر ويستخدمها مزوّدو التوصيل والضرائب وغيرهم.",
+ "description": "اربط مزودي الدفع والخدمات الأخرى بهذا المتجر. تُحفظ بيانات الاعتماد لكل متجر وتستخدمها عملية الدفع والتوصيل والضرائب والمزودون الآخرون.",
"disconnect": "قطع الاتصال",
"disconnect_confirm": {
"message": "هل تريد قطع اتصال {{name}}؟ ستُحذف بيانات الاعتماد المخزّنة وسيتوقف المزوّدون الذين يستخدمونها عن العمل.",
@@ -2454,19 +2454,25 @@
},
"groups": {
"other": "أخرى",
+ "payments": "المدفوعات",
"shipping": "الشحن",
"tax": "الضرائب"
},
+ "manage_payment_methods": "إدارة طرق الدفع",
"messages": {
"connected": "تم توصيل التكامل",
"disconnected": "تم قطع اتصال التكامل",
"updated": "تم تحديث التكامل"
},
+ "setup_guide": "دليل الإعداد",
"status": {
"active": "مفعّل",
"connected_inactive": "متصل (غير مفعّل)",
"not_connected": "غير متصل"
},
+ "tabs": {
+ "all": "الكل"
+ },
"test": {
"failure": "فشل الاتصال.",
"label": "الاتصال",
@@ -2474,7 +2480,9 @@
"success": "نجح الاتصال.",
"testing": "جارٍ الاختبار…"
},
+ "test_mode": "وضع الاختبار",
"title": "التكاملات",
+ "toggle_label": "تشغيل {{name}} أو إيقافه",
"view_cta": "عرض"
},
"invitation": {
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index cd765742a5..4bda4dfa5c 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2423,7 +2423,7 @@
"configure_cta": "Konfigurieren",
"connect_cta": "Verbinden",
"connect_description": "Geben Sie die Zugangsdaten für diesen Anbieter ein. Speichern legt sie ab; das Aktivieren prüft die Verbindung.",
- "description": "Verbinden Sie Anbieterdienste mit diesem Shop. Zugangsdaten werden pro Shop gespeichert und von Versand-, Steuer- und anderen Anbietern genutzt.",
+ "description": "Verbinden Sie Zahlungsanbieter und andere Dienste mit diesem Shop. Zugangsdaten werden pro Shop gespeichert und von Checkout, Versand, Steuern und anderen Anbietern verwendet.",
"disconnect": "Trennen",
"disconnect_confirm": {
"message": "{{name}} trennen? Die gespeicherten Zugangsdaten werden gelöscht und Anbieter, die sie nutzen, funktionieren nicht mehr.",
@@ -2436,19 +2436,25 @@
},
"groups": {
"other": "Sonstige",
+ "payments": "Zahlungen",
"shipping": "Versand",
"tax": "Steuern"
},
+ "manage_payment_methods": "Zahlungsmethoden verwalten",
"messages": {
"connected": "Integration verbunden",
"disconnected": "Integration getrennt",
"updated": "Integration aktualisiert"
},
+ "setup_guide": "Einrichtungsanleitung",
"status": {
"active": "Aktiv",
"connected_inactive": "Verbunden (inaktiv)",
"not_connected": "Nicht verbunden"
},
+ "tabs": {
+ "all": "Alle"
+ },
"test": {
"failure": "Verbindung fehlgeschlagen.",
"label": "Verbindung",
@@ -2456,7 +2462,9 @@
"success": "Verbindung erfolgreich.",
"testing": "Wird getestet…"
},
+ "test_mode": "Testmodus",
"title": "Integrationen",
+ "toggle_label": "{{name}} ein- oder ausschalten",
"view_cta": "Ansehen"
},
"invitation": {
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 969dc0b1fe..6aa8a061fa 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2423,7 +2423,7 @@
"configure_cta": "Configure",
"connect_cta": "Connect",
"connect_description": "Enter the credentials for this provider. Saving stores them; switching it active verifies the connection.",
- "description": "Connect provider services to this store. Credentials are stored per store and used by delivery, tax and other providers.",
+ "description": "Connect payment providers and other services to this store. Credentials are stored per store and used by checkout, delivery, tax and other providers.",
"disconnect": "Disconnect",
"disconnect_confirm": {
"message": "Disconnect {{name}}? Its stored credentials are deleted and providers using it stop working.",
@@ -2436,19 +2436,25 @@
},
"groups": {
"other": "Other",
+ "payments": "Payments",
"shipping": "Shipping",
"tax": "Tax"
},
+ "manage_payment_methods": "Manage payment methods",
"messages": {
"connected": "Integration connected",
"disconnected": "Integration disconnected",
"updated": "Integration updated"
},
+ "setup_guide": "Setup guide",
"status": {
"active": "Active",
"connected_inactive": "Connected (inactive)",
"not_connected": "Not connected"
},
+ "tabs": {
+ "all": "All"
+ },
"test": {
"failure": "Connection failed.",
"label": "Connection",
@@ -2456,7 +2462,9 @@
"success": "Connection successful.",
"testing": "Testing…"
},
+ "test_mode": "Test mode",
"title": "Integrations",
+ "toggle_label": "Turn {{name}} on or off",
"view_cta": "View"
},
"invitation": {
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index 4d6a9d38cf..18494a5b07 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -5018,7 +5018,7 @@
"configure_cta": "Configurar",
"connect_cta": "Conectar",
"connect_description": "Ingresá las credenciales de este proveedor. Guardar las almacena; pasarla a activa verifica la conexión.",
- "description": "Conectá servicios de proveedores a esta tienda. Las credenciales se guardan por tienda y las usan los proveedores de envío, impuestos y otros.",
+ "description": "Conecta proveedores de pago y otros servicios a esta tienda. Las credenciales se guardan por tienda y las usan el checkout, los envíos, los impuestos y otros proveedores.",
"disconnect": "Desconectar",
"disconnect_confirm": {
"message": "¿Desconectar {{name}}? Sus credenciales guardadas se eliminan y los proveedores que la usan dejan de funcionar.",
@@ -5031,19 +5031,25 @@
},
"groups": {
"other": "Otro",
+ "payments": "Pagos",
"shipping": "Envío",
"tax": "Impuestos"
},
+ "manage_payment_methods": "Gestionar métodos de pago",
"messages": {
"connected": "Integración conectada",
"disconnected": "Integración desconectada",
"updated": "Integración actualizada"
},
+ "setup_guide": "Guía de configuración",
"status": {
"active": "Activa",
"connected_inactive": "Conectada (inactiva)",
"not_connected": "No conectada"
},
+ "tabs": {
+ "all": "Todas"
+ },
"test": {
"failure": "La conexión falló.",
"label": "Conexión",
@@ -5051,7 +5057,9 @@
"success": "Conexión exitosa.",
"testing": "Probando…"
},
+ "test_mode": "Modo de prueba",
"title": "Integraciones",
+ "toggle_label": "Activar o desactivar {{name}}",
"view_cta": "Ver"
},
"tax_identifiers": {
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index a3ba491156..768d10353a 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2423,7 +2423,7 @@
"configure_cta": "Configurer",
"connect_cta": "Connecter",
"connect_description": "Saisissez les identifiants de ce fournisseur. L'enregistrement les stocke ; l'activation vérifie la connexion.",
- "description": "Connectez des services fournisseurs à cette boutique. Les identifiants sont stockés par boutique et utilisés par les fournisseurs de livraison, de taxes et autres.",
+ "description": "Connectez des prestataires de paiement et d’autres services à cette boutique. Les identifiants sont enregistrés par boutique et utilisés par le paiement, la livraison, les taxes et les autres prestataires.",
"disconnect": "Déconnecter",
"disconnect_confirm": {
"message": "Déconnecter {{name}} ? Ses identifiants stockés seront supprimés et les fournisseurs qui les utilisent cesseront de fonctionner.",
@@ -2436,19 +2436,25 @@
},
"groups": {
"other": "Autres",
+ "payments": "Paiements",
"shipping": "Livraison",
"tax": "Taxes"
},
+ "manage_payment_methods": "Gérer les moyens de paiement",
"messages": {
"connected": "Intégration connectée",
"disconnected": "Intégration déconnectée",
"updated": "Intégration mise à jour"
},
+ "setup_guide": "Guide de configuration",
"status": {
"active": "Active",
"connected_inactive": "Connectée (inactive)",
"not_connected": "Non connectée"
},
+ "tabs": {
+ "all": "Toutes"
+ },
"test": {
"failure": "Échec de la connexion.",
"label": "Connexion",
@@ -2456,7 +2462,9 @@
"success": "Connexion réussie.",
"testing": "Test en cours…"
},
+ "test_mode": "Mode test",
"title": "Intégrations",
+ "toggle_label": "Activer ou désactiver {{name}}",
"view_cta": "Voir"
},
"invitation": {
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index f0077bbe89..042cdc0ebd 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -2441,7 +2441,7 @@
"configure_cta": "Konfiguruj",
"connect_cta": "Połącz",
"connect_description": "Wprowadź dane dostępowe tego dostawcy. Zapis je przechowuje; aktywacja weryfikuje połączenie.",
- "description": "Połącz usługi dostawców z tym sklepem. Dane dostępowe są przechowywane per sklep i używane przez dostawców dostaw, podatków i innych.",
+ "description": "Połącz dostawców płatności i inne usługi z tym sklepem. Dane dostępowe są przechowywane osobno dla każdego sklepu i używane przez kasę, dostawę, podatki i innych dostawców.",
"disconnect": "Rozłącz",
"disconnect_confirm": {
"message": "Rozłączyć {{name}}? Zapisane dane dostępowe zostaną usunięte, a korzystający z nich dostawcy przestaną działać.",
@@ -2454,19 +2454,25 @@
},
"groups": {
"other": "Inne",
+ "payments": "Płatności",
"shipping": "Dostawa",
"tax": "Podatki"
},
+ "manage_payment_methods": "Zarządzaj metodami płatności",
"messages": {
"connected": "Integracja połączona",
"disconnected": "Integracja rozłączona",
"updated": "Integracja zaktualizowana"
},
+ "setup_guide": "Instrukcja konfiguracji",
"status": {
"active": "Aktywna",
"connected_inactive": "Połączona (nieaktywna)",
"not_connected": "Niepołączona"
},
+ "tabs": {
+ "all": "Wszystkie"
+ },
"test": {
"failure": "Połączenie nieudane.",
"label": "Połączenie",
@@ -2474,7 +2480,9 @@
"success": "Połączenie udane.",
"testing": "Testowanie…"
},
+ "test_mode": "Tryb testowy",
"title": "Integracje",
+ "toggle_label": "Włącz lub wyłącz {{name}}",
"view_cta": "Zobacz"
},
"invitation": {
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 358e0ded57..0356bb0477 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2418,7 +2418,7 @@
"configure_cta": "配置",
"connect_cta": "连接",
"connect_description": "输入此提供方的凭据。保存即存储;启用时会验证连接。",
- "description": "将服务提供方连接到此商店。凭据按商店存储,供配送、税务及其他提供方使用。",
+ "description": "将支付服务商和其他服务连接到此店铺。凭据按店铺存储,供结账、配送、税费和其他服务商使用。",
"disconnect": "断开连接",
"disconnect_confirm": {
"message": "断开 {{name}}?其存储的凭据将被删除,使用它的提供方将停止工作。",
@@ -2431,19 +2431,25 @@
},
"groups": {
"other": "其他",
+ "payments": "支付",
"shipping": "配送",
"tax": "税务"
},
+ "manage_payment_methods": "管理支付方式",
"messages": {
"connected": "集成已连接",
"disconnected": "集成已断开",
"updated": "集成已更新"
},
+ "setup_guide": "设置指南",
"status": {
"active": "已启用",
"connected_inactive": "已连接(未启用)",
"not_connected": "未连接"
},
+ "tabs": {
+ "all": "全部"
+ },
"test": {
"failure": "连接失败。",
"label": "连接",
@@ -2451,7 +2457,9 @@
"success": "连接成功。",
"testing": "正在测试…"
},
+ "test_mode": "测试模式",
"title": "集成",
+ "toggle_label": "开启或关闭 {{name}}",
"view_cta": "查看"
},
"invitation": {
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx
index 75765a7cd6..ed32285dd8 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx
@@ -1,53 +1,106 @@
-import type { Integration, IntegrationTypeDefinition } from '@spree/admin-sdk'
+import type {
+ Integration,
+ IntegrationTypeDefinition,
+ PaymentMethod,
+ PaymentMethodType,
+} from '@spree/admin-sdk'
import { PageHeader, Subject, typeDescription, usePermissions } from '@spree/dashboard-core'
import {
- Avatar,
- AvatarFallback,
- AvatarImage,
Badge,
Button,
- Card,
- CardContent,
Empty,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
+ Tabs,
+ TabsList,
+ TabsTrigger,
} from '@spree/dashboard-ui'
import { PlugIcon } from '@spree/dashboard-ui/icons'
-import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import { useMemo } from 'react'
+import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
+import { type ReactNode, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
import { ConfigureIntegrationSheet } from '../../../../components/spree/integrations/configure-integration-sheet'
-import { useIntegrations, useIntegrationTypes } from '../../../../hooks/use-integrations'
+import { IntegrationCard } from '../../../../components/spree/integrations/integration-card'
+import {
+ CreatePaymentMethodSheet,
+ EditPaymentMethodSheet,
+ paymentProviderLabel,
+} from '../../../../components/spree/payment-method-editors/payment-method-sheets'
+import {
+ useIntegrations,
+ useIntegrationTypes,
+ useUpdateIntegration,
+} from '../../../../hooks/use-integrations'
+import {
+ usePaymentMethods,
+ usePaymentMethodTypes,
+ useUpdatePaymentMethod,
+} from '../../../../hooks/use-payment-methods'
+
+const PAYMENTS_GROUP = 'payments'
+const ALL_TAB = 'all'
const integrationsSearchSchema = z.object({
+ tab: z.string().optional(),
configure: z.string().optional(),
+ payment_method: z.string().optional(),
+ add_payment_method: z.string().optional(),
+ activate: z.coerce.boolean().optional(),
})
+type IntegrationsSearch = z.infer<typeof integrationsSearchSchema>
+
export const Route = createFileRoute('/_authenticated/$storeId/settings/integrations')({
validateSearch: integrationsSearchSchema,
component: IntegrationsPage,
})
+function groupLabel(t: (key: string, options?: Record<string, unknown>) => string, group: string) {
+ // Groups arrive as open strings from gems, so unknown ones fall back to a
+ // capitalized version of the token.
+ return t(`admin.integrations.groups.${group}`, {
+ defaultValue: group.charAt(0).toUpperCase() + group.slice(1),
+ })
+}
+
function IntegrationsPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const search = Route.useSearch()
- const { data: typesResponse, isLoading } = useIntegrationTypes()
+ const { storeId } = Route.useParams()
+ const { permissions } = usePermissions()
+ const canReadPayments = permissions.can('read', Subject.PaymentMethod)
+ const canCreatePayments = permissions.can('create', Subject.PaymentMethod)
+
+ const { data: typesResponse, isLoading: loadingTypes } = useIntegrationTypes()
const { data: integrationsResponse } = useIntegrations()
+ const { data: paymentMethodsResponse, isLoading: loadingPaymentMethods } = usePaymentMethods({
+ enabled: canReadPayments,
+ })
+ const { data: paymentTypesResponse, isLoading: loadingPaymentTypes } = usePaymentMethodTypes({
+ enabled: canCreatePayments,
+ })
const types = useMemo(() => typesResponse?.data ?? [], [typesResponse])
- const integrations = useMemo(() => integrationsResponse?.data ?? [], [integrationsResponse])
const integrationsByType = useMemo(
- () => new Map(integrations.map((integration) => [integration.type, integration])),
- [integrations],
+ () => new Map((integrationsResponse?.data ?? []).map((record) => [record.type, record])),
+ [integrationsResponse],
+ )
+ const paymentMethods = useMemo(
+ () => (canReadPayments ? (paymentMethodsResponse?.data ?? []) : []),
+ [canReadPayments, paymentMethodsResponse],
+ )
+ // The server already leaves out providers installed on this store, so
+ // these are only the ones still to set up.
+ const availablePaymentTypes = useMemo(
+ () => (paymentTypesResponse?.data ?? []).filter((type) => !type.superseded),
+ [paymentTypesResponse],
)
- // Gallery grouped by integration_group; groups arrive as open strings from
- // gems, so unknown ones fall back to a capitalized version of the token.
- const grouped = useMemo(() => {
+ const integrationGroups = useMemo(() => {
const map = new Map<string, IntegrationTypeDefinition[]>()
for (const type of types) {
const group = type.group ?? 'other'
@@ -56,18 +109,41 @@ function IntegrationsPage() {
return [...map.entries()]
}, [types])
- const openConfigure = (type: string) =>
- navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, configure: type }) as never })
+ const hasPayments = paymentMethods.length > 0 || availablePaymentTypes.length > 0
+ const tabs = [
+ ALL_TAB,
+ ...(hasPayments ? [PAYMENTS_GROUP] : []),
+ ...integrationGroups.map(([group]) => group),
+ ]
+ const activeTab = search.tab && tabs.includes(search.tab) ? search.tab : ALL_TAB
+ const showGroup = (group: string) => activeTab === ALL_TAB || activeTab === group
- const closeSheet = () =>
+ const updateSearch = (patch: Partial<IntegrationsSearch>) =>
navigate({
search: (prev: Record<string, unknown>) => {
- const { configure: _c, ...rest } = prev
- return rest as never
+ const next: Record<string, unknown> = { ...prev, ...patch }
+ for (const key of Object.keys(next)) if (next[key] === undefined) delete next[key]
+ return next as never
},
})
+ const closeSheets = () =>
+ updateSearch({
+ configure: undefined,
+ activate: undefined,
+ payment_method: undefined,
+ add_payment_method: undefined,
+ })
+
const configuringType = types.find((type) => type.type === search.configure)
+ const addingPaymentType = availablePaymentTypes.find(
+ (type) => type.type === search.add_payment_method,
+ )
+ // Every list feeding the gallery has to land before it can be called empty.
+ const loading =
+ loadingTypes ||
+ (canReadPayments && loadingPaymentMethods) ||
+ (canCreatePayments && loadingPaymentTypes)
return (
<div className="flex flex-col gap-6">
@@ -77,7 +153,7 @@ function IntegrationsPage() {
description={t('admin.integrations.description')}
/>
- {!isLoading && types.length === 0 && (
+ {!loading && types.length === 0 && !hasPayments && (
<Empty>
<EmptyHeader>
<EmptyMedia variant="icon">
@@ -89,97 +165,270 @@ function IntegrationsPage() {
</Empty>
)}
- {grouped.map(([group, groupTypes]) => (
- <section key={group} className="flex flex-col gap-3">
- <h2 className="font-medium text-muted-foreground text-sm">
- {t(`admin.integrations.groups.${group}`, {
- defaultValue: group.charAt(0).toUpperCase() + group.slice(1),
- })}
- </h2>
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
+ {tabs.length > 2 && (
+ <Tabs
+ value={activeTab}
+ onValueChange={(value) =>
+ updateSearch({ tab: value === ALL_TAB ? undefined : (value as string) })
+ }
+ className="min-w-0 max-w-full overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
+ >
+ <TabsList className="w-max">
+ {tabs.map((tab) => (
+ <TabsTrigger key={tab} value={tab} className="whitespace-nowrap">
+ {tab === ALL_TAB ? t('admin.integrations.tabs.all') : groupLabel(t, tab)}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+ )}
+
+ {hasPayments && showGroup(PAYMENTS_GROUP) && (
+ <GallerySection
+ title={groupLabel(t, PAYMENTS_GROUP)}
+ action={
+ <Button asChild variant="link" size="sm" className="h-auto p-0">
+ <Link to="/$storeId/settings/payment-methods" params={{ storeId }}>
+ {t('admin.integrations.manage_payment_methods')}
+ </Link>
+ </Button>
+ }
+ >
+ {paymentMethods.map((paymentMethod) => (
+ <PaymentMethodCard
+ key={paymentMethod.id}
+ paymentMethod={paymentMethod}
+ onConfigure={() => updateSearch({ payment_method: paymentMethod.id })}
+ />
+ ))}
+ {availablePaymentTypes.map((type) => (
+ <PaymentProviderCard
+ key={type.type}
+ type={type}
+ onSetUp={() => updateSearch({ add_payment_method: type.type })}
+ />
+ ))}
+ </GallerySection>
+ )}
+
+ {integrationGroups
+ .filter(([group]) => showGroup(group))
+ .map(([group, groupTypes]) => (
+ <GallerySection key={group} title={groupLabel(t, group)}>
{groupTypes.map((type) => (
- <IntegrationCard
+ <ServiceIntegrationCard
key={type.type}
type={type}
integration={integrationsByType.get(type.type)}
- onConfigure={() => openConfigure(type.type)}
+ onConfigure={(activate) =>
+ updateSearch({ configure: type.type, activate: activate || undefined })
+ }
/>
))}
- </div>
- </section>
- ))}
+ </GallerySection>
+ ))}
{configuringType && (
<ConfigureIntegrationSheet
key={`${configuringType.type}:${integrationsByType.get(configuringType.type)?.id ?? 'new'}`}
type={configuringType}
integration={integrationsByType.get(configuringType.type)}
+ defaultActive={search.activate}
open
- onOpenChange={(open) => !open && closeSheet()}
+ onOpenChange={(open) => !open && closeSheets()}
+ />
+ )}
+ {search.payment_method && (
+ <EditPaymentMethodSheet
+ id={search.payment_method}
+ open
+ onOpenChange={(open) => !open && closeSheets()}
+ />
+ )}
+ {addingPaymentType && (
+ <CreatePaymentMethodSheet
+ key={addingPaymentType.type}
+ initialType={addingPaymentType}
+ open
+ onOpenChange={(open) => !open && closeSheets()}
/>
)}
</div>
)
}
-function IntegrationCard({
+function GallerySection({
+ title,
+ action,
+ children,
+}: {
+ title: string
+ action?: ReactNode
+ children: ReactNode
+}) {
+ return (
+ <section className="flex flex-col gap-3">
+ <div className="flex items-center justify-between gap-3">
+ <h2 className="font-medium text-muted-foreground text-sm">{title}</h2>
+ {action}
+ </div>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">{children}</div>
+ </section>
+ )
+}
+
+function GroupTag({ children }: { children: ReactNode }) {
+ return (
+ <Badge variant="secondary" className="uppercase tracking-wide">
+ {children}
+ </Badge>
+ )
+}
+
+function ServiceIntegrationCard({
type,
integration,
onConfigure,
}: {
type: IntegrationTypeDefinition
integration?: Integration
- onConfigure: () => void
+ /** Opens the connect sheet; `activate` pre-sets it to switch the integration on. */
+ onConfigure: (activate?: boolean) => void
}) {
const { t } = useTranslation()
const { permissions } = usePermissions()
const canWrite = permissions.can('update', Subject.Integration)
+ const updateMutation = useUpdateIntegration(integration?.id ?? '', {
+ showValidationErrors: true,
+ })
+
+ const status = !integration ? 'not_connected' : integration.active ? 'active' : 'inactive'
+
+ return (
+ <IntegrationCard
+ name={type.name}
+ logoUrl={type.logo_url}
+ docsUrl={type.docs_url}
+ docsLabel={t('admin.integrations.setup_guide')}
+ status={status}
+ statusLabels={{
+ active: t('admin.integrations.status.active'),
+ inactive: t('admin.integrations.status.connected_inactive'),
+ not_connected: t('admin.integrations.status.not_connected'),
+ }}
+ description={typeDescription('integration', type.type, type.description)}
+ tags={<GroupTag>{groupLabel(t, type.group ?? 'other')}</GroupTag>}
+ toggle={{
+ checked: integration?.active ?? false,
+ disabled: !canWrite,
+ label: t('admin.integrations.toggle_label', { name: type.name }),
+ // Not connected yet: there are no credentials to activate, so the
+ // switch opens the connect sheet ready to activate on save.
+ // Connected: activating verifies the connection server-side, and a
+ // refusal is toasted by the mutation while the switch flips back.
+ onCheckedChange: (active) => {
+ if (!integration) {
+ if (active) onConfigure(true)
+ return undefined
+ }
+ return updateMutation.mutateAsync({ active }).then((saved) => saved.active)
+ },
+ }}
+ actionLabel={
+ integration
+ ? t('admin.integrations.configure_cta')
+ : canWrite
+ ? t('admin.integrations.connect_cta')
+ : t('admin.integrations.view_cta')
+ }
+ onAction={() => onConfigure()}
+ />
+ )
+}
+
+function paymentStatusLabels(t: (key: string) => string) {
+ return {
+ active: t('admin.integrations.status.active'),
+ inactive: t('admin.payment_methods.status.disabled'),
+ not_connected: t('admin.integrations.status.not_connected'),
+ }
+}
+
+function PaymentMethodCard({
+ paymentMethod,
+ onConfigure,
+}: {
+ paymentMethod: PaymentMethod
+ onConfigure: () => void
+}) {
+ const { t } = useTranslation()
+ const { permissions } = usePermissions()
+ const canWrite = permissions.can('update', Subject.PaymentMethod)
+ const updateMutation = useUpdatePaymentMethod(paymentMethod.id, { showValidationErrors: true })
+ const testMode = paymentMethod.preferences?.test_mode === true
+ const provider = paymentProviderLabel(paymentMethod.type)
return (
- <Card>
- <CardContent className="flex flex-col gap-3 p-4">
- <div className="flex items-center gap-3">
- <IntegrationLogo name={type.name} logoUrl={type.logo_url} />
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <span className="truncate font-medium text-sm">{type.name}</span>
- {integration ? (
- <Badge variant={integration.active ? 'default' : 'secondary'} className="w-fit">
- {integration.active
- ? t('admin.integrations.status.active')
- : t('admin.integrations.status.connected_inactive')}
- </Badge>
- ) : (
- <span className="text-muted-foreground text-xs">
- {t('admin.integrations.status.not_connected')}
- </span>
- )}
- </div>
- <Button size="sm" variant={integration ? 'outline' : 'default'} onClick={onConfigure}>
- {integration
- ? t('admin.integrations.configure_cta')
- : canWrite
- ? t('admin.integrations.connect_cta')
- : t('admin.integrations.view_cta')}
- </Button>
- </div>
- {typeDescription('integration', type.type, type.description) && (
- <p className="line-clamp-2 text-muted-foreground text-xs">
- {typeDescription('integration', type.type, type.description)}
- </p>
- )}
- </CardContent>
- </Card>
+ <IntegrationCard
+ name={paymentMethod.name}
+ logoUrl={paymentMethod.logo_url}
+ docsUrl={paymentMethod.docs_url}
+ docsLabel={t('admin.integrations.setup_guide')}
+ status={paymentMethod.active ? 'active' : 'inactive'}
+ statusLabels={paymentStatusLabels(t)}
+ description={
+ paymentMethod.description !== paymentMethod.name
+ ? (paymentMethod.description ?? undefined)
+ : undefined
+ }
+ tags={
+ <>
+ <GroupTag>{groupLabel(t, PAYMENTS_GROUP)}</GroupTag>
+ {provider !== paymentMethod.name && <Badge variant="outline">{provider}</Badge>}
+ {testMode && <Badge variant="warning">{t('admin.integrations.test_mode')}</Badge>}
+ {!paymentMethod.storefront_visible && (
+ <Badge variant="outline">{t('admin.payment_methods.storefront.admin_only')}</Badge>
+ )}
+ </>
+ }
+ toggle={{
+ checked: paymentMethod.active,
+ disabled: !canWrite,
+ label: t('admin.integrations.toggle_label', { name: paymentMethod.name }),
+ onCheckedChange: (active) =>
+ updateMutation.mutateAsync({ active }).then((saved) => saved.active),
+ }}
+ actionLabel={t('admin.integrations.configure_cta')}
+ onAction={onConfigure}
+ />
)
}
-// Gem-declared logo (hosted URL or data URI); the Avatar compound shows the
-// initial-letter fallback until the image loads, covering unset and
-// unreachable URLs alike — same pattern as the store switcher.
-function IntegrationLogo({ name, logoUrl }: { name: string; logoUrl: string | null }) {
+function PaymentProviderCard({ type, onSetUp }: { type: PaymentMethodType; onSetUp: () => void }) {
+ const { t } = useTranslation()
+
return (
- <Avatar className="size-9 shrink-0 rounded-md">
- {logoUrl && <AvatarImage src={logoUrl} className="object-contain" />}
- <AvatarFallback className="rounded-md">{name.charAt(0).toUpperCase()}</AvatarFallback>
- </Avatar>
+ <IntegrationCard
+ name={type.label}
+ logoUrl={type.logo_url}
+ docsUrl={type.docs_url}
+ docsLabel={t('admin.integrations.setup_guide')}
+ status="not_connected"
+ statusLabels={paymentStatusLabels(t)}
+ description={type.description ?? undefined}
+ tags={<GroupTag>{groupLabel(t, PAYMENTS_GROUP)}</GroupTag>}
+ // Nothing to activate until the provider is set up; the add sheet it
+ // opens starts with the method active.
+ toggle={{
+ checked: false,
+ label: t('admin.integrations.toggle_label', { name: type.label }),
+ onCheckedChange: (active) => {
+ if (active) onSetUp()
+ return undefined
+ },
+ }}
+ actionLabel={t('admin.integrations.connect_cta')}
+ onAction={onSetUp}
+ />
)
}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/payment-methods.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
index ea1ca3eda7..57f4d52b15 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
@@ -1,52 +1,23 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import type { PaymentMethod, PreferenceField } from '@spree/admin-sdk'
+import type { PaymentMethod } from '@spree/admin-sdk'
import {
adminClient,
Can,
- defaultPreferences,
- mapSpreeErrorsToForm,
ResourceTable,
resourceSearchSchema,
Subject,
usePermissions,
- useStore,
} from '@spree/dashboard-core'
-import {
- Button,
- RowActions,
- Sheet,
- SheetContent,
- SheetDescription,
- SheetFooter,
- SheetHeader,
- SheetTitle,
- useConfirm,
- useRowClickBridge,
-} from '@spree/dashboard-ui'
+import { Button, RowActions, useConfirm, useRowClickBridge } from '@spree/dashboard-ui'
import { PlusIcon } from '@spree/dashboard-ui/icons'
import { useQueryClient } from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import { useEffect, useMemo, useRef, useState } from 'react'
-import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
-import { PaymentMethodForm } from '../../../../components/spree/payment-method-editors/payment-method-form'
-import type { PaymentMethodFormValues } from '../../../../components/spree/payment-method-editors/types'
-import {
- useCreatePaymentMethod,
- useDeletePaymentMethod,
- usePaymentMethod,
- usePaymentMethodTypes,
- useUpdatePaymentMethod,
-} from '../../../../hooks/use-payment-methods'
import {
- PAYMENT_METHOD_BASE_DEFAULTS,
- PAYMENT_METHOD_CREATE_DEFAULTS,
- paymentMethodBaseFormSchema,
- paymentMethodCreateFormSchema,
- paymentMethodValuesToCreateParams,
- paymentMethodValuesToUpdateParams,
-} from '../../../../schemas/payment-method'
+ CreatePaymentMethodSheet,
+ EditPaymentMethodSheet,
+} from '../../../../components/spree/payment-method-editors/payment-method-sheets'
+import { useDeletePaymentMethod } from '../../../../hooks/use-payment-methods'
import '../../../../tables/payment-methods'
const paymentMethodsSearchSchema = resourceSearchSchema.extend({
@@ -145,233 +116,3 @@ function PaymentMethodsPage() {
</>
)
}
-
-function CreatePaymentMethodSheet({
- open,
- onOpenChange,
-}: {
- open: boolean
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const createMutation = useCreatePaymentMethod()
- const { data: typesResponse, isLoading: loadingTypes } = usePaymentMethodTypes()
- const providerTypes = useMemo(() => typesResponse?.data ?? [], [typesResponse])
- // Seed `currency`-typed preferences with the store default so the merchant
- // sees and submits a real value — `CurrencySelect` only displays the
- // fallback now (it no longer commits via onChange).
- const { defaultCurrency } = useStore()
-
- const form = useForm<PaymentMethodFormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(paymentMethodCreateFormSchema) as any,
- defaultValues: PAYMENT_METHOD_CREATE_DEFAULTS,
- })
-
- 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, { currency: defaultCurrency }))
- }
-
- async function onSubmit(values: PaymentMethodFormValues) {
- try {
- await createMutation.mutateAsync(paymentMethodValuesToCreateParams(values, preferences))
- form.reset(PAYMENT_METHOD_CREATE_DEFAULTS)
- setPreferences({})
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- return (
- <Sheet
- open={open}
- onOpenChange={(next) => {
- if (!next) {
- form.reset(PAYMENT_METHOD_CREATE_DEFAULTS)
- setPreferences({})
- }
- onOpenChange(next)
- }}
- >
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{t('admin.pages.settings.payment_methods.add_sheet_title')}</SheetTitle>
- <SheetDescription>{t('admin.payment_methods.create_description')}</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">
- {form.formState.errors.root?.message && (
- <p className="text-sm text-destructive" role="alert">
- {form.formState.errors.root.message}
- </p>
- )}
- <PaymentMethodForm
- mode="create"
- form={form}
- providerTypes={providerTypes}
- loadingTypes={loadingTypes}
- preferenceSchema={preferenceSchema}
- providerType={providerType}
- paymentMethod={null}
- preferences={preferences}
- onPreferencesChange={setPreferences}
- onProviderTypeChange={handleProviderTypeChange}
- />
- </div>
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={form.formState.isSubmitting}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={form.formState.isSubmitting}>
- {form.formState.isSubmitting
- ? t('admin.actions.creating')
- : t('admin.payment_methods.create_label')}
- </Button>
- </SheetFooter>
- </form>
- </SheetContent>
- </Sheet>
- )
-}
-
-function EditPaymentMethodSheet({
- id,
- open,
- onOpenChange,
-}: {
- id: string
- open: boolean
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const { data: paymentMethod, isLoading } = usePaymentMethod(id)
- const updateMutation = useUpdatePaymentMethod(id)
-
- const form = useForm<PaymentMethodFormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(paymentMethodBaseFormSchema) as any,
- defaultValues: PAYMENT_METHOD_BASE_DEFAULTS,
- })
- const [preferences, setPreferences] = useState<Record<string, unknown>>({})
- // Snapshot of the preferences last loaded from the server. Derive the
- // dirty state by comparing JSON shape — avoids a separate flag that
- // can drift out of sync with the actual values.
- const originalPreferencesRef = useRef<string>('{}')
- // Track the loaded record so we don't clobber in-flight edits when the
- // cache invalidates after a save.
- const loadedIdRef = useRef<string | undefined>(undefined)
-
- useEffect(() => {
- if (!paymentMethod || paymentMethod.id === loadedIdRef.current) return
- form.reset({
- name: paymentMethod.name,
- description: paymentMethod.description ?? '',
- storefront_visible: paymentMethod.storefront_visible ?? true,
- active: paymentMethod.active,
- capture_method: paymentMethod.capture_method ?? '',
- })
- const initialPreferences = (paymentMethod.preferences as Record<string, unknown>) ?? {}
- setPreferences(initialPreferences)
- originalPreferencesRef.current = JSON.stringify(initialPreferences)
- loadedIdRef.current = paymentMethod.id
- }, [paymentMethod, form])
-
- const preferencesDirty = useMemo(
- () => JSON.stringify(preferences) !== originalPreferencesRef.current,
- [preferences],
- )
-
- async function onSubmit(values: PaymentMethodFormValues) {
- const params = paymentMethodValuesToUpdateParams(values)
- if (preferencesDirty) params.preferences = preferences
- try {
- await updateMutation.mutateAsync(params)
- form.reset(values)
- originalPreferencesRef.current = JSON.stringify(preferences)
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- // 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}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>
- {paymentMethod?.name ?? t('admin.pages.settings.payment_methods.edit_sheet_title')}
- </SheetTitle>
- <SheetDescription>
- {providerLabel
- ? t('admin.payment_methods.provider_description', { provider: providerLabel })
- : t('admin.payment_methods.edit_description')}
- </SheetDescription>
- </SheetHeader>
- {isLoading ? (
- <div className="p-4 text-sm text-muted-foreground">{t('admin.common.loading')}</div>
- ) : (
- <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">
- {form.formState.errors.root?.message && (
- <p className="text-sm text-destructive" role="alert">
- {form.formState.errors.root.message}
- </p>
- )}
- <PaymentMethodForm
- mode="edit"
- form={form}
- preferenceSchema={paymentMethod?.preference_schema ?? []}
- providerType={providerType}
- paymentMethod={paymentMethod ?? null}
- preferences={preferences}
- onPreferencesChange={setPreferences}
- />
- </div>
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={form.formState.isSubmitting}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button
- type="submit"
- disabled={
- form.formState.isSubmitting || (!form.formState.isDirty && !preferencesDirty)
- }
- >
- {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </SheetFooter>
- </form>
- )}
- </SheetContent>
- </Sheet>
- )
-}
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.rb
index 26acf9d39a..85523b74cf 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
@@ -11,7 +11,9 @@ module Spree
position: :number,
metadata: 'Record<string, unknown>',
preferences: 'Record<string, unknown>',
- preference_schema: "Array<{ key: string; type: string; default: unknown; choices?: string[] }>"
+ preference_schema: "Array<{ key: string; type: string; default: unknown; choices?: string[] }>",
+ logo_url: [:string, nullable: true],
+ docs_url: [:string, nullable: true]
# Null capture_method means the method inherits from its store;
# resolved_capture_method is what actually applies, so the dashboard
@@ -22,6 +24,8 @@ module Spree
attribute :preferences, &:serialized_preferences
attribute :preference_schema, &:serialized_preference_schema
+ attribute(:logo_url) { |payment_method| payment_method.class.logo_url }
+ attribute(:docs_url) { |payment_method| payment_method.class.docs_url }
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/integrations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/integrations_controller_spec.rb
index 69358205e2..bc56ab90c8 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/integrations_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/integrations_controller_spec.rb
@@ -45,7 +45,7 @@ RSpec.describe Spree::Api::V3::Admin::IntegrationsController, type: :controller
end
describe 'gallery metadata' do
- it 'serves the class description and no logo by default' do
+ it 'serves the class description and no logo or setup guide by default' do
allow(TestIntegrations::Carrier).to receive(:description).and_return('Ships things')
get :types, as: :json
@@ -53,15 +53,20 @@ RSpec.describe Spree::Api::V3::Admin::IntegrationsController, type: :controller
entry = json_response['data'].find { |row| row['type'] == 'carrier' }
expect(entry['description']).to eq('Ships things')
expect(entry['logo_url']).to be_nil
+ expect(entry['docs_url']).to be_nil
end
- it 'serves the declared logo url untouched' do
- allow(TestIntegrations::Carrier).to receive(:logo_url).and_return('https://cdn.example.com/logo.svg')
+ it 'serves the declared logo and setup guide urls untouched' do
+ allow(TestIntegrations::Carrier).to receive_messages(
+ logo_url: 'https://cdn.example.com/logo.svg',
+ docs_url: 'https://docs.example.com/carrier'
+ )
get :types, as: :json
entry = json_response['data'].find { |row| row['type'] == 'carrier' }
expect(entry['logo_url']).to eq('https://cdn.example.com/logo.svg')
+ expect(entry['docs_url']).to eq('https://docs.example.com/carrier')
end
end
end
diff --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.rb
index 9469ab954c..d628564f0f 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
@@ -319,6 +319,19 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
expect(response.body).not_to include('SECRETKEY123')
end
+ it 'exposes the logo and setup guide a provider declares' do
+ allow(Spree::Gateway::Bogus).to receive_messages(
+ logo_url: 'https://example.com/bogus.png',
+ docs_url: 'https://example.com/docs/bogus'
+ )
+
+ get :types, as: :json
+
+ bogus = json_response['data'].find { |entry| entry['type'] == 'bogus' }
+ expect(bogus).to include('logo_url' => 'https://example.com/bogus.png',
+ 'docs_url' => 'https://example.com/docs/bogus')
+ end
+
context 'with provider gems that ship a top-level Gateway class' do
# Reproduces the duplicate-key bug from the admin SPA: two providers
# whose demodulized leaf is `"Gateway"` must still get unique `type`
diff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rb
index 8696b0213b..fa7664cb5b 100644
--- a/spree/core/app/models/concerns/spree/preference_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema.rb
@@ -216,6 +216,9 @@ module Spree
# their wire shape byte-identical. Pickers stop offering a
# superseded kind; existing rows still render and match.
entry[:superseded] = true if klass.respond_to?(:superseded?) && klass.superseded?
+ # Provider families (payment methods) add their gallery logo and
+ # setup guide; other families keep their wire shape unchanged.
+ entry.merge!(klass.provider_listing) if klass.respond_to?(:provider_listing)
entry
end.sort_by { |entry| entry[:label] }
end
diff --git a/spree/core/app/models/concerns/spree/provider_listing.rb b/spree/core/app/models/concerns/spree/provider_listing.rb
new file mode 100644
index 0000000000..04b0296de3
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/provider_listing.rb
@@ -0,0 +1,41 @@
+module Spree
+ # What a provider shows on its gallery card in the dashboard: a logo and a
+ # link to its setup guide. Shared by integrations and payment methods so a
+ # provider gem declares both the same way whichever family it extends.
+ #
+ # class SpreeStripe::Gateway < Spree::Gateway
+ # def self.logo_url = 'https://example.com/stripe.png'
+ # def self.docs_url = 'https://spreecommerce.org/docs/integrations/payments/stripe'
+ # end
+ module ProviderListing
+ extend ActiveSupport::Concern
+
+ class_methods do
+ # Logo shown on the gallery card: an absolute URL to publicly hosted
+ # brand assets, or a `data:` URI for gems that want to be self-contained
+ # (works air-gapped, no CSP domain to allowlist). Anything an `<img src>`
+ # accepts. Deliberately not an asset-pipeline path — provider gems must
+ # not force an asset pipeline onto headless API hosts. Hosted logos are a
+ # courtesy, not a guarantee: the dashboard falls back to a letter avatar
+ # when unset or unreachable.
+ #
+ # @return [String, nil]
+ def logo_url
+ nil
+ end
+
+ # Absolute URL of the provider's setup guide, linked from its gallery
+ # card. A third-party gem points at its own documentation.
+ #
+ # @return [String, nil]
+ def docs_url
+ nil
+ end
+
+ # @return [Hash] the listing attributes merged into a type-discovery entry
+ def provider_listing
+ { logo_url: logo_url, docs_url: docs_url }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/integration.rb b/spree/core/app/models/spree/integration.rb
index ad3cb0f559..5731e96834 100644
--- a/spree/core/app/models/spree/integration.rb
+++ b/spree/core/app/models/spree/integration.rb
@@ -10,6 +10,7 @@ module Spree
include Spree::SingleStoreResource
include Spree::PreferenceSchema
+ include Spree::ProviderListing
# Spree::Current.integrations snapshots the active set for the request;
# connecting or deactivating one mid-request (the activate-and-verify
@@ -64,19 +65,6 @@ module Spree
nil
end
- # Logo shown on the gallery card: an absolute URL to publicly hosted
- # brand assets, or a `data:` URI for gems that want to be self-contained
- # (works air-gapped, no CSP domain to allowlist). Anything an `<img src>`
- # accepts. Deliberately not an asset-pipeline path — integration gems
- # must not force an asset pipeline onto headless API hosts. Hosted logos
- # are a courtesy, not a guarantee: the dashboard falls back to a letter
- # avatar when unset or unreachable.
- #
- # @return [String, nil]
- def self.logo_url
- nil
- end
-
# One-line marketing description shown on the integration's gallery card.
# Localize by shipping a Rails translation instead (or additionally):
# `spree.integrations.<api_type>.description` wins over this fallback.
@@ -107,7 +95,7 @@ module Spree
name: klass.integration_name,
group: klass.integration_group,
description: klass.human_description,
- logo_url: klass.logo_url,
+ **klass.provider_listing,
preference_schema: klass.serialized_preference_schema
}
end.sort_by { |entry| entry[:name] }
diff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rb
index 7f0ac985ce..914db02dfb 100644
--- a/spree/core/app/models/spree/payment_method.rb
+++ b/spree/core/app/models/spree/payment_method.rb
@@ -14,6 +14,7 @@ module Spree
include Spree::HasCustomFields
include Spree::Metadata
include Spree::CaptureMethod
+ include Spree::ProviderListing
if defined?(Spree::Security::PaymentMethods)
include Spree::Security::PaymentMethods
end
diff --git a/spree/core/spec/models/spree/integration_spec.rb b/spree/core/spec/models/spree/integration_spec.rb
index 525a8cfb77..fac8e9a6f1 100644
--- a/spree/core/spec/models/spree/integration_spec.rb
+++ b/spree/core/spec/models/spree/integration_spec.rb
@@ -48,8 +48,9 @@ RSpec.describe Spree::Integration, type: :model do
before { stub_const('SpreeCarrier::Integration', described_klass) }
- it 'declares no logo or description by default' do
+ it 'declares no logo, setup guide or description by default' do
expect(described_class.logo_url).to be_nil
+ expect(described_class.docs_url).to be_nil
expect(described_class.description).to be_nil
end
diff --git a/spree/providers/easypost/app/models/spree_easypost/integration.rb b/spree/providers/easypost/app/models/spree_easypost/integration.rb
index a548c4a104..54b364bfb7 100644
--- a/spree/providers/easypost/app/models/spree_easypost/integration.rb
+++ b/spree/providers/easypost/app/models/spree_easypost/integration.rb
@@ -67,6 +67,10 @@ module SpreeEasyPost
'https://www.easypost.com/wp-content/uploads/2026/03/EasyPost-Logo.svg'
end
+ def self.docs_url
+ 'https://spreecommerce.org/docs/integrations/shipping/easypost'
+ end
+
# Fallback for hosts without the gem's translations; the localized
# description in config/locales wins.
def self.description
diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway.rb b/spree/providers/stripe/app/models/spree_stripe/gateway.rb
index 37ee21a7bf..c7a182611d 100644
--- a/spree/providers/stripe/app/models/spree_stripe/gateway.rb
+++ b/spree/providers/stripe/app/models/spree_stripe/gateway.rb
@@ -22,6 +22,14 @@ module SpreeStripe
validates :preferred_secret_key, :preferred_publishable_key, presence: true
validate :validate_secret_key, unless: -> { Rails.env.test? }, if: -> { preferred_secret_key.present? }
+ def self.logo_url
+ 'https://spreecommerce.org/docs/images/integrations/logos/stripe.png'
+ end
+
+ def self.docs_url
+ 'https://spreecommerce.org/docs/integrations/payments/stripe'
+ end
+
def provider_class
self.class
end