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.

Introduce new improved filters for dashboard tables (#14523)

Damian Legawiecd94750190053
diff --git a/packages/dashboard-core/src/components/table-toolbar.tsx b/packages/dashboard-core/src/components/table-toolbar.tsx
index 320bd49167..f3c8839dc3 100644
--- a/packages/dashboard-core/src/components/table-toolbar.tsx
+++ b/packages/dashboard-core/src/components/table-toolbar.tsx
@@ -1,7 +1,7 @@
import {
- Badge,
Button,
CardTitle,
+ Checkbox,
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
@@ -20,6 +20,7 @@ import {
SelectItem,
SelectTrigger,
SelectValue,
+ StatusDot,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -27,25 +28,33 @@ import {
import { useQuery } from '@tanstack/react-query'
import {
ArrowUpDownIcon,
+ CheckIcon,
+ ChevronDownIcon,
+ ChevronRightIcon,
Columns3Icon,
- FilterIcon,
- PlusIcon,
- Trash2Icon,
+ ListFilter,
XIcon,
} from 'lucide-react'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { getApiClient } from '../api-client'
+import { useAuth } from '../hooks/use-auth'
+import {
+ DATE_PRESET_KEYS,
+ type DatePresetKey,
+ matchDatePreset,
+ resolveDatePreset,
+} from '../lib/date-presets'
import {
type ColumnDef,
type FilterRule,
parseFilterIds,
type SortOption,
+ type TaggableType,
} from '../lib/table-registry'
import { useOptionalStore } from '../providers/store-provider'
import { useTenantId } from '../providers/tenant-provider'
-import { ResourceMultiAutocomplete } from './resource-multi-autocomplete'
import { StoreDatePicker } from './store-date-picker'
-import { TagCombobox } from './tag-combobox'
interface TableToolbarProps {
/** Displayable columns (for column selector and table headers) */
@@ -179,20 +188,95 @@ export function TableToolbar({
// in the field-picker Select, which Base UI re-emits as a state change.
const sortableColumns = useMemo(() => allCols.filter((c) => c.sortable), [allCols])
const filterableColumns = useMemo(() => allCols.filter((c) => c.filterable), [allCols])
- const activeFilterCount = filters.length
+ // Only enum and date columns have a control worth surfacing — the rest need
+ // a free-text value, which is what the popover is for.
+ const quickFilterColumns = useMemo(
+ () =>
+ filterableColumns.filter(
+ (c) =>
+ c.quickFilter &&
+ (c.filterType === 'enum' || c.filterType === 'boolean' || c.filterType === 'date'),
+ ),
+ [filterableColumns],
+ )
+ // A filter a quick control actually displays needs no chip — the control
+ // already states its value, and a second copy would offer two ways to clear
+ // one constraint.
+ //
+ // Matched on operator as well as field, because each control speaks exactly
+ // one: the enum control reads `in`, the date control `gteq`/`lteq`. A
+ // `status not_eq active` set from the panel lands on a field a control owns
+ // but in an operator it cannot show, so it must keep its chip — hiding it
+ // would leave the list filtered by something invisible and unremovable.
+ // The field list skips anything with a quick control on the row: that field
+ // already has a visible control, and listing it here offers a second route
+ // to the same thing. It stays reachable through the panel's field-switch
+ // select, which is how a `status is not` gets built.
+ const panelColumns = useMemo(() => {
+ const covered = new Set(quickFilterColumns.map((c) => c.key))
+ return filterableColumns.filter((c) => !covered.has(c.key))
+ }, [filterableColumns, quickFilterColumns])
+ const chipFilters = useMemo(() => {
+ const covered = new Set(
+ quickFilterColumns.flatMap((c) =>
+ c.filterType === 'date' ? [`${c.key}:gteq`, `${c.key}:lteq`] : [`${c.key}:in`],
+ ),
+ )
+ const visible = filters.filter((f) => !covered.has(`${f.field}:${f.operator}`))
+
+ // A bounded date range is stored as two rules but is one idea, so it shows
+ // as one chip. Two chips read as two unrelated filters, and removing
+ // either leaves a half-range the operator did not ask for — a "between"
+ // that silently became an "after".
+ const entries: { key: string; rules: FilterRule[] }[] = []
+ const rangeIndex = new Map<string, number>()
+ for (const rule of visible) {
+ const isBound = rule.operator === 'gteq' || rule.operator === 'lteq'
+ const column = allCols.find((c) => c.key === rule.field)
+ if (isBound && column?.filterType === 'date') {
+ const existing = rangeIndex.get(rule.field)
+ if (existing !== undefined) {
+ entries[existing].rules.push(rule)
+ continue
+ }
+ rangeIndex.set(rule.field, entries.length)
+ entries.push({ key: rule.id, rules: [rule] })
+ continue
+ }
+ entries.push({ key: rule.id, rules: [rule] })
+ }
+ return entries
+ }, [filters, quickFilterColumns, allCols])
return (
<>
- {/* A phone shows the title and the controls only — search lives in the
- TopBar there. From `lg` the search field joins them on one row. */}
+ {/* Title and page actions only. Every control that acts on the list —
+ search, filters, sort, columns — lives on the row below, so the two
+ rows split by what they are for rather than by how they are built. */}
<div className="flex flex-row items-center gap-2 border-b border-border-subtle p-3 pl-4 lg:justify-between">
{title && <CardTitle className="min-w-0 truncate text-lg">{title}</CardTitle>}
- {/* Hidden on a phone: the TopBar already carries a search field there,
- and two search boxes stacked in one column is the more confusing
- cost. Any term already set stays visible as a removable chip below,
- so a search made on desktop is never silently filtering a list the
- merchant cannot see it on. */}
- <div className="hidden items-center gap-2 lg:ml-auto lg:flex">
+ <div className="ml-auto flex shrink-0 items-center gap-2">{actions}</div>
+ </div>
+
+ {/* One filter row: the quick controls and any filters set the long way
+ sit together, because to the operator they are the same thing — a
+ constraint currently on the list. Splitting them into a "controls"
+ band and an "applied" band asked the reader to learn which of their
+ own filters lives where, and cost a third row of chrome above every
+ table to say it. */}
+ {/* Renders whenever the row has anything to hold. Sort and columns count:
+ without them a table with no filterable columns would lose both
+ controls along with the row. */}
+ {(filterableColumns.length > 0 ||
+ search ||
+ (!hideSort && sortableColumns.length > 0) ||
+ columns.some((c) => c.default !== undefined)) && (
+ <div className="flex flex-wrap items-center gap-2 border-b border-border-subtle px-3 py-2">
+ {/* Search leads: it is the widest net, and the filters beside it
+ narrow what it finds. Hidden on a phone, where the TopBar already
+ carries a search field — two search boxes stacked in one column is
+ the more confusing cost. A term set on desktop still shows as a
+ chip there, so it never filters a list invisibly. */}
<SearchInput
value={search}
onValueChange={onSearchChange}
@@ -200,83 +284,64 @@ export function TableToolbar({
searchPlaceholder ?? t('admin.components.table_toolbar.search_placeholder')
}
clearLabel={t('admin.common.clear')}
- className="h-11 w-full bg-card text-sm lg:h-[2.125rem] lg:w-[300px]"
+ className="hidden h-[2.125rem] w-[240px] bg-card text-sm lg:flex"
/>
- </div>
- {/* One row at every width, controls pinned to the end. Import and
- Export drop their labels on a phone so the row still fits; the
- title truncates ahead of them rather than pushing them off. */}
- <div className="ml-auto lg:ml-0 flex shrink-0 items-center gap-2">
- {/* Filter button */}
- {filterableColumns.length > 0 && (
+ {/* Reads as a verb rather than an icon: it is the way *in* to
+ everything the quick controls beside it don't cover, so it has to
+ look like an action and not a toggle. */}
+ {/* Hidden when every filterable field already has a quick control:
+ the button would open onto an empty list. */}
+ {panelColumns.length > 0 && (
<Popover open={filterOpen} onOpenChange={setFilterOpen}>
- <Tooltip>
- <TooltipTrigger asChild>
- <PopoverTrigger asChild>
- <Button
- variant="ghost"
- size="sm"
- className="h-11 lg:h-[2.125rem]"
- aria-label={t('admin.components.table_toolbar.filters_button')}
- >
- <FilterIcon className="size-4" />
- {activeFilterCount > 0 && (
- <Badge variant="outline" className="ml-1 px-1.5 py-0 text-xs">
- {activeFilterCount}
- </Badge>
- )}
- </Button>
- </PopoverTrigger>
- </TooltipTrigger>
- <TooltipContent>
- {t('admin.components.table_toolbar.filters_button')}
- </TooltipContent>
- </Tooltip>
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm" className="h-11 gap-1.5 lg:h-[2.125rem]">
+ <ListFilter className="size-3.5" />
+ {t('admin.components.table_toolbar.add_filter')}
+ </Button>
+ </PopoverTrigger>
{/* `min(480px, …)` rather than a flat 480px: the panel is wider
than a phone, so a fixed width runs its right edge and the
Apply button off the screen. */}
- <PopoverContent align="end" className="w-[min(480px,calc(100vw-1rem))] p-0">
+ <PopoverContent align="start" className="w-[min(480px,calc(100vw-1rem))] p-0">
<FilterPanel
- columns={filterableColumns}
+ columns={panelColumns}
+ allColumns={filterableColumns}
filters={filters}
onApply={(f) => {
onFiltersChange(f)
setFilterOpen(false)
}}
+ onChange={onFiltersChange}
onClose={() => setFilterOpen(false)}
/>
</PopoverContent>
</Popover>
)}
- {/* Sort dropdown — hidden when the table is drag-reorderable, since free sorting would defeat the drag. */}
- {!hideSort && sortableColumns.length > 0 && (
- <SortDropdown columns={sortableColumns} sort={sort} onSortChange={onSortChange} />
+ {quickFilterColumns.map((col) =>
+ col.filterType === 'date' ? (
+ <QuickDateFilter
+ key={col.key}
+ column={col}
+ filters={filters}
+ onFiltersChange={onFiltersChange}
+ />
+ ) : (
+ <QuickEnumFilter
+ key={col.key}
+ column={col}
+ filters={filters}
+ onFiltersChange={onFiltersChange}
+ />
+ ),
)}
- {/* Column selector — hidden on a phone, where too few columns are
- visible at once for choosing between them to mean anything. */}
- <div className="hidden lg:contents">
- <ColumnSelector
- columns={columns.filter((c) => c.default !== undefined)}
- visibleColumns={visibleColumns}
- onVisibleColumnsChange={onVisibleColumnsChange}
- />
- </div>
-
- {actions}
- </div>
- </div>
-
- {/* Active filter badges */}
- {(filters.length > 0 || search) && (
- <div className="flex flex-wrap items-center gap-2 border-b border-border-subtle px-3 py-2">
{/* The search term as a chip, mobile only — the field it came from is
hidden there, so this is the only way to see or clear it. */}
{search && (
- <Badge variant="outline" className="h-7 gap-1.5 pr-1 pl-2.5 text-sm lg:hidden">
- <span className="font-medium">
+ <span className="inline-flex h-11 shrink-0 items-center gap-1.5 rounded-lg border border-border bg-muted py-1 pr-1 pl-2.5 text-sm lg:hidden">
+ <span className="text-muted-foreground">
{t('admin.components.table_toolbar.search_placeholder')}
</span>
<span className="truncate">{search}</span>
@@ -289,27 +354,56 @@ export function TableToolbar({
>
<XIcon className="size-3.5" />
</Button>
- </Badge>
+ </span>
)}
- {filters.map((filter) => (
+ {chipFilters.map((entry) => (
<FilterChip
- key={filter.id}
- filter={filter}
- col={allCols.find((c) => c.key === filter.field)}
- onRemove={() => onFiltersChange(filters.filter((f) => f.id !== filter.id))}
+ key={entry.key}
+ rules={entry.rules}
+ col={allCols.find((c) => c.key === entry.rules[0].field)}
+ onRemove={() => {
+ const removing = new Set(entry.rules.map((r) => r.id))
+ onFiltersChange(filters.filter((f) => !removing.has(f.id)))
+ }}
/>
))}
{filters.length > 0 && (
+ // Stays borderless while everything beside it is outlined: the
+ // rest of the row sets constraints, this one undoes them, and
+ // giving it the same weight would make "clear" look like a fifth
+ // filter. It matches on height so the row still sits on one line.
<Button
type="button"
variant="ghost"
size="sm"
- className="text-muted-foreground hover:text-foreground"
+ className="h-11 text-muted-foreground hover:text-foreground lg:h-[2.125rem]"
onClick={() => onFiltersChange([])}
>
{t('admin.components.table_toolbar.clear_all')}
</Button>
)}
+
+ {/* Sort and columns close the row from the right. They shape the
+ view rather than narrowing it, so they sit apart from the filters
+ — but on the same line, since both are things you reach for while
+ reading a list rather than while naming one. */}
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ {/* Hidden when the table is drag-reorderable, since free sorting
+ would defeat the drag. */}
+ {!hideSort && sortableColumns.length > 0 && (
+ <SortDropdown columns={sortableColumns} sort={sort} onSortChange={onSortChange} />
+ )}
+
+ {/* Hidden on a phone, where too few columns are visible at once for
+ choosing between them to mean anything. */}
+ <div className="hidden lg:contents">
+ <ColumnSelector
+ columns={columns.filter((c) => c.default !== undefined)}
+ visibleColumns={visibleColumns}
+ onVisibleColumnsChange={onVisibleColumnsChange}
+ />
+ </div>
+ </div>
</div>
)}
</>
@@ -321,35 +415,79 @@ export function TableToolbar({
// ============================================================================
function FilterChip({
- filter,
+ rules,
col,
onRemove,
}: {
- filter: FilterRule
+ /** Usually one rule; a bounded date range is two, shown as one chip. */
+ rules: FilterRule[]
col: ColumnDef | undefined
onRemove: () => void
}) {
- const { t } = useTranslation()
- const opLabelKey = getOperatorLabelKey(col?.filterType ?? 'string', filter.operator)
- const opLabel = opLabelKey ? t(opLabelKey) : filter.operator
- const showValue = !noValueOperators.includes(filter.operator)
+ const { t, i18n } = useTranslation()
+ const first = rules[0]
+
+ /**
+ * A `yyyy-MM-dd` bound is a calendar date, not an instant, so it is
+ * formatted in the viewer's locale without a timezone conversion — shifting
+ * it by a zone offset is what would turn "1 August" into "31 July".
+ */
+ function formatDate(value: string) {
+ const [year, month, day] = value.split('-').map(Number)
+ if (!year || !month || !day) return value
+ return new Date(year, month - 1, day).toLocaleDateString(i18n.language, {
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ })
+ }
+
+ // Read the range's ends rather than assuming an order: the two rules arrive
+ // in whatever order they were applied.
+ const from = rules.find((rule) => rule.operator === 'gteq')?.value
+ const to = rules.find((rule) => rule.operator === 'lteq')?.value
+ const isRange = col?.filterType === 'date' && rules.length > 1 && from && to
+
+ const label = col?.label ?? first.field
+ const opLabelKey = getOperatorLabelKey(col?.filterType ?? 'string', first.operator)
+ const opLabel = opLabelKey ? t(opLabelKey) : first.operator
+ const showValue = !noValueOperators.includes(first.operator)
return (
- <Badge variant="outline" className="h-7 gap-1.5 pr-1 pl-2.5 text-sm">
- <span className="font-medium">{col?.label ?? filter.field}</span>
- <span className="text-muted-foreground">{opLabel}</span>
- {showValue &&
- (col?.filterType === 'resource' && col.filterResource ? (
- <ResourceFilterValue value={filter.value} config={col.filterResource} />
- ) : col?.filterType === 'tags' ? (
- <span className="font-medium">{parseFilterIds(filter.value).join(', ')}</span>
- ) : col?.filterType === 'enum' && col.filterOptions ? (
- <span className="font-medium">
- {col.filterOptions.find((o) => o.value === filter.value)?.label ?? filter.value}
- </span>
- ) : (
- <span className="font-medium">{filter.value}</span>
- ))}
+ // Deliberately shaped like the quick-filter buttons beside it rather than
+ // like a Badge: on this row it is the same kind of thing — a constraint
+ // you can see and remove — and a chip that reads as a label instead of a
+ // control invites the reader to look for the control elsewhere.
+ <span className="inline-flex h-11 shrink-0 items-center gap-1.5 rounded-lg border border-border bg-muted py-1 pr-1 pl-2.5 text-sm lg:h-[2.125rem]">
+ <span className="text-muted-foreground">{label}</span>
+ {isRange ? (
+ // "1 Aug – 29 Aug 2026" rather than two chips of ISO bounds: the range
+ // is what was asked for, and it is read far more often than it is
+ // edited.
+ <span>
+ {formatDate(from)} – {formatDate(to)}
+ </span>
+ ) : (
+ <>
+ <span className="text-muted-foreground">{opLabel}</span>
+ {showValue &&
+ (col?.filterType === 'date' ? (
+ <span>{formatDate(first.value)}</span>
+ ) : col?.filterType === 'resource' && col.filterResource ? (
+ <ResourceFilterValue value={first.value} config={col.filterResource} />
+ ) : col?.filterType === 'tags' ? (
+ <span>{parseFilterIds(first.value).join(', ')}</span>
+ ) : col?.filterType === 'enum' && col.filterOptions ? (
+ <span>
+ {parseFilterIds(first.value)
+ .map((v) => col.filterOptions?.find((o) => o.value === v)?.label ?? v)
+ .join(', ')}
+ </span>
+ ) : (
+ <span>{first.value}</span>
+ ))}
+ </>
+ )}
{/* 20px box around a 12px glyph: the chip's own height caps how large
this can be, and the chips are spaced by `gap-2`, which is what the
target-size rule asks for when the control itself is under 24px. */}
@@ -361,7 +499,7 @@ function FilterChip({
>
<XIcon className="size-3" />
</button>
- </Badge>
+ </span>
)
}
@@ -396,95 +534,7 @@ function ResourceFilterValue({
return record ? config.getOptionLabel(record) : id
})
- return <span className="font-medium">{labels.join(', ')}</span>
-}
-
-/**
- * Currency value-picker for `filterType: 'currency'`. Options come from the
- * active store's `supported_currencies`. Branches on operator: `eq`/`not_eq`
- * use a single `<Select>`; `in`/`not_in` accept a CSV via Base UI's
- * multi-select Combobox chips, matching the other array-valued filters.
- */
-function CurrencyFilterPicker({
- value,
- operator,
- onChange,
-}: {
- value: string
- operator: string
- onChange: (next: string) => void
-}) {
- const { t } = useTranslation()
- // `filterType: 'currency'` is only declared by tables in the operator's
- // dashboard, which always has a store. Reading the store optionally keeps
- // the panel mountable in a panel that has none.
- const currencies = useOptionalStore()?.currencies ?? noCurrencies
- const items = useMemo(
- () => currencies.map((code) => ({ value: code, label: code })),
- [currencies],
- )
-
- if (operator === 'in' || operator === 'not_in') {
- return (
- <div className="flex-1 min-w-0">
- <CurrencyMultiSelect
- codes={currencies}
- value={parseFilterIds(value)}
- onChange={(next) => onChange(next.join(','))}
- />
- </div>
- )
- }
-
- return (
- <Select items={items} value={value || undefined} onValueChange={(val) => onChange(val)}>
- <SelectTrigger size="sm" className="flex-1">
- <SelectValue placeholder={t('admin.components.table_toolbar.filter_select_placeholder')} />
- </SelectTrigger>
- <SelectContent>
- {items.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )
-}
-
-function CurrencyMultiSelect({
- codes,
- value,
- onChange,
-}: {
- codes: string[]
- value: string[]
- onChange: (next: string[]) => void
-}) {
- function toggle(code: string) {
- onChange(value.includes(code) ? value.filter((c) => c !== code) : [...value, code])
- }
- return (
- <div className="flex flex-wrap gap-1 rounded-md border border-input px-2 py-1.5 text-sm">
- {codes.map((code) => {
- const selected = value.includes(code)
- return (
- <button
- key={code}
- type="button"
- onClick={() => toggle(code)}
- className={`rounded px-1.5 py-0.5 text-xs font-medium ${
- selected
- ? 'bg-primary text-primary-foreground'
- : 'bg-muted text-muted-foreground hover:bg-accent'
- }`}
- >
- {code}
- </button>
- )
- })}
- </div>
- )
+ return <span>{labels.join(', ')}</span>
}
// ============================================================================
@@ -509,7 +559,7 @@ function SortDropdown({
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button
- variant="ghost"
+ variant="outline"
size="sm"
className="h-11 lg:h-[2.125rem]"
aria-label={t('admin.components.table_toolbar.sort_tooltip')}
@@ -559,6 +609,266 @@ function SortDropdown({
)
}
+// ============================================================================
+// Quick filters
+// ============================================================================
+
+/**
+ * Always-visible control for one heavily-used filter.
+ *
+ * These write ordinary `FilterRule`s, so a status set here is indistinguishable
+ * from one set in the popover — same URL state, same chips, same export. The
+ * difference is only how many clicks it took.
+ *
+ * Unlike the popover, a quick filter applies on change rather than on Apply: a
+ * single toggle is cheap to undo, so making the operator confirm it costs more
+ * than it protects. The popover keeps its Apply, where several half-edited rows
+ * would otherwise each fire a request.
+ */
+function QuickEnumFilter({
+ column,
+ filters,
+ onFiltersChange,
+}: {
+ column: ColumnDef
+ filters: FilterRule[]
+ onFiltersChange: (filters: FilterRule[]) => void
+}) {
+ const { t } = useTranslation()
+ // A boolean column carries no `filterOptions` — its two values are fixed, so
+ // the control supplies them rather than every such column restating them.
+ const options = useMemo(
+ () =>
+ column.filterType === 'boolean'
+ ? [
+ { value: 'true', label: t('admin.common.yes') },
+ { value: 'false', label: t('admin.common.no') },
+ ]
+ : (column.filterOptions ?? []),
+ [column.filterType, column.filterOptions, t],
+ )
+ const existing = filters.find((f) => f.field === column.key && f.operator === 'in')
+
+ // No rule means no constraint, which is every option — not none. Showing
+ // "0/7" for an unfiltered list would read as "nothing matches".
+ const selected = existing ? parseFilterIds(existing.value) : options.map((o) => o.value)
+ const allSelected = selected.length === options.length
+
+ const apply = useCallback(
+ (values: string[]) => {
+ const others = filters.filter((f) => !(f.field === column.key && f.operator === 'in'))
+ // Selecting everything is the same as filtering by nothing, so drop the
+ // rule instead of listing every value in the URL.
+ if (values.length === 0 || values.length === options.length) {
+ onFiltersChange(others)
+ return
+ }
+ onFiltersChange([
+ ...others,
+ {
+ id: existing?.id ?? crypto.randomUUID(),
+ field: column.key,
+ operator: 'in',
+ value: values.join(','),
+ },
+ ])
+ },
+ [filters, column.key, options.length, existing?.id, onFiltersChange],
+ )
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm" className="h-11 gap-1.5 lg:h-[2.125rem]">
+ <span className="text-muted-foreground">{column.label}</span>
+ <span className="tabular-nums">
+ {allSelected ? t('admin.common.all') : `${selected.length}/${options.length}`}
+ </span>
+ <ChevronDownIcon className="size-3.5 text-muted-foreground" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-52">
+ {options.map((option) => (
+ <DropdownMenuCheckboxItem
+ key={option.value}
+ checked={selected.includes(option.value)}
+ onCheckedChange={(checked) =>
+ apply(
+ checked ? [...selected, option.value] : selected.filter((v) => v !== option.value),
+ )
+ }
+ >
+ <StatusDot status={option.value} />
+ {option.label}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+/**
+ * Relative date presets for one date column.
+ *
+ * A preset is a single choice rather than a range builder, which keeps it one
+ * `FilterRule` and therefore one chip. Bounded ranges — "last month", or
+ * anything picked by hand — need both ends, so those write two rules and read
+ * back as two chips, which is honest about what was asked for.
+ */
+function QuickDateFilter({
+ column,
+ filters,
+ onFiltersChange,
+}: {
+ column: ColumnDef
+ filters: FilterRule[]
+ onFiltersChange: (filters: FilterRule[]) => void
+}) {
+ const { t } = useTranslation()
+ const store = useOptionalStore()
+ // A panel with no store context (a seller's) falls back to the viewer's zone
+ // rather than refusing to offer presets.
+ const timezone = store?.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC'
+
+ const from = filters.find((f) => f.field === column.key && f.operator === 'gteq')
+ const to = filters.find((f) => f.field === column.key && f.operator === 'lteq')
+ const active = matchDatePreset({ from: from?.value ?? null, to: to?.value ?? null }, timezone)
+ // Seeded from what is applied, so reopening on a hand-picked range shows the
+ // dates it is filtering by rather than an empty form.
+ const [custom, setCustom] = useState<{ from: string; to: string } | null>(null)
+ const [open, setOpen] = useState(false)
+
+ /** Replace this column's bounds. Either end may be null for an open range. */
+ const applyRange = useCallback(
+ (rangeFrom: string | null, rangeTo: string | null) => {
+ const others = filters.filter(
+ (f) => !(f.field === column.key && (f.operator === 'gteq' || f.operator === 'lteq')),
+ )
+ const next: FilterRule[] = [...others]
+ if (rangeFrom) {
+ next.push({
+ id: crypto.randomUUID(),
+ field: column.key,
+ operator: 'gteq',
+ value: rangeFrom,
+ })
+ }
+ if (rangeTo) {
+ next.push({ id: crypto.randomUUID(), field: column.key, operator: 'lteq', value: rangeTo })
+ }
+ onFiltersChange(next)
+ },
+ [filters, column.key, onFiltersChange],
+ )
+
+ const apply = useCallback(
+ (preset: DatePresetKey) => {
+ const range = resolveDatePreset(preset, timezone)
+ applyRange(range.from, range.to)
+ },
+ [timezone, applyRange],
+ )
+
+ // A Popover rather than a DropdownMenu: the custom branch holds date pickers
+ // and a submit, which a menu's roving focus fights.
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next)
+ // Reopening starts on the preset list unless a custom range is what is
+ // applied — then it opens on the range, so the dates stay editable.
+ if (next) {
+ setCustom(active === 'custom' ? { from: from?.value ?? '', to: to?.value ?? '' } : null)
+ }
+ }}
+ >
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm" className="h-11 gap-1.5 lg:h-[2.125rem]">
+ <span className="text-muted-foreground">{column.label}</span>
+ <span>{t(`admin.components.table_toolbar.date_presets.${active}`)}</span>
+ <ChevronDownIcon className="size-3.5 text-muted-foreground" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-[min(320px,calc(100vw-1rem))] p-1">
+ {custom ? (
+ <div data-slot="filter-panel-controls" className="flex flex-col gap-2 p-2">
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-muted-foreground">
+ {t('admin.components.table_toolbar.date_range_start')}
+ </span>
+ <StoreDatePicker
+ value={custom.from || null}
+ onChange={(next) => setCustom({ ...custom, from: next ?? '' })}
+ placeholder={t('admin.components.table_toolbar.filter_date_placeholder')}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-muted-foreground">
+ {t('admin.components.table_toolbar.date_range_end')}
+ </span>
+ <StoreDatePicker
+ value={custom.to || null}
+ onChange={(next) => setCustom({ ...custom, to: next ?? '' })}
+ placeholder={t('admin.components.table_toolbar.filter_date_placeholder')}
+ />
+ </div>
+ <div className="flex justify-end gap-1.5">
+ <Button variant="ghost" size="sm" onClick={() => setCustom(null)}>
+ {t('admin.actions.back')}
+ </Button>
+ <Button
+ size="sm"
+ // Either bound alone is a valid filter — "everything since
+ // March" is a question people ask.
+ disabled={!custom.from && !custom.to}
+ onClick={() => {
+ applyRange(custom.from || null, custom.to || null)
+ setOpen(false)
+ }}
+ >
+ {t('admin.actions.apply')}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col">
+ {DATE_PRESET_KEYS.map((preset) => (
+ <button
+ key={preset}
+ type="button"
+ data-slot="filter-panel-item"
+ className="flex w-full items-center justify-between gap-2 rounded-lg px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ onClick={() => {
+ apply(preset)
+ setOpen(false)
+ }}
+ >
+ {t(`admin.components.table_toolbar.date_presets.${preset}`)}
+ {active === preset && <CheckIcon className="size-3.5 shrink-0" />}
+ </button>
+ ))}
+ {/* Without this the quick control is the only route to a date
+ filter on tables whose every filterable column is a quick one —
+ and it offers presets only, so a hand-picked range would be
+ unreachable, and one restored from a URL would show as neither
+ selected nor removable. */}
+ <button
+ type="button"
+ data-slot="filter-panel-item"
+ className="flex w-full items-center justify-between gap-2 rounded-lg px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ onClick={() => setCustom({ from: from?.value ?? '', to: to?.value ?? '' })}
+ >
+ {t('admin.components.table_toolbar.date_presets.custom')}
+ <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" />
+ </button>
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ )
+}
+
// ============================================================================
// Column Selector
// ============================================================================
@@ -581,9 +891,9 @@ function ColumnSelector({
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button
- variant="ghost"
+ variant="outline"
size="sm"
- className="h-[2.125rem]"
+ className="h-11 lg:h-[2.125rem]"
aria-label={t('admin.components.table_toolbar.columns_tooltip')}
>
<Columns3Icon className="size-4" />
@@ -628,254 +938,562 @@ function ColumnSelector({
// ============================================================================
// Filter Drawer
// ============================================================================
+/**
+ * Inline, searchable, multi-select list of a filter's candidate values.
+ *
+ * Tags and resources previously rendered a combobox, which opened its own
+ * dropdown inside a panel that already had the room to show the options — a
+ * popup over a popup, to display a list. Here the list is simply the panel's
+ * body, filtered by the search box already in its header.
+ *
+ * Both types are "is any of" by nature, so there is no operator to choose:
+ * ticking two tags means either, which is the only reading a set of tags has.
+ */
+function InlineValueList({
+ column,
+ tenantId,
+ query,
+ selected,
+ onToggle,
+}: {
+ column: ColumnDef
+ tenantId: string | undefined
+ query: string
+ selected: string[]
+ onToggle: (value: string) => void
+}) {
+ const { t } = useTranslation()
+ const { isAuthenticated } = useAuth()
+ const tagsClient = getApiClient().tags
+ const 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
+
+ // Tags arrive as one list and are filtered client-side; resources are
+ // searched server-side, since their vocabulary is unbounded.
+ const tags = useQuery({
+ // Tenant-scoped like the resource query below: tag vocabularies are
+ // per-store, and a shared key would serve one store's tags to the next for
+ // as long as the result stays fresh.
+ queryKey: ['panel-tags', tenantId, column.taggableType],
+ queryFn: () => tagsClient?.list({ taggable_type: column.taggableType as TaggableType }),
+ enabled: isTags && isAuthenticated && Boolean(tagsClient),
+ staleTime: 60_000,
+ })
+ 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, query],
+ queryFn: () => column.filterResource?.search(query),
+ enabled: !isTags && !isCurrency && Boolean(column.filterResource),
+ staleTime: 30_000,
+ })
+
+ const options = useMemo(() => {
+ if (isCurrency) {
+ const needle = query.trim().toLowerCase()
+ return currencies
+ .filter((code) => !needle || code.toLowerCase().includes(needle))
+ .map((code) => ({ value: code, label: code }))
+ }
+ if (isTags) {
+ const names = tags.data?.data?.map((tag) => tag.name) ?? []
+ const needle = query.trim().toLowerCase()
+ const matching = needle ? names.filter((name) => name.toLowerCase().includes(needle)) : names
+ return matching.map((name) => ({ value: name, label: name }))
+ }
+ const config = column.filterResource
+ if (!config) return []
+ return (resources.data?.data ?? []).map((record) => ({
+ value: record.id,
+ label: config.getOptionLabel(record),
+ }))
+ }, [isCurrency, currencies, isTags, tags.data, resources.data, column.filterResource, query])
+
+ // Selected values ride at the top so a choice made before searching does not
+ // disappear the moment the query stops matching it.
+ const ordered = useMemo(() => {
+ const chosen = options.filter((option) => selected.includes(option.value))
+ const rest = options.filter((option) => !selected.includes(option.value))
+ // Not truncated: a list cut at ten looks like a list of ten, and a
+ // vocabulary of forty tags would silently lose thirty with nothing on
+ // screen to say so. The container scrolls instead, so the scrollbar
+ // reports how much more there is — and searching narrows it.
+ return [...chosen, ...rest]
+ }, [options, selected])
+
+ if (!isCurrency && (tags.isLoading || resources.isLoading)) {
+ return (
+ <p className="px-2 py-6 text-center text-sm text-muted-foreground">
+ {t('admin.common.loading')}
+ </p>
+ )
+ }
+
+ if (ordered.length === 0) {
+ return (
+ <p className="px-2 py-6 text-center text-sm text-muted-foreground">
+ {t('admin.common.no_results')}
+ </p>
+ )
+ }
+
+ return (
+ <>
+ {ordered.map((option) => (
+ <button
+ key={option.value}
+ type="button"
+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ onClick={() => onToggle(option.value)}
+ >
+ <Checkbox checked={selected.includes(option.value)} className="pointer-events-none" />
+ <span className="truncate">{option.label}</span>
+ </button>
+ ))}
+ </>
+ )
+}
+
+/**
+ * The advanced filter panel, in two stages.
+ *
+ * Stage one lists the fields. Stage two commits to one of them and shows its
+ * values, with the field name kept as a select in the header so switching
+ * subject is one click rather than a trip back.
+ *
+ * One filter at a time, deliberately: filters compose by being applied in
+ * succession, and each one lands as a chip on the toolbar row, so the row is
+ * the list of what is active. A panel that also held several half-built rows
+ * duplicated that list in a second place, in a different notation.
+ */
function FilterPanel({
columns,
- filters: initialFilters,
+ allColumns,
+ filters,
onApply,
+ onChange,
onClose,
}: {
+ /** Fields offered in the list — excludes those with a quick control. */
columns: ColumnDef[]
+ /** Every filterable field, for the field-switch select once one is chosen. */
+ allColumns: ColumnDef[]
filters: FilterRule[]
+ /** Commit and close — for the filters that are finished in one action. */
onApply: (filters: FilterRule[]) => void
+ /** Update without closing — for a multi-select the user is still building. */
+ onChange: (filters: FilterRule[]) => void
onClose: () => void
}) {
const { t } = useTranslation()
const tenantId = useTenantId()
- const [draft, setDraft] = useState<FilterRule[]>(initialFilters)
- const booleanItems = useMemo(
- () => [
- { value: 'true', label: t('admin.common.yes') },
- { value: 'false', label: t('admin.common.no') },
- ],
- [t],
+ const store = useOptionalStore()
+ const timezone = store?.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC'
+ // The field being built, or null while the field list is showing.
+ const [field, setField] = useState<string | null>(null)
+ const [operator, setOperator] = useState('')
+ const [value, setValue] = useState('')
+ const [query, setQuery] = useState('')
+ // Set once the user picks "custom" from the date presets, revealing the two
+ // date fields. Kept separate from `value` so backing out of custom does not
+ // strand a half-entered range.
+ const [customRange, setCustomRange] = useState<{ from: string; to: string } | null>(null)
+
+ // Resolved against every field, not just the offered ones: the switch
+ // select can land on a quick-filtered field the list deliberately omits.
+ const column = allColumns.find((c) => c.key === field)
+ const type = column?.filterType ?? 'string'
+ const operators = useMemo(
+ () => getOperators(type).map((op) => ({ value: op.value, label: t(op.labelKey) })),
+ [type, t],
)
- // Stable `{ value, label }` array for the field-picker `<Select items>`.
- // Building it inline per render produces a new reference each time, which
- // Base UI's Select treats as an `items` change and re-emits state — causing
- // a "Maximum update depth exceeded" loop when the value-Select sits inside
- // the same panel.
+ // The switch select offers what the field list offered, plus whatever is
+ // currently chosen. Listing every filterable field would put the
+ // quick-filtered ones — which have their own control on the row — back into
+ // the panel, so "Date" would appear twice on screen at once.
+ const switchColumns = useMemo(() => {
+ const offered = columns.slice()
+ if (field && !offered.some((c) => c.key === field)) {
+ const current = allColumns.find((c) => c.key === field)
+ if (current) offered.unshift(current)
+ }
+ return offered
+ }, [columns, allColumns, field])
const fieldItems = useMemo(
- () => columns.map((c) => ({ value: c.key, label: c.label })),
- [columns],
+ () => switchColumns.map((c) => ({ value: c.key, label: c.label })),
+ [switchColumns],
)
- const addFilter = useCallback(() => {
- const first = columns[0]
- if (!first) return
- setDraft((prev) => [
- ...prev,
- {
- id: crypto.randomUUID(),
- field: first.key,
- operator: getOperators(first.filterType ?? 'string')[0].value,
- value: '',
- },
+ // Types whose values are a fixed list the panel can render inline. Anything
+ // else needs its own control (an autocomplete, a date picker, a text box),
+ // which is what the second branch below draws.
+ // 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'
+ // 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.
+ const dated = type === 'date'
+ const listed = type === 'enum' || type === 'boolean' || multi
+ // The header search filters the list below it, so it earns its place only
+ // when there is a list: the fields, or a list-shaped type's values.
+ const searchable = (!field || listed) && !dated
+ const listOptions = useMemo(() => {
+ const options =
+ type === 'boolean'
+ ? [
+ { value: 'true', label: t('admin.common.yes') },
+ { value: 'false', label: t('admin.common.no') },
+ ]
+ : (column?.filterOptions ?? [])
+ if (!query.trim()) return options
+ const needle = query.trim().toLowerCase()
+ return options.filter((o) => o.label.toLowerCase().includes(needle))
+ }, [type, column?.filterOptions, query, t])
+
+ const visibleFields = useMemo(() => {
+ if (!query.trim()) return columns
+ const needle = query.trim().toLowerCase()
+ return columns.filter((c) => c.label.toLowerCase().includes(needle))
+ }, [columns, query])
+
+ function chooseField(key: string) {
+ const col = allColumns.find((c) => c.key === key)
+ const firstOperator = getOperators(col?.filterType ?? 'string')[0].value
+ setField(key)
+ setOperator(firstOperator)
+ // Seed from what is already applied, so reopening a multi-select shows the
+ // values it is filtering by. Without this the list reads as empty and the
+ // next tick would replace the existing set rather than extend it.
+ const applied = filters.find((f) => f.field === key && f.operator === 'in')
+ setValue(applied?.value ?? '')
+ setQuery('')
+ }
+
+ /**
+ * Apply this filter and close.
+ *
+ * Replaces any rule already set on the same field and operator rather than
+ * adding a second: picking "Status is Active", then reopening and picking
+ * "Status is Draft", would otherwise leave two `eq` rules that the server
+ * ANDs together into nothing. Rules on the same field with a *different*
+ * operator survive — `created_at after X` and `created_at before Y` are a
+ * range, not a contradiction.
+ */
+ function commit(nextValue: string, nextOperator = operator) {
+ if (!field) return
+ if (!noValueOperators.includes(nextOperator) && nextValue.trim() === '') return
+ const others = filters.filter((f) => !(f.field === field && f.operator === nextOperator))
+ onApply([
+ ...others,
+ { id: crypto.randomUUID(), field, operator: nextOperator, value: nextValue },
])
- }, [columns])
+ }
- const updateFilter = useCallback((id: string, update: Partial<FilterRule>) => {
- setDraft((prev) => prev.map((f) => (f.id === id ? { ...f, ...update } : f)))
- }, [])
+ /** Replace this field's bounds with a preset's, and close. */
+ function commitDatePreset(preset: DatePresetKey) {
+ if (!field) return
+ const range = resolveDatePreset(preset, timezone)
+ const others = filters.filter(
+ (f) => !(f.field === field && (f.operator === 'gteq' || f.operator === 'lteq')),
+ )
+ const next = [...others]
+ if (range.from) {
+ next.push({ id: crypto.randomUUID(), field, operator: 'gteq', value: range.from })
+ }
+ if (range.to) {
+ next.push({ id: crypto.randomUUID(), field, operator: 'lteq', value: range.to })
+ }
+ onApply(next)
+ }
- const removeFilter = useCallback((id: string) => {
- setDraft((prev) => prev.filter((f) => f.id !== id))
- }, [])
+ /**
+ * Apply a multi-select as it is ticked, keeping the panel open.
+ *
+ * Replaces this field's rule rather than appending, so ticking three tags
+ * leaves one rule listing three values instead of three rules — and
+ * unticking the last one removes it, rather than leaving an empty rule that
+ * would match nothing.
+ */
+ function toggleValue(option: string) {
+ if (!field) return
+ const current = parseFilterIds(value)
+ const next = current.includes(option)
+ ? current.filter((v) => v !== option)
+ : [...current, option]
+ setValue(next.join(','))
- function handleApply() {
- const valid = draft.filter(
- (f) => noValueOperators.includes(f.operator) || f.value.trim() !== '',
+ const others = filters.filter((f) => !(f.field === field && f.operator === 'in'))
+ onChange(
+ next.length === 0
+ ? others
+ : [...others, { id: crypto.randomUUID(), field, operator: 'in', value: next.join(',') }],
)
- onApply(valid)
}
return (
<div className="flex flex-col">
- <div className="flex items-center justify-between border-b px-3 py-2">
- <span className="text-sm font-medium">
- {t('admin.components.table_toolbar.filters_button')}
- </span>
- <button type="button" onClick={onClose} className="p-1 rounded hover:bg-muted">
- <XIcon className="size-3.5" />
- </button>
+ {/* Header. Before a field is chosen this is a label and a search box over
+ the field list; after, the label becomes a select, so changing subject
+ costs one click instead of backing out. */}
+ <div className="flex items-stretch border-b">
+ {field ? (
+ <Select items={fieldItems} value={field} onValueChange={chooseField}>
+ <SelectTrigger
+ size="sm"
+ // Sits flush in the panel's top-left corner, so it drops the
+ // standalone-field focus treatment: a blue border and a 3px
+ // outer glow paint past the panel's rounded edge and read as a
+ // rendering fault. A background change carries focus instead,
+ // which stays inside the element's own box.
+ className="w-auto shrink-0 rounded-none border-0 border-r bg-transparent shadow-none focus:border-border focus:bg-accent focus:shadow-none"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {switchColumns.map((c) => (
+ <SelectItem key={c.key} value={c.key}>
+ {c.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <span className="flex shrink-0 items-center border-r px-3 py-2 text-sm font-medium">
+ {t('admin.components.table_toolbar.filter_by')}
+ </span>
+ )}
+ {/* Only where it filters something: a list of fields, or a list of
+ values. The other value types bring their own input — a resource
+ autocomplete, a date picker, a text box — and a second search box
+ above one of those searches nothing. */}
+ {searchable ? (
+ <Input
+ autoFocus
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t('admin.components.table_toolbar.filter_to_placeholder')}
+ className="min-w-0 flex-1 rounded-none border-0 shadow-none focus:shadow-none"
+ />
+ ) : (
+ <span className="flex-1" />
+ )}
+ <Button onClick={onClose} size="icon-sm" variant="ghost" className="m-1 shrink-0">
+ <XIcon className="size-4" />
+ </Button>
</div>
- <div className="max-h-[320px] overflow-y-auto p-3 space-y-2">
- {draft.map((filter) => {
- const col = columns.find((c) => c.key === filter.field)
- const type = col?.filterType ?? 'string'
- const ops = getOperators(type).map((op) => ({
- value: op.value,
- label: t(op.labelKey),
- }))
-
- return (
- // `flex-wrap` with a `basis` floor on each control: field,
- // operator and value cannot share one line on a phone, so they
- // stack instead of squeezing every control below legibility.
- <div key={filter.id} className="flex min-w-0 flex-wrap items-center gap-1.5">
- <Select
- items={fieldItems}
- value={filter.field}
- onValueChange={(val) => {
- const newCol = columns.find((c) => c.key === val)
- const newOps = getOperators(newCol?.filterType ?? 'string')
- updateFilter(filter.id, {
- field: val,
- operator: newOps[0].value,
- value: '',
- })
- }}
- >
- <SelectTrigger size="sm" className="min-w-[8rem] flex-1">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {columns.map((c) => (
- <SelectItem key={c.key} value={c.key}>
- {c.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- <Select
- items={ops}
- value={filter.operator}
- onValueChange={(val) => updateFilter(filter.id, { operator: val })}
- >
- <SelectTrigger size="sm" className="w-[120px] shrink-0 max-sm:flex-1">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {ops.map((op) => (
- <SelectItem key={op.value} value={op.value}>
- {op.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- {!noValueOperators.includes(filter.operator) &&
- (col?.filterType === 'resource' && col.filterResource ? (
- <div className="flex-1 min-w-0">
- <ResourceMultiAutocomplete
- // Tenant-scope the cache key so a store or seller switch
- // can't reuse the previous tenant's search results.
- queryKey={`${col.filterResource.queryKey}-${tenantId}`}
- value={parseFilterIds(filter.value)}
- onChange={(ids) => updateFilter(filter.id, { value: ids.join(',') })}
- search={col.filterResource.search}
- hydrate={col.filterResource.hydrate}
- getOptionLabel={col.filterResource.getOptionLabel}
- placeholder={col.filterResource.placeholder}
- emptyText={col.filterResource.emptyText}
- />
- </div>
- ) : col?.filterType === 'tags' && col.taggableType ? (
- <div className="flex-1 min-w-0">
- <TagCombobox
- taggableType={col.taggableType}
- value={parseFilterIds(filter.value)}
- onChange={(names) => updateFilter(filter.id, { value: names.join(',') })}
- />
- </div>
- ) : col?.filterType === 'enum' && col.filterOptions ? (
- <Select
- items={col.filterOptions}
- value={filter.value || undefined}
- onValueChange={(val) => updateFilter(filter.id, { value: val })}
- >
- <SelectTrigger size="sm" className="min-w-[8rem] flex-1">
- <SelectValue
- placeholder={t('admin.components.table_toolbar.filter_select_placeholder')}
- />
- </SelectTrigger>
- <SelectContent>
- {col.filterOptions.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- ) : col?.filterType === 'currency' ? (
- <CurrencyFilterPicker
- value={filter.value}
- operator={filter.operator}
- onChange={(val) => updateFilter(filter.id, { value: val })}
- />
- ) : col?.filterType === 'boolean' ? (
- <Select
- items={booleanItems}
- value={filter.value || undefined}
- onValueChange={(val) => updateFilter(filter.id, { value: val })}
- >
- <SelectTrigger size="sm" className="min-w-[8rem] flex-1">
- <SelectValue
- placeholder={t('admin.components.table_toolbar.filter_select_placeholder')}
- />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="true">{t('admin.common.yes')}</SelectItem>
- <SelectItem value="false">{t('admin.common.no')}</SelectItem>
- </SelectContent>
- </Select>
- ) : col?.filterType === 'date' ? (
- // Filter values are stored as plain strings; for dates we
- // persist `yyyy-MM-dd`, which Ransack accepts as-is for
- // `*_eq`/`*_gt`/`*_lt`. The picker emits `yyyy-MM-dd`
- // directly in date-only mode.
- <div className="flex-1">
- <StoreDatePicker
- value={filter.value || null}
- onChange={(next) => updateFilter(filter.id, { value: next ?? '' })}
- placeholder={t('admin.components.table_toolbar.filter_date_placeholder')}
- />
- </div>
- ) : (
- <Input
- type={col?.filterType === 'number' ? 'number' : 'text'}
- className="flex-1 py-1 px-2 text-sm h-7"
- placeholder={t('admin.components.table_toolbar.filter_text_placeholder')}
- value={filter.value}
- onChange={(e) => updateFilter(filter.id, { value: e.target.value })}
- />
- ))}
+ {/* Scrolls, and says so. `overscroll-contain` keeps a flick at the end of
+ the list from scrolling the page behind the panel; the themed
+ scrollbar the popover supplies is what tells the reader there is more
+ below, since the rows themselves end flush at the container's edge. */}
+ <div className="max-h-[320px] overflow-y-auto overscroll-contain p-1 themed-scrollbar">
+ {/* Stage one: pick a subject. */}
+ {!field &&
+ visibleFields.map((col) => (
+ <button
+ key={col.key}
+ type="button"
+ data-slot="filter-panel-item"
+ className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ onClick={() => chooseField(col.key)}
+ >
+ {col.label}
+ <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" />
+ </button>
+ ))}
+ {/* Stage two, list-shaped types: the values themselves, one click to
+ apply. No operator control — "is" is the only thing a list of
+ values can mean, and offering "is not" here would double the list's
+ length for a case the panel's other branch already covers. */}
+ {field &&
+ listed &&
+ !multi &&
+ listOptions.map((option) => (
+ <button
+ key={option.value}
+ type="button"
+ data-slot="filter-panel-item"
+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ onClick={() => commit(option.value, 'eq')}
+ >
+ {/* Booleans get one too: their values carry the same
+ green/red reading as any other state. */}
+ {(type === 'enum' || type === 'boolean') && <StatusDot status={option.value} />}
+ {option.label}
+ </button>
+ ))}
+
+ {/* Tags and resources: several values at once. Each tick applies
+ immediately and the list stays open, so narrowing to two sellers is
+ two clicks rather than two clicks and a confirmation — the table
+ behind the panel is already showing the result. */}
+ {field && multi && column && (
+ <InlineValueList
+ column={column}
+ tenantId={tenantId}
+ query={query}
+ selected={parseFilterIds(value)}
+ onToggle={toggleValue}
+ />
+ )}
+
+ {/* Stage two, dates: the same relative presets the quick filter
+ offers, so a range means the same thing wherever it was set.
+ "Custom" swaps in two date fields rather than opening a third
+ popup on top of this one. */}
+ {field && dated && !customRange && (
+ <>
+ {DATE_PRESET_KEYS.map((preset) => (
<button
+ key={preset}
type="button"
- className="p-1 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 shrink-0"
- onClick={() => removeFilter(filter.id)}
+ data-slot="filter-panel-item"
+ className="flex w-full items-center rounded-lg px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ onClick={() => commitDatePreset(preset)}
>
- <Trash2Icon className="size-3.5" />
+ {t(`admin.components.table_toolbar.date_presets.${preset}`)}
</button>
+ ))}
+ <button
+ type="button"
+ data-slot="filter-panel-item"
+ className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ onClick={() => setCustomRange({ from: '', to: '' })}
+ >
+ {t('admin.components.table_toolbar.date_presets.custom')}
+ <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" />
+ </button>
+ </>
+ )}
+
+ {field && dated && customRange && (
+ <div data-slot="filter-panel-controls" className="flex flex-col gap-2 p-2">
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-muted-foreground">
+ {t('admin.components.table_toolbar.date_range_start')}
+ </span>
+ <StoreDatePicker
+ value={customRange.from || null}
+ onChange={(next) => setCustomRange({ ...customRange, from: next ?? '' })}
+ placeholder={t('admin.components.table_toolbar.filter_date_placeholder')}
+ />
</div>
- )
- })}
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-muted-foreground">
+ {t('admin.components.table_toolbar.date_range_end')}
+ </span>
+ <StoreDatePicker
+ value={customRange.to || null}
+ onChange={(next) => setCustomRange({ ...customRange, to: next ?? '' })}
+ placeholder={t('admin.components.table_toolbar.filter_date_placeholder')}
+ />
+ </div>
+ <div className="flex justify-end gap-1.5">
+ <Button variant="ghost" size="sm" onClick={() => setCustomRange(null)}>
+ {t('admin.actions.back')}
+ </Button>
+ <Button
+ size="sm"
+ // Either bound alone is a valid filter — "everything since
+ // March" is a question people ask.
+ disabled={!customRange.from && !customRange.to}
+ onClick={() => {
+ if (!field) return
+ const others = filters.filter(
+ (f) => !(f.field === field && (f.operator === 'gteq' || f.operator === 'lteq')),
+ )
+ const next = [...others]
+ if (customRange.from) {
+ next.push({
+ id: crypto.randomUUID(),
+ field,
+ operator: 'gteq',
+ value: customRange.from,
+ })
+ }
+ if (customRange.to) {
+ next.push({
+ id: crypto.randomUUID(),
+ field,
+ operator: 'lteq',
+ value: customRange.to,
+ })
+ }
+ onApply(next)
+ }}
+ >
+ {t('admin.actions.apply')}
+ </Button>
+ </div>
+ </div>
+ )}
- {draft.length === 0 && (
- <p className="text-xs text-muted-foreground text-center py-4">
- {t('admin.components.table_toolbar.no_filters')}
- </p>
+ {/* Stage two, everything else: an operator and a value. The operator
+ lives here rather than in the header because it only exists for
+ these types — a text column's "contains" versus "starts with" is a
+ real choice, where a status has nothing to choose. */}
+ {field && !listed && !dated && (
+ <div data-slot="filter-panel-controls" className="flex flex-col gap-2 p-2">
+ <Select items={operators} value={operator} onValueChange={setOperator}>
+ <SelectTrigger size="sm">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {operators.map((op) => (
+ <SelectItem key={op.value} value={op.value}>
+ {op.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ {/* Everything picked from a list — currency, tags, resources — or
+ from a calendar is handled above; this branch is only the types
+ you type into. */}
+ {!noValueOperators.includes(operator) && (
+ <Input
+ type={type === 'number' ? 'number' : 'text'}
+ placeholder={t('admin.components.table_toolbar.filter_text_placeholder')}
+ value={value}
+ onChange={(event) => setValue(event.target.value)}
+ // Enter applies, so a text filter is type-and-go rather than
+ // type-then-reach-for-the-button.
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault()
+ commit(value)
+ }
+ }}
+ />
+ )}
+
+ {/* Right-aligned rather than stretched: a full-width black bar
+ reads as the panel's primary purpose, when it is one step in a
+ filter the operator is still composing. */}
+ <div className="flex justify-end">
+ <Button size="sm" onClick={() => commit(value)}>
+ {t('admin.actions.apply')}
+ </Button>
+ </div>
+ </div>
)}
- </div>
- <div className="flex items-center justify-between border-t px-3 py-2">
- <Button variant="ghost" size="sm" onClick={addFilter}>
- <PlusIcon className="size-3.5" />
- {t('admin.components.table_toolbar.add_filter')}
- </Button>
- <div className="flex gap-1.5">
- {draft.length > 0 && (
- <Button variant="ghost" size="sm" onClick={() => setDraft([])}>
- {t('admin.actions.clear')}
- </Button>
- )}
- <Button size="sm" onClick={handleApply}>
- {t('admin.actions.apply')}
- </Button>
- </div>
+ {/* Nothing matched the search — say so rather than showing a blank
+ panel that reads as broken. */}
+ {((!field && visibleFields.length === 0) ||
+ (field && listed && !multi && listOptions.length === 0)) && (
+ <p className="px-2 py-6 text-center text-sm text-muted-foreground">
+ {t('admin.common.no_results')}
+ </p>
+ )}
</div>
</div>
)
diff --git a/packages/dashboard-core/src/components/tag-combobox.tsx b/packages/dashboard-core/src/components/tag-combobox.tsx
index f01abf1f63..68d5477ea9 100644
--- a/packages/dashboard-core/src/components/tag-combobox.tsx
+++ b/packages/dashboard-core/src/components/tag-combobox.tsx
@@ -16,6 +16,7 @@ import { useTranslation } from 'react-i18next'
import { getApiClient } from '../api-client'
import { useAuth } from '../hooks/use-auth'
import type { TaggableType } from '../lib/table-registry'
+import { useTenantId } from '../providers/tenant-provider'
export type { TaggableType }
@@ -35,13 +36,16 @@ export function TagCombobox({
const anchorRef = useComboboxAnchor()
const [inputValue, setInputValue] = useState('')
const { isAuthenticated } = useAuth()
+ const tenantId = useTenantId()
// Through the registered client, so a panel without a tag vocabulary
// simply has none rather than calling an API it holds no key for.
const tagsClient = getApiClient().tags
const { data } = useQuery({
- queryKey: ['panel-tags', taggableType],
+ // Tenant-scoped: tag vocabularies are per-store, so a shared key would
+ // serve one store's tags to the next for as long as the result stays fresh.
+ queryKey: ['panel-tags', tenantId, taggableType],
queryFn: () => tagsClient?.list({ taggable_type: taggableType }),
enabled: isAuthenticated && Boolean(tagsClient),
staleTime: 60_000,
diff --git a/packages/dashboard-core/src/components/top-bar.tsx b/packages/dashboard-core/src/components/top-bar.tsx
index 9d6cf10065..d21dfb7a23 100644
--- a/packages/dashboard-core/src/components/top-bar.tsx
+++ b/packages/dashboard-core/src/components/top-bar.tsx
@@ -261,7 +261,7 @@ export function TopBarUser({
{t('admin.account.contact_support')}
</DropdownMenuItem>
<DropdownMenuSeparator />
- <DropdownMenuItem onClick={logout} variant="destructive">
+ <DropdownMenuItem onClick={logout}>
<LogOutIcon className="size-4" />
{t('admin.account.log_out')}
</DropdownMenuItem>
diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.ts
index d7aacdb065..c991590679 100644
--- a/packages/dashboard-core/src/index.ts
+++ b/packages/dashboard-core/src/index.ts
@@ -71,6 +71,7 @@ export * from './lib/create-action-registry'
// settings-nav, form fields, custom field components)
// ---------------------------------------------------------------------------
export * from './lib/custom-field-components'
+export * from './lib/date-presets'
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
diff --git a/packages/dashboard-core/src/lib/date-presets.test.ts b/packages/dashboard-core/src/lib/date-presets.test.ts
new file mode 100644
index 0000000000..f28ea8611b
--- /dev/null
+++ b/packages/dashboard-core/src/lib/date-presets.test.ts
@@ -0,0 +1,86 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { matchDatePreset, resolveDatePreset } from './date-presets'
+
+// A fixed instant with a deliberately awkward property: 23:30 UTC on the 15th
+// is already the 16th in Sydney and still the 15th in Los Angeles. Every
+// assertion below turns on which calendar the range is computed against.
+const INSTANT = new Date('2026-03-15T23:30:00Z')
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(INSTANT)
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+describe('resolveDatePreset', () => {
+ it('reads "today" on the store\'s calendar, not the viewer\'s', () => {
+ // Same instant, three zones, three different answers for "today". This is
+ // the whole reason the timezone is threaded through.
+ expect(resolveDatePreset('today', 'America/Los_Angeles')).toEqual({
+ from: '2026-03-15',
+ to: '2026-03-15',
+ })
+ expect(resolveDatePreset('today', 'UTC')).toEqual({ from: '2026-03-15', to: '2026-03-15' })
+ expect(resolveDatePreset('today', 'Australia/Sydney')).toEqual({
+ from: '2026-03-16',
+ to: '2026-03-16',
+ })
+ })
+
+ it('counts "last 7 days" inclusively, so it spans exactly 7 dates', () => {
+ expect(resolveDatePreset('last_7_days', 'UTC')).toEqual({
+ from: '2026-03-09',
+ to: '2026-03-15',
+ })
+ })
+
+ it('runs "this month" from the 1st to today', () => {
+ expect(resolveDatePreset('this_month', 'UTC')).toEqual({
+ from: '2026-03-01',
+ to: '2026-03-15',
+ })
+ })
+
+ it('ends "last month" the day before this one starts, whatever its length', () => {
+ // February 2026 has 28 days — derived, never assumed.
+ expect(resolveDatePreset('last_month', 'UTC')).toEqual({
+ from: '2026-02-01',
+ to: '2026-02-28',
+ })
+ })
+
+ it('treats "all" as unbounded on both sides', () => {
+ expect(resolveDatePreset('all', 'UTC')).toEqual({ from: null, to: null })
+ })
+})
+
+describe('matchDatePreset', () => {
+ it('recognises a range it produced, so a restored filter re-selects its entry', () => {
+ const range = resolveDatePreset('last_30_days', 'UTC')
+ expect(matchDatePreset(range, 'UTC')).toBe('last_30_days')
+ })
+
+ it('reads empty bounds as "all"', () => {
+ expect(matchDatePreset({ from: null, to: null }, 'UTC')).toBe('all')
+ })
+
+ it('reads a hand-picked range as custom', () => {
+ expect(matchDatePreset({ from: '2026-01-02', to: '2026-01-09' }, 'UTC')).toBe('custom')
+ })
+
+ it('reads a stale preset as custom once it no longer matches', () => {
+ // Yesterday's "last 7 days", reopened today, is a fixed range that no
+ // preset would produce now — calling it "Last 7 days" would misdescribe
+ // what the list is actually filtered to.
+ const stale = { from: '2026-03-08', to: '2026-03-14' }
+ expect(matchDatePreset(stale, 'UTC')).toBe('custom')
+ })
+
+ it('does not match a range computed in another zone', () => {
+ const sydney = resolveDatePreset('today', 'Australia/Sydney')
+ expect(matchDatePreset(sydney, 'America/Los_Angeles')).toBe('custom')
+ })
+})
diff --git a/packages/dashboard-core/src/lib/date-presets.ts b/packages/dashboard-core/src/lib/date-presets.ts
new file mode 100644
index 0000000000..cdcbacf179
--- /dev/null
+++ b/packages/dashboard-core/src/lib/date-presets.ts
@@ -0,0 +1,98 @@
+import { format, startOfMonth, subDays, subMonths } from 'date-fns'
+import { toZonedTime } from 'date-fns-tz'
+
+/**
+ * Relative date ranges offered by the toolbar's quick date filter.
+ *
+ * `null` bounds mean "unbounded on that side", which is how `all` clears the
+ * filter without needing a separate signal.
+ */
+export type DatePresetKey =
+ | 'all'
+ | 'today'
+ | 'last_7_days'
+ | 'last_30_days'
+ | 'this_month'
+ | 'last_month'
+ | 'custom'
+
+/** Presets in menu order. `custom` is handled by the panel, not by this table. */
+export const DATE_PRESET_KEYS: DatePresetKey[] = [
+ 'all',
+ 'today',
+ 'last_7_days',
+ 'last_30_days',
+ 'this_month',
+ 'last_month',
+]
+
+export interface DateRange {
+ /** Inclusive lower bound as `yyyy-MM-dd`, or null for unbounded. */
+ from: string | null
+ /** Inclusive upper bound as `yyyy-MM-dd`, or null for unbounded. */
+ to: string | null
+}
+
+/**
+ * Resolve a preset into concrete `yyyy-MM-dd` bounds.
+ *
+ * The timezone argument is not decoration: these ranges are relative to *now*,
+ * and "today" means today where the merchant trades. Computing them in the
+ * browser's zone puts the boundary hours off for anyone checking a store from
+ * another country — and it moves depending on who is looking, which makes a
+ * shared link mean different things to two people.
+ *
+ * Bounds are whole dates because that is what the filter stores and what
+ * Ransack compares against; the day itself is the smallest unit a merchant
+ * reasons about here.
+ */
+export function resolveDatePreset(preset: DatePresetKey, timezone: string): DateRange {
+ if (preset === 'all' || preset === 'custom') return { from: null, to: null }
+
+ // "Now" shifted so that reading its *local* fields yields the store's
+ // wall-clock date. All arithmetic below then happens on the merchant's
+ // calendar, and `format` reads those same local fields back out.
+ //
+ // `formatInTimeZone` must not be used on these values: it would convert a
+ // second time, moving every bound by the offset that was already applied.
+ const now = toZonedTime(new Date(), timezone)
+ const day = (date: Date) => format(date, 'yyyy-MM-dd')
+
+ switch (preset) {
+ case 'today':
+ return { from: day(now), to: day(now) }
+ case 'last_7_days':
+ return { from: day(subDays(now, 6)), to: day(now) }
+ case 'last_30_days':
+ return { from: day(subDays(now, 29)), to: day(now) }
+ case 'this_month':
+ return { from: day(startOfMonth(now)), to: day(now) }
+ case 'last_month': {
+ const previous = subMonths(now, 1)
+ return {
+ from: day(startOfMonth(previous)),
+ // The day before this month starts — avoids month-length arithmetic.
+ to: day(subDays(startOfMonth(now), 1)),
+ }
+ }
+ }
+}
+
+/**
+ * Recognise which preset a pair of bounds came from, so a filter restored from
+ * the URL re-selects its menu entry instead of always reading as "Custom".
+ *
+ * Matching by value rather than storing the preset key keeps the filter a plain
+ * `FilterRule` — the preset is a way of writing a range, not a thing the rest
+ * of the pipeline has to know about. A range that no longer matches any preset
+ * (yesterday's "last 7 days", reopened today) correctly reads as custom.
+ */
+export function matchDatePreset(range: DateRange, timezone: string): DatePresetKey {
+ if (!range.from && !range.to) return 'all'
+ for (const key of DATE_PRESET_KEYS) {
+ if (key === 'all') continue
+ const candidate = resolveDatePreset(key, timezone)
+ if (candidate.from === range.from && candidate.to === range.to) return key
+ }
+ return 'custom'
+}
diff --git a/packages/dashboard-core/src/lib/filters-to-ransack.test.ts b/packages/dashboard-core/src/lib/filters-to-ransack.test.ts
new file mode 100644
index 0000000000..382c18de8d
--- /dev/null
+++ b/packages/dashboard-core/src/lib/filters-to-ransack.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest'
+import { filtersToRansack } from './filters-to-ransack'
+import type { ColumnDef, FilterRule } from './table-registry'
+
+const columns: ColumnDef[] = [
+ { key: 'completed_at', label: 'Date', filterType: 'date' },
+ { key: 'status', label: 'Status', filterType: 'enum', filterOptions: [] },
+ { key: 'tags', label: 'Tags', filterType: 'tags', taggableType: 'Spree::Product' },
+ { key: 'sku', label: 'SKU', ransackAttribute: 'master_sku' },
+]
+
+const rule = (partial: Partial<FilterRule>): FilterRule => ({
+ id: 'r1',
+ field: 'completed_at',
+ operator: 'lteq',
+ value: '2026-08-29',
+ ...partial,
+})
+
+describe('filtersToRansack', () => {
+ it('carries a date upper bound to the end of its day', () => {
+ // The columns these target are datetimes, so a bare date casts to
+ // midnight — "up to the 29th" would drop everything that happened on the
+ // 29th, which is usually the very rows the operator is looking for.
+ expect(filtersToRansack([rule({})], columns)).toEqual({
+ completed_at_lteq: '2026-08-29 23:59:59.999999',
+ })
+ })
+
+ it('leaves a date lower bound alone, since midnight already starts the day', () => {
+ expect(filtersToRansack([rule({ operator: 'gteq', value: '2026-08-01' })], columns)).toEqual({
+ completed_at_gteq: '2026-08-01',
+ })
+ })
+
+ it('emits both ends of a range', () => {
+ const filters = [
+ rule({ id: 'a', operator: 'gteq', value: '2026-08-01' }),
+ rule({ id: 'b', operator: 'lteq', value: '2026-08-29' }),
+ ]
+ expect(filtersToRansack(filters, columns)).toEqual({
+ completed_at_gteq: '2026-08-01',
+ completed_at_lteq: '2026-08-29 23:59:59.999999',
+ })
+ })
+
+ it('does not widen a non-date column that happens to use lteq', () => {
+ const columnsWithNumber: ColumnDef[] = [
+ ...columns,
+ { key: 'total', label: 'Total', filterType: 'number' },
+ ]
+ const filters = [rule({ field: 'total', operator: 'lteq', value: '100' })]
+ expect(filtersToRansack(filters, columnsWithNumber)).toEqual({ total_lteq: '100' })
+ })
+
+ it('splits array operators into a list', () => {
+ const filters = [rule({ field: 'status', operator: 'in', value: 'active,draft' })]
+ expect(filtersToRansack(filters, columns)).toEqual({ status_in: ['active', 'draft'] })
+ })
+
+ it('drops an array operator with no values rather than filtering by nothing', () => {
+ const filters = [rule({ field: 'status', operator: 'in', value: '' })]
+ expect(filtersToRansack(filters, columns)).toEqual({})
+ })
+
+ it('targets the join column for tags', () => {
+ const filters = [rule({ field: 'tags', operator: 'in', value: 'sale' })]
+ expect(filtersToRansack(filters, columns)).toEqual({ tags_name_in: ['sale'] })
+ })
+
+ it('honours an explicit ransack alias', () => {
+ const filters = [rule({ field: 'sku', operator: 'i_cont', value: 'ABC' })]
+ expect(filtersToRansack(filters, columns)).toEqual({ master_sku_i_cont: 'ABC' })
+ })
+})
diff --git a/packages/dashboard-core/src/lib/filters-to-ransack.ts b/packages/dashboard-core/src/lib/filters-to-ransack.ts
index eed1d23a0a..639776e43d 100644
--- a/packages/dashboard-core/src/lib/filters-to-ransack.ts
+++ b/packages/dashboard-core/src/lib/filters-to-ransack.ts
@@ -39,6 +39,20 @@ export function filtersToRansack(
if (ARRAY_OPERATORS.has(filter.operator)) {
const ids = parseFilterIds(filter.value)
if (ids.length > 0) out[key] = ids
+ } else if (col?.filterType === 'date' && filter.operator === 'lteq') {
+ // A date filter's upper bound is a whole day, but the columns it targets
+ // are datetimes: Ransack casts `2026-08-29` to midnight, so "up to the
+ // 29th" would drop everything that happened during the 29th. Carry the
+ // day's last instant instead — to the microsecond, since Rails defaults
+ // datetime columns to that precision and a bound of `23:59:59` would
+ // drop the final second of the day. The lower bound needs no such
+ // treatment: midnight is already the start of its day.
+ //
+ // Both ends are read in the server's zone, so a store trading far from
+ // it sees the same edge-of-day skew its other date filters already have.
+ // Fixing that means sending zoned bounds, which is a change to the
+ // filter wire format rather than to this conversion.
+ out[key] = `${filter.value} 23:59:59.999999`
} else {
out[key] = filter.value
}
diff --git a/packages/dashboard-core/src/lib/table-registry.ts b/packages/dashboard-core/src/lib/table-registry.ts
index 5329961975..490d8be094 100644
--- a/packages/dashboard-core/src/lib/table-registry.ts
+++ b/packages/dashboard-core/src/lib/table-registry.ts
@@ -26,6 +26,20 @@ interface ColumnDefBase<T = any> {
className?: string
/** Whether this column is displayable in the table. Set to false for filter-only columns. */
displayable?: boolean
+ /**
+ * Surface this column as a always-visible control in the toolbar, beside the
+ * search field, instead of only inside the filter popover.
+ *
+ * For the handful of filters an operator reaches for constantly — a status,
+ * a date range — the popover costs an open, an "Add filter", a field pick, a
+ * value pick and an Apply. A quick filter is the same `FilterRule` reached in
+ * one click, so it shares the URL state, the chips and the export with
+ * everything set the long way.
+ *
+ * Only `enum`/`boolean` (multi-select) and `date` (relative presets) render
+ * one; the flag is ignored on other filter types.
+ */
+ quickFilter?: boolean
}
/**
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index 3cafa64d11..8667d05f3d 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -405,12 +405,23 @@
"ascending": "تصاعدي",
"clear_all": "مسح الكل",
"columns_tooltip": "الأعمدة",
+ "date_presets": {
+ "all": "أي تاريخ",
+ "custom": "مخصص",
+ "last_30_days": "آخر 30 يومًا",
+ "last_7_days": "آخر 7 أيام",
+ "last_month": "الشهر الماضي",
+ "this_month": "هذا الشهر",
+ "today": "اليوم"
+ },
+ "date_range_end": "إلى",
+ "date_range_start": "من",
"descending": "تنازلي",
+ "filter_by": "تصفية حسب…",
"filter_date_placeholder": "اختر تاريخًا",
"filter_select_placeholder": "اختر…",
"filter_text_placeholder": "تصفية…",
- "filters_button": "الفلاتر",
- "no_filters": "لا توجد فلاتر. انقر أدناه لإضافة واحد.",
+ "filter_to_placeholder": "التصفية إلى…",
"operators": {
"after": "بعد",
"before": "قبل",
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index 435f70baa0..d182c054fd 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -405,12 +405,23 @@
"ascending": "Aufsteigend",
"clear_all": "Alle löschen",
"columns_tooltip": "Spalten",
+ "date_presets": {
+ "all": "Beliebiges Datum",
+ "custom": "Benutzerdefiniert",
+ "last_30_days": "Letzte 30 Tage",
+ "last_7_days": "Letzte 7 Tage",
+ "last_month": "Letzten Monat",
+ "this_month": "Diesen Monat",
+ "today": "Heute"
+ },
+ "date_range_end": "Bis",
+ "date_range_start": "Von",
"descending": "Absteigend",
+ "filter_by": "Filtern nach…",
"filter_date_placeholder": "Datum auswählen",
"filter_select_placeholder": "Auswählen…",
"filter_text_placeholder": "Filtern…",
- "filters_button": "Filter",
- "no_filters": "Keine Filter. Klicken Sie unten, um einen hinzuzufügen.",
+ "filter_to_placeholder": "Filtern auf…",
"operators": {
"after": "nach",
"before": "vor",
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index 5ef1303412..2087635485 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -407,12 +407,23 @@
"ascending": "Ascending",
"clear_all": "Clear all",
"columns_tooltip": "Columns",
+ "date_presets": {
+ "all": "Any date",
+ "custom": "Custom",
+ "last_30_days": "Last 30 days",
+ "last_7_days": "Last 7 days",
+ "last_month": "Last month",
+ "this_month": "This month",
+ "today": "Today"
+ },
+ "date_range_end": "End",
+ "date_range_start": "Start",
"descending": "Descending",
+ "filter_by": "Filter by…",
"filter_date_placeholder": "Pick a date",
"filter_select_placeholder": "Select…",
"filter_text_placeholder": "Filter…",
- "filters_button": "Filters",
- "no_filters": "No filters. Click below to add one.",
+ "filter_to_placeholder": "Filter to…",
"operators": {
"after": "after",
"before": "before",
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index 0c9c75f294..f1e3712ca5 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -405,12 +405,23 @@
"ascending": "Croissant",
"clear_all": "Tout effacer",
"columns_tooltip": "Colonnes",
+ "date_presets": {
+ "all": "Toute date",
+ "custom": "Personnalisé",
+ "last_30_days": "30 derniers jours",
+ "last_7_days": "7 derniers jours",
+ "last_month": "Le mois dernier",
+ "this_month": "Ce mois-ci",
+ "today": "Aujourd'hui"
+ },
+ "date_range_end": "Fin",
+ "date_range_start": "Début",
"descending": "Décroissant",
+ "filter_by": "Filtrer par…",
"filter_date_placeholder": "Choisir une date",
"filter_select_placeholder": "Sélectionner…",
"filter_text_placeholder": "Filtrer…",
- "filters_button": "Filtres",
- "no_filters": "Aucun filtre. Cliquez ci-dessous pour en ajouter un.",
+ "filter_to_placeholder": "Filtrer sur…",
"operators": {
"after": "après",
"before": "avant",
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index 5e584f782d..8e31dad082 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -405,12 +405,23 @@
"ascending": "Rosnąco",
"clear_all": "Wyczyść wszystko",
"columns_tooltip": "Kolumny",
+ "date_presets": {
+ "all": "Dowolna data",
+ "custom": "Niestandardowy",
+ "last_30_days": "Ostatnie 30 dni",
+ "last_7_days": "Ostatnie 7 dni",
+ "last_month": "Poprzedni miesiąc",
+ "this_month": "Ten miesiąc",
+ "today": "Dzisiaj"
+ },
+ "date_range_end": "Do",
+ "date_range_start": "Od",
"descending": "Malejąco",
+ "filter_by": "Filtruj według…",
"filter_date_placeholder": "Wybierz datę",
"filter_select_placeholder": "Wybierz…",
"filter_text_placeholder": "Filtruj…",
- "filters_button": "Filtry",
- "no_filters": "Brak filtrów. Kliknij poniżej, aby dodać filtr.",
+ "filter_to_placeholder": "Filtruj do…",
"operators": {
"after": "po",
"before": "przed",
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index 826e585b7d..19cda1a68d 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -405,12 +405,23 @@
"ascending": "升序",
"clear_all": "全部清除",
"columns_tooltip": "列",
+ "date_presets": {
+ "all": "任意日期",
+ "custom": "自定义",
+ "last_30_days": "最近 30 天",
+ "last_7_days": "最近 7 天",
+ "last_month": "上月",
+ "this_month": "本月",
+ "today": "今天"
+ },
+ "date_range_end": "结束",
+ "date_range_start": "开始",
"descending": "降序",
+ "filter_by": "筛选依据…",
"filter_date_placeholder": "选择日期",
"filter_select_placeholder": "选择…",
"filter_text_placeholder": "筛选…",
- "filters_button": "筛选",
- "no_filters": "暂无筛选条件。点击下方添加。",
+ "filter_to_placeholder": "筛选至…",
"operators": {
"after": "晚于",
"before": "早于",
diff --git a/packages/dashboard-core/src/tables/stock-locations.tsx b/packages/dashboard-core/src/tables/stock-locations.tsx
index d6e47428fa..538411690d 100644
--- a/packages/dashboard-core/src/tables/stock-locations.tsx
+++ b/packages/dashboard-core/src/tables/stock-locations.tsx
@@ -16,7 +16,6 @@ defineTable<PanelStockLocation>('stock-locations', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (sl) => (
<ResourceNameCell
@@ -42,6 +41,7 @@ defineTable<PanelStockLocation>('stock-locations', {
label: i18n.t('admin.stock_locations.kinds.fulfillment_center'),
},
],
+ quickFilter: true,
render: (sl) => {
const key = `admin.stock_locations.kinds.${sl.kind}`
const label = i18n.exists(key) ? i18n.t(key) : sl.kind.replace('_', ' ')
diff --git a/packages/dashboard-ui/src/styles.css b/packages/dashboard-ui/src/styles.css
index 305c76198e..f62e428784 100644
--- a/packages/dashboard-ui/src/styles.css
+++ b/packages/dashboard-ui/src/styles.css
@@ -245,6 +245,7 @@
— including the `calc(var(--radius-2xl) - 1px)` a card header derives its
own corner from, which would drift out of alignment if the components
were each edited by hand instead. */
+ --radius-sm: 0.4rem;
--radius-md: 0.5rem;
--radius-lg: 0.625rem;
--radius-xl: 0.875rem;
@@ -493,7 +494,8 @@
[data-slot='sidebar-menu-sub-button'],
[data-slot='dropdown-menu-item'],
[data-slot='select-item'],
- [data-slot='command-item'] {
+ [data-slot='command-item'],
+ [data-slot='filter-panel-item'] {
font-size: 1rem !important;
}
}
@@ -510,7 +512,21 @@
[data-slot='dropdown-menu-sub-trigger'],
[data-slot='select-item'],
[data-slot='command-item'],
- [data-slot='combobox-item'] {
+ [data-slot='combobox-item'],
+ /* The filter panel's own rows: fields, values and date presets. They are
+ hand-rolled buttons rather than menu items, so they carry this slot
+ deliberately to opt into the same touch sizing. */
+ [data-slot='filter-panel-item'] {
+ min-height: 2.75rem !important;
+ }
+
+ /* The controls inside the filter panel's value step — the operator select,
+ its input and the buttons under them. They are sized for a pointer
+ (`size="sm"`, roughly 30px), which is below the touch minimum on the one
+ surface where a merchant is most likely to be on a phone. */
+ [data-slot='filter-panel-controls'] [data-slot='select-trigger'],
+ [data-slot='filter-panel-controls'] [data-slot='input'],
+ [data-slot='filter-panel-controls'] button {
min-height: 2.75rem !important;
}
}
diff --git a/packages/dashboard-ui/src/ui/badge.tsx b/packages/dashboard-ui/src/ui/badge.tsx
index 1458ce98f0..03c5454afd 100644
--- a/packages/dashboard-ui/src/ui/badge.tsx
+++ b/packages/dashboard-ui/src/ui/badge.tsx
@@ -1,5 +1,4 @@
import { cva, type VariantProps } from 'class-variance-authority'
-import { CheckIcon } from 'lucide-react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { cn } from '../lib/utils'
@@ -61,11 +60,22 @@ function Badge({
)
}
-// Maps order/payment/etc. status strings to one of the canonical Badge
-// variants. Success-y states ("active", "paid", "shipped", …) route through
-// the `success` variant so the UI stays color-coded; everything else leans
-// on the canonical shadcn variants with shape + label carrying meaning.
-const statusVariantMap: Record<string, VariantProps<typeof badgeVariants>['variant']> = {
+/**
+ * Semantic tone of a status, independent of how it is drawn. `StatusBadge`
+ * renders it as a coloured dot, `Badge` as a tinted pill — same vocabulary,
+ * two presentations.
+ */
+type StatusTone = 'success' | 'warning' | 'destructive' | 'info' | 'neutral'
+
+/**
+ * Maps an order/payment/product status code to its semantic tone.
+ *
+ * Kept as one table because the same codes surface in tables, cards, page
+ * headers and filter menus — a local copy in any one of those is how two
+ * surfaces end up disagreeing about what "pending" looks like. Extend it
+ * rather than branching on status at a call site.
+ */
+const statusToneMap: Record<string, StatusTone> = {
active: 'success',
authorized: 'info',
complete: 'success',
@@ -79,20 +89,20 @@ const statusVariantMap: Record<string, VariantProps<typeof badgeVariants>['varia
approved: 'success',
verified: 'success',
unverified: 'destructive',
- unavailable: 'secondary',
- unsupported: 'secondary',
+ unavailable: 'neutral',
+ unsupported: 'neutral',
revoked: 'destructive',
expired: 'destructive',
ready: 'warning',
available: 'success',
- draft: 'outline',
+ draft: 'neutral',
pending: 'warning',
processing: 'warning',
- inactive: 'secondary',
- confirm: 'outline',
- resumed: 'secondary',
+ inactive: 'neutral',
+ confirm: 'neutral',
+ resumed: 'neutral',
partial: 'info',
- archived: 'secondary',
+ archived: 'neutral',
returned: 'success',
backorder: 'warning',
balance_due: 'warning',
@@ -101,18 +111,74 @@ const statusVariantMap: Record<string, VariantProps<typeof badgeVariants>['varia
suspended: 'destructive',
invited: 'info',
onboarding: 'warning',
+ incomplete: 'neutral',
ready_for_review: 'warning',
failed: 'destructive',
void: 'destructive',
error: 'destructive',
rejected: 'destructive',
used_up: 'destructive',
+ // Returns, exchanges and claims: amber while the merchant still owes an
+ // action, green once settled, muted when it went nowhere.
+ requested: 'warning',
+ open: 'warning',
+ received: 'warning',
+ refunded: 'success',
+ resolved: 'success',
+ denied: 'destructive',
+ // Gift cards.
+ partially_redeemed: 'info',
+ redeemed: 'neutral',
+ // Price lists — `scheduled` is live-but-not-yet, which is the same shape as
+ // any other "waiting on the clock" state.
+ scheduled: 'info',
+ // Boolean filter values. A yes/no pair is a state like any other — "in
+ // stock: no" is the row an operator is looking for, and reading it in the
+ // same green/red the rest of the app uses saves them parsing the word.
+ true: 'success',
+ false: 'destructive',
+}
+
+// Dot fills, by tone. These read the same `--status-*` ramps the tinted Badge
+// variants use, but take the *reading* step rather than the fill step: a 6px
+// dot needs the saturated end of the ramp to register at all, where a pill can
+// rely on area.
+const dotToneClasses: Record<StatusTone, string> = {
+ success: 'bg-success',
+ warning: 'bg-warning',
+ destructive: 'bg-danger',
+ info: 'bg-info',
+ neutral: 'bg-muted-foreground/50',
}
/**
- * Status pill whose color is derived from the raw status code. Stays headless:
- * pass a translated `label` from the app layer; without one it humanizes the
- * code itself (`balance_due` → `balance due`) as a best-effort fallback.
+ * Bare status dot. Decorative by construction — it carries no accessible name,
+ * so it must always sit beside text that says the same thing. Use it to align
+ * a status with its label in a menu or list; use `StatusBadge` when you want
+ * the dot and its label together.
+ */
+function StatusDot({ status, className }: { status: string; className?: string }) {
+ const tone = statusToneMap[status] ?? 'neutral'
+ return (
+ <span
+ aria-hidden
+ className={cn('inline-block size-1.5 shrink-0 rounded-full', dotToneClasses[tone], className)}
+ />
+ )
+}
+
+/**
+ * Status indicator: a coloured dot beside the label, rather than a tinted pill.
+ *
+ * A table column of pills reads as a column of coloured blocks — the eye lands
+ * on the fills instead of the words, and a row where three statuses sit side by
+ * side becomes a bar chart of nothing. A dot puts the colour where it belongs:
+ * a small mark that the label does the talking for. Colour is never the only
+ * channel, since the label is always rendered.
+ *
+ * Stays headless: pass a translated `label` from the app layer; without one it
+ * humanizes the code itself (`balance_due` → `balance due`) as a best-effort
+ * fallback.
*/
function StatusBadge({
status,
@@ -123,11 +189,18 @@ function StatusBadge({
label?: string
className?: string
}) {
- const variant = statusVariantMap[status] ?? 'outline'
return (
- <Badge variant={variant} className={cn('capitalize', className)}>
+ <span
+ data-slot="status-badge"
+ data-status={status}
+ className={cn(
+ 'inline-flex w-fit shrink-0 items-center gap-1.5 whitespace-nowrap text-sm capitalize',
+ className,
+ )}
+ >
+ <StatusDot status={status} />
{label ?? status.replace(/_/g, ' ')}
- </Badge>
+ </span>
)
}
@@ -164,22 +237,21 @@ function ActiveBadge({
const { t } = useTranslation()
const resolvedActiveLabel = activeLabel ?? t('admin.common.yes')
const resolvedInactiveLabel = inactiveLabel ?? t('admin.common.no')
- if (active) {
- return (
- <Badge variant="success" className={className}>
- <CheckIcon />
- {resolvedActiveLabel}
- </Badge>
- )
- }
- if (dashWhenInactive) {
+ if (dashWhenInactive && !active) {
return <span className={cn('text-muted-foreground', className)}>—</span>
}
+ // Boolean states read through the same map as every other status, so an
+ // "Active / Inactive" column and a "Paid / Failed" one agree on what green
+ // and red mean. The tick the active case used to carry is redundant beside
+ // a dot that already says the same thing.
return (
- <Badge variant="outline" className={className}>
- {resolvedInactiveLabel}
- </Badge>
+ <StatusBadge
+ status={active ? 'true' : 'false'}
+ label={active ? resolvedActiveLabel : resolvedInactiveLabel}
+ className={className}
+ />
)
}
-export { ActiveBadge, Badge, badgeVariants, StatusBadge }
+export type { StatusTone }
+export { ActiveBadge, Badge, badgeVariants, StatusBadge, StatusDot, statusToneMap }
diff --git a/packages/dashboard-ui/src/ui/button.tsx b/packages/dashboard-ui/src/ui/button.tsx
index 0336c5914f..9a677c790a 100644
--- a/packages/dashboard-ui/src/ui/button.tsx
+++ b/packages/dashboard-ui/src/ui/button.tsx
@@ -22,12 +22,12 @@ const buttonVariants = cva(
},
size: {
default: 'h-9 px-3 py-1.5',
- xs: "h-6 gap-1 rounded-lg px-2 text-xs [&_svg:not([class*='size-'])]:size-3",
- sm: "h-7 gap-1 rounded-lg px-2 py-1 text-sm [&_svg:not([class*='size-'])]:size-3.5",
+ xs: "h-6 gap-1 rounded-md px-2 text-xs [&_svg:not([class*='size-'])]:size-3",
+ sm: "h-7 gap-1 rounded-md px-2 py-1 text-sm [&_svg:not([class*='size-'])]:size-3.5",
lg: 'h-10 px-3 py-2 text-base',
icon: 'size-9',
- 'icon-xs': "size-6 rounded-lg [&_svg:not([class*='size-'])]:size-3",
- 'icon-sm': 'size-7 rounded-lg',
+ 'icon-xs': "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
+ 'icon-sm': 'size-7 rounded-md',
'icon-lg': 'size-10',
},
},
diff --git a/packages/dashboard-ui/src/ui/checkbox.tsx b/packages/dashboard-ui/src/ui/checkbox.tsx
index 1eee541db8..2b2f8291dc 100644
--- a/packages/dashboard-ui/src/ui/checkbox.tsx
+++ b/packages/dashboard-ui/src/ui/checkbox.tsx
@@ -25,7 +25,7 @@ function Checkbox({
disabled={disabled}
name={name}
className={cn(
- 'peer relative inline-block size-4 shrink-0 cursor-pointer rounded-[4px] border border-input align-[-3px] shadow-xs outline-none transition-shadow',
+ 'peer relative inline-block size-4 shrink-0 cursor-pointer rounded-[4px] border border-border align-[-3px] shadow-xs outline-none transition-shadow',
'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50',
'disabled:cursor-not-allowed disabled:opacity-50',
'aria-invalid:border-destructive aria-invalid:ring-destructive/20',
diff --git a/packages/dashboard-ui/src/ui/command.tsx b/packages/dashboard-ui/src/ui/command.tsx
index 5417676c30..734c75cd53 100644
--- a/packages/dashboard-ui/src/ui/command.tsx
+++ b/packages/dashboard-ui/src/ui/command.tsx
@@ -209,7 +209,7 @@ function CommandKey({ className, ...props }: React.ComponentProps<'kbd'>) {
<kbd
data-slot="command-key"
className={cn(
- 'inline-flex h-6 min-w-6 items-center justify-center rounded-md bg-card border border-border-subtle px-1.5 font-sans text-xs text-muted-foreground',
+ 'inline-flex h-5 min-w-6 items-center justify-center rounded-sm bg-card border border-border px-1 font-sans text-xs text-muted-foreground',
className,
)}
{...props}
@@ -252,7 +252,7 @@ function CommandFooter({ className, children, ...props }: React.ComponentProps<'
className={cn(
// Hidden on touch: the footer documents arrow/enter/esc shortcuts,
// which a phone has no keys for, and it costs 45px of a short viewport.
- 'hidden shrink-0 items-center justify-between gap-4 border-t border-border-subtle bg-muted px-4 py-2.5 text-muted-foreground md:flex',
+ 'hidden shrink-0 items-center justify-between gap-4 border-t border-border-subtle bg-muted px-4 py-2.5 text-muted-foreground md:flex capitalize',
className,
)}
{...props}
diff --git a/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx b/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx
index b35ae3c61f..46570ba7cb 100644
--- a/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx
+++ b/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx
@@ -18,6 +18,7 @@ import {
RelativeTime,
RowActions,
Skeleton,
+ StatusBadge,
Table,
TableBody,
TableCell,
@@ -236,7 +237,7 @@ function ApiKeyRow({
<TableCell>
<div className="flex items-center gap-2">
<span className="font-medium">{apiKey.name}</span>
- {isRevoked && <Badge variant="destructive">{t('admin.api_keys.badge.revoked')}</Badge>}
+ {isRevoked && <StatusBadge status="revoked" label={t('admin.api_keys.badge.revoked')} />}
</div>
</TableCell>
<TableCell>
diff --git a/packages/dashboard/src/components/spree/price-list-editors/status-badge.tsx b/packages/dashboard/src/components/spree/price-list-editors/status-badge.tsx
index ce539282f7..b86879c2a4 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/status-badge.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/status-badge.tsx
@@ -1,21 +1,17 @@
import type { PriceList } from '@spree/admin-sdk'
-import { Badge } from '@spree/dashboard-ui'
+import { StatusBadge } from '@spree/dashboard-ui'
import { useTranslation } from 'react-i18next'
-// `scheduled` collapses into the active treatment whenever the date
-// range puts it live now — mirrors the legacy admin's
-// `price_list_status_badge` helper.
-const STATUS_STYLES = {
- active: { variant: 'success' as const },
- scheduled: { variant: 'info' as const },
- inactive: { variant: 'secondary' as const },
- draft: { variant: 'outline' as const },
-} as const
+// Colour comes from the shared status map; this component owns only the
+// question of *which* status a price list is actually in.
+const PRICE_LIST_STATUSES = ['active', 'scheduled', 'inactive', 'draft'] as const
-type PriceListStatus = keyof typeof STATUS_STYLES
+type PriceListStatus = (typeof PRICE_LIST_STATUSES)[number]
function normalizeStatus(value: unknown): PriceListStatus {
- return typeof value === 'string' && value in STATUS_STYLES ? (value as PriceListStatus) : 'draft'
+ return typeof value === 'string' && (PRICE_LIST_STATUSES as readonly string[]).includes(value)
+ ? (value as PriceListStatus)
+ : 'draft'
}
export function PriceListStatusBadge({ priceList }: { priceList: PriceList }) {
@@ -26,9 +22,5 @@ export function PriceListStatusBadge({ priceList }: { priceList: PriceList }) {
// reports a stale `currently_active: true`.
const status: PriceListStatus = priceList.currently_active && raw !== 'inactive' ? 'active' : raw
- return (
- <Badge variant={STATUS_STYLES[status].variant}>
- {t(`admin.fields.price_list.status.${status}`)}
- </Badge>
- )
+ return <StatusBadge status={status} label={t(`admin.fields.price_list.status.${status}`)} />
}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-address-card.tsx b/packages/dashboard/src/components/spree/sellers/seller-address-card.tsx
index 878e80c982..744aad1ed5 100644
--- a/packages/dashboard/src/components/spree/sellers/seller-address-card.tsx
+++ b/packages/dashboard/src/components/spree/sellers/seller-address-card.tsx
@@ -10,6 +10,7 @@ import {
CardContent,
CardHeader,
CardTitle,
+ StatusBadge,
} from '@spree/dashboard-ui'
import { PencilIcon } from 'lucide-react'
import { useState } from 'react'
@@ -54,7 +55,7 @@ export function SellerAddressCard({
<CardTitle>
{title}
{address ? (
- <Badge variant="success">{t('admin.sellers.address.filled')}</Badge>
+ <StatusBadge status="complete" label={t('admin.sellers.address.filled')} />
) : (
<Badge variant="outline">{t('admin.sellers.address.not_filled')}</Badge>
)}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-onboarding-card.tsx b/packages/dashboard/src/components/spree/sellers/seller-onboarding-card.tsx
index dd034f8e8e..94ff93b45f 100644
--- a/packages/dashboard/src/components/spree/sellers/seller-onboarding-card.tsx
+++ b/packages/dashboard/src/components/spree/sellers/seller-onboarding-card.tsx
@@ -13,6 +13,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
Progress,
+ StatusBadge as SharedStatusBadge,
Sheet,
SheetContent,
SheetDescription,
@@ -65,7 +66,7 @@ export function SellerOnboardingCard({ seller, canEdit }: { seller: Seller; canE
<CollapsibleTrigger className="group flex w-full cursor-pointer items-center gap-3 p-4 text-left hover:bg-muted/50 border-border-subtle">
<CardTitle>{t('admin.sellers.onboarding.title')}</CardTitle>
{seller.onboarding_complete ? (
- <Badge variant="success">{t('admin.sellers.onboarding.all_done')}</Badge>
+ <SharedStatusBadge status="complete" label={t('admin.sellers.onboarding.all_done')} />
) : (
<Badge variant="secondary">
{t('admin.sellers.onboarding.progress', {
@@ -279,22 +280,36 @@ function RequirementRow({
function StatusBadge({ status, waived }: { status: string; waived: boolean }) {
const { t } = useTranslation()
+ // Only the wording is local — the colour comes from the shared status map,
+ // so this checklist agrees with every other surface showing the same states.
if (status === 'complete') {
return (
- <Badge variant="success">
- {waived
- ? t('admin.sellers.onboarding.waived')
- : t('admin.sellers.onboarding.status.complete')}
- </Badge>
+ <SharedStatusBadge
+ status="complete"
+ label={
+ waived
+ ? t('admin.sellers.onboarding.waived')
+ : t('admin.sellers.onboarding.status.complete')
+ }
+ />
)
}
if (status === 'pending') {
- return <Badge variant="secondary">{t('admin.sellers.onboarding.status.pending')}</Badge>
+ return (
+ <SharedStatusBadge status="pending" label={t('admin.sellers.onboarding.status.pending')} />
+ )
}
if (status === 'rejected') {
- return <Badge variant="destructive">{t('admin.sellers.onboarding.status.rejected')}</Badge>
+ return (
+ <SharedStatusBadge status="rejected" label={t('admin.sellers.onboarding.status.rejected')} />
+ )
}
- return <Badge variant="outline">{t('admin.sellers.onboarding.status.incomplete')}</Badge>
+ return (
+ <SharedStatusBadge
+ status="incomplete"
+ label={t('admin.sellers.onboarding.status.incomplete')}
+ />
+ )
}
function StatusIcon({ status }: { status: string }) {
diff --git a/packages/dashboard/src/components/spree/tax-exemption-certificates-card.tsx b/packages/dashboard/src/components/spree/tax-exemption-certificates-card.tsx
index da58038e6b..9e5d2141f4 100644
--- a/packages/dashboard/src/components/spree/tax-exemption-certificates-card.tsx
+++ b/packages/dashboard/src/components/spree/tax-exemption-certificates-card.tsx
@@ -194,9 +194,10 @@ export function TaxExemptionCertificatesCard({
})}
/>
{certificate.lapsed && certificate.status !== 'expired' && (
- <Badge variant="destructive">
- {t('admin.tax_exemption_certificates.lapsed')}
- </Badge>
+ <StatusBadge
+ status="expired"
+ label={t('admin.tax_exemption_certificates.lapsed')}
+ />
)}
</div>
<span className="text-muted-foreground text-xs">
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx
index f6e2ede95a..5f3b1f2e5b 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx
@@ -73,7 +73,7 @@ function CategoriesPage() {
return (
<>
<Card className="overflow-hidden rounded-xl">
- <div className="flex flex-col items-start justify-between gap-2 border-b border-border p-3 lg:flex-row lg:items-center">
+ <div className="flex flex-col items-start justify-between gap-2 border-b border-border-subtle p-3 lg:flex-row lg:items-center">
<CardTitle>{t('admin.categories.title')}</CardTitle>
<div className="flex items-center gap-2">
<InputGroup className="lg:w-[300px]">
diff --git a/packages/dashboard/src/tables/allowed-origins.tsx b/packages/dashboard/src/tables/allowed-origins.tsx
index d145510185..f3b1ec4736 100644
--- a/packages/dashboard/src/tables/allowed-origins.tsx
+++ b/packages/dashboard/src/tables/allowed-origins.tsx
@@ -16,7 +16,6 @@ defineTable<AllowedOrigin>('allowed-origins', {
key: 'origin',
label: i18n.t('admin.fields.allowed_origin.origin.label'),
sortable: true,
- filterable: true,
default: true,
render: (origin) => (
<ResourceNameCell id={origin.id} dataAttr="data-allowed-origin-id" name={origin.origin} />
diff --git a/packages/dashboard/src/tables/catalogs.tsx b/packages/dashboard/src/tables/catalogs.tsx
index 2ee6c8e985..248d207ba8 100644
--- a/packages/dashboard/src/tables/catalogs.tsx
+++ b/packages/dashboard/src/tables/catalogs.tsx
@@ -16,7 +16,6 @@ defineTable<Catalog>('catalogs', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (catalog) => (
<ResourceNameCell id={catalog.id} dataAttr="data-catalog-id" name={catalog.name} />
diff --git a/packages/dashboard/src/tables/channels.tsx b/packages/dashboard/src/tables/channels.tsx
index 1bc27c037d..0ca86967be 100644
--- a/packages/dashboard/src/tables/channels.tsx
+++ b/packages/dashboard/src/tables/channels.tsx
@@ -16,7 +16,6 @@ defineTable<Channel>('channels', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (channel) => (
<ResourceNameCell
@@ -31,7 +30,6 @@ defineTable<Channel>('channels', {
key: 'code',
label: i18n.t('admin.fields.channel.code.label'),
sortable: true,
- filterable: true,
default: true,
className: 'text-sm text-muted-foreground',
render: (channel) => channel.code,
diff --git a/packages/dashboard/src/tables/collections.tsx b/packages/dashboard/src/tables/collections.tsx
index ebbd9d0f82..219e4db962 100644
--- a/packages/dashboard/src/tables/collections.tsx
+++ b/packages/dashboard/src/tables/collections.tsx
@@ -17,7 +17,6 @@ defineTable<Collection>('collections', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (collection) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/commission-rates.tsx b/packages/dashboard/src/tables/commission-rates.tsx
index 1407ce1fc7..752fe5d894 100644
--- a/packages/dashboard/src/tables/commission-rates.tsx
+++ b/packages/dashboard/src/tables/commission-rates.tsx
@@ -19,7 +19,6 @@ defineTable<CommissionRate>('commission-rates', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (rate) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/companies.tsx b/packages/dashboard/src/tables/companies.tsx
index d02da15c78..2e36c4cd8f 100644
--- a/packages/dashboard/src/tables/companies.tsx
+++ b/packages/dashboard/src/tables/companies.tsx
@@ -17,7 +17,6 @@ defineTable<Company>('companies', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (company) => (
<ResourceNameCell
@@ -44,6 +43,7 @@ defineTable<Company>('companies', {
{ value: 'company', label: i18n.t('admin.companies.kind.company') },
{ value: 'division', label: i18n.t('admin.companies.kind.division') },
],
+ quickFilter: true,
default: true,
render: (company) => <CompanyKindBadge kind={company.kind} />,
},
diff --git a/packages/dashboard/src/tables/custom-field-definitions.tsx b/packages/dashboard/src/tables/custom-field-definitions.tsx
index c05c3f4310..4e63dcfbee 100644
--- a/packages/dashboard/src/tables/custom-field-definitions.tsx
+++ b/packages/dashboard/src/tables/custom-field-definitions.tsx
@@ -23,8 +23,10 @@ defineTable<CustomFieldDefinition>('custom-field-definitions', {
key: 'name',
label: t('admin.fields.custom_field_definition.label.label'),
sortable: true,
- filterable: true,
default: true,
+ // Not filterable: `name` is not a ransackable attribute on this model,
+ // so the predicate was rejected server-side. The label it renders is
+ // already matched by the search box.
ransackAttribute: 'name',
render: (def) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/customer-groups.tsx b/packages/dashboard/src/tables/customer-groups.tsx
index 2afc0041c3..265672ead7 100644
--- a/packages/dashboard/src/tables/customer-groups.tsx
+++ b/packages/dashboard/src/tables/customer-groups.tsx
@@ -16,7 +16,6 @@ defineTable<CustomerGroup>('customer-groups', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (g) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/customers.tsx b/packages/dashboard/src/tables/customers.tsx
index 092f228850..52ec20263e 100644
--- a/packages/dashboard/src/tables/customers.tsx
+++ b/packages/dashboard/src/tables/customers.tsx
@@ -17,7 +17,6 @@ defineTable('customers', {
key: 'email',
label: i18n.t('admin.fields.email.label'),
sortable: true,
- filterable: true,
default: true,
render: (c) => (
<Link
@@ -33,7 +32,6 @@ defineTable('customers', {
key: 'first_name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (c) => c.full_name ?? ([c.first_name, c.last_name].filter(Boolean).join(' ') || '—'),
},
@@ -41,6 +39,9 @@ defineTable('customers', {
key: 'phone',
label: i18n.t('admin.fields.phone.label'),
sortable: true,
+ // Kept filterable where email and name are not: the search scope matches
+ // those two but never `phone`, so this is the only way to look a customer
+ // up by number.
filterable: true,
default: false,
render: (c) => c.phone ?? '—',
diff --git a/packages/dashboard/src/tables/delivery-profiles.tsx b/packages/dashboard/src/tables/delivery-profiles.tsx
index 68f4ec49b7..00e0b68a50 100644
--- a/packages/dashboard/src/tables/delivery-profiles.tsx
+++ b/packages/dashboard/src/tables/delivery-profiles.tsx
@@ -16,7 +16,6 @@ defineTable<DeliveryProfile>('delivery-profiles', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (profile) => (
<div className="flex items-center gap-2">
diff --git a/packages/dashboard/src/tables/gift-cards.tsx b/packages/dashboard/src/tables/gift-cards.tsx
index 632088635d..c5a0efec04 100644
--- a/packages/dashboard/src/tables/gift-cards.tsx
+++ b/packages/dashboard/src/tables/gift-cards.tsx
@@ -1,6 +1,6 @@
import type { GiftCard } from '@spree/admin-sdk'
import { defineTable } from '@spree/dashboard-core'
-import { Badge, RelativeTime, ResourceNameCell } from '@spree/dashboard-ui'
+import { Badge, RelativeTime, ResourceNameCell, StatusBadge } from '@spree/dashboard-ui'
import i18n from 'i18next'
import { GiftIcon } from 'lucide-react'
import { adminUserAutocompleteProps } from '../hooks/use-admin-users'
@@ -18,17 +18,6 @@ const STATUS_OPTIONS = [
{ value: 'canceled', label: i18n.t('admin.gift_cards.statuses.canceled') },
] as const
-const STATUS_VARIANT: Record<
- string,
- 'success' | 'destructive' | 'secondary' | 'default' | 'outline'
-> = {
- active: 'success',
- partially_redeemed: 'default',
- redeemed: 'secondary',
- canceled: 'destructive',
- expired: 'destructive',
-}
-
function statusLabel(value: string): string {
return i18n.exists(`admin.gift_cards.statuses.${value}`)
? i18n.t(`admin.gift_cards.statuses.${value}`)
@@ -47,7 +36,6 @@ defineTable<GiftCard>('gift-cards', {
key: 'code',
label: i18n.t('admin.fields.gift_card.code.label'),
sortable: true,
- filterable: true,
default: true,
render: (g) => (
<ResourceNameCell
@@ -69,10 +57,11 @@ defineTable<GiftCard>('gift-cards', {
filterType: 'enum',
// Spread to narrow the readonly type into ColumnDef's mutable shape.
filterOptions: STATUS_OPTIONS.map(({ value, label }) => ({ value, label })),
+ quickFilter: true,
default: true,
render: (g) => {
const status = g.status ?? 'active'
- return <Badge variant={STATUS_VARIANT[status] ?? 'secondary'}>{statusLabel(status)}</Badge>
+ return <StatusBadge status={status} label={statusLabel(status)} />
},
},
{
diff --git a/packages/dashboard/src/tables/imports.tsx b/packages/dashboard/src/tables/imports.tsx
index 6ea9969043..a8d6e8a4a2 100644
--- a/packages/dashboard/src/tables/imports.tsx
+++ b/packages/dashboard/src/tables/imports.tsx
@@ -17,7 +17,6 @@ defineTable<Import>('imports', {
key: 'number',
label: i18n.t('admin.pages.settings.imports.table.number'),
sortable: true,
- filterable: true,
default: true,
render: (imp) => <ResourceNameCell id={imp.id} dataAttr="data-import-id" name={imp.number} />,
},
diff --git a/packages/dashboard/src/tables/markets.tsx b/packages/dashboard/src/tables/markets.tsx
index bd90b23305..8b0625cb05 100644
--- a/packages/dashboard/src/tables/markets.tsx
+++ b/packages/dashboard/src/tables/markets.tsx
@@ -16,7 +16,6 @@ defineTable<Market>('markets', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (market) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/option-types.tsx b/packages/dashboard/src/tables/option-types.tsx
index e94ceab41b..5df610fb85 100644
--- a/packages/dashboard/src/tables/option-types.tsx
+++ b/packages/dashboard/src/tables/option-types.tsx
@@ -22,7 +22,6 @@ defineTable<OptionType>('option-types', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (ot) => (
<ResourceNameCell
@@ -40,6 +39,7 @@ defineTable<OptionType>('option-types', {
filterable: true,
filterType: 'enum',
filterOptions: Object.entries(KIND_LABELS).map(([value, label]) => ({ value, label })),
+ quickFilter: true,
default: true,
render: (ot) => <Badge variant="secondary">{KIND_LABELS[ot.kind] ?? ot.kind}</Badge>,
},
diff --git a/packages/dashboard/src/tables/orders.tsx b/packages/dashboard/src/tables/orders.tsx
index b5eb4d75c4..91ab147f07 100644
--- a/packages/dashboard/src/tables/orders.tsx
+++ b/packages/dashboard/src/tables/orders.tsx
@@ -29,7 +29,6 @@ defineTable('orders', {
key: 'number',
label: i18n.t('admin.orders.columns.number'),
sortable: true,
- filterable: true,
default: true,
render: (order) => (
<Link
@@ -45,8 +44,10 @@ defineTable('orders', {
key: 'completed_at',
label: i18n.t('admin.orders.columns.date'),
sortable: true,
+ filterable: true,
default: true,
filterType: 'date',
+ quickFilter: true,
className: 'text-sm text-muted-foreground whitespace-nowrap',
render: (order) => <RelativeTime iso={order.completed_at} />,
},
@@ -85,6 +86,7 @@ defineTable('orders', {
{ value: 'paid', label: i18n.t('admin.orders.payment_statuses.paid') },
{ value: 'void', label: i18n.t('admin.orders.payment_statuses.void') },
],
+ quickFilter: true,
render: (order) =>
order.payment_status ? (
<StatusBadge
@@ -110,6 +112,7 @@ defineTable('orders', {
{ value: 'fulfilled', label: i18n.t('admin.orders.fulfillment_statuses.fulfilled') },
{ value: 'delivered', label: i18n.t('admin.orders.fulfillment_statuses.delivered') },
],
+ quickFilter: true,
render: (order) =>
order.fulfillment_status ? (
<StatusBadge
@@ -185,7 +188,10 @@ defineTable('orders', {
{
key: 'order_group',
label: i18n.t('admin.fields.order.order_group.label'),
- filterable: true,
+ // Not filterable by hand: the value is an opaque id, so the panel's text
+ // operators ("contains", "starts with") match it by substring and find
+ // nothing useful. The column is reached by clicking through from an
+ // order, which builds the `eq` rule this actually needs.
ransackAttribute: 'order_group_id',
default: false,
className: 'text-sm text-muted-foreground',
@@ -202,22 +208,11 @@ defineTable('orders', {
'—'
),
},
- {
- key: 'status',
- label: i18n.t('admin.fields.status.label'),
- sortable: true,
- filterable: true,
- default: false,
- filterType: 'enum',
- filterOptions: [
- { value: 'draft', label: i18n.t('admin.orders.statuses.draft') },
- { value: 'placed', label: i18n.t('admin.orders.statuses.placed') },
- { value: 'canceled', label: i18n.t('admin.orders.statuses.canceled') },
- ],
- render: (order) => (
- <StatusBadge status={order.status} label={statusLabel('statuses', order.status)} />
- ),
- },
+ // No `status` column: its three values are already answered elsewhere.
+ // Draft orders have their own page (scoped server-side by `incomplete`),
+ // and cancellation reads off `fulfillment_status`. A filter offering
+ // "draft" on a list that has already been split by that distinction only
+ // invites the operator to wonder which of the two they are looking at.
{
key: 'tags',
label: i18n.t('admin.orders.columns.tags'),
diff --git a/packages/dashboard/src/tables/payment-methods.tsx b/packages/dashboard/src/tables/payment-methods.tsx
index fe27d487aa..e25588e0e2 100644
--- a/packages/dashboard/src/tables/payment-methods.tsx
+++ b/packages/dashboard/src/tables/payment-methods.tsx
@@ -16,7 +16,6 @@ defineTable<PaymentMethod>('payment-methods', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (pm) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/policies.tsx b/packages/dashboard/src/tables/policies.tsx
index eb439a50fc..a8370a653b 100644
--- a/packages/dashboard/src/tables/policies.tsx
+++ b/packages/dashboard/src/tables/policies.tsx
@@ -16,7 +16,6 @@ defineTable<Policy>('policies', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (policy) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/post-sale.tsx b/packages/dashboard/src/tables/post-sale.tsx
index e59fb67959..f59d7d9aa1 100644
--- a/packages/dashboard/src/tables/post-sale.tsx
+++ b/packages/dashboard/src/tables/post-sale.tsx
@@ -1,29 +1,10 @@
import type { Claim, Exchange, Return } from '@spree/admin-sdk'
import { defineTable } from '@spree/dashboard-core'
-import { Badge, RelativeTime } from '@spree/dashboard-ui'
+import { RelativeTime, StatusBadge } from '@spree/dashboard-ui'
import { Link } from '@tanstack/react-router'
import i18n from 'i18next'
import { RepeatIcon, RotateCcwIcon, ShieldAlertIcon } from 'lucide-react'
-/**
- * Status colours read the same way across all three: amber while the merchant
- * still owes an action, green once settled, muted when it went nowhere.
- */
-const STATUS_VARIANT: Record<
- string,
- 'success' | 'destructive' | 'secondary' | 'default' | 'outline'
-> = {
- requested: 'default',
- open: 'default',
- approved: 'default',
- received: 'default',
- refunded: 'success',
- fulfilled: 'success',
- resolved: 'success',
- denied: 'destructive',
- canceled: 'secondary',
-}
-
/**
* The record's own number, linking to the order it belongs to — that page is
* where it can actually be actioned, so there is nowhere else useful to go.
@@ -57,11 +38,10 @@ function statusColumn(values: string[]) {
filterable: true,
filterType: 'enum' as const,
filterOptions: values.map((value) => ({ value, label: statusLabel(value) })),
+ quickFilter: true,
default: true,
render: (record: { status: string }) => (
- <Badge variant={STATUS_VARIANT[record.status] ?? 'secondary'}>
- {statusLabel(record.status)}
- </Badge>
+ <StatusBadge status={record.status} label={statusLabel(record.status)} />
),
}
}
diff --git a/packages/dashboard/src/tables/price-lists.tsx b/packages/dashboard/src/tables/price-lists.tsx
index eafd25d980..63e850071b 100644
--- a/packages/dashboard/src/tables/price-lists.tsx
+++ b/packages/dashboard/src/tables/price-lists.tsx
@@ -17,7 +17,6 @@ defineTable<PriceList>('price-lists', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (list) => (
<ResourceNameCell
@@ -40,7 +39,14 @@ defineTable<PriceList>('price-lists', {
{ value: 'scheduled', label: i18n.t('admin.fields.price_list.status.scheduled') },
{ value: 'inactive', label: i18n.t('admin.fields.price_list.status.inactive') },
],
+ quickFilter: true,
default: true,
+ // Filters the stored `status`, which is the only thing the API can
+ // filter on — `currently_active?` is a Ruby predicate, not a ransackable
+ // attribute. The badge shows a `scheduled` list that is within its dates
+ // as Active, so filtering by Active omits those rows. Closing that gap
+ // needs an effective-status scope server-side; until then the filter
+ // names the stored value and the badge names the effective one.
render: (list) => <PriceListStatusBadge priceList={list} />,
},
{
diff --git a/packages/dashboard/src/tables/product-types.tsx b/packages/dashboard/src/tables/product-types.tsx
index 39b9b3692e..9872301b2d 100644
--- a/packages/dashboard/src/tables/product-types.tsx
+++ b/packages/dashboard/src/tables/product-types.tsx
@@ -16,7 +16,6 @@ defineTable<ProductType>('product-types', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (productType) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/products.tsx b/packages/dashboard/src/tables/products.tsx
index 7eda464660..2c39e8ceea 100644
--- a/packages/dashboard/src/tables/products.tsx
+++ b/packages/dashboard/src/tables/products.tsx
@@ -21,7 +21,6 @@ defineTable('products', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (product) => (
<Link
@@ -43,6 +42,7 @@ defineTable('products', {
filterable: true,
default: true,
filterType: 'enum',
+ quickFilter: true,
filterOptions: [
{ value: 'draft', label: i18n.t('admin.pages.products.status_options.draft') },
{ value: 'active', label: i18n.t('admin.fields.active.label') },
@@ -95,9 +95,10 @@ defineTable('products', {
key: 'sku',
label: i18n.t('admin.products.columns.sku'),
sortable: false,
- filterable: true,
+ // Not filterable: the search box already matches SKUs, and matches them
+ // better — it searches every variant's, where this filtered only the
+ // default variant's.
default: false,
- ransackAttribute: 'master_sku',
className: 'text-sm text-muted-foreground',
render: (product) => product.sku ?? '—',
},
@@ -122,14 +123,14 @@ defineTable('products', {
default: false,
render: (product) => <TagList tags={product.tags} />,
},
- {
- key: 'in_stock',
- label: i18n.t('admin.products.columns.in_stock'),
- filterable: true,
- filterType: 'boolean',
- displayable: false,
- default: false,
- },
+ // No `in_stock` filter. `in_stock` is a Ransack *scope* on Spree::Product,
+ // not a ransackable attribute, so any `in_stock_*` predicate is dropped
+ // server-side without error — the list comes back unfiltered while the
+ // control says otherwise. The scope also cannot express the negative:
+ // `in_stock('0')` returns everything, and "out of stock" is a second,
+ // separate scope. Restoring this needs `filtersToRansack` to learn how to
+ // emit a bare scope key, which is a change to the filter contract rather
+ // than a column flag.
// Filter-only — Ransack joins through `products.taxons`, so the predicate
// emitted is `taxons_id_in`. We don't render a categories cell on the
// index to avoid expanding categories on every list refetch; users can
diff --git a/packages/dashboard/src/tables/promotions.tsx b/packages/dashboard/src/tables/promotions.tsx
index 0f65b037d9..f5c00d9489 100644
--- a/packages/dashboard/src/tables/promotions.tsx
+++ b/packages/dashboard/src/tables/promotions.tsx
@@ -16,7 +16,6 @@ defineTable<Promotion>('promotions', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (p) => (
<ResourceNameCell
@@ -31,7 +30,6 @@ defineTable<Promotion>('promotions', {
key: 'code',
label: i18n.t('admin.fields.code.label'),
sortable: true,
- filterable: true,
default: true,
render: (p) => {
if (p.kind === 'automatic')
diff --git a/packages/dashboard/src/tables/sellers.tsx b/packages/dashboard/src/tables/sellers.tsx
index 8341c85e01..7908ea61ae 100644
--- a/packages/dashboard/src/tables/sellers.tsx
+++ b/packages/dashboard/src/tables/sellers.tsx
@@ -18,7 +18,6 @@ defineTable<Seller>('sellers', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (seller) => (
<Link
@@ -40,6 +39,7 @@ defineTable<Seller>('sellers', {
value: status,
label: i18n.t(`admin.sellers.status.${status}`),
})),
+ quickFilter: true,
default: true,
render: (seller) => (
<StatusBadge
diff --git a/packages/dashboard/src/tables/stock-transfers.tsx b/packages/dashboard/src/tables/stock-transfers.tsx
index b7e85a4cf4..b373ac4f76 100644
--- a/packages/dashboard/src/tables/stock-transfers.tsx
+++ b/packages/dashboard/src/tables/stock-transfers.tsx
@@ -16,7 +16,6 @@ defineTable<StockTransfer>('stock-transfers', {
key: 'number',
label: i18n.t('admin.stock_transfers.columns.number'),
sortable: true,
- filterable: true,
default: true,
render: (st) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/tax-categories.tsx b/packages/dashboard/src/tables/tax-categories.tsx
index 95b48259d5..784d7b724c 100644
--- a/packages/dashboard/src/tables/tax-categories.tsx
+++ b/packages/dashboard/src/tables/tax-categories.tsx
@@ -16,7 +16,6 @@ defineTable<TaxCategory>('tax-categories', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (tc) => (
<ResourceNameCell
diff --git a/packages/dashboard/src/tables/tax-rates.tsx b/packages/dashboard/src/tables/tax-rates.tsx
index dccb92c510..278b3cf446 100644
--- a/packages/dashboard/src/tables/tax-rates.tsx
+++ b/packages/dashboard/src/tables/tax-rates.tsx
@@ -18,7 +18,6 @@ defineTable<TaxRate>('tax-rates', {
key: 'name',
label: i18n.t('admin.fields.name.label'),
sortable: true,
- filterable: true,
default: true,
render: (taxRate) => (
<ResourceNameCell id={taxRate.id} dataAttr="data-tax-rate-id" name={taxRate.name} />
diff --git a/packages/dashboard/src/tables/webhook-deliveries.tsx b/packages/dashboard/src/tables/webhook-deliveries.tsx
index e1536d4c31..588d8340fb 100644
--- a/packages/dashboard/src/tables/webhook-deliveries.tsx
+++ b/packages/dashboard/src/tables/webhook-deliveries.tsx
@@ -1,6 +1,6 @@
import type { WebhookDelivery } from '@spree/admin-sdk'
import { defineTable } from '@spree/dashboard-core'
-import { Badge, RelativeTime } from '@spree/dashboard-ui'
+import { Badge, RelativeTime, StatusBadge } from '@spree/dashboard-ui'
import i18n from 'i18next'
import { ListIcon } from 'lucide-react'
@@ -29,7 +29,6 @@ defineTable<WebhookDelivery>('webhook-deliveries', {
key: 'event_name',
label: i18n.t('admin.pages.settings.webhooks.deliveries.table.event'),
sortable: true,
- filterable: true,
default: true,
render: (delivery) => (
<button
@@ -60,19 +59,26 @@ defineTable<WebhookDelivery>('webhook-deliveries', {
)
}
if (delivery.success === true) {
- return <Badge>{i18n.t('admin.pages.settings.webhooks.deliveries.status.success')}</Badge>
+ return (
+ <StatusBadge
+ status="complete"
+ label={i18n.t('admin.pages.settings.webhooks.deliveries.status.success')}
+ />
+ )
}
if (delivery.error_type) {
return (
- <Badge variant="destructive">
- {i18n.t('admin.pages.settings.webhooks.deliveries.status.error')}
- </Badge>
+ <StatusBadge
+ status="error"
+ label={i18n.t('admin.pages.settings.webhooks.deliveries.status.error')}
+ />
)
}
return (
- <Badge variant="destructive">
- {i18n.t('admin.pages.settings.webhooks.deliveries.status.failure')}
- </Badge>
+ <StatusBadge
+ status="failed"
+ label={i18n.t('admin.pages.settings.webhooks.deliveries.status.failure')}
+ />
)
},
},
diff --git a/packages/dashboard/src/tables/webhook-endpoints.tsx b/packages/dashboard/src/tables/webhook-endpoints.tsx
index 123e959293..5eb382f086 100644
--- a/packages/dashboard/src/tables/webhook-endpoints.tsx
+++ b/packages/dashboard/src/tables/webhook-endpoints.tsx
@@ -6,6 +6,7 @@ import {
CopyToClipboardButton,
RelativeTime,
ResourceNameCell,
+ StatusBadge,
} from '@spree/dashboard-ui'
import i18n from 'i18next'
import { WebhookIcon } from 'lucide-react'
@@ -37,7 +38,6 @@ defineTable<WebhookEndpoint>('webhook-endpoints', {
key: 'url',
label: i18n.t('admin.pages.settings.webhooks.table.url'),
sortable: true,
- filterable: true,
default: true,
render: (endpoint) => (
<span className="inline-flex items-center gap-1.5">
@@ -82,9 +82,10 @@ defineTable<WebhookEndpoint>('webhook-endpoints', {
// than the regular inactive outline so admins can spot it at a glance.
if (endpoint.disabled_at) {
return (
- <Badge variant="destructive">
- {i18n.t('admin.pages.settings.webhooks.status.disabled')}
- </Badge>
+ <StatusBadge
+ status="suspended"
+ label={i18n.t('admin.pages.settings.webhooks.status.disabled')}
+ />
)
}
return (
diff --git a/packages/seller-dashboard/src/components/seller-address-card.tsx b/packages/seller-dashboard/src/components/seller-address-card.tsx
index 232df056ff..286b37e552 100644
--- a/packages/seller-dashboard/src/components/seller-address-card.tsx
+++ b/packages/seller-dashboard/src/components/seller-address-card.tsx
@@ -8,6 +8,7 @@ import {
CardContent,
CardHeader,
CardTitle,
+ StatusBadge,
toastManager,
} from '@spree/dashboard-ui'
import type { Profile, SellerAddressParams } from '@spree/seller-sdk'
@@ -107,7 +108,7 @@ export function SellerAddressCard({
<CardTitle>
{title}
{address ? (
- <Badge variant="success">{t('profile.address_filled')}</Badge>
+ <StatusBadge status="complete" label={t('profile.address_filled')} />
) : (
<Badge variant="outline">{t('profile.address_missing')}</Badge>
)}
diff --git a/packages/seller-dashboard/src/components/seller-returns-location-card.tsx b/packages/seller-dashboard/src/components/seller-returns-location-card.tsx
index c240fcd3c7..211fd1b702 100644
--- a/packages/seller-dashboard/src/components/seller-returns-location-card.tsx
+++ b/packages/seller-dashboard/src/components/seller-returns-location-card.tsx
@@ -8,6 +8,7 @@ import {
CardContent,
CardHeader,
CardTitle,
+ StatusBadge,
toastManager,
} from '@spree/dashboard-ui'
import type { StockLocation, StockLocationParams } from '@spree/seller-sdk'
@@ -117,7 +118,7 @@ export function SellerReturnsLocationCard({ headless = false }: { headless?: boo
<CardTitle>
{title}
{hasAddress ? (
- <Badge variant="success">{t('profile.address_filled')}</Badge>
+ <StatusBadge status="complete" label={t('profile.address_filled')} />
) : (
<Badge variant="outline">{t('profile.address_missing')}</Badge>
)}
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index 3d667f55c6..c5ae605701 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -196,8 +196,23 @@
"fulfill": "Mark as shipped",
"fulfilled": "Marked as shipped",
"fulfilling": "Marking…",
+ "fulfillment_statuses": {
+ "backorder": "Backorder",
+ "canceled": "Canceled",
+ "delivered": "Delivered",
+ "fulfilled": "Fulfilled",
+ "partial": "Partial",
+ "unfulfilled": "Unfulfilled"
+ },
"items": "Items",
"not_found": "That order could not be found.",
+ "payment_statuses": {
+ "balance_due": "Balance due",
+ "credit_owed": "Credit owed",
+ "failed": "Failed",
+ "paid": "Paid",
+ "void": "Void"
+ },
"search_placeholder": "Search by order number…",
"shipping_address": "Ships to",
"ships_from": "Ships from {{name}}",
diff --git a/packages/seller-dashboard/src/pages/onboarding.tsx b/packages/seller-dashboard/src/pages/onboarding.tsx
index b1258b5ca3..5fd769ca94 100644
--- a/packages/seller-dashboard/src/pages/onboarding.tsx
+++ b/packages/seller-dashboard/src/pages/onboarding.tsx
@@ -16,6 +16,7 @@ import {
FieldLabel,
Input,
Progress,
+ StatusBadge as SharedStatusBadge,
Textarea,
toastManager,
} from '@spree/dashboard-ui'
@@ -466,10 +467,12 @@ function StatusIcon({ status }: { status: string }) {
function StatusBadge({ status }: { status: string }) {
const { t } = useTranslation()
+ // Only the wording is local — the colour comes from the shared status map.
if (status === 'complete')
- return <Badge variant="success">{t('onboarding.status.complete')}</Badge>
- if (status === 'pending') return <Badge variant="warning">{t('onboarding.status.pending')}</Badge>
+ return <SharedStatusBadge status="complete" label={t('onboarding.status.complete')} />
+ if (status === 'pending')
+ return <SharedStatusBadge status="pending" label={t('onboarding.status.pending')} />
if (status === 'rejected')
- return <Badge variant="destructive">{t('onboarding.status.rejected')}</Badge>
+ return <SharedStatusBadge status="rejected" label={t('onboarding.status.rejected')} />
return null
}
diff --git a/packages/seller-dashboard/src/pages/order.tsx b/packages/seller-dashboard/src/pages/order.tsx
index 5e9ffd532d..a0e9ce6a4e 100644
--- a/packages/seller-dashboard/src/pages/order.tsx
+++ b/packages/seller-dashboard/src/pages/order.tsx
@@ -83,7 +83,14 @@ export function OrderPage() {
title={order.number}
backTo="orders"
subtitle={order.completed_at ? new Date(order.completed_at).toLocaleString() : undefined}
- badges={order.fulfillment_status && <StatusBadge status={order.fulfillment_status} />}
+ badges={
+ order.fulfillment_status && (
+ <StatusBadge
+ status={order.fulfillment_status}
+ label={t(`orders.fulfillment_statuses.${order.fulfillment_status}`)}
+ />
+ )
+ }
resource={{ id: order.id, number: order.number }}
destructiveItems={
cancelable ? (
@@ -177,7 +184,10 @@ function FulfillmentCard({ orderId, fulfillment }: { orderId: string; fulfillmen
<CardHeader>
<CardTitle>{fulfillment.number}</CardTitle>
<CardAction>
- <StatusBadge status={fulfillment.status} />
+ <StatusBadge
+ status={fulfillment.status}
+ label={t(`orders.fulfillment_statuses.${fulfillment.status}`)}
+ />
</CardAction>
</CardHeader>
<CardContent className="flex flex-col gap-3">
diff --git a/packages/seller-dashboard/src/tables/orders.tsx b/packages/seller-dashboard/src/tables/orders.tsx
index 404c50fd11..cd3c400c81 100644
--- a/packages/seller-dashboard/src/tables/orders.tsx
+++ b/packages/seller-dashboard/src/tables/orders.tsx
@@ -4,6 +4,17 @@ import type { Order } from '@spree/seller-sdk'
import i18n from 'i18next'
import { PackageIcon } from 'lucide-react'
+/** Mirrors the operator dashboard's order status vocabularies. */
+const FULFILLMENT_STATUSES = [
+ 'unfulfilled',
+ 'backorder',
+ 'partial',
+ 'fulfilled',
+ 'delivered',
+ 'canceled',
+] as const
+const PAYMENT_STATUSES = ['balance_due', 'paid', 'credit_owed', 'failed', 'void'] as const
+
defineTable<Order>('seller-orders', {
title: i18n.t('orders.title'),
searchParam: 'number_cont',
@@ -25,6 +36,9 @@ defineTable<Order>('seller-orders', {
key: 'completed_at',
label: i18n.t('orders.columns.placed'),
sortable: true,
+ filterable: true,
+ filterType: 'date',
+ quickFilter: true,
default: true,
render: (order) =>
order.completed_at ? new Date(order.completed_at).toLocaleDateString() : '—',
@@ -32,16 +46,44 @@ defineTable<Order>('seller-orders', {
{
key: 'fulfillment_status',
label: i18n.t('orders.columns.fulfillment'),
+ filterable: true,
+ filterType: 'enum',
+ filterOptions: FULFILLMENT_STATUSES.map((status) => ({
+ value: status,
+ label: i18n.t(`orders.fulfillment_statuses.${status}`),
+ })),
+ quickFilter: true,
default: true,
render: (order) =>
- order.fulfillment_status ? <StatusBadge status={order.fulfillment_status} /> : '—',
+ order.fulfillment_status ? (
+ <StatusBadge
+ status={order.fulfillment_status}
+ label={i18n.t(`orders.fulfillment_statuses.${order.fulfillment_status}`)}
+ />
+ ) : (
+ '—'
+ ),
},
{
key: 'payment_status',
label: i18n.t('orders.columns.payment'),
+ filterable: true,
+ filterType: 'enum',
+ filterOptions: PAYMENT_STATUSES.map((status) => ({
+ value: status,
+ label: i18n.t(`orders.payment_statuses.${status}`),
+ })),
+ quickFilter: true,
default: true,
render: (order) =>
- order.payment_status ? <StatusBadge status={order.payment_status} /> : '—',
+ order.payment_status ? (
+ <StatusBadge
+ status={order.payment_status}
+ label={i18n.t(`orders.payment_statuses.${order.payment_status}`)}
+ />
+ ) : (
+ '—'
+ ),
},
{
key: 'total',
diff --git a/packages/seller-dashboard/src/tables/policies.tsx b/packages/seller-dashboard/src/tables/policies.tsx
index f9c2d3e076..8d58dbdf0f 100644
--- a/packages/seller-dashboard/src/tables/policies.tsx
+++ b/packages/seller-dashboard/src/tables/policies.tsx
@@ -16,7 +16,6 @@ defineTable<Policy>('seller-policies', {
key: 'name',
label: i18n.t('policies.columns.name'),
sortable: true,
- filterable: true,
default: true,
render: (policy) => (
<ResourceNameCell
diff --git a/packages/seller-dashboard/src/tables/products.tsx b/packages/seller-dashboard/src/tables/products.tsx
index bb4e5bb41b..bc09fc5702 100644
--- a/packages/seller-dashboard/src/tables/products.tsx
+++ b/packages/seller-dashboard/src/tables/products.tsx
@@ -4,6 +4,9 @@ import type { Product } from '@spree/seller-sdk'
import i18n from 'i18next'
import { PackageIcon } from 'lucide-react'
+/** Mirrors the operator dashboard's product statuses. */
+const PRODUCT_STATUSES = ['active', 'draft', 'proposed', 'rejected', 'archived'] as const
+
defineTable<Product>('seller-products', {
title: i18n.t('products.title'),
searchParam: 'name_cont',
@@ -16,7 +19,6 @@ defineTable<Product>('seller-products', {
key: 'name',
label: i18n.t('products.columns.name'),
sortable: true,
- filterable: true,
default: true,
render: (product) => (
<div className="flex items-center gap-3">
@@ -29,6 +31,13 @@ defineTable<Product>('seller-products', {
key: 'status',
label: i18n.t('products.columns.status'),
sortable: true,
+ filterable: true,
+ filterType: 'enum',
+ filterOptions: PRODUCT_STATUSES.map((status) => ({
+ value: status,
+ label: i18n.t(`products.statuses.${status}`),
+ })),
+ quickFilter: true,
default: true,
render: (product) => (
<StatusBadge