Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: dashboard date range picker keeps the selected preset (#14633)
Damian Legawiecc0f6ccd1c5e9
diff --git a/.changeset/dashboard-date-range-preset.md b/.changeset/dashboard-date-range-preset.mdnew file mode 100644index 0000000000..e71f18f643--- /dev/null+++ b/.changeset/dashboard-date-range-preset.md@@ -0,0 +1,8 @@+---+'@spree/dashboard': patch+'@spree/dashboard-ui': patch+---++Fix the dashboard date range picker remembering "Last 30 days" after another preset is chosen.++The trigger label lived in local state that reset whenever analytics refetch replaced the page. It now follows the selected dates, so Last 90 days stays selected after the figures update.diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.tsindex 59f7f85230..e883ecfc05 100644--- a/packages/dashboard-ui/src/index.ts+++ b/packages/dashboard-ui/src/index.ts@@ -18,6 +18,11 @@ export * from './hooks/use-scrolled'// ---------------------------------------------------------------------------// Helpers + hooks// ---------------------------------------------------------------------------+export {+ type DateRangePresetKey,+ matchDateRangePreset,+ resolveDateRangePreset,+} from './lib/date-range-presets'export { sameRichText } from './lib/same-rich-text'export { cn } from './lib/utils'export { requiredMessage } from './lib/validation-messages'diff --git a/packages/dashboard-ui/src/lib/date-range-presets.ts b/packages/dashboard-ui/src/lib/date-range-presets.tsnew file mode 100644index 0000000000..cfff609910--- /dev/null+++ b/packages/dashboard-ui/src/lib/date-range-presets.ts@@ -0,0 +1,79 @@+import { format, startOfMonth, startOfYear, subDays } from 'date-fns'+import { toZonedTime } from 'date-fns-tz'++/**+ * Named ranges the date-range picker offers. `custom` is a hand-picked+ * span that no named entry produces today.+ */+export type DateRangePresetKey = '7d' | '14d' | '30d' | '90d' | 'this_month' | 'ytd' | 'custom'++export const DATE_RANGE_PRESET_KEYS: Exclude<DateRangePresetKey, 'custom'>[] = [+ '7d',+ '14d',+ '30d',+ '90d',+ 'this_month',+ 'ytd',+]++export interface CalendarDateRange {+ from: Date+ to: Date+}++/**+ * Resolve a named range on the given calendar.+ *+ * "Last N days" is inclusive of today — last 30 days is 30 dates, so the+ * start is 29 days back. The timezone argument is the merchant's zone:+ * these ranges are relative to *now* where they trade, not where the+ * browser happens to be.+ */+export function resolveDateRangePreset(+ preset: Exclude<DateRangePresetKey, 'custom'>,+ timezone: string,+): CalendarDateRange {+ const now = toZonedTime(new Date(), timezone)++ switch (preset) {+ case '7d':+ return { from: subDays(now, 6), to: now }+ case '14d':+ return { from: subDays(now, 13), to: now }+ case '30d':+ return { from: subDays(now, 29), to: now }+ case '90d':+ return { from: subDays(now, 89), to: now }+ case 'this_month':+ return { from: startOfMonth(now), to: now }+ case 'ytd':+ return { from: startOfYear(now), to: now }+ }+}++/**+ * Recognise which named range a pair of dates came from, so a picker that+ * remounts (or is given a range from outside) re-selects its menu entry+ * instead of always reading as the default.+ *+ * Matching by calendar day rather than storing the key keeps the value a+ * plain range — the preset is a way of writing dates, not a second piece+ * of state that can drift. A range that no longer matches any preset+ * (yesterday's "last 7 days", reopened today) correctly reads as custom.+ */+export function matchDateRangePreset(+ range: CalendarDateRange,+ timezone: string,+): DateRangePresetKey {+ const from = dayKey(range.from)+ const to = dayKey(range.to)+ for (const key of DATE_RANGE_PRESET_KEYS) {+ const candidate = resolveDateRangePreset(key, timezone)+ if (dayKey(candidate.from) === from && dayKey(candidate.to) === to) return key+ }+ return 'custom'+}++function dayKey(date: Date): string {+ return format(date, 'yyyy-MM-dd')+}diff --git a/packages/dashboard-ui/src/ui/date-range-picker.tsx b/packages/dashboard-ui/src/ui/date-range-picker.tsxindex 5e70c9c53e..bc846a104d 100644--- a/packages/dashboard-ui/src/ui/date-range-picker.tsx+++ b/packages/dashboard-ui/src/ui/date-range-picker.tsx@@ -1,8 +1,14 @@-import { format, startOfMonth, startOfYear, subDays } from 'date-fns'-import { useState } from 'react'+import { format } from 'date-fns'+import { useMemo, useState } from 'react'import type { DateRange as DayPickerDateRange } from 'react-day-picker'import { useTranslation } from 'react-i18next'import { activeDateLocale } from '../lib/date-locale'+import {+ DATE_RANGE_PRESET_KEYS,+ type DateRangePresetKey,+ matchDateRangePreset,+ resolveDateRangePreset,+} from '../lib/date-range-presets'import { cn } from '../lib/utils'import { CalendarIcon, ChevronDownIcon } from '../spree/icons'import { Button } from './button'@@ -14,79 +20,58 @@ export interface DateRange {to: Date}-type PresetKey = '7d' | '14d' | '30d' | '90d' | 'this_month' | 'ytd' | 'custom'--interface Preset {- key: PresetKey- labelKey: string- value: () => DateRange+const PRESET_LABEL_KEYS: Record<Exclude<DateRangePresetKey, 'custom'>, string> = {+ '7d': 'admin.components.date_range_picker.presets.last_7_days',+ '14d': 'admin.components.date_range_picker.presets.last_14_days',+ '30d': 'admin.components.date_range_picker.presets.last_30_days',+ '90d': 'admin.components.date_range_picker.presets.last_90_days',+ this_month: 'admin.components.date_range_picker.presets.this_month',+ ytd: 'admin.components.date_range_picker.presets.year_to_date',}-const presets: Preset[] = [- {- key: '7d',- labelKey: 'admin.components.date_range_picker.presets.last_7_days',- value: () => ({ from: subDays(new Date(), 7), to: new Date() }),- },- {- key: '14d',- labelKey: 'admin.components.date_range_picker.presets.last_14_days',- value: () => ({ from: subDays(new Date(), 14), to: new Date() }),- },- {- key: '30d',- labelKey: 'admin.components.date_range_picker.presets.last_30_days',- value: () => ({ from: subDays(new Date(), 30), to: new Date() }),- },- {- key: '90d',- labelKey: 'admin.components.date_range_picker.presets.last_90_days',- value: () => ({ from: subDays(new Date(), 90), to: new Date() }),- },- {- key: 'this_month',- labelKey: 'admin.components.date_range_picker.presets.this_month',- value: () => ({ from: startOfMonth(new Date()), to: new Date() }),- },- {- key: 'ytd',- labelKey: 'admin.components.date_range_picker.presets.year_to_date',- value: () => ({ from: startOfYear(new Date()), to: new Date() }),- },-]--interface DateRangePickerProps {+export interface DateRangePickerProps {value: DateRangeonChange: (range: DateRange) => void+ /**+ * IANA timezone used to resolve relative presets ("last 30 days").+ * Defaults to the browser zone. Pass the store timezone on admin+ * surfaces so every merchant sees the same span.+ */+ timezone?: string}-export function DateRangePicker({ value, onChange }: DateRangePickerProps) {+export function DateRangePicker({ value, onChange, timezone }: DateRangePickerProps) {const { t } = useTranslation()const [open, setOpen] = useState(false)- const [activePreset, setActivePreset] = useState<PresetKey>('30d')const [calendarRange, setCalendarRange] = useState<DayPickerDateRange | undefined>()+ const [month, setMonth] = useState<Date>(value.from)- const activePresetLabelKey =- presets.find((p) => p.key === activePreset)?.labelKey ??- 'admin.components.date_range_picker.presets.last_30_days'+ const zone = useMemo(+ () => timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC',+ [timezone],+ )+ // Derived from `value` so a remount — or a range written by the parent —+ // keeps the trigger and the highlighted preset in sync. A second piece of+ // preset state is what made "Last 90 days" revert to "Last 30 days"+ // after the dashboard swapped the picker for a skeleton.+ const activePreset = matchDateRangePreset(value, zone)const dateLocale = activeDateLocale()const triggerLabel =activePreset === 'custom'? `${format(value.from, 'MMM d', { locale: dateLocale })} – ${format(value.to, 'MMM d', { locale: dateLocale })}`- : t(activePresetLabelKey)+ : t(PRESET_LABEL_KEYS[activePreset])- function selectPreset(preset: Preset) {- const range = preset.value()- setActivePreset(preset.key)+ function selectPreset(key: Exclude<DateRangePresetKey, 'custom'>) {+ const range = resolveDateRangePreset(key, zone)setCalendarRange({ from: range.from, to: range.to })+ setMonth(range.from)onChange(range)setOpen(false)}function applyCustomRange() {if (calendarRange?.from && calendarRange?.to) {- setActivePreset('custom')onChange({ from: calendarRange.from, to: calendarRange.to })setOpen(false)}@@ -101,6 +86,7 @@ export function DateRangePicker({ value, onChange }: DateRangePickerProps) {setOpen(nextOpen)if (nextOpen) {setCalendarRange({ from: value.from, to: value.to })+ setMonth(value.from)}}}>@@ -114,25 +100,26 @@ export function DateRangePicker({ value, onChange }: DateRangePickerProps) {<PopoverContent align="end" className="w-auto p-0"><div className="flex"><div className="flex flex-col border-r py-2">- {presets.map((preset) => (+ {DATE_RANGE_PRESET_KEYS.map((key) => (<button- key={preset.key}+ key={key}type="button"- onClick={() => selectPreset(preset)}+ onClick={() => selectPreset(key)}className={cn('whitespace-nowrap px-4 py-1.5 text-left text-sm transition-colors hover:bg-accent',- activePreset === preset.key && 'font-medium text-foreground',- activePreset !== preset.key && 'text-muted-foreground',+ activePreset === key && 'font-medium text-foreground',+ activePreset !== key && 'text-muted-foreground',)}>- {t(preset.labelKey)}+ {t(PRESET_LABEL_KEYS[key])}</button>))}</div><div className="flex flex-col p-3"><Calendarmode="range"- defaultMonth={calendarRange?.from}+ month={month}+ onMonthChange={setMonth}selected={calendarRange}onSelect={setCalendarRange}numberOfMonths={2}diff --git a/packages/dashboard/src/components/spree/reporting/report-builder.tsx b/packages/dashboard/src/components/spree/reporting/report-builder.tsxindex 9facb4110a..afe160ae73 100644--- a/packages/dashboard/src/components/spree/reporting/report-builder.tsx+++ b/packages/dashboard/src/components/spree/reporting/report-builder.tsx@@ -32,7 +32,7 @@ import {SelectValue,} from '@spree/dashboard-ui'import { PlusIcon, XIcon } from '@spree/dashboard-ui/icons'-import { format, parseISO } from 'date-fns'+import { format, parse } from 'date-fns'import { useTranslation } from 'react-i18next'import { categoryAutocompleteProps } from '../../../hooks/use-categories'import { channelAutocompleteProps, useChannels } from '../../../hooks/use-channels'@@ -113,8 +113,14 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {const defaultRange = resolveDatePreset('last_30_days', timezone)const customRange: DateRange ='since' in draft.timeRange- ? { from: parseISO(draft.timeRange.since), to: parseISO(draft.timeRange.until) }- : { from: parseISO(defaultRange.from as string), to: parseISO(defaultRange.to as string) }+ ? {+ from: parse(draft.timeRange.since, 'yyyy-MM-dd', new Date()),+ to: parse(draft.timeRange.until, 'yyyy-MM-dd', new Date()),+ }+ : {+ from: parse(defaultRange.from as string, 'yyyy-MM-dd', new Date()),+ to: parse(defaultRange.to as string, 'yyyy-MM-dd', new Date()),+ }const dateRangeValue = (range: DateRange) => ({since: format(range.from, 'yyyy-MM-dd'),until: format(range.to, 'yyyy-MM-dd'),@@ -261,6 +267,7 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {<DateRangePickervalue={customRange}onChange={(range) => update({ timeRange: dateRangeValue(range) })}+ timezone={timezone}/>)}</Field>diff --git a/packages/dashboard/src/lib/date-range-presets.test.ts b/packages/dashboard/src/lib/date-range-presets.test.tsnew file mode 100644index 0000000000..8b9418a514--- /dev/null+++ b/packages/dashboard/src/lib/date-range-presets.test.ts@@ -0,0 +1,67 @@+import { matchDateRangePreset, resolveDateRangePreset } from '@spree/dashboard-ui'+import { parse } from 'date-fns'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// 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('resolveDateRangePreset', () => {+ it('counts last-N ranges inclusively, so last 30 days is 30 dates', () => {+ const range = resolveDateRangePreset('30d', 'UTC')+ expect(day(range.from)).toBe('2026-02-14')+ expect(day(range.to)).toBe('2026-03-15')+ })++ it('counts last 90 days as 90 dates, not 91', () => {+ const range = resolveDateRangePreset('90d', 'UTC')+ expect(day(range.from)).toBe('2025-12-16')+ expect(day(range.to)).toBe('2026-03-15')+ })++ it('reads "this month" and year-to-date on the store calendar', () => {+ expect(day(resolveDateRangePreset('this_month', 'UTC').from)).toBe('2026-03-01')+ expect(day(resolveDateRangePreset('ytd', 'UTC').from)).toBe('2026-01-01')+ expect(day(resolveDateRangePreset('this_month', 'Australia/Sydney').from)).toBe('2026-03-01')+ expect(day(resolveDateRangePreset('this_month', 'Australia/Sydney').to)).toBe('2026-03-16')+ })+})++describe('matchDateRangePreset', () => {+ it('recognises a range it produced, so a remounted picker re-selects its entry', () => {+ const range = resolveDateRangePreset('90d', 'UTC')+ expect(matchDateRangePreset(range, 'UTC')).toBe('90d')+ })++ it('recognises a range written as bare dates, the way the dashboard seeds last 30 days', () => {+ const from = parse('2026-02-14', 'yyyy-MM-dd', new Date())+ const to = parse('2026-03-15', 'yyyy-MM-dd', new Date())+ expect(matchDateRangePreset({ from, to }, 'UTC')).toBe('30d')+ })++ it('reads a hand-picked range as custom', () => {+ const from = parse('2026-01-02', 'yyyy-MM-dd', new Date())+ const to = parse('2026-01-09', 'yyyy-MM-dd', new Date())+ expect(matchDateRangePreset({ from, to }, 'UTC')).toBe('custom')+ })++ it('reads a stale preset as custom once it no longer matches', () => {+ const from = parse('2026-03-08', 'yyyy-MM-dd', new Date())+ const to = parse('2026-03-14', 'yyyy-MM-dd', new Date())+ expect(matchDateRangePreset({ from, to }, 'UTC')).toBe('custom')+ })+})++function day(date: Date): string {+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`+}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsxindex bcac913f43..27d63e2dab 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx@@ -50,7 +50,7 @@ import {TruckIcon,} from '@spree/dashboard-ui/icons'import { createFileRoute, Link, type LinkProps } from '@tanstack/react-router'-import { format, parseISO } from 'date-fns'+import { format, parse } from 'date-fns'import type { CSSProperties } from 'react'import { useState } from 'react'import { useTranslation } from 'react-i18next'@@ -87,7 +87,10 @@ function DashboardPage() {// so the server widens both edges to the store's whole day.const [dateRange, setDateRange] = useState<DateRange>(() => {const preset = resolveDatePreset('last_30_days', timezone)- return { from: parseISO(preset.from as string), to: parseISO(preset.to as string) }+ return {+ from: parse(preset.from as string, 'yyyy-MM-dd', new Date()),+ to: parse(preset.to as string, 'yyyy-MM-dd', new Date()),+ }})const [channelId, setChannelId] = useState<string>(ALL_CHANNELS)// Undefined until the merchant picks one, so the store's default applies as@@ -176,10 +179,9 @@ function DashboardPage() {)}- if (!overview) {- return <DashboardSkeleton />- }-+ // The toolbar stays mounted while a new range loads. Swapping the whole+ // page for a skeleton remounted the picker and reset its trigger to+ // "Last 30 days" even though the query had already moved.return (<div className="flex flex-col gap-6"><div className="flex flex-wrap items-center justify-between gap-3">@@ -210,28 +212,34 @@ function DashboardPage() {searchPlaceholder={t('admin.pages.home.currency.search')}/>)}- <DateRangePicker value={dateRange} onChange={setDateRange} />+ <DateRangePicker value={dateRange} onChange={setDateRange} timezone={timezone} /></div></div>- <TimeSeriesChart- metrics={chartMetrics}- result={overview}- dimension="completed_at"- grain="day"- compare- />- <div className="grid gap-6 lg:grid-cols-5">- <OperationsCard- data={operations}- failed={!!operationsError}- channelId={channelParam}- className={rankingTabs.length > 0 ? 'lg:col-span-2' : 'lg:col-span-5'}- />- {rankingTabs.length > 0 && <RankingsCard scope={scope} tabs={rankingTabs} />}- </div>- <Can I="read" a={Subject.Product}>- <TopProducts scope={scope} />- </Can>+ {!overview ? (+ <DashboardWidgetsSkeleton />+ ) : (+ <>+ <TimeSeriesChart+ metrics={chartMetrics}+ result={overview}+ dimension="completed_at"+ grain="day"+ compare+ />+ <div className="grid gap-6 lg:grid-cols-5">+ <OperationsCard+ data={operations}+ failed={!!operationsError}+ channelId={channelParam}+ className={rankingTabs.length > 0 ? 'lg:col-span-2' : 'lg:col-span-5'}+ />+ {rankingTabs.length > 0 && <RankingsCard scope={scope} tabs={rankingTabs} />}+ </div>+ <Can I="read" a={Subject.Product}>+ <TopProducts scope={scope} />+ </Can>+ </>+ )}</div>)}@@ -777,14 +785,9 @@ function TopProducts({ scope }: { scope: Pick<ReportingQuery, 'time_range' | 'fi)}-function DashboardSkeleton() {- const { t } = useTranslation()+function DashboardWidgetsSkeleton() {return (- <div className="flex flex-col gap-6">- <div>- <h1 className="text-2xl font-bold">{t('admin.pages.home.title')}</h1>- <p className="text-muted-foreground">{t('admin.pages.home.subtitle')}</p>- </div>+ <><ReportSkeleton /><div className="grid gap-6 lg:grid-cols-5"><Card className="lg:col-span-2">@@ -817,6 +820,6 @@ function DashboardSkeleton() {</CardContent></Card></div>- </div>+ </>)}