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 localized storefront SEO settings (#14997)

Damian Legawiec730c9daa414b
diff --git a/.changeset/storefront-seo-settings.md b/.changeset/storefront-seo-settings.md
new file mode 100644
index 0000000000..9f90f23551
--- /dev/null
+++ b/.changeset/storefront-seo-settings.md
@@ -0,0 +1,7 @@
+---
+"@spree/sdk": minor
+"@spree/admin-sdk": minor
+"@spree/dashboard": minor
+---
+
+Added localized storefront SEO settings. Merchants edit the store's SEO title and meta description on Store Settings and translate them for each supported language. The Store SDK reads them with `client.store.get()`, and the Admin SDK reaches the store's translations with `client.store.translations.get()`.
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index 756a166a9b..6d1e374946 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -30879,8 +30879,10 @@ paths:
application/json:
example:
id: store_UkLWZg9DAJ
- metadata: {}
name: Spree Test Store
+ seo_title:
+ meta_description: Sample store description.
+ metadata: {}
code: spree_1
default_currency: USD
default_locale: en
@@ -31249,8 +31251,10 @@ paths:
application/json:
example:
id: store_UkLWZg9DAJ
- metadata: {}
name: Renamed Store
+ seo_title:
+ meta_description: Sample store description.
+ metadata: {}
code: spree_1
default_currency: USD
default_locale: en
@@ -72945,10 +72949,16 @@ components:
properties:
id:
type: string
- metadata:
- type: object
name:
type: string
+ seo_title:
+ type: string
+ nullable: true
+ meta_description:
+ type: string
+ nullable: true
+ metadata:
+ type: object
code:
type: string
default_currency:
@@ -74122,8 +74132,10 @@ components:
nullable: true
required:
- id
- - metadata
- name
+ - seo_title
+ - meta_description
+ - metadata
- code
- default_currency
- default_locale
@@ -84217,6 +84229,16 @@ components:
name:
type: string
example: My Store
+ seo_title:
+ type: string
+ description: The storefront's default page title, in the store's default
+ language. Translate it through the translations endpoints.
+ nullable: true
+ meta_description:
+ type: string
+ description: The storefront's default meta description, in the store's default
+ language.
+ nullable: true
admin_locale:
type: string
example: en
diff --git a/docs/api-reference/store.yaml b/docs/api-reference/store.yaml
index aa3852fe2d..aa245b80af 100644
--- a/docs/api-reference/store.yaml
+++ b/docs/api-reference/store.yaml
@@ -10798,6 +10798,66 @@ paths:
message: record not found
schema:
"$ref": "#/components/schemas/ErrorResponse"
+ "/api/v3/store/store":
+ get:
+ summary: Get the current store
+ tags:
+ - Store
+ security:
+ - api_key: []
+ description: Returns the current store's name and default SEO metadata in the
+ requested locale. A field without a translation falls back to the store's
+ default locale.
+ x-codeSamples:
+ - lang: javascript
+ label: Spree SDK
+ source: |-
+ import { createClient } from '@spree/sdk'
+
+ const client = createClient({
+ baseUrl: 'https://your-store.com',
+ publishableKey: '<api-key>',
+ })
+
+ const store = await client.store.get()
+
+ const title = store.seo_title ?? store.name
+ const description = store.meta_description
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: x-spree-locale
+ in: header
+ required: false
+ description: Locale for translated values, e.g. `de`. Defaults to the store
+ locale.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: store found
+ content:
+ application/json:
+ example:
+ id: store_UkLWZg9DAJ
+ name: Spree Test Store
+ seo_title:
+ meta_description: Sample store description.
+ schema:
+ "$ref": "#/components/schemas/Store"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ example:
+ error:
+ code: invalid_token
+ message: Valid API key required
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
"/api/v3/store/wishlists":
get:
summary: List wishlists
@@ -13652,6 +13712,8 @@ tags:
description: Customer account, addresses, saved payment methods, and order history
- name: Markets
description: Markets, countries, currencies, and locales
+- name: Store
+ description: The current store's name and default SEO metadata
- name: Wishlists
description: Customer wishlists
- name: Newsletter Subscribers
@@ -23109,6 +23171,25 @@ components:
- display_amount_remaining
- currency
x-typelizer: true
+ Store:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ seo_title:
+ type: string
+ nullable: true
+ meta_description:
+ type: string
+ nullable: true
+ required:
+ - id
+ - name
+ - seo_title
+ - meta_description
+ x-typelizer: true
SupplierEvent:
type: object
properties:
diff --git a/docs/developer/core-concepts/stores.mdx b/docs/developer/core-concepts/stores.mdx
index f17d1c9b81..a7c41f56cb 100644
--- a/docs/developer/core-concepts/stores.mdx
+++ b/docs/developer/core-concepts/stores.mdx
@@ -72,6 +72,28 @@ curl 'https://api.mystore.com/api/v3/admin/store' \
This is an admin endpoint, so it requires a secret API key (`sk_xxx`) or a Bearer JWT — a publishable key cannot reach it.
+### Storefront SEO
+
+A storefront reads the store's public name and default SEO metadata — `seo_title` and `meta_description` — from the Store API, in the shopper's language. Use them for the home page title and description. A field with no translation for the requested locale returns the default-language value.
+
+<Tabs>
+ <Tab title="Store SDK">
+ ```typescript
+ const store = await client.store.get({ locale: 'de' })
+ // { id: "store_k5nR8xLq", name: "My Store", seo_title: "Frischer Kaffee", meta_description: "…" }
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl 'https://api.mystore.com/api/v3/store/store' \
+ -H 'X-Spree-API-Key: pk_xxx' \
+ -H 'X-Spree-Locale: de'
+ ```
+ </Tab>
+</Tabs>
+
+Merchants edit the default-language values on **Settings → Store** in the dashboard and translate them with **Manage translations** on the same page. See [Translations](/developer/core-concepts/translations).
+
## Channels vs. Markets
Two different ways to split a store, often confused:
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index a62e249913..4502d01e11 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -1252,6 +1252,8 @@ export class AdminClient {
this.request<{ data: StoreDataSources }>('GET', '/store/data_sources', options).then(
(r) => r.data,
),
+
+ translations: this.parentScopedTranslations('/stores'),
}
/** The locales a merchant can translate content into for the current store. */
diff --git a/packages/admin-sdk/src/types/generated/Store.ts b/packages/admin-sdk/src/types/generated/Store.ts
index 5cc9b6311e..c8ddac5b99 100644
--- a/packages/admin-sdk/src/types/generated/Store.ts
+++ b/packages/admin-sdk/src/types/generated/Store.ts
@@ -1,12 +1,14 @@
-// Typelizer digest 2dcf057b9f14ca9e573e79af02ce726b
+// Typelizer digest bbb738f00ecbe61bcfd8eb1b1d88f384
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {SetupTask, CurrencyCode, LocaleCode, WeightUnit, UnitSystem, StorefrontAccess, CaptureMethod, ProviderFailurePolicy, PayoutScheduleInterval, DocumentNumberFormat, EmailFont} from '@/types'
interface Store {
id: string;
- metadata: Record<string, unknown>;
name: string;
+ seo_title: string | null;
+ meta_description: string | null;
+ metadata: Record<string, unknown>;
code: string;
default_currency: CurrencyCode;
default_locale: LocaleCode;
diff --git a/packages/admin-sdk/src/types/params/StoreUpdateParams.ts b/packages/admin-sdk/src/types/params/StoreUpdateParams.ts
index 185a538b81..298f248a0f 100644
--- a/packages/admin-sdk/src/types/params/StoreUpdateParams.ts
+++ b/packages/admin-sdk/src/types/params/StoreUpdateParams.ts
@@ -4,6 +4,13 @@ import type { WeightUnit } from '../generated'
export type StoreUpdateParams = {
name?: string
+ /**
+ * The storefront's default page title, in the store's default language. Translate it through the
+ * translations endpoints.
+ */
+ seo_title?: string | null
+ /** The storefront's default meta description, in the store's default language. */
+ meta_description?: string | null
admin_locale?: string
timezone?: string
weight_unit?: WeightUnit
diff --git a/packages/admin-sdk/src/zod/generated/Store.ts b/packages/admin-sdk/src/zod/generated/Store.ts
index 371813fa6b..6bd68ee2e8 100644
--- a/packages/admin-sdk/src/zod/generated/Store.ts
+++ b/packages/admin-sdk/src/zod/generated/Store.ts
@@ -4,8 +4,10 @@ import { SetupTaskSchema } from './SetupTask';
export const StoreSchema = z.object({
id: z.string(),
- metadata: z.record(z.string(), z.unknown()),
name: z.string(),
+ seo_title: z.string().nullable(),
+ meta_description: z.string().nullable(),
+ metadata: z.record(z.string(), z.unknown()),
code: z.string(),
default_currency: z.string(),
default_locale: z.string(),
diff --git a/packages/dashboard/e2e/store-settings.spec.ts b/packages/dashboard/e2e/store-settings.spec.ts
index c5f772b8e6..c379fa4782 100644
--- a/packages/dashboard/e2e/store-settings.spec.ts
+++ b/packages/dashboard/e2e/store-settings.spec.ts
@@ -205,6 +205,66 @@ test.describe('store settings — general', () => {
await expect(save).toBeDisabled({ timeout: 15_000 })
})
+ // The e2e store supports `de` through its Europe market, so the
+ // translations editor offers it as a target language.
+ test('saves the SEO title and description, and translates them', async ({ page }) => {
+ const creds = await login(page)
+ await page.goto(STORE_PATH(creds.store_id))
+ const seoTitle = page.locator('#store-seo-title')
+ const metaDescription = page.locator('#store-meta-description')
+ await expect(seoTitle).toBeVisible({ timeout: 15_000 })
+
+ const suffix = Date.now()
+ const title = `E2E Coffee ${suffix}`
+ await seoTitle.fill(title)
+ await metaDescription.fill('Freshly roasted coffee')
+ const save = page.getByRole('button', { name: /^save$/i })
+ await save.click()
+ await expect(save).toBeDisabled({ timeout: 15_000 })
+
+ await page.reload()
+ await expect(seoTitle).toHaveValue(title, { timeout: 15_000 })
+ await expect(metaDescription).toHaveValue('Freshly roasted coffee')
+
+ await page.getByRole('button', { name: /manage translations/i }).click()
+ const dialog = page.getByRole('dialog')
+ await expect(dialog.getByTestId('source-seo_title')).toContainText(title, { timeout: 15_000 })
+ await expect(dialog.getByLabel('name de')).toHaveCount(0)
+ const translated = `E2E Kaffee ${suffix}`
+ await dialog.getByLabel('seo_title de').fill(translated)
+ await dialog.getByRole('button', { name: /^save translations$/i }).click()
+ await expect(page.getByText(/translations saved/i)).toBeVisible({ timeout: 15_000 })
+
+ await page.getByRole('button', { name: /^close$/i }).click()
+ await page.getByRole('button', { name: /manage translations/i }).click()
+ await expect(page.getByRole('dialog').getByLabel('seo_title de')).toHaveValue(translated, {
+ timeout: 15_000,
+ })
+ await page.getByRole('button', { name: /^close$/i }).click()
+
+ // Delete the translation so later specs in this shard start without it.
+ const cleared = await page.request.post('/api/v3/admin/translations/batch', {
+ headers: { 'X-Spree-Store-Id': creds.store_id, Authorization: `Bearer ${creds.accessToken}` },
+ data: {
+ translations: [
+ {
+ resource_type: 'store',
+ resource_id: creds.store_id,
+ values: { de: { seo_title: null } },
+ },
+ ],
+ },
+ })
+ if (!cleared.ok()) {
+ throw new Error(`Failed to delete translation: ${cleared.status()} ${await cleared.text()}`)
+ }
+
+ await seoTitle.fill('')
+ await metaDescription.fill('')
+ await save.click()
+ await expect(save).toBeDisabled({ timeout: 15_000 })
+ })
+
// A store with no storefront of its own reads back no storefront URL: the
// dashboard neither offers to "View store" nor prefills the connect form
// with an address the merchant never entered.
diff --git a/packages/dashboard/src/components/spree/translations/resource-translations-card.tsx b/packages/dashboard/src/components/spree/translations/resource-translations-card.tsx
index 897e624e45..8102a881a1 100644
--- a/packages/dashboard/src/components/spree/translations/resource-translations-card.tsx
+++ b/packages/dashboard/src/components/spree/translations/resource-translations-card.tsx
@@ -13,6 +13,8 @@ interface ResourceTranslationsCardProps {
resourceType: TranslatableResourceType
/** Prefixed id of the resource being translated. */
resourceId: string
+ /** Limits the editor and the coverage summary to these field keys. */
+ fields?: readonly string[]
}
/**
@@ -25,15 +27,18 @@ interface ResourceTranslationsCardProps {
export function ResourceTranslationsCard({
resourceType,
resourceId,
+ fields,
}: ResourceTranslationsCardProps) {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const { data } = useResourceTranslations(resourceType, resourceId)
const targetLocales = data ? data.supported_locales.filter((l) => l !== data.default_locale) : []
- const translatedCount = targetLocales.filter(
- (l) => (data?.translations[l]?.translated_field_count ?? 0) > 0,
- ).length
+ const translatedCount = targetLocales.filter((l) => {
+ const translated = data?.translations[l]
+ if (!fields) return (translated?.translated_field_count ?? 0) > 0
+ return fields.some((field) => !!translated?.[field])
+ }).length
return (
<Card>
@@ -66,6 +71,7 @@ export function ResourceTranslationsCard({
onOpenChange={setOpen}
resourceType={resourceType}
resourceId={resourceId}
+ fields={fields}
/>
</Card>
)
diff --git a/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx b/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx
index cbc54da47e..9df705a387 100644
--- a/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx
+++ b/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx
@@ -74,6 +74,8 @@ interface ResourceTranslationsDialogProps {
resourceType: TranslatableResourceType
/** Prefixed id of the resource being translated. */
resourceId: string
+ /** Limits the resource's own rows to these field keys; omit to edit every field. */
+ fields?: readonly string[]
}
/** Edits keyed by `${resourceId}::${locale}::${field}` → value. */
@@ -95,13 +97,14 @@ export function ResourceTranslationsDialog({
onOpenChange,
resourceType,
resourceId,
+ fields,
}: ResourceTranslationsDialogProps) {
const { t } = useTranslation()
const confirm = useConfirm()
const { data, isLoading, isError, refetch } = useResourceTranslations(resourceType, resourceId)
const invalidateTranslations = useInvalidateTranslations()
- const rows = useMemo(() => (data ? flattenTree(data) : []), [data])
+ const rows = useMemo(() => (data ? flattenTree(data, fields) : []), [data, fields])
const targetLocales = useMemo(
() => (data ? data.supported_locales.filter((l) => l !== data.default_locale) : []),
[data],
@@ -392,7 +395,7 @@ function TranslationGrid({
/** Flattens the matrix tree (root + nested children) into ordered rows.
* A child's left-column label is its own source value (e.g. "Small"), so the
* grid reads as a hierarchy; the root's rows use the field i18n labels. */
-function flattenTree(data: ResourceTranslations): TranslationRow[] {
+function flattenTree(data: ResourceTranslations, fields?: readonly string[]): TranslationRow[] {
const rows: TranslationRow[] = []
const pushNode = (node: ResourceTranslations | ResourceTranslationsNode, indent: number) => {
@@ -400,7 +403,8 @@ function flattenTree(data: ResourceTranslations): TranslationRow[] {
resourceType: node.resource_type,
resourceId: node.resource_id,
indent,
- fields: node.fields,
+ fields:
+ indent === 0 && fields ? node.fields.filter((f) => fields.includes(f.key)) : node.fields,
translations: node.translations,
// Children typically have a single field; label the row by its source so
// the hierarchy reads naturally ("Size" → "Small", "Medium").
diff --git a/packages/dashboard/src/hooks/use-store-settings.ts b/packages/dashboard/src/hooks/use-store-settings.ts
index 11291e19e1..a40563a87b 100644
--- a/packages/dashboard/src/hooks/use-store-settings.ts
+++ b/packages/dashboard/src/hooks/use-store-settings.ts
@@ -6,6 +6,7 @@ import {
useResourceMutation,
} from '@spree/dashboard-core'
import { useQuery } from '@tanstack/react-query'
+import { TRANSLATIONS_QUERY_RESOURCE } from './use-translations'
// Reads the same cache entry `<StoreProvider>` maintains — settings pages and
// the provider (nav badge, pickers, Getting Started) always agree.
@@ -47,7 +48,7 @@ export function usePayoutProviders() {
export function useUpdateStoreSettings() {
return useResourceMutation<unknown, Error, StoreUpdateParams>({
mutationFn: (params) => adminClient.store.update(params),
- invalidate: [[STORE_QUERY_RESOURCE]],
+ invalidate: [[STORE_QUERY_RESOURCE], [TRANSLATIONS_QUERY_RESOURCE, 'store']],
successMessage: false,
errorMessage: false,
})
diff --git a/packages/dashboard/src/hooks/use-translations.ts b/packages/dashboard/src/hooks/use-translations.ts
index 5d4f9da512..2de307e07d 100644
--- a/packages/dashboard/src/hooks/use-translations.ts
+++ b/packages/dashboard/src/hooks/use-translations.ts
@@ -34,6 +34,7 @@ const TRANSLATIONS_ACCESSORS = {
category: adminClient.categories.translations,
collection: adminClient.collections.translations,
option_type: adminClient.optionTypes.translations,
+ store: adminClient.store.translations,
} as const
export type TranslatableResourceType = keyof typeof TRANSLATIONS_ACCESSORS
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index be20604ef0..e1ffec3379 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2388,6 +2388,14 @@
"email_font": {
"label": "الخط",
"help": "تستخدم تطبيقات البريد التي لا يمكنها تحميله خطًا مشابهًا."
+ },
+ "seo_title": {
+ "label": "عنوان تحسين محركات البحث",
+ "help": "العنوان الذي تعرضه محركات البحث وعلامات تبويب المتصفح للصفحة الرئيسية لمتجرك."
+ },
+ "meta_description": {
+ "label": "الوصف التعريفي",
+ "help": "ملخص قصير تعرضه محركات البحث أسفل العنوان."
}
},
"store_credit": {
@@ -5923,6 +5931,10 @@
"kg": "كيلوغرام (كجم)",
"lb": "جنيه (رطل)",
"oz": "أوقية (أوقية)"
+ },
+ "seo": {
+ "title": "الظهور في محركات البحث",
+ "description": "العنوان والوصف الافتراضيان لمتجرك. ترجمهما إلى كل لغة يدعمها متجرك."
}
},
"table_descriptions": {
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index b1eb4f9da4..b3119ac9a5 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2370,6 +2370,14 @@
"email_font": {
"label": "Schrift",
"help": "E-Mail-Programme, die sie nicht laden können, verwenden eine ähnliche Schrift."
+ },
+ "seo_title": {
+ "label": "SEO-Titel",
+ "help": "Der Titel, den Suchmaschinen und Browser-Tabs für die Startseite Ihres Shops anzeigen."
+ },
+ "meta_description": {
+ "label": "Meta-Beschreibung",
+ "help": "Eine kurze Zusammenfassung, die Suchmaschinen unter dem Titel anzeigen."
}
},
"store_credit": {
@@ -5882,6 +5890,10 @@
"kg": "Kilogramm (kg)",
"lb": "Pfund (lb)",
"oz": "Unze (oz)"
+ },
+ "seo": {
+ "title": "Suchmaschinen-Eintrag",
+ "description": "Standardtitel und -beschreibung Ihres Shops. Übersetzen Sie sie für jede Sprache, die Ihr Shop unterstützt."
}
},
"table_descriptions": {
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 129c8a9156..a79e035382 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2370,6 +2370,14 @@
"email_font": {
"label": "Font",
"help": "Email apps that can't load it fall back to a similar font."
+ },
+ "seo_title": {
+ "label": "SEO title",
+ "help": "The title search engines and browser tabs show for your storefront's home page."
+ },
+ "meta_description": {
+ "label": "Meta description",
+ "help": "A short summary search engines show under the title."
}
},
"store_credit": {
@@ -5882,6 +5890,10 @@
"kg": "Kilogram (kg)",
"lb": "Pound (lb)",
"oz": "Ounce (oz)"
+ },
+ "seo": {
+ "title": "Search engine listing",
+ "description": "The default title and description of your storefront. Translate them for each language your store supports."
}
},
"table_descriptions": {
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index b509f8cff5..96fb36b816 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -2394,6 +2394,14 @@
"email_font": {
"label": "Fuente",
"help": "Las aplicaciones de correo que no puedan cargarla usarán una fuente similar."
+ },
+ "seo_title": {
+ "label": "Título SEO",
+ "help": "El título que muestran los buscadores y las pestañas del navegador para la página de inicio de tu tienda."
+ },
+ "meta_description": {
+ "label": "Meta descripción",
+ "help": "Un breve resumen que los buscadores muestran bajo el título."
}
},
"store_credit": {
@@ -6249,6 +6257,10 @@
"kg": "Kilogramo (kg)",
"lb": "Libra (lb)",
"oz": "Onza (oz)"
+ },
+ "seo": {
+ "title": "Ficha en buscadores",
+ "description": "El título y la descripción predeterminados de tu tienda. Tradúcelos a cada idioma que admite tu tienda."
}
},
"company_invitations": {
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 0052231db6..c000b34187 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2370,6 +2370,14 @@
"email_font": {
"label": "Police",
"help": "Les applications de messagerie qui ne peuvent pas la charger utilisent une police similaire."
+ },
+ "seo_title": {
+ "label": "Titre SEO",
+ "help": "Le titre affiché par les moteurs de recherche et les onglets du navigateur pour la page d’accueil de votre boutique."
+ },
+ "meta_description": {
+ "label": "Méta-description",
+ "help": "Un court résumé que les moteurs de recherche affichent sous le titre."
}
},
"store_credit": {
@@ -5883,6 +5891,10 @@
"kg": "Kilogramme (kg)",
"lb": "Livre (lb)",
"oz": "Once (oz)"
+ },
+ "seo": {
+ "title": "Référencement",
+ "description": "Le titre et la description par défaut de votre boutique. Traduisez-les pour chaque langue prise en charge par votre boutique."
}
},
"table_descriptions": {
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 6ce6c22916..265ce42cc0 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -2388,6 +2388,14 @@
"email_font": {
"label": "Czcionka",
"help": "Programy pocztowe, które nie mogą jej wczytać, użyją podobnej czcionki."
+ },
+ "seo_title": {
+ "label": "Tytuł SEO",
+ "help": "Tytuł, który wyszukiwarki i karty przeglądarki pokazują dla strony głównej Twojego sklepu."
+ },
+ "meta_description": {
+ "label": "Opis meta",
+ "help": "Krótkie podsumowanie, które wyszukiwarki pokazują pod tytułem."
}
},
"store_credit": {
@@ -5950,6 +5958,10 @@
"kg": "Kilogram (kg)",
"lb": "Funt (lb)",
"oz": "Uncja (oz)"
+ },
+ "seo": {
+ "title": "Wynik w wyszukiwarce",
+ "description": "Domyślny tytuł i opis Twojego sklepu. Przetłumacz je na każdy język obsługiwany przez sklep."
}
},
"table_descriptions": {
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index adb685707e..da34e8f455 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2365,6 +2365,14 @@
"email_font": {
"label": "字体",
"help": "无法加载该字体的邮件应用会使用相近的字体。"
+ },
+ "seo_title": {
+ "label": "SEO 标题",
+ "help": "搜索引擎和浏览器标签页为您店铺首页显示的标题。"
+ },
+ "meta_description": {
+ "label": "元描述",
+ "help": "搜索引擎在标题下方显示的简短摘要。"
}
},
"store_credit": {
@@ -5869,6 +5877,10 @@
"kg": "千克 (kg)",
"lb": "磅 (lb)",
"oz": "盎司 (oz)"
+ },
+ "seo": {
+ "title": "搜索引擎展示",
+ "description": "店铺的默认标题和描述。请为店铺支持的每种语言进行翻译。"
}
},
"table_descriptions": {
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/translations.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/translations.tsx
index 11a2f85a89..cdd8733dbe 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/translations.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/translations.tsx
@@ -82,9 +82,15 @@ function TranslationsPage() {
// A type needs both a dedicated read route and an SDK accessor before the
// editor can open it — the registry reports the first, the type guard the
// second. Offering a type without an accessor would open a dialog that
- // throws when it tries to fetch.
+ // throws when it tries to fetch. The store's own text is translated on
+ // Store Settings, next to the fields it translates.
const resourceOptions = (resources ?? [])
- .filter((resource) => resource.readable && isTranslatableResourceType(resource.resource_type))
+ .filter(
+ (resource) =>
+ resource.readable &&
+ resource.resource_type !== 'store' &&
+ isTranslatableResourceType(resource.resource_type),
+ )
.map((resource) => ({
value: resource.resource_type,
label: t(`admin.pages.translations.resource_types.${resource.resource_type}`, {
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
index 0ba1cd4620..476c7a1f8d 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
@@ -47,6 +47,7 @@ import {
SelectValue,
Skeleton,
Switch,
+ Textarea,
toastManager,
useFormSubmitShortcut,
} from '@spree/dashboard-ui'
@@ -66,6 +67,7 @@ import {
DraftCustomFieldsCard,
useCustomFieldsDraft,
} from '../../../../components/spree/custom-fields/custom-fields-inline'
+import { ResourceTranslationsCard } from '../../../../components/spree/translations/resource-translations-card'
import {
useStoreDataSources,
useStoreSettings,
@@ -82,6 +84,8 @@ export const Route = createFileRoute('/_authenticated/$storeId/settings/store')(
component: StoreSettingsPage,
})
+const SEO_TRANSLATABLE_FIELDS = ['seo_title', 'meta_description'] as const
+
const PRICING_PROVIDER_DOCS_URL = 'https://spreecommerce.org/docs/developer/providers/pim'
const INVENTORY_PROVIDER_DOCS_URL = 'https://spreecommerce.org/docs/developer/providers/erp'
@@ -111,6 +115,8 @@ const TIMEZONES: string[] = (() => {
function storeToFormValues(store: Store): StoreSettingsFormValues {
return {
name: store.name,
+ seo_title: store.seo_title ?? '',
+ meta_description: store.meta_description ?? '',
admin_locale: store.admin_locale ?? '',
timezone: store.timezone,
unit_system: (store.unit_system as UnitSystem) ?? 'metric',
@@ -245,6 +251,8 @@ function StoreSettingsForm({ store }: { store: Store }) {
if (storeDirty) {
await updateMutation.mutateAsync({
name: values.name,
+ seo_title: values.seo_title || null,
+ meta_description: values.meta_description || null,
admin_locale: values.admin_locale || undefined,
timezone: values.timezone,
unit_system: values.unit_system,
@@ -447,6 +455,49 @@ function StoreSettingsForm({ store }: { store: Store }) {
</CardContent>
</Card>
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.store.seo.title')}</CardTitle>
+ <CardDescription>{t('admin.store.seo.description')}</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="store-seo-title">
+ {t('admin.fields.store.seo_title.label')}
+ </FieldLabel>
+ <Input
+ id="store-seo-title"
+ aria-invalid={!!errors.seo_title || undefined}
+ {...form.register('seo_title')}
+ />
+ <FieldDescription>{t('admin.fields.store.seo_title.help')}</FieldDescription>
+ <FieldError errors={[errors.seo_title]} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="store-meta-description">
+ {t('admin.fields.store.meta_description.label')}
+ </FieldLabel>
+ <Textarea
+ id="store-meta-description"
+ rows={3}
+ aria-invalid={!!errors.meta_description || undefined}
+ {...form.register('meta_description')}
+ />
+ <FieldDescription>
+ {t('admin.fields.store.meta_description.help')}
+ </FieldDescription>
+ <FieldError errors={[errors.meta_description]} />
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+ <ResourceTranslationsCard
+ resourceType="store"
+ resourceId={store.id}
+ fields={SEO_TRANSLATABLE_FIELDS}
+ />
+
<Card>
<CardHeader>
<CardTitle>{t('admin.pages.settings.store.tab_standards')}</CardTitle>
diff --git a/packages/dashboard/src/schemas/store.ts b/packages/dashboard/src/schemas/store.ts
index 4e9e981ac2..66798cb0d7 100644
--- a/packages/dashboard/src/schemas/store.ts
+++ b/packages/dashboard/src/schemas/store.ts
@@ -18,6 +18,8 @@ export const INTERNAL_PROVIDER_KEY = 'internal'
export const storeSettingsFormSchema = z.object({
name: z.string().min(1, { error: requiredMessage('store.name') }),
+ seo_title: z.string(),
+ meta_description: z.string(),
admin_locale: z.string().nullable().optional(),
timezone: z.string().min(1, { error: requiredMessage('store.timezone') }),
unit_system: z.enum(UNIT_SYSTEMS),
diff --git a/packages/sdk/examples/store/get.ts b/packages/sdk/examples/store/get.ts
new file mode 100644
index 0000000000..296abe142a
--- /dev/null
+++ b/packages/sdk/examples/store/get.ts
@@ -0,0 +1,17 @@
+import { createClient } from '@spree/sdk'
+
+const client = createClient({
+ baseUrl: 'https://your-store.com',
+ publishableKey: '<api-key>',
+ locale: 'de',
+})
+
+// region:example
+const store = await client.store.get()
+
+const title = store.seo_title ?? store.name
+const description = store.meta_description
+
+// endregion:example
+
+export { description, store, title }
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index c9a2c8779d..14530992e6 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -78,6 +78,7 @@ import type {
ReturnSort,
Seller,
StockLocation,
+ Store,
StoreCredit,
UpdateCartParams,
UpdateCompanyParams,
@@ -388,6 +389,16 @@ export class StoreClient {
this.request<Channel>('GET', '/channel', options),
}
+ readonly store = {
+ /**
+ * Get the current store's name and default SEO metadata (`seo_title`,
+ * `meta_description`) in the request locale. A field without a
+ * translation falls back to the store's default locale.
+ */
+ get: (options?: RequestOptions): Promise<Store> =>
+ this.request<Store>('GET', '/store', options),
+ }
+
// ============================================
// Policies
// ============================================
diff --git a/packages/sdk/src/types/generated/Store.ts b/packages/sdk/src/types/generated/Store.ts
new file mode 100644
index 0000000000..63a08d17ad
--- /dev/null
+++ b/packages/sdk/src/types/generated/Store.ts
@@ -0,0 +1,12 @@
+// Typelizer digest 7afed168c91e23e7b0b4546f3eb9c25e
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface Store {
+ id: string;
+ name: string;
+ seo_title: string | null;
+ meta_description: string | null;
+}
+
+export default Store;
diff --git a/packages/sdk/src/types/generated/index.ts b/packages/sdk/src/types/generated/index.ts
index ddc49d1106..d7510a162f 100644
--- a/packages/sdk/src/types/generated/index.ts
+++ b/packages/sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest cad37b1a1c0f234fa29aacb42d37ceb6
+// Typelizer digest 9a0af50815b4891ee1774e8d6ff03117
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { AddressOwnerType, ClaimResolution, ClaimStatus, CollectionSortOrder, CompanyInvitationStatus, CompanyKind, CountryCode, CurrencyCode, DataRequestKind, DataRequestStatus, DeliveryStatus, DeliveryZoneMemberType, DimensionUnit, DiscountKind, ExchangeStatus, FeeKind, FileUploadVisibility, FulfillmentStatus, FulfillmentType, GiftCardStatus, ImportRowStatus, ImportStatus, InvitationStatus, LocaleCode, MediaType, OptionTypeKind, OrderFulfillmentStatus, OrderPaymentStatus, PaymentSessionStatus, PaymentSetupSessionStatus, PaymentSourceType, PaymentStatus, ProductSubmissionStatus, PurchaseUnit, ReturnStatus, ShippingLabelOwnerType, ShippingLabelStatus, StockAvailability, StockMovementKind, StockReceiptReceivableType, WeightUnit } from './Enums'
@@ -97,6 +97,7 @@ export type { default as StockReservation } from './StockReservation'
export type { default as StockTransfer } from './StockTransfer'
export type { default as StoreCreditEvent } from './StoreCreditEvent'
export type { default as StoreCredit } from './StoreCredit'
+export type { default as Store } from './Store'
export type { default as SupplierEvent } from './SupplierEvent'
export type { default as TaxIdentifier } from './TaxIdentifier'
export type { default as TaxLine } from './TaxLine'
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index 558ddd8f30..a78aaa20c2 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -82,6 +82,7 @@ export type {
Seller,
State,
StockLocation,
+ Store,
StoreCredit,
TaxLine,
Variant,
diff --git a/packages/sdk/src/zod/generated/Store.ts b/packages/sdk/src/zod/generated/Store.ts
new file mode 100644
index 0000000000..e9ec0a2333
--- /dev/null
+++ b/packages/sdk/src/zod/generated/Store.ts
@@ -0,0 +1,11 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+
+export const StoreSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ seo_title: z.string().nullable(),
+ meta_description: z.string().nullable(),
+});
+
+export type Store = z.infer<typeof StoreSchema>;
diff --git a/packages/sdk/src/zod/generated/index.ts b/packages/sdk/src/zod/generated/index.ts
index abfa0127a1..39d78b8f90 100644
--- a/packages/sdk/src/zod/generated/index.ts
+++ b/packages/sdk/src/zod/generated/index.ts
@@ -92,6 +92,7 @@ export { StockMovementSchema, type StockMovement } from './StockMovement';
export { StockReceiptEventSchema, type StockReceiptEvent } from './StockReceiptEvent';
export { StockReservationSchema, type StockReservation } from './StockReservation';
export { StockTransferSchema, type StockTransfer } from './StockTransfer';
+export { StoreSchema, type Store } from './Store';
export { StoreCreditSchema, type StoreCredit } from './StoreCredit';
export { StoreCreditEventSchema, type StoreCreditEvent } from './StoreCreditEvent';
export { SupplierEventSchema, type SupplierEvent } from './SupplierEvent';
diff --git a/packages/sdk/tests/mocks/handlers.ts b/packages/sdk/tests/mocks/handlers.ts
index 36c5a8d755..aee9c02244 100644
--- a/packages/sdk/tests/mocks/handlers.ts
+++ b/packages/sdk/tests/mocks/handlers.ts
@@ -615,6 +615,17 @@ export const handlers = [
HttpResponse.json({ token: 'new-jwt-token', user: fixtures.user }),
),
+ // Store — answers in the requested locale so client locale wiring is testable
+ http.get(`${API_PREFIX}/store`, ({ request }) => {
+ const german = request.headers.get('X-Spree-Locale') === 'de'
+ return HttpResponse.json({
+ id: 'store_1',
+ name: 'Coffee Shop',
+ seo_title: german ? 'Kaffeeladen' : 'Coffee Shop',
+ meta_description: german ? null : 'Freshly roasted coffee',
+ })
+ }),
+
// Channel — echoes the X-Spree-Channel header so client channel wiring is testable
http.get(`${API_PREFIX}/channel`, ({ request }) => {
if (request.headers.get('X-Spree-Channel') === 'wholesale') {
diff --git a/packages/sdk/tests/store.test.ts b/packages/sdk/tests/store.test.ts
new file mode 100644
index 0000000000..0634ac3087
--- /dev/null
+++ b/packages/sdk/tests/store.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { createClient } from '../src'
+import { createTestClient, TEST_API_KEY, TEST_BASE_URL } from './helpers'
+
+describe('store', () => {
+ it('gets the current store with its SEO metadata', async () => {
+ const client = createTestClient()
+
+ const store = await client.store.get()
+
+ expect(store.name).toBe('Coffee Shop')
+ expect(store.seo_title).toBe('Coffee Shop')
+ expect(store.meta_description).toBe('Freshly roasted coffee')
+ })
+
+ it('requests the configured locale', async () => {
+ const client = createClient({
+ baseUrl: TEST_BASE_URL,
+ publishableKey: TEST_API_KEY,
+ locale: 'de',
+ })
+
+ const store = await client.store.get()
+
+ expect(store.seo_title).toBe('Kaffeeladen')
+ })
+})
diff --git a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
index e8a8fd9d7e..365a33fdc4 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
@@ -7,6 +7,12 @@ module Spree
request_params :store do |body|
body.attribute :name, :string, example: 'My Store'
+ body.attribute :seo_title, :string,
+ nullable: true,
+ description: "The storefront's default page title, in the store's default language. Translate it through the translations endpoints."
+ body.attribute :meta_description, :string,
+ nullable: true,
+ description: "The storefront's default meta description, in the store's default language."
body.attribute :admin_locale, :string, example: 'en'
body.attribute :timezone, :string, example: 'Europe/Berlin'
body.attribute :weight_unit, :weight_unit
@@ -143,17 +149,19 @@ module Spree
# GET /api/v3/admin/store
def show
authorize! :show, current_store
- render json: serialize_store
+ render json: in_default_locale { serialize_store }
end
# PATCH /api/v3/admin/store
def update
authorize! :update, current_store
- if current_store.update(permitted_params)
- render json: serialize_store
- else
- render_validation_error(current_store.errors)
+ in_default_locale do
+ if current_store.update(permitted_params)
+ render json: serialize_store
+ else
+ render_validation_error(current_store.errors)
+ end
end
end
@@ -177,6 +185,13 @@ module Spree
private
+ # Settings hold the store's default-language values, whatever locale
+ # the request resolved to. Other languages are written through the
+ # translations endpoints.
+ def in_default_locale(&)
+ Mobility.with_locale(current_store.default_locale, &)
+ end
+
def describe(provider_classes)
provider_classes.map do |provider_class|
{
diff --git a/spree/api/app/controllers/spree/api/v3/store/store_controller.rb b/spree/api/app/controllers/spree/api/v3/store/store_controller.rb
new file mode 100644
index 0000000000..c784d60d96
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/store/store_controller.rb
@@ -0,0 +1,25 @@
+module Spree
+ module Api
+ module V3
+ module Store
+ # Exposes the store the request resolved to, so a storefront can render
+ # its name and default SEO metadata in the requested locale.
+ class StoreController < Store::BaseController
+ # A gated storefront still needs a page title on its sign-in wall.
+ allow_guest_storefront_access!
+
+ # GET /api/v3/store/store
+ def show
+ render json: serialize_resource(current_store)
+ end
+
+ protected
+
+ def serializer_class
+ Spree.api.store_serializer
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
index ab8e7c867d..947b38f5e0 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
@@ -2,8 +2,8 @@ module Spree
module Api
module V3
module Admin
- class StoreSerializer < V3::BaseSerializer
- typelize name: :string, url: :string, code: :string, api_url: :string,
+ class StoreSerializer < V3::StoreSerializer
+ typelize url: :string, code: :string, api_url: :string,
default_currency: [:string, enum: Spree::Money::Rounding::CURRENCY_CODES, enum_type_name: 'CurrencyCode'], default_locale: [:string, enum: Spree::Locales::ALL, enum_type_name: 'LocaleCode'],
default_country_code: [:string, nullable: true],
supported_currencies: [:string, multi: true, enum: Spree::Money::Rounding::CURRENCY_CODES, enum_type_name: 'CurrencyCode'],
@@ -20,7 +20,6 @@ module Spree
metadata: 'Record<string, unknown>'
attributes :metadata,
- :name,
:code,
:default_currency,
:default_locale,
diff --git a/spree/api/app/serializers/spree/api/v3/store_serializer.rb b/spree/api/app/serializers/spree/api/v3/store_serializer.rb
new file mode 100644
index 0000000000..4af7a628ee
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/store_serializer.rb
@@ -0,0 +1,16 @@
+module Spree
+ module Api
+ module V3
+ # The current store's public identity and default SEO metadata, in the
+ # request's locale. Missing translations fall back to the store's default
+ # locale.
+ class StoreSerializer < BaseSerializer
+ typelize name: :string,
+ seo_title: [:string, nullable: true],
+ meta_description: [:string, nullable: true]
+
+ attributes :name, :seo_title, :meta_description
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index a885f27c2e..c45bdecacd 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -22,6 +22,9 @@ Spree::Core::Engine.add_routes do
# Current channel context (never a list — see Store::ChannelController)
resource :channel, only: [:show], controller: 'channel'
+ # Current store context (name and default SEO metadata, localized)
+ resource :store, only: [:show], controller: 'store'
+
# Catalog
resources :products, only: [:index, :show] do
collection do
@@ -287,9 +290,9 @@ Spree::Core::Engine.add_routes do
resource :store, only: [:show, :update], controller: 'store' do
get :data_sources
end
- # The store's own custom fields, addressed by its id like every other
+ # The store's own custom fields and translations, addressed by its id like every other
# parent. The controller only ever resolves the current store.
- resources :stores, only: [], concerns: :custom_fieldable
+ resources :stores, only: [], concerns: [:custom_fieldable, :translatable]
# Staff & access (invitations, admin users, roles, API keys)
resources :admin_users, only: [:index, :show, :update, :destroy]
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 8e7e4133ab..56884a67fb 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -18,7 +18,7 @@ module Spree
product_filter_sort_option media_event return return_line_item exchange exchange_line_item claim
claim_line_item return_reason claim_reason digital_asset export gift_card_batch import import_row
invitation newsletter_subscriber promotion refund stock_level stock_movement stock_reservation
- stock_transfer company company_membership company_invitation seller file_upload file_upload_target].freeze
+ stock_transfer company company_membership company_invitation seller file_upload file_upload_target store].freeze
ADMIN_SERIALIZERS =
%i[country state locale applied_promotion discount tax_line cart delivery_zone delivery_profile
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
index 50ebd0cbb6..9bdddef74d 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
@@ -198,6 +198,37 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
end
end
+ context 'with SEO params' do
+ let(:params) { { seo_title: 'Fresh Coffee Beans', meta_description: 'Roasted every morning' } }
+
+ it 'saves them and returns them' do
+ subject
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['seo_title']).to eq('Fresh Coffee Beans')
+ expect(json_response['meta_description']).to eq('Roasted every morning')
+ expect(store.reload.seo_title).to eq('Fresh Coffee Beans')
+ end
+
+ context 'when the request resolves to a non-default locale' do
+ before do
+ configure_supported_locales(store, %w[en de])
+ store.upsert_translations('de' => { 'seo_title' => 'Frische Kaffeebohnen' })
+ request.headers['x-spree-locale'] = 'de'
+ end
+
+ after { I18n.locale = :en }
+
+ it 'writes the default-language value and leaves the translation alone' do
+ subject
+
+ expect(json_response['seo_title']).to eq('Fresh Coffee Beans')
+ expect(Mobility.with_locale(:en) { store.reload.seo_title }).to eq('Fresh Coffee Beans')
+ expect(Mobility.with_locale(:de) { store.reload.seo_title(fallback: false) }).to eq('Frische Kaffeebohnen')
+ end
+ end
+ end
+
context 'with the low stock threshold' do
let(:params) { { low_stock_threshold: 12 } }
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/translatable_resources_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/translatable_resources_controller_spec.rb
index d1a7317e99..77acd25aa1 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/translatable_resources_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/translatable_resources_controller_spec.rb
@@ -37,9 +37,9 @@ RSpec.describe Spree::Api::V3::Admin::TranslatableResourcesController, type: :co
expect(resources['collection']['readable']).to be(true)
expect(resources['policy']['readable']).to be(true)
expect(resources['option_type']['readable']).to be(true)
+ expect(resources['store']['readable']).to be(true)
# Writable via batch + readable inline as children, but no standalone route.
expect(resources['option_value']['readable']).to be(false)
- expect(resources['store']['readable']).to be(false)
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/translations/batches_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/translations/batches_controller_spec.rb
index 4e1cccb4c4..f676a8eb77 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/translations/batches_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/translations/batches_controller_spec.rb
@@ -78,5 +78,19 @@ RSpec.describe Spree::Api::V3::Admin::Translations::BatchesController, type: :co
post :create, params: { translations: { resource_type: 'product' } }, as: :json
expect(response).to have_http_status(:unprocessable_content)
end
+
+ it 'deletes a store translation cell with null' do
+ store.upsert_translations('de' => { 'seo_title' => 'Kaffeeladen' })
+
+ post :create, params: {
+ translations: [{ resource_type: 'store', resource_id: store.prefixed_id, values: { de: { seo_title: nil } } }]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(Mobility.with_locale(:de) { store.reload.seo_title(fallback: false) }).to be_nil
+
+ store.reload.upsert_translations('de' => { 'seo_title' => 'Kaffeehaus' })
+ expect(Mobility.with_locale(:de) { store.reload.seo_title(fallback: false) }).to eq('Kaffeehaus')
+ end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/translations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/translations_controller_spec.rb
index bff7bb0cc4..7e25532ccc 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/translations_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/translations_controller_spec.rb
@@ -120,6 +120,26 @@ RSpec.describe Spree::Api::V3::Admin::TranslationsController, type: :controller
end
end
+ context 'when the parent is the store' do
+ before { store.upsert_translations('de' => { 'seo_title' => 'Kaffeeladen' }) }
+
+ it 'returns the translation matrix for the current store' do
+ get :index, params: { store_id: store.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ data = json_response['data']
+ expect(data['resource_type']).to eq('store')
+ expect(data['resource_id']).to eq(store.prefixed_id)
+ expect(data['translations']['de']['seo_title']).to eq('Kaffeeladen')
+ end
+
+ it 'returns 404 for another store' do
+ get :index, params: { store_id: create(:store).prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
context 'when the parent param resolves to nothing translatable' do
it 'has no route for a non-translatable parent' do
# tax_categories are not in Spree.translatable_resources and the
diff --git a/spree/api/spec/controllers/spree/api/v3/store/store_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/store_controller_spec.rb
new file mode 100644
index 0000000000..70b0eb2fdf
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/store/store_controller_spec.rb
@@ -0,0 +1,62 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Store::StoreController, type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ let(:store) do
+ create(:store, name: 'Coffee Shop', default_locale: 'en',
+ seo_title: 'Coffee Shop — Fresh Beans', meta_description: 'Freshly roasted coffee')
+ end
+
+ before do
+ allow(store).to receive(:supported_locales_list).and_return(%w[en de fr])
+ store.upsert_translations('de' => { 'seo_title' => 'Kaffeeladen — Frische Bohnen' })
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ end
+
+ after { I18n.locale = :en }
+
+ describe 'GET #show' do
+ it 'returns the current store with its default-locale SEO values' do
+ get :show
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(store.prefixed_id)
+ expect(json_response['name']).to eq('Coffee Shop')
+ expect(json_response['seo_title']).to eq('Coffee Shop — Fresh Beans')
+ expect(json_response['meta_description']).to eq('Freshly roasted coffee')
+ end
+
+ it 'returns the translation for the requested locale' do
+ request.headers['x-spree-locale'] = 'de'
+
+ get :show
+
+ expect(json_response['seo_title']).to eq('Kaffeeladen — Frische Bohnen')
+ end
+
+ it 'falls back to the default locale for a field without a translation' do
+ request.headers['x-spree-locale'] = 'de'
+
+ get :show
+
+ expect(json_response['meta_description']).to eq('Freshly roasted coffee')
+ end
+
+ it 'falls back to the default locale for a supported locale with no translations' do
+ request.headers['x-spree-locale'] = 'fr'
+
+ get :show
+
+ expect(json_response['seo_title']).to eq('Coffee Shop — Fresh Beans')
+ end
+
+ it 'does not expose back-office store settings' do
+ get :show
+
+ expect(json_response.keys).to match_array(%w[id name seo_title meta_description])
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/store/store_spec.rb b/spree/api/spec/integration/spree/api/v3/store/store_spec.rb
new file mode 100644
index 0000000000..9c29436b11
--- /dev/null
+++ b/spree/api/spec/integration/spree/api/v3/store/store_spec.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+RSpec.describe 'Store API', type: :request, swagger_doc: 'api-reference/store.yaml' do
+ include_context 'API v3 Store'
+
+ path '/api/v3/store/store' do
+ get 'Get the current store' do
+ tags 'Store'
+ produces 'application/json'
+ security [api_key: []]
+ description "Returns the current store's name and default SEO metadata in the requested locale. " \
+ "A field without a translation falls back to the store's default locale."
+
+ sdk_example 'store/get'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: 'x-spree-locale', in: :header, type: :string, required: false,
+ description: 'Locale for translated values, e.g. `de`. Defaults to the store locale.'
+
+ response '200', 'store found' do
+ let(:'x-spree-api-key') { api_key.token }
+ let(:'x-spree-locale') { nil }
+
+ schema '$ref' => '#/components/schemas/Store'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['id']).to eq(store.prefixed_id)
+ expect(data['name']).to eq(store.name)
+ end
+ end
+
+ response '401', 'unauthorized' do
+ let(:'x-spree-api-key') { 'invalid' }
+ let(:'x-spree-locale') { nil }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/swagger_helper.rb b/spree/api/spec/swagger_helper.rb
index 9c9ec5b967..4e4ee4990e 100644
--- a/spree/api/spec/swagger_helper.rb
+++ b/spree/api/spec/swagger_helper.rb
@@ -75,6 +75,7 @@ RSpec.configure do |config|
{ name: 'Orders', description: 'Order lookup' },
{ name: 'Customers', description: 'Customer account, addresses, saved payment methods, and order history' },
{ name: 'Markets', description: 'Markets, countries, currencies, and locales' },
+ { name: 'Store', description: "The current store's name and default SEO metadata" },
{ name: 'Wishlists', description: 'Customer wishlists' },
{ name: 'Newsletter Subscribers', description: 'Guest and customer newsletter subscriptions (double opt-in)' },
{ name: 'Policies', description: 'Store policies (return policy, privacy policy, terms of service)' },
diff --git a/spree/core/app/models/concerns/spree/translatable_resource.rb b/spree/core/app/models/concerns/spree/translatable_resource.rb
index 4b5569608d..61592da575 100644
--- a/spree/core/app/models/concerns/spree/translatable_resource.rb
+++ b/spree/core/app/models/concerns/spree/translatable_resource.rb
@@ -5,6 +5,9 @@ module Spree
included do
extend Mobility
default_scope { i18n }
+
+ # Before the translations are autosaved, so it has to run first.
+ after_update :discard_blank_new_translations, prepend: true
end
class_methods do
@@ -178,6 +181,22 @@ module Spree
private
+ # Clearing a translation's last value deletes its row, and Mobility then
+ # rebuilds a blank one for that locale while it finalizes dirty tracking.
+ # Saved, that blank row is either junk or, where translation rows are soft
+ # deleted (stores), a duplicate of the deleted row.
+ def discard_blank_new_translations
+ return unless association(:translations).loaded?
+
+ columns = self.class.translatable_fields.map(&:to_s)
+ translations.each do |translation|
+ next unless translation.new_record?
+ next if columns.any? { |column| translation[column].present? }
+
+ translation.mark_for_destruction
+ end
+ end
+
# @raise [ActiveRecord::RecordInvalid] if any locale isn't supported by the store
def validate_translation_locales!(locales)
supported = translatable_store&.supported_locales_list || []
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 97463b549c..415d453bfa 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -42,6 +42,11 @@ module Spree
acts_as_paranoid
# deleted translation values still need to be accessible - remove deleted_at scope
default_scope { unscope(where: :deleted_at) }
+
+ # Mobility deletes a row once its last value is cleared. The soft delete
+ # stamps only `deleted_at`, and the row stays readable, so the cleared
+ # values have to be written too or the old translation keeps showing.
+ before_destroy { update_columns(changes_to_save.transform_values(&:last)) if has_changes_to_save? }
end
#
diff --git a/spree/core/spec/models/spree/concerns/translatable_resource_spec.rb b/spree/core/spec/models/spree/concerns/translatable_resource_spec.rb
index 43ee59ca58..3b99a3675d 100644
--- a/spree/core/spec/models/spree/concerns/translatable_resource_spec.rb
+++ b/spree/core/spec/models/spree/concerns/translatable_resource_spec.rb
@@ -53,6 +53,33 @@ RSpec.describe Spree::TranslatableResource, type: :model do
Mobility.with_locale(:es) { expect(product.reload.name).not_to eq 'Máquina de espresso' }
end
+
+ context 'when the last translated value of a locale is cleared' do
+ it 'removes the translation without leaving a blank row behind' do
+ option_type = create(:option_type, label: 'Size')
+ option_type.upsert_translations('de' => { 'label' => 'Größe' })
+ option_type.reload.upsert_translations('de' => { 'label' => nil })
+
+ expect(option_type.translations.reload.where(locale: 'de')).to be_empty
+ end
+
+ context 'on a store, whose translation rows are soft deleted' do
+ let(:translated_store) { create(:store, default_locale: 'en') }
+
+ before { allow(translated_store).to receive(:supported_locales_list).and_return(%w[en de]) }
+
+ it 'stops reading the cleared value and accepts a new one' do
+ translated_store.upsert_translations('de' => { 'seo_title' => 'Kaffeeladen' })
+ translated_store.upsert_translations('de' => { 'seo_title' => nil })
+
+ Mobility.with_locale(:de) { expect(translated_store.reload.seo_title(fallback: false)).to be_nil }
+
+ translated_store.upsert_translations('de' => { 'seo_title' => 'Kaffeehaus' })
+
+ Mobility.with_locale(:de) { expect(translated_store.reload.seo_title(fallback: false)).to eq 'Kaffeehaus' }
+ end
+ end
+ end
end
# OptionType's translatable column and public name are both `label` since