A local-first personal finance app
[AI] Migrate FormulaCard to DateRangePicker #8449 (#8557)
Ronan Presle8867158f0a2e
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex 28c83440d6..9d80eada68 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -58,8 +58,10 @@"#components/reports/chart-theme": "./src/components/reports/chart-theme.ts","#components/reports/constants": "./src/components/reports/constants.ts","#components/reports/disabledList": "./src/components/reports/disabledList.ts",+ "#components/reports/dateRangePresets": "./src/components/reports/dateRangePresets.ts","#components/reports/getCustomTick": "./src/components/reports/getCustomTick.ts","#components/reports/getLiveRange": "./src/components/reports/getLiveRange.ts",+ "#components/reports/monthRange": "./src/components/reports/monthRange.ts","#components/reports/graphs/showActivity": "./src/components/reports/graphs/showActivity.ts","#components/reports/graphs/util/computePadding": "./src/components/reports/graphs/util/computePadding.ts","#components/reports/numberFormatter": "./src/components/reports/numberFormatter.ts",diff --git a/packages/desktop-client/src/components/formula/QueryManager.test.ts b/packages/desktop-client/src/components/formula/QueryManager.test.tsnew file mode 100644index 0000000000..c0494c096e--- /dev/null+++ b/packages/desktop-client/src/components/formula/QueryManager.test.ts@@ -0,0 +1,65 @@+import * as monthUtils from '@actual-app/core/shared/months';+import { describe, expect, it } from 'vitest';++import {+ calculateDateRangeBoundMonths,+ canRenderDateRangePicker,+ normalizeMonthPickerSelectionForQuery,+ normalizeMonthRangeForPicker,+ shouldIgnoreMonthPickerNoop,+} from './QueryManager';++describe('QueryManager month-only DateRangePicker helpers', () => {+ it('normalizes day-shaped range to month-shaped picker values', () => {+ expect(normalizeMonthRangeForPicker('2026-02-01', '2026-02-17')).toEqual([+ '2026-02',+ '2026-02',+ ]);+ });++ it('treats day-shaped range and equivalent month selection as a no-op', () => {+ expect(+ shouldIgnoreMonthPickerNoop(+ '2026-01-01',+ '2026-03-15',+ '2026-01',+ '2026-03',+ ),+ ).toBe(true);+ });++ it('does not ignore actual month changes from the picker', () => {+ expect(+ shouldIgnoreMonthPickerNoop(+ '2026-01-01',+ '2026-03-15',+ '2026-02',+ '2026-03',+ ),+ ).toBe(false);+ });++ it('normalizes month-only picker selection to day-shaped query bounds', () => {+ expect(normalizeMonthPickerSelectionForQuery('2026-02', '2026-04')).toEqual(+ ['2026-02-01', '2026-04-30'],+ );+ });++ it('waits to enable the picker until transaction bounds finish loading', () => {+ expect(canRenderDateRangePicker(false, '2026-01', '2026-12')).toBe(false);+ expect(canRenderDateRangePicker(true, '', '2026-12')).toBe(false);+ expect(canRenderDateRangePicker(true, '2026-01', '2026-12')).toBe(true);+ });++ it('falls back to current-month bounds when transaction lookups fail', () => {+ const currentMonth = monthUtils.currentMonth();+ const currentDay = monthUtils.currentDay();++ expect(calculateDateRangeBoundMonths(null, null)).toEqual({+ earliestMonth: currentMonth,+ latestMonth: currentMonth,+ earliestTransactionDate: currentDay,+ latestTransactionDate: currentDay,+ });+ });+});diff --git a/packages/desktop-client/src/components/formula/QueryManager.tsx b/packages/desktop-client/src/components/formula/QueryManager.tsxindex 3475375e91..945cd9c2fe 100644--- a/packages/desktop-client/src/components/formula/QueryManager.tsx+++ b/packages/desktop-client/src/components/formula/QueryManager.tsx@@ -3,12 +3,12 @@ import { Dialog, DialogTrigger } from 'react-aria-components';import { Trans, useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';+import { DateRangePicker } from '@actual-app/components/date-range-picker';+import type { DateRangePreset } from '@actual-app/components/date-range-picker';import { SvgCopy, SvgTrash } from '@actual-app/components/icons/v1';import { SvgDownloadThickBottom } from '@actual-app/components/icons/v2';import { Input } from '@actual-app/components/input';-import { Menu } from '@actual-app/components/menu';import { Popover } from '@actual-app/components/popover';-import { Select } from '@actual-app/components/select';import { Text } from '@actual-app/components/text';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';@@ -18,20 +18,17 @@ import type {RuleConditionEntity,TimeFrame,} from '@actual-app/core/types/models';-import { parseISO } from 'date-fns';import { AppliedFilters } from '#components/filters/AppliedFilters';import { FilterButton } from '#components/filters/FiltersMenu';-import { getLiveRange } from '#components/reports/getLiveRange';+import { buildDateRangePresets } from '#components/reports/dateRangePresets';+import { clampMonthRangeToBounds } from '#components/reports/monthRange';import {asMonthSlidingTimeFrame,calculateTimeRange,- getLatestRange,- validateEnd,- validateStart,} from '#components/reports/reportRanges';-import { fromDateRepr } from '#components/reports/util';-import { useLocale } from '#hooks/useLocale';+import { useDateFormat } from '#hooks/useDateFormat';+import { useLanguage } from '#hooks/useLocale';import { useRuleConditionFilters } from '#hooks/useRuleConditionFilters';import { addNotification } from '#notifications/notificationsSlice';import { useDispatch } from '#redux';@@ -48,6 +45,81 @@ type QueryConfig = {timeFrame?: TimeFrame;};+export function normalizeMonthRangeForPicker(start: string, end: string) {+ return [monthUtils.getMonth(start), monthUtils.getMonth(end)] satisfies [+ string,+ string,+ ];+}++export function normalizeMonthPickerSelectionForQuery(+ start: string,+ end: string,+) {+ return [+ normalizeQueryTimeFrameStart(start),+ normalizeQueryTimeFrameEnd(end),+ ] satisfies [string, string];+}++export function shouldIgnoreMonthPickerNoop(+ startDate: string,+ endDate: string,+ nextStart: string,+ nextEnd: string,+) {+ const [currentStartMonth, currentEndMonth] = normalizeMonthRangeForPicker(+ startDate,+ endDate,+ );++ return currentStartMonth === nextStart && currentEndMonth === nextEnd;+}++export function canRenderDateRangePicker(+ isTransactionBoundsReady: boolean,+ earliestMonth: string,+ latestMonth: string,+) {+ return (+ isTransactionBoundsReady && Boolean(earliestMonth) && Boolean(latestMonth)+ );+}++export function calculateDateRangeBoundMonths(+ earliestTransaction: { date: string } | null,+ latestTransaction: { date: string } | null,+) {+ const currentMonth = monthUtils.currentMonth();+ const currentDay = monthUtils.currentDay();++ const earliestTransactionDate = earliestTransaction+ ? earliestTransaction.date+ : currentDay;+ const latestTransactionDate = latestTransaction+ ? latestTransaction.date+ : currentDay;++ const computedEarliestMonth = earliestTransaction+ ? monthUtils.getMonth(earliestTransaction.date)+ : currentMonth;+ const latestTransactionMonth = latestTransaction+ ? monthUtils.getMonth(latestTransaction.date)+ : currentMonth;++ const computedLatestMonth =+ latestTransactionMonth > currentMonth+ ? latestTransactionMonth+ : currentMonth;++ return {+ earliestMonth: computedEarliestMonth,+ latestMonth: computedLatestMonth,+ earliestTransactionDate,+ latestTransactionDate,+ };+}+type PresetTimeRangeMode = Exclude<TimeFrame['mode'],'sliding-window' | 'static'@@ -219,12 +291,11 @@ function QueryItem({onUpdate,onRemove,}: QueryItemProps) {- const locale = useLocale();+ const language = useLanguage();+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';const { t } = useTranslation();const [importJsonText, setImportJsonText] = useState('');const dispatch = useDispatch<AppDispatch>();- const timeRangeMenuTriggerRef = useRef(null);- const [timeRangeMenuOpen, setTimeRangeMenuOpen] = useState(false);// Time range stateconst [startDate, setStartDate] = useState(@@ -235,15 +306,16 @@ function QueryItem({defaultConfig.timeFrame?.end || monthUtils.currentDay(),);- // Months data for range picker- const [allMonths, setAllMonths] = useState<- Array<{- name: string;- pretty: string;- }>- >([]);- const [_earliestTransaction, setEarliestTransaction] = useState('');- const [_latestTransaction, setLatestTransaction] = useState('');+ const [earliestMonth, setEarliestMonth] = useState(monthUtils.currentMonth());+ const [latestMonth, setLatestMonth] = useState(monthUtils.currentMonth());+ const [isTransactionBoundsReady, setIsTransactionBoundsReady] =+ useState(false);+ const [earliestTransaction, setEarliestTransaction] = useState(+ monthUtils.currentDay(),+ );+ const [latestTransaction, setLatestTransaction] = useState(+ monthUtils.currentDay(),+ );const timeRangeRef = useRef<string>(defaultConfig.timeFrame?.mode || 'sliding-window',@@ -267,53 +339,41 @@ function QueryItem({}}, [defaultConfig]);- // Fetch transaction data for month range picker+ // Fetch transaction bounds for per-query date picker limits and presets.useEffect(() => {async function run() {- const earliestTransaction = await send('get-earliest-transaction');- setEarliestTransaction(- earliestTransaction- ? earliestTransaction.date- : monthUtils.currentDay(),- );-- const latestTransaction = await send('get-latest-transaction');- setLatestTransaction(- latestTransaction ? latestTransaction.date : monthUtils.currentDay(),- );+ try {+ const [earliestTransactionResult, latestTransactionResult] =+ await Promise.all([+ send('get-earliest-transaction').catch(() => null),+ send('get-latest-transaction').catch(() => null),+ ]);++ const computedBounds = calculateDateRangeBoundMonths(+ earliestTransactionResult,+ latestTransactionResult,+ );- const currentMonth = monthUtils.currentMonth();- let earliestMonth = earliestTransaction- ? monthUtils.monthFromDate(- parseISO(fromDateRepr(earliestTransaction.date)),- )- : currentMonth;- const latestMonth = latestTransaction- ? monthUtils.monthFromDate(- parseISO(fromDateRepr(latestTransaction.date)),- )- : currentMonth;-- // Make sure the month selects are at least populated with a- // year's worth of months. We can undo this when we have fancier- // date selects.- const yearAgo = monthUtils.subMonths(latestMonth, 12);- if (earliestMonth > yearAgo) {- earliestMonth = yearAgo;+ setEarliestTransaction(computedBounds.earliestTransactionDate);+ setLatestTransaction(computedBounds.latestTransactionDate);++ // Make sure the month selects are at least populated with a+ // year's worth of months. We can undo this when we have fancier+ // date selects.+ let computedEarliestMonth = computedBounds.earliestMonth;+ const yearAgo = monthUtils.subMonths(computedBounds.latestMonth, 12);+ if (computedEarliestMonth > yearAgo) {+ computedEarliestMonth = yearAgo;+ }++ setEarliestMonth(computedEarliestMonth);+ setLatestMonth(computedBounds.latestMonth);+ } finally {+ setIsTransactionBoundsReady(true);}-- const allMonths = monthUtils- .rangeInclusive(earliestMonth, latestMonth)- .map(month => ({- name: month,- pretty: monthUtils.format(month, 'MMMM yyyy', locale),- }))- .reverse();-- setAllMonths(allMonths);}void run();- }, [locale]);+ }, []);const filters = useRuleConditionFilters(conditionsRef.current,@@ -384,28 +444,6 @@ function QueryItem({sendUpdate,]);- function handleStartDateChange(newStart: string) {- setStartDate(normalizeQueryTimeFrameStart(newStart));- sendUpdate(- filters.conditions,- filters.conditionsOp,- normalizeQueryTimeFrameStart(newStart),- endDate,- timeRangeRef.current as TimeFrame['mode'],- );- }-- function handleEndDateChange(newEnd: string) {- setEndDate(normalizeQueryTimeFrameEnd(newEnd));- sendUpdate(- filters.conditions,- filters.conditionsOp,- startDate,- normalizeQueryTimeFrameEnd(newEnd),- timeRangeRef.current as TimeFrame['mode'],- );- }-async function handleExport() {const config = {conditions: filters.conditions,@@ -519,6 +557,44 @@ function QueryItem({? presetTimeRangeLabels[timeRangeMode]: null;+ function formatDayLabel(date: string) {+ return monthUtils.format(date, dateFormat);+ }++ const [pickerStartDate, pickerEndDate] = clampMonthRangeToBounds(+ ...normalizeMonthRangeForPicker(startDate, endDate),+ earliestMonth,+ latestMonth,+ );++ const presets: DateRangePreset[] = buildDateRangePresets({+ t,+ onSelectRange: ([rangeStart, rangeEnd, rangeMode]) => {+ const [normalizedRangeStart, normalizedRangeEnd] =+ normalizeMonthPickerSelectionForQuery(rangeStart, rangeEnd);++ setStartDate(normalizedRangeStart);+ setEndDate(normalizedRangeEnd);+ sendUpdate(+ filters.conditions,+ filters.conditionsOp,+ normalizedRangeStart,+ normalizedRangeEnd,+ rangeMode,+ );+ },+ earliestTransaction,+ latestTransaction,+ show1Month: true,+ includeAllTime: true,+ });++ const isDateRangePickerReady = canRenderDateRangePicker(+ isTransactionBoundsReady,+ earliestMonth,+ latestMonth,+ );+return (<Viewstyle={{@@ -666,6 +742,7 @@ function QueryItem({justifyContent: 'flex-end',gap: 8,marginTop: 16,+ alignItems: 'center',}}><Button@@ -684,7 +761,6 @@ function QueryItem({setStartDate(newStart);setEndDate(newEnd);- timeRangeRef.current = newMode;sendUpdate(filters.conditions,filters.conditionsOp,@@ -696,163 +772,63 @@ function QueryItem({>{timeRangeLabel}</Button>- <Button- ref={timeRangeMenuTriggerRef}- variant="bare"- onPress={() => setTimeRangeMenuOpen(true)}- >- ⋮- </Button>- <Popover- triggerRef={timeRangeMenuTriggerRef}- placement="bottom start"- isOpen={timeRangeMenuOpen}- onOpenChange={() => setTimeRangeMenuOpen(false)}- >- <Menu- onMenuSelect={item => {- let start: string, end: string, mode: TimeFrame['mode'];- const currentMode = timeRangeRef.current as TimeFrame['mode'];- // For quick selections, use the current toggle state (static vs sliding-window)- const quickSelectMode = ['static', 'sliding-window'].includes(- currentMode,- )- ? currentMode- : 'sliding-window';-- switch (item) {- case 'last-month': {- const prevMonth = monthUtils.subMonths(- monthUtils.currentMonth(),- 1,- );- start = monthUtils.firstDayOfMonth(prevMonth);- end = monthUtils.lastDayOfMonth(prevMonth);- mode = 'lastMonth';- break;- }- case '1-month': {- const [startMonth, endMonth] = getLatestRange(0);- start = monthUtils.firstDayOfMonth(startMonth);- end = monthUtils.lastDayOfMonth(endMonth);- mode = quickSelectMode;- break;- }- case '3-months': {- const [startMonth, endMonth] = getLatestRange(2);- start = monthUtils.firstDayOfMonth(startMonth);- end = monthUtils.lastDayOfMonth(endMonth);- mode = quickSelectMode;- break;- }- case '6-months': {- const [startMonth, endMonth] = getLatestRange(5);- start = monthUtils.firstDayOfMonth(startMonth);- end = monthUtils.lastDayOfMonth(endMonth);- mode = quickSelectMode;- break;- }- case '1-year': {- const [startMonth, endMonth] = getLatestRange(11);- start = monthUtils.firstDayOfMonth(startMonth);- end = monthUtils.lastDayOfMonth(endMonth);- mode = quickSelectMode;- break;- }- case 'year-to-date': {- [start, end] = getLiveRange(- 'Year to date',- _earliestTransaction,- _latestTransaction,- true,- );- mode = 'yearToDate';- break;- }- case 'last-year': {- [start, end] = getLiveRange(- 'Last year',- _earliestTransaction,- _latestTransaction,- false,- );- mode = 'lastYear';- break;- }- case 'prior-year-to-date': {- [start, end] = getLiveRange(- 'Prior year to date',- _earliestTransaction,- _latestTransaction,- false,- );- mode = 'priorYearToDate';- break;- }- case 'current-quarter': {- [start, end] = getLiveRange(- 'Current quarter',- _earliestTransaction,- _latestTransaction,- false,- );- mode = 'currentQuarter';- break;- }- case 'previous-quarter': {- [start, end] = getLiveRange(- 'Previous quarter',- _earliestTransaction,- _latestTransaction,- false,- );- mode = 'previousQuarter';- break;- }- case 'all-time': {- [start, end] = getLiveRange(- 'All time',- _earliestTransaction,- _latestTransaction,- true,- );- mode = 'full';- break;- }- default:- return;+ {isDateRangePickerReady ? (+ <DateRangePicker+ start={pickerStartDate}+ end={pickerEndDate}+ minDate={earliestMonth}+ maxDate={latestMonth}+ granularities={['month']}+ locale={language}+ formatDayLabel={formatDayLabel}+ labels={{+ selectBy: t('Select by'),+ quickSelect: t('Quick select'),+ month: t('Month'),+ day: t('Day'),+ previous: t('Previous'),+ next: t('Next'),+ previousMonth: t('Previous month'),+ nextMonth: t('Next month'),+ year: t('Year'),+ dateRange: t('Date range'),+ }}+ presets={presets}+ onChangeDates={(newStart, newEnd) => {+ if (+ shouldIgnoreMonthPickerNoop(+ startDate,+ endDate,+ newStart,+ newEnd,+ )+ ) {+ return;}- setStartDate(start);- setEndDate(end);- timeRangeRef.current = mode;++ const [normalizedStart, normalizedEnd] =+ normalizeMonthPickerSelectionForQuery(newStart, newEnd);++ setStartDate(normalizedStart);+ setEndDate(normalizedEnd);sendUpdate(filters.conditions,filters.conditionsOp,- start,- end,- mode,+ normalizedStart,+ normalizedEnd,+ 'static',);- setTimeRangeMenuOpen(false);}}- items={[- { name: '1-month', text: t('1 month') },- { name: '3-months', text: t('3 months') },- { name: '6-months', text: t('6 months') },- { name: '1-year', text: t('1 year') },- Menu.line,- { name: 'year-to-date', text: t('Year to date') },- { name: 'last-month', text: t('Last month') },- { name: 'last-year', text: t('Last year') },- {- name: 'prior-year-to-date',- text: t('Prior year to date'),- },- { name: 'current-quarter', text: t('Current quarter') },- { name: 'previous-quarter', text: t('Previous quarter') },- { name: 'all-time', text: t('All time') },- ]}/>- </Popover>+ ) : (+ <Button+ variant="normal"+ isDisabled+ aria-label={t('Loading date range...')}+ >+ {t('Loading date range...')}+ </Button>+ )}</View>{presetTimeRangeLabel ? (@@ -867,62 +843,6 @@ function QueryItem({}}/>) : null}-- {allMonths.length > 0 && (- <View- style={{- display: 'flex',- flexDirection: 'row',- gap: 10,- marginTop: 8,- alignItems: 'center',- }}- >- <Select- disabled={isPresetTimeRange}- value={fromDateRepr(startDate)}- defaultLabel={monthUtils.format(- fromDateRepr(startDate),- 'MMMM yyyy',- locale,- )}- onChange={newValue => {- const [validatedStart] = validateStart(- allMonths[allMonths.length - 1].name,- allMonths[0].name,- newValue,- fromDateRepr(endDate),- );- handleStartDateChange(validatedStart);- }}- options={allMonths.map(({ name, pretty }) => [name, pretty])}- style={{ flex: 1 }}- />- <Text style={{ fontSize: 12, color: theme.pageTextSubdued }}>- <Trans>to</Trans>- </Text>- <Select- disabled={isPresetTimeRange}- value={fromDateRepr(endDate)}- defaultLabel={monthUtils.format(- fromDateRepr(endDate),- 'MMMM yyyy',- locale,- )}- onChange={newValue => {- const [, validatedEnd] = validateEnd(- allMonths[allMonths.length - 1].name,- allMonths[0].name,- fromDateRepr(startDate),- newValue,- );- handleEndDateChange(validatedEnd);- }}- options={allMonths.map(({ name, pretty }) => [name, pretty])}- style={{ flex: 1 }}- />- </View>- )}</View><View style={{ marginBottom: 8, flex: 1 }}>diff --git a/packages/desktop-client/src/components/reports/Header.tsx b/packages/desktop-client/src/components/reports/Header.tsxindex 3f60b423a3..f78e990e30 100644--- a/packages/desktop-client/src/components/reports/Header.tsx+++ b/packages/desktop-client/src/components/reports/Header.tsx@@ -1,5 +1,5 @@import type { ComponentProps, ReactNode } from 'react';-import { Trans, useTranslation } from 'react-i18next';+import { useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';import { DateRangePicker } from '@actual-app/components/date-range-picker';@@ -23,14 +23,8 @@ import { getFirstDayOfWeek } from '#components/select/getFirstDayOfWeek';import { useDateFormat } from '#hooks/useDateFormat';import { useLanguage } from '#hooks/useLocale';-import { getLiveRange } from './getLiveRange';-import {- calculateTimeRange,- getFullFutureRange,- getFullRange,- getLatestRange,- getNextRange,-} from './reportRanges';+import { buildDateRangePresets } from './dateRangePresets';+import { calculateTimeRange } from './reportRanges';type HeaderProps = {start: TimeFrame['start'];@@ -106,115 +100,16 @@ export function Header({const language = useLanguage();const dateFormat = useDateFormat() || 'MM/dd/yyyy';- // Live-range presets return day-shaped bounds; collapse them to months.- function liveRangeAsMonths(- rangeName: string,- includeCurrentInterval: boolean,- mode: TimeFrame['mode'],- ): [string, string, TimeFrame['mode']] {- const [rangeStart, rangeEnd] = getLiveRange(- rangeName,- earliestTransaction,- latestTransaction,- includeCurrentInterval,- firstDayOfWeekIdx,- );- return [- monthUtils.getMonth(rangeStart),- monthUtils.getMonth(rangeEnd),- mode,- ];- }-- // The picker previews the range via getRange while staying open, then- // commits via onSelect on close so the preset's mode is preserved.- function makePreset(- key: string,- label: ReactNode,- getFullRange: () => readonly [string, string, TimeFrame['mode']],- ): DateRangePreset {- return {- key,- label,- getRange: () => {- const [rangeStart, rangeEnd] = getFullRange();- return [rangeStart, rangeEnd];- },- onSelect: () => onChangeDates(...getFullRange()),- };- }-- const presets: DateRangePreset[] = showFutureRange- ? [- ...(show1Month- ? [- makePreset('next-month', <Trans>Next month</Trans>, () =>- getNextRange(0),- ),- ]- : []),- makePreset('next-3-months', <Trans>Next 3 months</Trans>, () =>- getNextRange(2),- ),- makePreset('next-6-months', <Trans>Next 6 months</Trans>, () =>- getNextRange(5),- ),- makePreset('next-year', <Trans>Next year</Trans>, () =>- getNextRange(11),- ),- makePreset('all-future', <Trans>All future</Trans>, () =>- getFullFutureRange(latestTransaction),- ),- ]- : [- ...(show1Month- ? [- makePreset('1-month', <Trans>1 month</Trans>, () =>- getLatestRange(0),- ),- ]- : []),- makePreset('3-months', <Trans>3 months</Trans>, () =>- getLatestRange(2),- ),- makePreset('6-months', <Trans>6 months</Trans>, () =>- getLatestRange(5),- ),- makePreset('1-year', <Trans>1 year</Trans>, () => getLatestRange(11)),- makePreset('year-to-date', <Trans>Year to date</Trans>, () =>- liveRangeAsMonths('Year to date', true, 'yearToDate'),- ),- makePreset('last-month', <Trans>Last month</Trans>, () =>- liveRangeAsMonths('Last month', false, 'lastMonth'),- ),- makePreset('last-year', <Trans>Last year</Trans>, () =>- liveRangeAsMonths('Last year', false, 'lastYear'),- ),- makePreset(- 'prior-year-to-date',- <Trans>Prior year to date</Trans>,- () =>- liveRangeAsMonths('Prior year to date', false, 'priorYearToDate'),- ),- makePreset('current-quarter', <Trans>Current quarter</Trans>, () =>- liveRangeAsMonths('Current quarter', false, 'currentQuarter'),- ),- makePreset('previous-quarter', <Trans>Previous quarter</Trans>, () =>- liveRangeAsMonths('Previous quarter', false, 'previousQuarter'),- ),- // `allMonths` may still be empty before the report's async load- // finishes.- ...(allMonths.length- ? [- makePreset('all-time', <Trans>All time</Trans>, () =>- getFullRange(- allMonths[allMonths.length - 1].name,- allMonths[0].name,- ),- ),- ]- : []),- ];+ const presets: DateRangePreset[] = buildDateRangePresets({+ t,+ onSelectRange: range => onChangeDates(...range),+ earliestTransaction,+ latestTransaction,+ show1Month,+ showFutureRange,+ includeAllTime: allMonths.length > 0,+ firstDayOfWeekIdx,+ });return (<Viewdiff --git a/packages/desktop-client/src/components/reports/dateRangePresets.test.ts b/packages/desktop-client/src/components/reports/dateRangePresets.test.tsnew file mode 100644index 0000000000..ad633fd97b--- /dev/null+++ b/packages/desktop-client/src/components/reports/dateRangePresets.test.ts@@ -0,0 +1,396 @@+import { describe, expect, it, vi } from 'vitest';++import { buildDateRangePresets } from './dateRangePresets';++// In test mode, monthUtils.currentDay() returns '2017-01-01'+// and monthUtils.currentMonth() returns '2017-01'+const EARLIEST_TRANSACTION = '2015-01-01';+const LATEST_TRANSACTION = '2017-01-01';++describe('buildDateRangePresets', () => {+ const mockOnSelectRange = vi.fn();+ const mockT = (text: string) => text;++ describe('past presets (default, non-future)', () => {+ it('builds 1-month preset when show1Month is true', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: true,+ includeAllTime: true,+ });++ const oneMonthPreset = presets.find(p => p.key === '1-month');+ expect(oneMonthPreset).toBeDefined();+ expect(oneMonthPreset?.label).toBe('1 month');+ });++ it('omits 1-month preset when show1Month is false', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const oneMonthPreset = presets.find(p => p.key === '1-month');+ expect(oneMonthPreset).toBeUndefined();+ });++ it('includes standard past presets (3-month, 6-month, 1-year)', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const keys = presets.map(p => p.key);+ expect(keys).toContain('3-months');+ expect(keys).toContain('6-months');+ expect(keys).toContain('1-year');+ });++ it('includes live presets (year-to-date, last-month, last-year, prior-year-to-date)', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const keys = presets.map(p => p.key);+ expect(keys).toContain('year-to-date');+ expect(keys).toContain('last-month');+ expect(keys).toContain('last-year');+ expect(keys).toContain('prior-year-to-date');+ expect(keys).toContain('current-quarter');+ expect(keys).toContain('previous-quarter');+ });++ it('includes all-time preset when includeAllTime is true', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const allTimePreset = presets.find(p => p.key === 'all-time');+ expect(allTimePreset).toBeDefined();+ });++ it('omits all-time preset when includeAllTime is false', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: false,+ });++ const allTimePreset = presets.find(p => p.key === 'all-time');+ expect(allTimePreset).toBeUndefined();+ });++ it('preset getRange returns month-shaped range for past presets', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const threeMonthPreset = presets.find(p => p.key === '3-months');+ const [start, end] = threeMonthPreset!.getRange();+ // 3 months (offset=2) back from 2017-01 = 2016-11 to 2017-01+ expect(start).toBe('2016-11');+ expect(end).toBe('2017-01');+ });++ it('preset onSelect triggers callback with range and mode', () => {+ const onSelect = vi.fn();+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: onSelect,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const threeMonthPreset = presets.find(p => p.key === '3-months');+ threeMonthPreset!.onSelect();++ expect(onSelect).toHaveBeenCalledOnce();+ const [start, end, mode] = onSelect.mock.calls[0][0];+ // 3 months (offset=2) back from 2017-01 = 2016-11 to 2017-01+ expect(start).toBe('2016-11');+ expect(end).toBe('2017-01');+ expect(mode).toBe('sliding-window');+ });+ });++ describe('future presets (showFutureRange=true)', () => {+ it('builds next-month preset when show1Month is true', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: true,+ showFutureRange: true,+ includeAllTime: true,+ });++ const nextMonthPreset = presets.find(p => p.key === 'next-month');+ expect(nextMonthPreset).toBeDefined();+ });++ it('omits next-month preset when show1Month is false', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ showFutureRange: true,+ includeAllTime: true,+ });++ const nextMonthPreset = presets.find(p => p.key === 'next-month');+ expect(nextMonthPreset).toBeUndefined();+ });++ it('includes future presets (next-3-months, next-6-months, next-year, all-future)', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ showFutureRange: true,+ includeAllTime: true,+ });++ const keys = presets.map(p => p.key);+ expect(keys).toContain('next-3-months');+ expect(keys).toContain('next-6-months');+ expect(keys).toContain('next-year');+ expect(keys).toContain('all-future');+ });++ it('does not include past presets when showFutureRange is true', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ showFutureRange: true,+ includeAllTime: true,+ });++ const keys = presets.map(p => p.key);+ expect(keys).not.toContain('3-months');+ expect(keys).not.toContain('6-months');+ expect(keys).not.toContain('year-to-date');+ expect(keys).not.toContain('last-month');+ });+ });++ describe('live range presets clamped to transaction bounds', () => {+ it('year-to-date returns range clamped to earliest transaction', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: '2016-06-15',+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const ytdPreset = presets.find(p => p.key === 'year-to-date');+ const [start, end] = ytdPreset!.getRange();+ // Year-to-date starts 2017-01-01, clamped to earliest transaction month 2016-06+ expect(start).toBe('2017-01');+ expect(end).toBe('2017-01');+ });++ it('last-month returns correct month regardless of transaction bounds', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const lastMonthPreset = presets.find(p => p.key === 'last-month');+ const [start, end] = lastMonthPreset!.getRange();+ expect(start).toBe('2016-12');+ expect(end).toBe('2016-12');+ });++ it('all-time returns full transaction range as month bounds', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: '2015-03-15',+ latestTransaction: '2017-01-20',+ show1Month: false,+ includeAllTime: true,+ });++ const allTimePreset = presets.find(p => p.key === 'all-time');+ const [start, end] = allTimePreset!.getRange();+ // Full range is earliest month to latest month+ expect(start).toBe('2015-03');+ expect(end).toBe('2017-01');+ });++ it('live presets include mode in onSelect callback', () => {+ const onSelect = vi.fn();+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: onSelect,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const ytdPreset = presets.find(p => p.key === 'year-to-date');+ ytdPreset!.onSelect();++ expect(onSelect).toHaveBeenCalledOnce();+ const [, , mode] = onSelect.mock.calls[0][0];+ expect(mode).toBe('yearToDate');+ });++ it('past presets include sliding-window mode in onSelect callback', () => {+ const onSelect = vi.fn();+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: onSelect,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const threeMonthPreset = presets.find(p => p.key === '3-months');+ threeMonthPreset!.onSelect();++ expect(onSelect).toHaveBeenCalledOnce();+ const [, , mode] = onSelect.mock.calls[0][0];+ expect(mode).toBe('sliding-window');+ });++ it('all-time preset includes full mode in onSelect callback', () => {+ const onSelect = vi.fn();+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: onSelect,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const allTimePreset = presets.find(p => p.key === 'all-time');+ allTimePreset!.onSelect();++ expect(onSelect).toHaveBeenCalledOnce();+ const [, , mode] = onSelect.mock.calls[0][0];+ expect(mode).toBe('full');+ });++ it('quarter presets return quarter month bounds and preserve their modes', () => {+ const onSelect = vi.fn();+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: onSelect,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: LATEST_TRANSACTION,+ show1Month: false,+ includeAllTime: true,+ });++ const currentQuarterPreset = presets.find(+ p => p.key === 'current-quarter',+ );+ const previousQuarterPreset = presets.find(+ p => p.key === 'previous-quarter',+ );++ // The current quarter is unfinished in test mode (2017-01), so it is+ // clamped to the latest available transaction month.+ expect(currentQuarterPreset?.getRange()).toEqual(['2017-01', '2017-01']);+ expect(previousQuarterPreset?.getRange()).toEqual(['2016-10', '2016-12']);++ currentQuarterPreset!.onSelect();+ previousQuarterPreset!.onSelect();++ expect(onSelect.mock.calls[0][0][2]).toBe('currentQuarter');+ expect(onSelect.mock.calls[1][0][2]).toBe('previousQuarter');+ });++ it('clamps current-quarter preset selection to latest transaction month in unfinished quarters', () => {+ const onSelect = vi.fn();+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: onSelect,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: '2017-02-10',+ show1Month: false,+ includeAllTime: true,+ });++ const currentQuarterPreset = presets.find(+ p => p.key === 'current-quarter',+ );++ expect(currentQuarterPreset?.getRange()).toEqual(['2017-01', '2017-02']);++ currentQuarterPreset!.onSelect();++ expect(onSelect).toHaveBeenCalledWith([+ '2017-01',+ '2017-02',+ 'currentQuarter',+ ]);+ });++ it('returns latestMonth for both endpoints when the current quarter lies entirely beyond the latest transaction', () => {+ const presets = buildDateRangePresets({+ t: mockT,+ onSelectRange: mockOnSelectRange,+ earliestTransaction: EARLIEST_TRANSACTION,+ latestTransaction: '2016-12-15',+ show1Month: false,+ includeAllTime: true,+ });++ const currentQuarterPreset = presets.find(+ p => p.key === 'current-quarter',+ );++ expect(currentQuarterPreset?.getRange()).toEqual(['2016-12', '2016-12']);+ });+ });+});diff --git a/packages/desktop-client/src/components/reports/dateRangePresets.ts b/packages/desktop-client/src/components/reports/dateRangePresets.tsnew file mode 100644index 0000000000..5695534787--- /dev/null+++ b/packages/desktop-client/src/components/reports/dateRangePresets.ts@@ -0,0 +1,245 @@+import type { DateRangePreset } from '@actual-app/components/date-range-picker';+import * as monthUtils from '@actual-app/core/shared/months';+import type { TimeFrame } from '@actual-app/core/types/models';+import type { SyncedPrefs } from '@actual-app/core/types/prefs';++import { getLiveRange } from './getLiveRange';+import { clampMonthRangeToBounds } from './monthRange';+import {+ getFullFutureRange,+ getFullRange,+ getLatestRange,+ getNextRange,+} from './reportRanges';++type PresetRange = readonly [string, string, TimeFrame['mode']];++type BuildDateRangePresetsOptions = {+ t: (text: string) => string;+ onSelectRange: (range: PresetRange) => void;+ earliestTransaction: string;+ latestTransaction: string;+ show1Month?: boolean;+ showFutureRange?: boolean;+ includeAllTime?: boolean;+ firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'];+};++function liveRangeAsMonths(+ rangeName: string,+ includeCurrentInterval: boolean,+ mode: TimeFrame['mode'],+ earliestTransaction: string,+ latestTransaction: string,+ firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'],+): PresetRange {+ const [rangeStart, rangeEnd] = getLiveRange(+ rangeName,+ earliestTransaction,+ latestTransaction,+ includeCurrentInterval,+ firstDayOfWeekIdx,+ );++ return [monthUtils.getMonth(rangeStart), monthUtils.getMonth(rangeEnd), mode];+}++function makePreset(+ key: string,+ label: string,+ getRange: () => PresetRange,+ onSelectRange: (range: PresetRange) => void,+): DateRangePreset {+ return {+ key,+ label,+ getRange: () => {+ const [rangeStart, rangeEnd] = getRange();+ return [rangeStart, rangeEnd];+ },+ onSelect: () => {+ onSelectRange(getRange());+ },+ };+}++export function buildDateRangePresets({+ t,+ onSelectRange,+ earliestTransaction,+ latestTransaction,+ show1Month = false,+ showFutureRange = false,+ includeAllTime = true,+ firstDayOfWeekIdx,+}: BuildDateRangePresetsOptions): DateRangePreset[] {+ const earliestMonth = monthUtils.getMonth(earliestTransaction);+ const latestMonth = monthUtils.getMonth(latestTransaction);++ if (showFutureRange) {+ return [+ ...(show1Month+ ? [+ makePreset(+ 'next-month',+ t('Next month'),+ () => getNextRange(0),+ onSelectRange,+ ),+ ]+ : []),+ makePreset(+ 'next-3-months',+ t('Next 3 months'),+ () => getNextRange(2),+ onSelectRange,+ ),+ makePreset(+ 'next-6-months',+ t('Next 6 months'),+ () => getNextRange(5),+ onSelectRange,+ ),+ makePreset(+ 'next-year',+ t('Next year'),+ () => getNextRange(11),+ onSelectRange,+ ),+ makePreset(+ 'all-future',+ t('All future'),+ () => getFullFutureRange(latestMonth),+ onSelectRange,+ ),+ ];+ }++ return [+ ...(show1Month+ ? [+ makePreset(+ '1-month',+ t('1 month'),+ () => getLatestRange(0),+ onSelectRange,+ ),+ ]+ : []),+ makePreset(+ '3-months',+ t('3 months'),+ () => getLatestRange(2),+ onSelectRange,+ ),+ makePreset(+ '6-months',+ t('6 months'),+ () => getLatestRange(5),+ onSelectRange,+ ),+ makePreset('1-year', t('1 year'), () => getLatestRange(11), onSelectRange),+ makePreset(+ 'year-to-date',+ t('Year to date'),+ () =>+ liveRangeAsMonths(+ 'Year to date',+ true,+ 'yearToDate',+ earliestTransaction,+ latestTransaction,+ firstDayOfWeekIdx,+ ),+ onSelectRange,+ ),+ makePreset(+ 'last-month',+ t('Last month'),+ () =>+ liveRangeAsMonths(+ 'Last month',+ false,+ 'lastMonth',+ earliestTransaction,+ latestTransaction,+ firstDayOfWeekIdx,+ ),+ onSelectRange,+ ),+ makePreset(+ 'last-year',+ t('Last year'),+ () =>+ liveRangeAsMonths(+ 'Last year',+ false,+ 'lastYear',+ earliestTransaction,+ latestTransaction,+ firstDayOfWeekIdx,+ ),+ onSelectRange,+ ),+ makePreset(+ 'prior-year-to-date',+ t('Prior year to date'),+ () =>+ liveRangeAsMonths(+ 'Prior year to date',+ false,+ 'priorYearToDate',+ earliestTransaction,+ latestTransaction,+ firstDayOfWeekIdx,+ ),+ onSelectRange,+ ),+ makePreset(+ 'current-quarter',+ t('Current quarter'),+ () => {+ const [start, end, mode] = liveRangeAsMonths(+ 'Current quarter',+ false,+ 'currentQuarter',+ earliestTransaction,+ latestTransaction,+ firstDayOfWeekIdx,+ );+ const [clampedStart, clampedEnd] = clampMonthRangeToBounds(+ start,+ end,+ earliestMonth,+ latestMonth,+ );+ return [clampedStart, clampedEnd, mode];+ },+ onSelectRange,+ ),+ makePreset(+ 'previous-quarter',+ t('Previous quarter'),+ () =>+ liveRangeAsMonths(+ 'Previous quarter',+ false,+ 'previousQuarter',+ earliestTransaction,+ latestTransaction,+ firstDayOfWeekIdx,+ ),+ onSelectRange,+ ),+ ...(includeAllTime+ ? [+ makePreset(+ 'all-time',+ t('All time'),+ () => getFullRange(earliestMonth, latestMonth),+ onSelectRange,+ ),+ ]+ : []),+ ];+}diff --git a/packages/desktop-client/src/components/reports/monthRange.test.ts b/packages/desktop-client/src/components/reports/monthRange.test.tsnew file mode 100644index 0000000000..9672b4acad--- /dev/null+++ b/packages/desktop-client/src/components/reports/monthRange.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';++import { clampMonthRangeToBounds } from './monthRange';++describe('clampMonthRangeToBounds', () => {+ it('clamps ranges to the transaction bounds, including inverted fallback ranges', () => {+ expect(+ clampMonthRangeToBounds('2025-12', '2026-02', '2026-03', '2026-12'),+ ).toEqual(['2026-03', '2026-03']);++ expect(+ clampMonthRangeToBounds('2026-12', '2027-01', '2026-03', '2026-12'),+ ).toEqual(['2026-12', '2026-12']);++ expect(+ clampMonthRangeToBounds('2027-01', '2027-03', '2026-03', '2026-12'),+ ).toEqual(['2026-12', '2026-12']);+ });+});diff --git a/packages/desktop-client/src/components/reports/monthRange.ts b/packages/desktop-client/src/components/reports/monthRange.tsnew file mode 100644index 0000000000..49029038de--- /dev/null+++ b/packages/desktop-client/src/components/reports/monthRange.ts@@ -0,0 +1,16 @@+export function clampMonthRangeToBounds(+ start: string,+ end: string,+ earliestMonth: string,+ latestMonth: string,+) {+ const clampedStart = start < earliestMonth ? earliestMonth : start;+ const clampedEnd = end > latestMonth ? latestMonth : end;++ if (clampedStart > clampedEnd) {+ const fallback = start < earliestMonth ? earliestMonth : latestMonth;+ return [fallback, fallback] satisfies [string, string];+ }++ return [clampedStart, clampedEnd] satisfies [string, string];+}diff --git a/upcoming-release-notes/daterange-in-formula-card.md b/upcoming-release-notes/daterange-in-formula-card.mdnew file mode 100644index 0000000000..0495e37770--- /dev/null+++ b/upcoming-release-notes/daterange-in-formula-card.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [RonanPresle]+---++Add the new DateRange component in the FormulaCard