Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added market and locale filters and columns to the orders tables (#14932)
Damian Legawiecaf9df9fc1d42
diff --git a/.changeset/orders-market-locale-filters.md b/.changeset/orders-market-locale-filters.mdnew file mode 100644index 0000000000..db9308363d--- /dev/null+++ b/.changeset/orders-market-locale-filters.md@@ -0,0 +1,6 @@+---+"@spree/dashboard": minor+"@spree/dashboard-core": minor+---++The orders and draft orders lists can be filtered by market and locale, and show both as optional columns. Table definitions gain a `locale` filter type that lists the store's languages by name.diff --git a/docs/developer/dashboard/customization/tables.mdx b/docs/developer/dashboard/customization/tables.mdxindex 8ac79ee3f6..e4c5ba418d 100644--- a/docs/developer/dashboard/customization/tables.mdx+++ b/docs/developer/dashboard/customization/tables.mdx@@ -92,7 +92,9 @@ When a column is `filterable`, `filterType` decides which filter UI it gets:|---|---|---|| `'string'` (default) | Text input with contains/equals operators | — || `'boolean'` | Yes/no toggle | — |-| `'number'`, `'currency'` | Numeric comparisons | — |+| `'number'` | Numeric comparisons | — |+| `'currency'` | Pick from the store's currencies | — |+| `'locale'` | Pick from the store's languages | — || `'date'` | Date range picker (store-timezone aware) | — || `'enum'` | Fixed option list | `filterOptions: [{ value, label }]` (required) || `'resource'` | Multi-select autocomplete against another resource | `filterResource` (required) — `queryKey`, `search`, `hydrate`, `getOptionLabel` |diff --git a/packages/dashboard-core/src/components/currency-select.tsx b/packages/dashboard-core/src/components/currency-select.tsxindex cb0cd9d46f..e54cbb2e0f 100644--- a/packages/dashboard-core/src/components/currency-select.tsx+++ b/packages/dashboard-core/src/components/currency-select.tsx@@ -33,8 +33,8 @@ interface CurrencySelectProps {/** Fires on every selection change. */onChange?: (currency: CurrencyCode) => void/**- * Currency codes to pick from. Defaults to the current store's- * `supported_currencies`. Pass `ALL_CURRENCY_CODES` (or any custom list) for+ * Currency codes to pick from. Defaults to the currencies of the current+ * store's markets. Pass `ALL_CURRENCY_CODES` (or any custom list) for* contexts where the merchant chooses a currency the store doesn't yet* support — e.g. a market's currency.*/@@ -55,8 +55,8 @@ interface CurrencySelectProps {}/**- * Picker for a currency code. Defaults to the current store's- * `supported_currencies` (and the store's `default_currency`), so callers+ * Picker for a currency code. Defaults to the currencies of the+ * current store's markets (the default market's first), so callers* choosing among already-configured currencies don't have to wire anything up.* Pass `options` (e.g. `ALL_CURRENCY_CODES`) when the merchant may pick any* currency, such as a market's currency. Each option reads `CODE — Full Name`diff --git a/packages/dashboard-core/src/components/locale-select.tsx b/packages/dashboard-core/src/components/locale-select.tsxindex 936a635b44..cb2783fb8e 100644--- a/packages/dashboard-core/src/components/locale-select.tsx+++ b/packages/dashboard-core/src/components/locale-select.tsx@@ -13,13 +13,13 @@ import {ComboboxValue,useComboboxAnchor,} from '@spree/dashboard-ui'-import { useMemo, useState } from 'react'+import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useDisplayName } from '../hooks/use-display-name'import { useStore } from '../providers/store-provider'interface BaseProps {- /** Locale codes to pick from. Defaults to the current store's `supported_locales`. */+ /** Locale codes to pick from. Defaults to the languages of the current store's markets. */options?: string[]/** Locale to filter out (e.g. the default locale when picking additional supported ones). */excludeCode?: string@@ -63,16 +63,6 @@ interface MultiProps extends BaseProps {type LocaleSelectProps = SingleProps | MultiProps-/**- * Resolves a locale code (`en`, `pt-BR`) to its display name (`English`,- * `Portuguese (Brazil)`) in the admin UI language, falling back to the code- * itself when the runtime lacks coverage.- */-function useLocaleDisplayName() {- const displayName = useDisplayName('language')- return (code: string) => displayName(code) ?? code-}-/*** Mirrors `CurrencySelect`'s row format: `CODE — Localized Name`. Codes the* runtime cannot name (`Intl.DisplayNames` returns the code back, as it does@@ -96,6 +86,16 @@ function localeFilter(labelFor: (locale: string) => string) {}}+/**+ * Returns a function that labels a locale code the way the dashboard shows+ * locales everywhere: `EN — English`, named in the admin UI language. For+ * plain-text contexts (option lists, search); render `LocaleLabel` in JSX.+ */+export function useLocaleLabel() {+ const displayName = useDisplayName('language')+ return useCallback((code: string) => formatOption(code, displayName(code) ?? code), [displayName])+}+/*** Static text label for a locale code: `EN — English`. Use this in tables* and read-only contexts where the picker isn't needed but the same@@ -103,16 +103,16 @@ function localeFilter(labelFor: (locale: string) => string) {* has no entry.*/export function LocaleLabel({ code }: { code: string }) {- const displayNameFor = useLocaleDisplayName()+ const labelFor = useLocaleLabel()if (!code) return null- return <>{formatOption(code, displayNameFor(code))}</>+ return <>{labelFor(code)}</>}/**- * Picker for one of the current store's `supported_locales`. Single-select by- * default; pass `multiple` for a chips multi-select. Each option reads- * `CODE — Localized Name` (e.g. `EN — English`), localized via the browser's- * `Intl.DisplayNames` against the store's `default_locale`. Use this anywhere+ * Picker for one of the languages the current store's markets offer.+ * Single-select by default; pass `multiple` for a chips multi-select. Each+ * option reads `CODE — Localized Name` (e.g. `EN — English`), named in the+ * admin UI language via the browser's `Intl.DisplayNames`. Use this anywhere* the merchant is choosing a storefront language (market default, supported* locales list, customer preference, etc.).*@@ -124,7 +124,7 @@ export function LocaleLabel({ code }: { code: string }) {export function LocaleSelect(props: LocaleSelectProps) {const { t } = useTranslation()const { locales: storeLocales } = useStore()- const displayNameFor = useLocaleDisplayName()+ const localeLabel = useLocaleLabel()// Union of `props.options` (everything the picker should show) and the// currently selected values — so editing an existing record doesn't@@ -145,15 +145,14 @@ export function LocaleSelect(props: LocaleSelectProps) {// per character; a lookup map keeps it to a single pass per list change.const labels = useMemo(() => {const map = new Map<string, string>()- for (const locale of items) map.set(locale, formatOption(locale, displayNameFor(locale)))+ for (const locale of items) map.set(locale, localeLabel(locale))return map- }, [items, displayNameFor])+ }, [items, localeLabel])// `CODE — Name` label for a locale, from the precomputed map (falls back to a// direct lookup for a value not in the current option list, e.g. a selected// chip the list later dropped).- const labelFor = (locale: string) =>- labels.get(locale) ?? formatOption(locale, displayNameFor(locale))+ const labelFor = (locale: string) => labels.get(locale) ?? localeLabel(locale)if (props.multiple) {return (diff --git a/packages/dashboard-core/src/components/table-toolbar.tsx b/packages/dashboard-core/src/components/table-toolbar.tsxindex 1f4cdd5004..645aa5420e 100644--- a/packages/dashboard-core/src/components/table-toolbar.tsx+++ b/packages/dashboard-core/src/components/table-toolbar.tsx@@ -36,7 +36,7 @@ import {XIcon,} from '@spree/dashboard-ui/icons'import { useQuery } from '@tanstack/react-query'-import { useCallback, useDeferredValue, useMemo, useState } from 'react'+import { Fragment, useCallback, useDeferredValue, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { getApiClient } from '../api-client'import { useAuth } from '../hooks/use-auth'@@ -55,6 +55,7 @@ import {} from '../lib/table-registry'import { useOptionalStore } from '../providers/store-provider'import { useTenantId } from '../providers/tenant-provider'+import { LocaleLabel, useLocaleLabel } from './locale-select'import { StoreDatePicker } from './store-date-picker'interface TableToolbarProps {@@ -81,6 +82,13 @@ interface TableToolbarProps {// Operator labels are stored as i18n keys (`admin.components.table_toolbar.operators.*`)// and resolved with `t()` at render time so they follow the active language.+const storeCodeOperators = [+ { value: 'eq', labelKey: 'admin.components.table_toolbar.operators.is' },+ { value: 'not_eq', labelKey: 'admin.components.table_toolbar.operators.is_not' },+ { value: 'in', labelKey: 'admin.components.table_toolbar.operators.is_any_of' },+ { value: 'not_in', labelKey: 'admin.components.table_toolbar.operators.is_none_of' },+]+const operatorsByType: Record<string, { value: string; labelKey: string }[]> = {string: [// `i_cont` (case-insensitive) rather than `cont` — an admin typing@@ -125,13 +133,9 @@ const operatorsByType: Record<string, { value: string; labelKey: string }[]> = {{ value: 'not_in', labelKey: 'admin.components.table_toolbar.operators.is_none_of' },],// Same shape as `enum` — the value picker just sources its option list- // from the active store's `supported_currencies`.- currency: [- { value: 'eq', labelKey: 'admin.components.table_toolbar.operators.is' },- { value: 'not_eq', labelKey: 'admin.components.table_toolbar.operators.is_not' },- { value: 'in', labelKey: 'admin.components.table_toolbar.operators.is_any_of' },- { value: 'not_in', labelKey: 'admin.components.table_toolbar.operators.is_none_of' },- ],+ // from the currencies / languages of the active store's markets.+ currency: storeCodeOperators,+ locale: storeCodeOperators,}function getOperators(type: string) {@@ -155,7 +159,7 @@ const noValueOperators = ['present', 'blank']/** Stable empty list, so a panel with no store doesn't rebuild `items` (and* re-emit Base UI Select state) on every render. */-const noCurrencies: string[] = []+const noCodes: string[] = []// ============================================================================// TableToolbar@@ -489,6 +493,15 @@ function FilterChip({<ResourceFilterValue value={first.value} config={col.filterResource} />) : col?.filterType === 'tags' ? (<span>{parseFilterIds(first.value).join(', ')}</span>+ ) : col?.filterType === 'locale' ? (+ <span>+ {parseFilterIds(first.value).map((code, index) => (+ <Fragment key={code}>+ {index > 0 && ', '}+ <LocaleLabel code={code} />+ </Fragment>+ ))}+ </span>) : col?.filterType === 'enum' && col.filterOptions ? (<span>{parseFilterIds(first.value)@@ -515,6 +528,25 @@ function FilterChip({)}+/**+ * The whole option list of a resource small enough to fetch once (`listAll`),+ * cached under `[queryKey, tenant, 'all']` — the key the resource's own+ * full-list hook uses, so filters and the rest of the dashboard share one+ * fetch that the resource's writes invalidate.+ */+function useListAll(+ config: ColumnDef['filterResource'],+ tenantId: string | undefined,+ enabled = true,+) {+ return useQuery({+ queryKey: [config?.queryKey, tenantId, 'all'],+ queryFn: () => config?.listAll?.() ?? Promise.resolve({ data: [] }),+ enabled: enabled && Boolean(config?.listAll),+ staleTime: config?.staleTime ?? 60_000,+ })+}+/*** Hydrates the CSV id list in a resource filter into human labels. Reuses* the resource's `hydrate` callback so each chip benefits from React Query's@@ -530,19 +562,21 @@ function ResourceFilterValue({const tenantId = useTenantId()const ids = useMemo(() => parseFilterIds(value), [value])- const { data } = useQuery({+ const all = useListAll(config, tenantId, ids.length > 0)+ const hydrated = useQuery({// Tenant-scope the cache key so chips don't resolve against another// tenant's hydrate results after a store or seller switch.- queryKey: ['filter-chip', config.queryKey, tenantId, ids],+ queryKey: [config.queryKey, tenantId, 'filter-chip', ids],queryFn: () => config.hydrate(ids),- enabled: ids.length > 0,- staleTime: 60_000,+ enabled: ids.length > 0 && !config.listAll,+ staleTime: config.staleTime ?? 60_000,})+ const records = config.listAll ? all.data?.data : hydrated.data?.dataif (ids.length === 0) return nullconst labels = ids.map((id) => {- const record = data?.data.find((r) => r.id === id)+ const record = records?.find((r) => r.id === id)return record ? config.getOptionLabel(record) : id})@@ -768,12 +802,7 @@ function QuickResourceFilter({[existingValue],)- const { data } = useQuery({- queryKey: ['quick-filter-all', config.queryKey, tenantId],- queryFn: () => config.listAll?.() ?? Promise.resolve({ data: [] }),- enabled: !!config.listAll,- staleTime: 60_000,- })+ const { data } = useListAll(config, tenantId)const options = useMemo(() =>(data?.data ?? []).map((item) => ({ value: item.id, label: config.getOptionLabel(item) })),@@ -1101,10 +1130,15 @@ function InlineValueList({const tagsClient = getApiClient().tagsconst isTags = column.filterType === 'tags'const isCurrency = column.filterType === 'currency'- // `filterType: 'currency'` is only declared by tables in the operator's- // dashboard, which always has a store. Reading it optionally keeps the panel- // mountable in one that has none.- const currencies = useOptionalStore()?.currencies ?? noCurrencies+ const isLocale = column.filterType === 'locale'+ // Store codes are listed client-side from the store payload, never searched.+ const isStoreCode = isCurrency || isLocale+ // `filterType: 'currency'` / `'locale'` are only declared by tables in the+ // operator's dashboard, which always has a store. Reading it optionally+ // keeps the panel mountable in one that has none.+ const store = useOptionalStore()+ const storeCodes = (isCurrency ? store?.currencies : isLocale ? store?.locales : null) ?? noCodes+ const localeLabel = useLocaleLabel()// Tags arrive as one list and are filtered client-side; resources are// searched server-side, since their vocabulary is unbounded.@@ -1129,18 +1163,23 @@ function InlineValueList({// genuinely new query reaches the network.const deferredQuery = useDeferredValue(query)+ // A resource listed whole is fetched once and narrowed here as the operator+ // types; anything larger is searched server-side.+ const listed = Boolean(column.filterResource?.listAll)+ const all = useListAll(column.filterResource, tenantId, !isTags && !isStoreCode)+const resources = useQuery({// Tenant-scoped so a store or seller switch cannot reuse the previous// tenant's results.- queryKey: ['panel-resource-filter', column.filterResource?.queryKey, tenantId, deferredQuery],+ queryKey: [column.filterResource?.queryKey, tenantId, 'panel-resource-filter', deferredQuery],queryFn: () => column.filterResource?.search(deferredQuery),- enabled: !isTags && !isCurrency && Boolean(column.filterResource),+ enabled: !isTags && !isStoreCode && !listed && Boolean(column.filterResource),// These lists are reference data an operator reopens repeatedly while// narrowing one list, and the result is small now that only the displayed// fields are requested. Holding it for the session keeps reopening the// panel instant; `gcTime` outlives the unmount between opens.- staleTime: 5 * 60_000,- gcTime: 30 * 60_000,+ staleTime: column.filterResource?.staleTime ?? 5 * 60_000,+ gcTime: Math.max(30 * 60_000, column.filterResource?.staleTime ?? 0),// Keeps the previous matches on screen while the next query resolves, so// the list does not blank on every keystroke.//@@ -1149,7 +1188,7 @@ function InlineValueList({// drops them instead of briefly offering another tenant's records as// though they were this one's.placeholderData: (previous, previousQuery) => {- const [, previousResource, previousTenant] = (previousQuery?.queryKey ?? []) as unknown[]+ const [previousResource, previousTenant] = (previousQuery?.queryKey ?? []) as unknown[]const sameScope =previousResource === column.filterResource?.queryKey && previousTenant === tenantIdreturn sameScope ? previous : undefined@@ -1157,11 +1196,14 @@ function InlineValueList({})const options = useMemo(() => {- if (isCurrency) {+ if (isStoreCode) {const needle = query.trim().toLowerCase()- return currencies- .filter((code) => !needle || code.toLowerCase().includes(needle))- .map((code) => ({ value: code, label: code }))+ return storeCodes+ .map((code) => ({+ value: code,+ label: isLocale ? localeLabel(code) : code,+ }))+ .filter((option) => !needle || option.label.toLowerCase().includes(needle))}if (isTags) {const names = tags.data?.data?.map((tag) => tag.name) ?? []@@ -1171,11 +1213,29 @@ function InlineValueList({}const config = column.filterResourceif (!config) return []- return (resources.data?.data ?? []).map((record) => ({+ const records = (listed ? all.data?.data : resources.data?.data) ?? []+ const resourceOptions = records.map((record) => ({value: record.id,label: config.getOptionLabel(record),}))- }, [isCurrency, currencies, isTags, tags.data, resources.data, column.filterResource, query])+ if (!listed) return resourceOptions+ const needle = query.trim().toLowerCase()+ return resourceOptions.filter(+ (option) => !needle || option.label.toLowerCase().includes(needle),+ )+ }, [+ listed,+ all.data,+ isStoreCode,+ isLocale,+ storeCodes,+ localeLabel,+ isTags,+ tags.data,+ resources.data,+ column.filterResource,+ query,+ ])// Values already selected when the list opens ride at the top, so an active// filter is visible without scrolling. The set is frozen at mount: ticking a@@ -1191,7 +1251,7 @@ function InlineValueList({return [...chosen, ...rest]}, [options, pinned])- if (!isCurrency && (tags.isLoading || resources.isLoading)) {+ if (!isStoreCode && (tags.isLoading || resources.isLoading || all.isLoading)) {return (<p className="px-2 py-6 text-center text-muted-foreground">{t('admin.common.loading')}</p>)@@ -1274,7 +1334,7 @@ function FilterPanel({// Types whose values are chosen from a list rather than typed. `multi` ones// accumulate a set and need an explicit Apply; the single ones commit on the// click that picks them.- const multi = type === 'tags' || type === 'resource' || type === 'currency'+ const multi = type === 'tags' || type === 'resource' || type === 'currency' || type === 'locale'// Dates are their own shape: a list of relative presets, with the calendar// behind "custom". Same presets the quick filter offers, so a range means// the same thing wherever it was set.@@ -1653,7 +1713,7 @@ function FilterPanel({</Select>) : null}- {/* Everything picked from a list — currency, tags, resources — or+ {/* Everything picked from a list — currency, locale, tags, resources — orfrom a calendar is handled above; this branch is only the typesyou type into. */}{!noValueOperators.includes(operator) && listOptions.length === 0 && (diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.tsindex df362dd7db..f00a2d4984 100644--- a/packages/dashboard-core/src/index.ts+++ b/packages/dashboard-core/src/index.ts@@ -115,6 +115,7 @@ export * from './lib/route-registry'export * from './lib/search-registry'export * from './lib/settings-nav-registry'export * from './lib/slot-registry'+export * from './lib/store-config'export * from './lib/table-registry'export { ensureTimestampColumns } from './lib/timestamp-columns'export * from './lib/type-labels'diff --git a/packages/dashboard-core/src/lib/store-config.test.ts b/packages/dashboard-core/src/lib/store-config.test.tsnew file mode 100644index 0000000000..67c95350d5--- /dev/null+++ b/packages/dashboard-core/src/lib/store-config.test.ts@@ -0,0 +1,93 @@+import type { Market } from '@spree/admin-sdk'+import { describe, expect, it, vi } from 'vitest'+import { adminClient } from '../client'+import { listAllMarkets, marketLocalization } from './store-config'++vi.mock('../client', () => ({ adminClient: { markets: { list: vi.fn() } } }))++function market(attributes: Partial<Market>): Market {+ return {+ id: 'mkt_1',+ name: 'Market',+ currency: 'USD',+ default_locale: 'en',+ tax_inclusive: false,+ default: false,+ country_codes: [],+ supported_locales: [],+ created_at: '',+ updated_at: '',+ tax_provider: null,+ ...attributes,+ } as Market+}++describe('marketLocalization', () => {+ const markets = [+ market({+ id: 'mkt_eu',+ currency: 'EUR',+ default_locale: 'de',+ supported_locales: ['de', 'fr'],+ }),+ market({ id: 'mkt_us', currency: 'USD', default_locale: 'en', default: true }),+ market({ id: 'mkt_ie', currency: 'EUR', default_locale: 'en' }),+ ]++ it('takes the defaults from the default market', () => {+ const { defaultCurrency, defaultLocale } = marketLocalization(markets)++ expect(defaultCurrency).toBe('USD')+ expect(defaultLocale).toBe('en')+ })++ it('lists each market currency once, the default market first', () => {+ expect(marketLocalization(markets).currencies).toEqual(['USD', 'EUR'])+ })++ it('lists every language any market offers', () => {+ expect(marketLocalization(markets).locales).toEqual(['de', 'en', 'fr'])+ })++ it('falls back to the first market when none is flagged default', () => {+ const { defaultCurrency } = marketLocalization([market({ currency: 'GBP' })])++ expect(defaultCurrency).toBe('GBP')+ })++ it('returns empty lists before markets load', () => {+ expect(marketLocalization([])).toEqual({+ currencies: [],+ locales: [],+ defaultCurrency: undefined,+ defaultLocale: undefined,+ })+ })+})++describe('listAllMarkets', () => {+ it('joins every page so markets past the first page are not lost', async () => {+ const page = (number: number, pages: number) => ({+ data: [market({ id: `mkt_${number}` })],+ meta: {+ page: number,+ pages,+ limit: 100,+ count: pages,+ from: 1,+ to: 1,+ in: 1,+ previous: null,+ next: null,+ },+ })+ vi.mocked(adminClient.markets.list).mockImplementation(async (params) =>+ page(params?.page ?? 1, 3),+ )++ const result = await listAllMarkets()++ expect(result.data.map((record) => record.id)).toEqual(['mkt_1', 'mkt_2', 'mkt_3'])+ expect(adminClient.markets.list).toHaveBeenCalledTimes(3)+ })+})diff --git a/packages/dashboard-core/src/lib/store-config.ts b/packages/dashboard-core/src/lib/store-config.tsnew file mode 100644index 0000000000..63b2bafb61--- /dev/null+++ b/packages/dashboard-core/src/lib/store-config.ts@@ -0,0 +1,75 @@+import type { CurrencyCode, LocaleCode, Market, PaginatedResponse } from '@spree/admin-sdk'+import { adminClient } from '../client'++/**+ * Markets and channels are store configuration that rarely changes, so the+ * dashboard fetches each list once and keeps it for an hour. Their create,+ * update and delete mutations invalidate `[resource, storeId]`, which refreshes+ * the cached list immediately.+ */+export const STORE_CONFIG_STALE_TIME = 60 * 60_000++const PAGE_SIZE = 100++/**+ * Fetches every page of a list and joins them, so a store with more records+ * than one page holds still gets all of them.+ */+async function listEveryPage<T>(+ fetchPage: (page: number) => Promise<PaginatedResponse<T>>,+): Promise<PaginatedResponse<T>> {+ const first = await fetchPage(1)+ if (first.meta.pages <= 1) return first++ const rest = await Promise.all(+ Array.from({ length: first.meta.pages - 1 }, (_, index) => fetchPage(index + 2)),+ )+ return { ...first, data: [first, ...rest].flatMap((response) => response.data) }+}++/** Every market of the current store, under `['markets', storeId, 'all']`. */+export function listAllMarkets() {+ return listEveryPage((page) =>+ adminClient.markets.list({ page, limit: PAGE_SIZE, sort: 'position' }),+ )+}++/** Every channel of the current store, under `['channels', storeId, 'all']`. */+export function listAllChannels() {+ return listEveryPage((page) => adminClient.channels.list({ page, limit: PAGE_SIZE }))+}++export interface MarketLocalization {+ /** The default market's currency first, then every other market's. */+ currencies: CurrencyCode[]+ /** Every language any market offers, sorted. */+ locales: LocaleCode[]+ defaultCurrency: CurrencyCode | undefined+ defaultLocale: LocaleCode | undefined+}++/**+ * The currencies and languages a store sells in, read from its markets. The+ * default market's currency and language are the store's defaults.+ */+export function marketLocalization(markets: readonly Market[]): MarketLocalization {+ const defaultMarket = markets.find((market) => market.default) ?? markets[0]+ const currencies = [+ ...new Set([+ ...(defaultMarket ? [defaultMarket.currency] : []),+ ...markets.map((market) => market.currency),+ ]),+ ]+ const locales = [+ ...new Set(+ markets.flatMap((market) => [market.default_locale, ...(market.supported_locales ?? [])]),+ ),+ ].sort()++ return {+ currencies,+ locales,+ defaultCurrency: defaultMarket?.currency,+ defaultLocale: defaultMarket?.default_locale,+ }+}diff --git a/packages/dashboard-core/src/lib/table-registry.ts b/packages/dashboard-core/src/lib/table-registry.tsindex 372939d07b..f6b7c658c8 100644--- a/packages/dashboard-core/src/lib/table-registry.ts+++ b/packages/dashboard-core/src/lib/table-registry.ts@@ -67,6 +67,11 @@ interface ColumnDefBase<T = any> {* can show human-readable names instead of raw prefixed IDs.*/export interface ResourceFilterConfig<R extends { id: string } = { id: string }> {+ /**+ * Leads every cache entry the filter creates, ahead of the tenant. Naming+ * it after the resource (`'markets'`) lets that resource's writes, which+ * invalidate `[resource, tenant]`, refresh the filter's lists too.+ */queryKey: stringsearch: (query: string) => Promise<{ data: R[] }>hydrate: (ids: string[]) => Promise<{ data: R[] }>@@ -75,12 +80,18 @@ export interface ResourceFilterConfig<R extends { id: string } = { id: string }>emptyText?: string/*** Fetches the whole list, for a resource small enough to show in full —- * a store's warehouses, its channels. The control then opens as a plain- * list of options instead of an empty box waiting to be typed into, and- * still searches once the operator types. Leave it off for anything that- * could run to hundreds of rows.+ * a store's warehouses, its channels. It is fetched once and cached under+ * `[queryKey, tenant, 'all']`; the filter narrows it as the operator types+ * and labels its chips from it, without further requests. Use the same+ * request as the resource's own full-list hook, which shares that key.+ * Leave it off for anything that could run to hundreds of rows.*/listAll?: () => Promise<{ data: R[] }>+ /**+ * How long fetched options stay fresh, in milliseconds. Raise it for+ * rarely-changing resources whose writes invalidate `queryKey`.+ */+ staleTime?: number}/**@@ -100,7 +111,7 @@ export type TaggableType = 'product' | 'customer' | 'order' | (string & {})*/export type ColumnDef<T = any> =| (ColumnDefBase<T> & {- filterType?: 'string' | 'boolean' | 'number' | 'date' | 'currency'+ filterType?: 'string' | 'boolean' | 'number' | 'date' | 'currency' | 'locale'filterOptions?: neverfilterResource?: nevertaggableType?: neverdiff --git a/packages/dashboard-core/src/providers/store-provider.tsx b/packages/dashboard-core/src/providers/store-provider.tsxindex 3145dd3c27..c2c3375699 100644--- a/packages/dashboard-core/src/providers/store-provider.tsx+++ b/packages/dashboard-core/src/providers/store-provider.tsx@@ -1,9 +1,10 @@import type { CurrencyCode, LocaleCode, Store } from '@spree/admin-sdk'import { useQuery } from '@tanstack/react-query'-import { createContext, type ReactNode, useContext, useEffect, useRef } from 'react'+import { createContext, type ReactNode, useContext, useEffect, useMemo, useRef } from 'react'import { adminClient } from '../client'import { useAuth } from '../hooks/use-auth'import { coreLocaleCodes, reconcileStoreDefaultLocale } from '../lib/i18n'+import { listAllMarkets, marketLocalization, STORE_CONFIG_STALE_TIME } from '../lib/store-config'/*** Resource segment of the store query key: the current store lives in the@@ -19,14 +20,17 @@ interface StoreContextValue {store: Store | nullstoreId: stringisLoading: boolean+ /** Currencies of the store's markets, the default market's first. */currencies: CurrencyCode[]- /** Locales this store is configured to translate content into. */+ /** Languages the store's markets offer — what content is translated into. */locales: LocaleCode[]/** Every locale a merchant may translate content into — the full canonical* set, independent of which locales the store currently uses. Drives locale* pickers so a new locale can always be added. */availableLocales: LocaleCode[]+ /** The default market's currency. */defaultCurrency: CurrencyCode+ /** The default market's language. */defaultLocale: LocaleCode/** ISO country the store sells from — used to pre-fill new address forms. */defaultCountry: string@@ -75,6 +79,26 @@ export function StoreProvider({ storeId, children }: { storeId: string; children})const store = query.data ?? null+ // Same key and request as the dashboard's market list, so the shell and every+ // market picker share one cached fetch that market writes invalidate.+ const marketsQuery = useQuery({+ queryKey: ['markets', storeId, 'all'],+ queryFn: listAllMarkets,+ staleTime: STORE_CONFIG_STALE_TIME,+ })+ // Until the markets arrive, or if they cannot be read, the store payload+ // stands in: the server derives the same values from the same markets, and a+ // hardcoded USD/en would be wrong for most stores.+ const localization = useMemo(() => {+ if (marketsQuery.data) return marketLocalization(marketsQuery.data.data)+ return {+ currencies: store?.supported_currencies ?? [],+ locales: store?.supported_locales ?? [],+ defaultCurrency: store?.default_currency,+ defaultLocale: store?.default_locale,+ }+ }, [marketsQuery.data, store])+// Reconcile the admin language against this store's default — adopting it,// or dropping a now-stale auto-applied default — only when no account locale// or genuine personal choice owns it (legacy base_controller parity).@@ -90,11 +114,10 @@ export function StoreProvider({ storeId, children }: { storeId: string; children)}, [store, storeId])- const currencies = store?.supported_currencies ?? []- const locales = store?.supported_locales ?? []+ const { currencies, locales } = localizationconst availableLocales = store?.available_locales ?? []- const defaultCurrency = store?.default_currency ?? 'USD'- const defaultLocale = store?.default_locale ?? 'en'+ const defaultCurrency = localization.defaultCurrency ?? 'USD'+ const defaultLocale = localization.defaultLocale ?? 'en'const defaultCountry = store?.default_country_code ?? ''// A store's zone preference defaults to the host app's `Time.zone.name`,// which may be a Rails name ("Eastern Time (US & Canada)") that Intl anddiff --git a/packages/dashboard/e2e/helpers.ts b/packages/dashboard/e2e/helpers.tsindex 5411e4301f..da4656148f 100644--- a/packages/dashboard/e2e/helpers.ts+++ b/packages/dashboard/e2e/helpers.ts@@ -239,11 +239,15 @@ export function getCredentials(): E2ECredentials {* are single-use (rotated on every refresh), so each context needs its own.** Not used by `auth.spec.ts` — that spec exercises the login form itself.+ * Pass `account` to sign in as a teammate rather than the seeded admin.*/-export async function login(page: Page): Promise<E2ELoginSession> {+export async function login(+ page: Page,+ account?: { email: string; password: string },+): Promise<E2ELoginSession> {const creds = getCredentials()const res = await page.request.post('/api/v3/admin/auth/login', {- data: { email: creds.admin_email, password: creds.admin_password },+ data: account ?? { email: creds.admin_email, password: creds.admin_password },})if (!res.ok()) {throw new Error(`API login failed with ${res.status()}: ${await res.text()}`)@@ -501,12 +505,25 @@ export async function createShippedOrder(page: Page, accessToken: string, quanti/*** Places an order for the promo customer, paid by store credit, and ships it* unless `ship` is false. `firstName` / `lastName` set the billing name, so a- * list test can tell its own orders apart from everyone else's.+ * list test can tell its own orders apart from everyone else's. `locale`+ * places it in another of the store's languages.*/export async function createPlacedOrder(page: Page,accessToken: string,- { quantity = 2, ship = true, firstName = 'Promo', lastName = 'Customer' } = {},+ {+ quantity = 2,+ ship = true,+ firstName = 'Promo',+ lastName = 'Customer',+ locale,+ }: {+ quantity?: number+ ship?: boolean+ firstName?: string+ lastName?: string+ locale?: string+ } = {},) {const headers = { Authorization: `Bearer ${accessToken}` }const request = async (method: 'get' | 'post' | 'patch', path: string, data?: object) => {@@ -537,6 +554,7 @@ export async function createPlacedOrder(items: [{ variant_id: variants.data[0].id, quantity }],shipping_address: address,billing_address: address,+ ...(locale ? { locale } : {}),})await request('post', `/api/v3/admin/customers/${customerId}/store_credits`, {amount: order.total,diff --git a/packages/dashboard/e2e/orders-list.spec.ts b/packages/dashboard/e2e/orders-list.spec.tsindex 06ea74ec3c..c9f0842377 100644--- a/packages/dashboard/e2e/orders-list.spec.ts+++ b/packages/dashboard/e2e/orders-list.spec.ts@@ -1,6 +1,8 @@import { expect, type Page, test } from '@playwright/test'import {+ addRecordFilter,addTextFilter,+ adminRequest,createPlacedOrder,type E2ELoginSession,FIXTURE_PROMO_SKU,@@ -17,7 +19,7 @@ const SEARCH = /search by number/i* Two placed orders only this test owns: a shipped single item and an* unshipped three-item order, billed to names that carry a shared stamp.*/-async function seedOrders(page: Page, session: E2ELoginSession) {+async function seedOrders(page: Page, session: E2ELoginSession, largeLocale?: string) {const stamp = `${Date.now()}`const lastName = `Listtest${stamp}`const small = {@@ -35,14 +37,15 @@ async function seedOrders(page: Page, session: E2ELoginSession) {ship: false,firstName: `Bruno${stamp}`,lastName,+ locale: largeLocale,})),}return { lastName, small, large }}-async function openOrders(page: Page, storeId: string) {- await page.goto(ORDERS_PATH(storeId))+async function openOrders(page: Page, storeId: string, columns?: string[]) {+ await page.goto(`${ORDERS_PATH(storeId)}${columns ? `?columns=${columns.join(',')}` : ''}`)await expect(page.getByRole('heading', { name: /^orders$/i })).toBeVisible({ timeout: 15_000 })}@@ -132,4 +135,36 @@ test.describe('orders list', () => {await sortList(page, /^total$/i, 'ascending')await expect(firstRow).toContainText(small.number, { timeout: 15_000 })})++ test('shows and filters by market and locale', async ({ page }) => {+ const session = await login(page)+ // `de` is a store language through the seeded Europe market.+ const { lastName, small, large } = await seedOrders(page, session, 'de')+ const markets = await adminRequest<{ data: { name: string; currency: string }[] }>(+ page,+ session,+ 'get',+ '/markets?limit=100',+ )+ const usMarket = markets.data.find((market) => market.currency === 'USD')?.name as string+ await openOrders(page, session.store_id, ['number', 'market', 'locale'])+ await addTextFilter(page, /^last name$/i, /^contains$/i, lastName)++ await expect(row(page, small.number)).toContainText(usMarket, { timeout: 15_000 })+ await expect(+ row(page, large.number).getByRole('cell', { name: 'DE — German', exact: true }),+ ).toBeVisible()++ await addRecordFilter(page, /^locale$/i, 'German')+ await expect(row(page, large.number)).toBeVisible({ timeout: 15_000 })+ await expect(row(page, small.number)).toBeHidden()++ await page+ .getByRole('button', { name: /remove filter/i })+ .last()+ .click()+ await addRecordFilter(page, /^market$/i, 'Europe')+ await expect(row(page, small.number)).toBeHidden({ timeout: 15_000 })+ await expect(row(page, large.number)).toBeHidden()+ })})diff --git a/packages/dashboard/e2e/staff.spec.ts b/packages/dashboard/e2e/staff.spec.tsindex 8863b1d624..7d406ab0bb 100644--- a/packages/dashboard/e2e/staff.spec.ts+++ b/packages/dashboard/e2e/staff.spec.ts@@ -1,5 +1,6 @@import { expect, type Page, request, test } from '@playwright/test'import {+ adminRequest,type E2ELoginSession,escapeRegex,invitationAcceptancePath,@@ -24,12 +25,12 @@ async function inviteFromDialog(page: Page, email: string) {* context of its own — sharing the page's would swap the admin's session* cookie for the invitee's.*/-async function addTeammate(page: Page, session: E2ELoginSession, email: string) {+async function addTeammate(page: Page, session: E2ELoginSession, email: string, roleId?: string) {const headers = { Authorization: `Bearer ${session.accessToken}` }const roles = await page.request.get('/api/v3/admin/roles', { headers }).then((res) => res.json())const created = await page.request.post('/api/v3/admin/invitations', {headers,- data: { email, role_id: roles.data[0].id },+ data: { email, role_id: roleId ?? roles.data[0].id },})expect(created.status(), await created.text()).toBe(201)const invitation = (await created.json()) as { id: string }@@ -141,4 +142,43 @@ test.describe('staff', () => {timeout: 15_000,})})++ // Every teammate reads the store's markets and channels — the dashboard's+ // currencies and languages come from the markets — while the settings pages+ // that change them stay with the roles that may.+ test('a teammate limited to orders gets market currencies but no settings', async ({+ page,+ browser,+ }) => {+ const session = await login(page)+ const role = await adminRequest<{ id: string }>(page, session, 'post', '/roles', {+ name: `E2E Orders Only ${Date.now()}`,+ permissions: ['read_orders'],+ })+ const email = `e2e-orders-only-${Date.now()}@example.com`+ await addTeammate(page, session, email, role.id)++ const context = await browser.newContext({ baseURL: new URL(page.url()).origin })+ try {+ const teammate = await context.newPage()+ await login(teammate, { email, password: 'e2e-password-123' })+ await teammate.goto(`/${session.store_id}/orders`)+ // The Orders link only renders once the teammate's permissions have+ // loaded, so the Settings check below cannot pass on an empty sidebar.+ await expect(teammate.getByRole('link', { name: /^orders$/i })).toBeVisible({+ timeout: 15_000,+ })+ await expect(teammate.getByRole('link', { name: /^settings$/i })).toHaveCount(0)++ await teammate.getByRole('button', { name: /add filter/i }).click()+ await teammate+ .locator('[data-slot="filter-panel-item"]')+ .getByText(/^currency$/i)+ .click()+ await expect(teammate.getByRole('button', { name: /^USD$/ })).toBeVisible()+ await expect(teammate.getByRole('button', { name: /^EUR$/ })).toBeVisible()+ } finally {+ await context.close()+ }+ })})diff --git a/packages/dashboard/src/components/spree/catalog-terms-card.tsx b/packages/dashboard/src/components/spree/catalog-terms-card.tsxindex 2f084dc28b..16996c685f 100644--- a/packages/dashboard/src/components/spree/catalog-terms-card.tsx+++ b/packages/dashboard/src/components/spree/catalog-terms-card.tsx@@ -148,7 +148,7 @@ function OrderMinimums({canEdit: boolean}) {const { t } = useTranslation()- const { store } = useStore()+ const { currencies } = useStore()const rows: OrderMinimumEntry[] = form.watch('order_minimums') ?? []function update(next: OrderMinimumEntry[]) {@@ -156,9 +156,7 @@ function OrderMinimums({}const usedCurrencies = rows.map((row) => row.currency)- const nextCurrency = [store?.default_currency, ...(store?.supported_currencies ?? [])]- .filter((code) => code !== undefined)- .find((code) => !usedCurrencies.includes(code))+ const nextCurrency = currencies.find((code) => !usedCurrencies.includes(code))return (<section className="flex flex-col gap-3">diff --git a/packages/dashboard/src/hooks/use-channels.ts b/packages/dashboard/src/hooks/use-channels.tsindex 71c99994c0..8b047854d1 100644--- a/packages/dashboard/src/hooks/use-channels.ts+++ b/packages/dashboard/src/hooks/use-channels.ts@@ -1,6 +1,8 @@import type { Channel, ChannelCreateParams, ChannelUpdateParams } from '@spree/admin-sdk'import {adminClient,+ listAllChannels,+ STORE_CONFIG_STALE_TIME,useResourceKey,useResourceKeyBuilder,useResourceMutation,@@ -8,17 +10,15 @@ import {import { useQuery, useQueryClient } from '@tanstack/react-query'import i18n from 'i18next'-interface UseChannelsParams {- page?: number- limit?: number- expand?: string[]-}--export function useChannels({ page = 1, limit = 100, expand }: UseChannelsParams = {}) {+/**+ * Every channel of the store, fetched once and shared with the channel list+ * filter. Channel writes invalidate it.+ */+export function useChannels() {return useQuery({- queryKey: useResourceKey('channels', { page, limit, expand: expand?.join(',') ?? '' }),- queryFn: () => adminClient.channels.list({ page, limit, ...(expand ? { expand } : {}) }),- staleTime: 1000 * 60 * 5,+ queryKey: useResourceKey('channels', 'all'),+ queryFn: listAllChannels,+ staleTime: STORE_CONFIG_STALE_TIME,})}@@ -63,9 +63,15 @@ export function useDeleteChannel() {})}-export function channelAutocompleteProps(queryKey: string) {+/**+ * Channel picker. List filters call it bare, so they read the shared list+ * above; form pickers pass their own key and search as the operator types.+ */+export function channelAutocompleteProps(queryKey = 'channels') {return {queryKey,+ staleTime: STORE_CONFIG_STALE_TIME,+ listAll: listAllChannels,search: (q: string) =>adminClient.channels.list({search: q,diff --git a/packages/dashboard/src/hooks/use-markets.test.ts b/packages/dashboard/src/hooks/use-markets.test.tsindex 97d603c133..01f143d927 100644--- a/packages/dashboard/src/hooks/use-markets.test.ts+++ b/packages/dashboard/src/hooks/use-markets.test.ts@@ -1,7 +1,11 @@import { STORE_QUERY_RESOURCE, withStoreScope } from '@spree/dashboard-core'import { QueryClient } from '@tanstack/react-query'import { describe, expect, it } from 'vitest'-import { marketUpdateInvalidations, marketWriteInvalidations } from './use-markets'+import {+ marketAutocompleteProps,+ marketUpdateInvalidations,+ marketWriteInvalidations,+} from './use-markets'const STORE_ID = 'store_abc123'@@ -36,14 +40,14 @@ function staleKeysAfter(invalidate: ReturnType<typeof marketUpdateInvalidations>}describe('market write invalidations', () => {- // A store's supported currencies and locales are the union of its markets',- // so a market write leaves the cached store payload stale. Without this,- // pickers reading `useStore()` keep offering removed currencies/locales.- it('invalidates the store payload so derived currencies and locales refresh', () => {+ // The store payload still carries fields the server derives from markets.+ it('invalidates the store payload', () => {expect(staleKeysAfter(marketWriteInvalidations)).toContain('store')expect(staleKeysAfter(marketUpdateInvalidations('market_1'))).toContain('store')})+ // `marketList` is the shared list `useStore()` reads currencies and+ // languages from, so pickers drop a removed one at once.it('invalidates every market query', () => {const stale = staleKeysAfter(marketWriteInvalidations)@@ -51,6 +55,12 @@ describe('market write invalidations', () => {expect(stale).toContain('market')})+ // The store shell and the market list filter read the same cached list,+ // so these writes refresh both without waiting for its hour to pass.+ it('names the filter cache after markets so these writes reach it', () => {+ expect(marketAutocompleteProps().queryKey).toBe('markets')+ })+it('leaves unrelated resources cached', () => {expect(staleKeysAfter(marketWriteInvalidations)).not.toContain('unrelated')expect(staleKeysAfter(marketUpdateInvalidations('market_1'))).not.toContain('unrelated')diff --git a/packages/dashboard/src/hooks/use-markets.ts b/packages/dashboard/src/hooks/use-markets.tsindex 60fa9e6f10..345237e049 100644--- a/packages/dashboard/src/hooks/use-markets.ts+++ b/packages/dashboard/src/hooks/use-markets.ts@@ -1,6 +1,8 @@import type { Market, MarketCreateParams, MarketUpdateParams } from '@spree/admin-sdk'import {adminClient,+ listAllMarkets,+ STORE_CONFIG_STALE_TIME,STORE_QUERY_RESOURCE,useResourceKey,useResourceKeyBuilder,@@ -24,16 +26,15 @@ export function useMarkets({ page = 1, limit = 100, expand }: UseMarketsParams =}/**- * Cached full-list fetch for markets — markets are store-scoped, rarely- * change, and a store typically has only a handful. Reused by pickers- * (e.g. the Market price rule) that need to filter client-side without- * round-tripping the API on each keystroke.+ * Every market of the store, fetched once and shared with the store shell+ * (which derives the store's currencies and languages from it) and the market+ * list filter. Market writes invalidate it.*/export function useAllMarkets({ enabled = true }: { enabled?: boolean } = {}) {const { data, isLoading } = useQuery({queryKey: useResourceKey('markets', 'all'),- queryFn: () => adminClient.markets.list({ limit: 100, sort: 'position' }),- staleTime: 1000 * 60 * 30,+ queryFn: listAllMarkets,+ staleTime: STORE_CONFIG_STALE_TIME,enabled,})@@ -51,10 +52,10 @@ export function useMarket(id: string | undefined) {/*** Query keys every market write invalidates.*- * A store's supported currencies and locales are the union of its markets', so- * a market write makes the cached store payload stale — pickers built on- * `useStore()` would keep offering currencies and locales the markets no longer- * carry. `STORE_QUERY_RESOURCE` refreshes them alongside the market lists.+ * `['markets']` covers the shared market list the store shell derives+ * `useStore()`'s currencies and languages from, so pickers drop a removed+ * currency or language at once. `STORE_QUERY_RESOURCE` refreshes the store+ * payload too, which still carries fields the server derives from markets.** Exported so the invalidation contract is assertable without rendering hooks.*/@@ -97,3 +98,18 @@ export function useDeleteMarket() {},})}++/** Market picker for list filters, reading the shared list above. */+export function marketAutocompleteProps() {+ return {+ queryKey: 'markets',+ staleTime: STORE_CONFIG_STALE_TIME,+ search: (q: string) =>+ adminClient.markets.list({ search: q, limit: 100, sort: 'position', fields: ['name'] }),+ hydrate: (ids: string[]) => adminClient.markets.list({ id_in: ids, limit: ids.length }),+ listAll: listAllMarkets,+ getOptionLabel: (market: Market) => market.name ?? market.id,+ placeholder: i18n.t('admin.markets.search_placeholder'),+ emptyText: i18n.t('admin.markets.empty'),+ }+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 6a8ced093e..8afae69983 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1529,6 +1529,12 @@"internal_note": {"label": "ملاحظة داخلية (للموظفين فقط)"},+ "locale": {+ "label": "لغة"+ },+ "market": {+ "label": "سوق"+ },"order_group": {"label": "عملية الشراء","view": "عرض عملية الشراء"diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 306242490e..bcb1d8720b 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1511,6 +1511,12 @@"internal_note": {"label": "Interne Notiz (nur Mitarbeiter)"},+ "locale": {+ "label": "Sprache"+ },+ "market": {+ "label": "Markt"+ },"order_group": {"label": "Einkauf","view": "Einkauf anzeigen"diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 9c8bab085b..985b962293 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1511,6 +1511,12 @@"internal_note": {"label": "Internal note (staff only)"},+ "locale": {+ "label": "Locale"+ },+ "market": {+ "label": "Market"+ },"order_group": {"label": "Purchase","view": "View purchase"diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex cdfb864126..e6411bcbd5 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -1607,6 +1607,12 @@"internal_note": {"label": "Nota interna (solo staff)"},+ "locale": {+ "label": "Idioma"+ },+ "market": {+ "label": "Mercado"+ },"order_group": {"label": "Compra","view": "Ver compra"diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex bf61591dd6..985fe05e64 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1511,6 +1511,12 @@"internal_note": {"label": "Note interne (personnel uniquement)"},+ "locale": {+ "label": "Langue"+ },+ "market": {+ "label": "Marché"+ },"order_group": {"label": "Achat","view": "Voir l'achat"diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex e2c3ba225a..aca53c7d17 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1529,6 +1529,12 @@"internal_note": {"label": "Notatka wewnętrzna (tylko dla personelu)"},+ "locale": {+ "label": "Język"+ },+ "market": {+ "label": "Rynek"+ },"order_group": {"label": "Zakup","view": "Zobacz zakup"diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 5eba847943..67444c8251 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1506,6 +1506,12 @@"internal_note": {"label": "内部备注(仅员工可见)"},+ "locale": {+ "label": "语言区域"+ },+ "market": {+ "label": "市场"+ },"order_group": {"label": "本次购买","view": "查看本次购买"diff --git a/packages/dashboard/src/nav/settings.ts b/packages/dashboard/src/nav/settings.tsindex ba87c1d7f1..879ab6c1fb 100644--- a/packages/dashboard/src/nav/settings.ts+++ b/packages/dashboard/src/nav/settings.ts@@ -130,6 +130,9 @@ settingsNav.add({group: 'store',position: 300,subject: Subject.Channel,+ // Every staff member reads channels for the shell, so `read` would show+ // the page to all of them; it is for whoever may change them.+ action: 'update',})settingsNav.add({@@ -156,6 +159,9 @@ settingsNav.add({group: 'selling',position: 100,subject: Subject.Market,+ // Every staff member reads markets for the shell, so `read` would show+ // the page to all of them; it is for whoever may change them.+ action: 'update',})settingsNav.add({diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsxindex f61ca53dbb..2fcbe56599 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx@@ -6,6 +6,7 @@ import {mapSpreeErrorsToForm,PageHeader,percentToFraction,+ useStore,} from '@spree/dashboard-core'import {Alert,@@ -86,7 +87,8 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {const { storeId } = Route.useParams()const updateMutation = useUpdateStoreSettings()const { data: payoutProviders } = usePayoutProviders()- const { symbol: currencySymbol } = currencyParts(store.default_currency, i18n.language)+ const { defaultCurrency } = useStore()+ const { symbol: currencySymbol } = currencyParts(defaultCurrency, i18n.language)const form = useForm<MarketplaceSettingsFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anydiff --git a/packages/dashboard/src/tables/orders.tsx b/packages/dashboard/src/tables/orders.tsxindex 246f5234aa..f4cc622a73 100644--- a/packages/dashboard/src/tables/orders.tsx+++ b/packages/dashboard/src/tables/orders.tsx@@ -1,10 +1,11 @@-import { defineTable, Money } from '@spree/dashboard-core'+import { defineTable, LocaleLabel, Money } from '@spree/dashboard-core'import { RelativeTime, StatusBadge, TagList } from '@spree/dashboard-ui'import { ShoppingCartIcon } from '@spree/dashboard-ui/icons'import { Link } from '@tanstack/react-router'import i18n from 'i18next'import { channelAutocompleteProps } from '../hooks/use-channels'import { customerAutocompleteProps } from '../hooks/use-customers'+import { marketAutocompleteProps } from '../hooks/use-markets'import { sellerAutocompleteProps } from '../hooks/use-sellers'import { orderGroupSearch } from '../lib/order-group-search'@@ -76,7 +77,7 @@ defineTable('orders', {label: i18n.t('admin.fields.order.channel.label'),filterable: true,filterType: 'resource',- filterResource: channelAutocompleteProps('orders-table-channel-filter'),+ filterResource: channelAutocompleteProps(),ransackAttribute: 'channel_id',default: true,className: 'text-sm text-muted-foreground',@@ -180,6 +181,27 @@ defineTable('orders', {default: false,render: (order) => order.currency ?? '—',},+ {+ key: 'market',+ label: i18n.t('admin.fields.order.market.label'),+ filterable: true,+ filterType: 'resource',+ filterResource: marketAutocompleteProps(),+ ransackAttribute: 'market_id',+ default: false,+ className: 'text-sm text-muted-foreground',+ render: (order) => order.market?.name ?? '—',+ },+ {+ key: 'locale',+ label: i18n.t('admin.fields.order.locale.label'),+ sortable: true,+ filterable: true,+ filterType: 'locale',+ default: false,+ className: 'text-sm text-muted-foreground',+ render: (order) => (order.locale ? <LocaleLabel code={order.locale} /> : '—'),+ },// On a marketplace this list holds the operator's own orders and every// seller's together, so a row has to say which it is — shown by default// for the same reason the products and stock-locations lists show it. Adiff --git a/packages/dashboard/src/tables/products.tsx b/packages/dashboard/src/tables/products.tsxindex b8ab2bf321..891bc76524 100644--- a/packages/dashboard/src/tables/products.tsx+++ b/packages/dashboard/src/tables/products.tsx@@ -178,7 +178,7 @@ defineTable('products', {sortable: false,filterable: true,filterType: 'resource',- filterResource: channelAutocompleteProps('products-table-channel-filter'),+ filterResource: channelAutocompleteProps(),ransackAttribute: 'channels_id',default: false,render: (product) => product.channels?.map((c: Channel) => c.name).join(', ') ?? '—',diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rbindex a4b327415c..cc62f5f306 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb@@ -67,6 +67,27 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller doexpect(ids).to include(pos_order.prefixed_id, default_channel_order.prefixed_id)endend++ context 'filtering by market and locale' do+ let(:market) { create(:market, store: store) }+ let!(:market_order) do+ allow(store).to receive(:supported_locales_list).and_return(%w[de en])+ create(:order, store: store, market: market, locale: 'de')+ end++ it 'returns only orders in the requested market via a prefixed market_id_in' do+ get :index, params: { q: { market_id_in: [market.prefixed_id] } }, as: :json++ expect(json_response['data'].map { |o| o['id'] }).to eq([market_order.prefixed_id])+ expect(json_response['data'].first['market']['name']).to eq(market.name)+ end++ it 'returns only orders in the requested locale via locale_in' do+ get :index, params: { q: { locale_in: ['de'] } }, as: :json++ expect(json_response['data'].map { |o| o['id'] }).to eq([market_order.prefixed_id])+ end+ endendcontext 'with q[search] (full-text search)' dodiff --git a/spree/core/app/models/spree/ability.rb b/spree/core/app/models/spree/ability.rbindex 6b633cadc0..457252cabe 100644--- a/spree/core/app/models/spree/ability.rb+++ b/spree/core/app/models/spree/ability.rb@@ -167,6 +167,9 @@ module Spree# Reference data every staff member can read regardless of keys — address# forms need countries/states, and the dashboard shell reads the store.+ # The back office also reads the store's markets and channels: its+ # currencies and languages come from the markets, and list filters offer+ # both.## The store grant is unrestricted only for the store's own back office.# Another panel reads the one store it operates under and no other, so a@@ -180,6 +183,11 @@ module Spreeelsecan :read, Spree::Store, id: @store.idend++ return unless store_resource?++ can :read, Spree::Market, store_id: @resource.id+ can :read, Spree::Channel, store_id: @resource.idendenddiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex f89e33bd78..880a94cbca 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -152,7 +152,7 @@ module Spreeself.whitelisted_ransackable_attributes = %w[completed_at email number status payment_status payment_state fulfillment_status shipment_state delivery_totaltotal item_total total_quantity considered_risky channel_id currency coupon_code customer_id seller_id- order_group_id po_number+ order_group_id po_number market_id locale]self.whitelisted_ransackable_scopes = %w[complete incomplete refunded partially_refunded search]self.ransackable_scope_types = %w[complete incomplete refunded partially_refunded].index_with('boolean')diff --git a/spree/core/spec/models/spree/ability_spec.rb b/spree/core/spec/models/spree/ability_spec.rbindex dd7c26f5e3..4ceac77b0f 100644--- a/spree/core/spec/models/spree/ability_spec.rb+++ b/spree/core/spec/models/spree/ability_spec.rb@@ -131,6 +131,16 @@ describe Spree::Ability, type: :model doexpect(staff_ability).to be_able_to :read, Spree::State.newexpect(staff_ability).to be_able_to :read, storeend++ it "reads only this store's markets and channels" do+ other_store = create(:store)++ expect(staff_ability).to be_able_to :read, build(:market, store: store)+ expect(staff_ability).to be_able_to :read, build(:channel, store: store)+ expect(staff_ability).not_to be_able_to :update, build(:market, store: store)+ expect(staff_ability).not_to be_able_to :read, build(:market, store: other_store)+ expect(staff_ability).not_to be_able_to :read, build(:channel, store: other_store)+ endendcontext 'with the admin role' do