A local-first personal finance app
[AI] Respect the date format preference in daily and weekly report intervals (#8715)
Onika Dye-Flynnc85a03136e0c
diff --git a/packages/desktop-client/src/components/reports/ReportOptions.test.ts b/packages/desktop-client/src/components/reports/ReportOptions.test.tsnew file mode 100644index 0000000000..279bd7b312--- /dev/null+++ b/packages/desktop-client/src/components/reports/ReportOptions.test.ts@@ -0,0 +1,56 @@+import { getIntervalFormat, ReportOptions } from './ReportOptions';++// The six values selectable in Settings -> Formatting -> Dates.+// See `components/settings/Format.tsx`.+const DATE_FORMATS = [+ 'MM/dd/yyyy',+ 'dd/MM/yyyy',+ 'yyyy-MM-dd',+ 'MM.dd.yyyy',+ 'dd.MM.yyyy',+ 'dd-MM-yyyy',+] as const;++describe('getIntervalFormat', () => {+ describe('Daily and Weekly intervals', () => {+ // These two are the only intervals whose label encodes day/month ordering,+ // so they are the only ones the preference can disagree with.+ it.each(DATE_FORMATS)('uses %s exactly as it is set', dateFormat => {+ expect(getIntervalFormat('Daily', dateFormat)).toBe(dateFormat);+ expect(getIntervalFormat('Weekly', dateFormat)).toBe(dateFormat);+ });++ it('keeps the four-digit year the preference asks for', () => {+ // An earlier revision shortened `yyyy` to `yy` to keep tick labels narrow.+ // That was reversed in review: a preference of `yyyy` shows as `yyyy`,+ // even though it makes the labels wider.+ for (const dateFormat of DATE_FORMATS) {+ expect(getIntervalFormat('Daily', dateFormat)).toContain('yyyy');+ }+ });++ it('falls back to an ISO-style format when no preference is set', () => {+ expect(getIntervalFormat('Daily', undefined)).toBe('yyyy-MM-dd');+ expect(getIntervalFormat('Weekly', undefined)).toBe('yyyy-MM-dd');+ });+ });++ describe('Monthly and Yearly intervals', () => {+ // No day/month ambiguity to resolve, so the preference must not reach them.+ it.each(['Monthly', 'Yearly'])(+ '%s is unchanged by the date format preference',+ interval => {+ const base = ReportOptions.intervalFormat.get(interval);+ for (const dateFormat of DATE_FORMATS) {+ expect(getIntervalFormat(interval, dateFormat)).toBe(base);+ }+ },+ );+ });++ it('returns an empty string for an unknown interval', () => {+ // Call sites currently write `intervalFormat.get(interval) || ''`, so an+ // unknown key has to keep producing a falsy format rather than throwing.+ expect(getIntervalFormat('Fortnightly', 'MM/dd/yyyy')).toBe('');+ });+});diff --git a/packages/desktop-client/src/components/reports/ReportOptions.ts b/packages/desktop-client/src/components/reports/ReportOptions.tsindex 8c078fe18c..f2c2c0c137 100644--- a/packages/desktop-client/src/components/reports/ReportOptions.ts+++ b/packages/desktop-client/src/components/reports/ReportOptions.ts@@ -298,6 +298,31 @@ export const ReportOptions = {>(intervalOptions.map(item => [item.key, item.range])),};+// Only Daily and Weekly labels spell out a day and a month, so they are the+// only intervals whose ordering a date-format preference can disagree with.+// Monthly ("MMM ''yy") and Yearly ("yyyy") are unambiguous either way.+const dayLevelIntervals = new Set(['Daily', 'Weekly']);++/**+ * The display format for an interval's labels, following the user's date+ * format preference.+ *+ * @param interval one of the `intervalOptions` keys.+ * @param dateFormat the `dateFormat` synced pref, e.g. 'MM/dd/yyyy'.+ * @returns a date-fns format string, or '' for an unrecognised interval.+ */+export function getIntervalFormat(+ interval: string,+ dateFormat?: string,+): string {+ if (!dayLevelIntervals.has(interval)) {+ return ReportOptions.intervalFormat.get(interval) ?? '';+ }+ // The preference is used exactly as it is set, including a four-digit year.+ // This does make the tick labels wider than the format they replaced.+ return dateFormat || 'yyyy-MM-dd';+}+export type QueryDataEntity = {date: string;category: string;diff --git a/packages/desktop-client/src/components/reports/ReportSidebar.tsx b/packages/desktop-client/src/components/reports/ReportSidebar.tsxindex 7d001b21a8..dcea77a684 100644--- a/packages/desktop-client/src/components/reports/ReportSidebar.tsx+++ b/packages/desktop-client/src/components/reports/ReportSidebar.tsx@@ -25,12 +25,13 @@ import type {import type { SyncedPrefs } from '@actual-app/core/types/prefs';import { Information } from '#components/alerts';+import { useDateFormat } from '#hooks/useDateFormat';import { useLocale } from '#hooks/useLocale';import { CategorySelector } from './CategorySelector';import { defaultsList, disabledList } from './disabledList';import { getLiveRange } from './getLiveRange';-import { ReportOptions } from './ReportOptions';+import { getIntervalFormat, ReportOptions } from './ReportOptions';import type { dateRangeProps } from './ReportOptions';import { validateEnd, validateStart } from './reportRanges';import { setSessionReport } from './setSessionReport';@@ -112,6 +113,7 @@ export function ReportSidebar({}: ReportSidebarProps) {const { t } = useTranslation();const locale = useLocale();+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';const [menuOpen, setMenuOpen] = useState(false);const triggerRef = useRef(null);@@ -634,9 +636,7 @@ export function ReportSidebar({value={customReportItems.startDate}defaultLabel={monthUtils.format(customReportItems.startDate,- ReportOptions.intervalFormat.get(- customReportItems.interval,- ) || '',+ getIntervalFormat(customReportItems.interval, dateFormat),locale,)}options={allIntervals.map(({ name, pretty }) => [name, pretty])}@@ -668,9 +668,7 @@ export function ReportSidebar({value={customReportItems.endDate}defaultLabel={monthUtils.format(customReportItems.endDate,- ReportOptions.intervalFormat.get(- customReportItems.interval,- ) || '',+ getIntervalFormat(customReportItems.interval, dateFormat),locale,)}options={allIntervals.map(({ name, pretty }) => [name, pretty])}diff --git a/packages/desktop-client/src/components/reports/ReportSummary.tsx b/packages/desktop-client/src/components/reports/ReportSummary.tsxindex fab84bbde7..101352d345 100644--- a/packages/desktop-client/src/components/reports/ReportSummary.tsx+++ b/packages/desktop-client/src/components/reports/ReportSummary.tsx@@ -13,10 +13,11 @@ import type {import { FinancialText } from '#components/FinancialText';import { PrivacyFilter } from '#components/PrivacyFilter';+import { useDateFormat } from '#hooks/useDateFormat';import { useFormat } from '#hooks/useFormat';import { useLocale } from '#hooks/useLocale';-import { ReportOptions } from './ReportOptions';+import { getIntervalFormat, ReportOptions } from './ReportOptions';type ReportSummaryProps = {startDate: string;@@ -38,6 +39,8 @@ export function ReportSummary({const locale = useLocale();const { t } = useTranslation();const format = useFormat();+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';+ const intervalFormat = getIntervalFormat(interval, dateFormat);const net =balanceTypeOp === 'netAssets'@@ -71,27 +74,10 @@ export function ReportSummary({fontWeight: 600,}}>- {monthUtils.format(- startDate,- ReportOptions.intervalFormat.get(interval) || '',- locale,- )}- {monthUtils.format(- startDate,- ReportOptions.intervalFormat.get(interval) || '',- locale,- ) !==- monthUtils.format(- endDate,- ReportOptions.intervalFormat.get(interval) || '',- locale,- ) &&- ` ${t('to')} ` +- monthUtils.format(- endDate,- ReportOptions.intervalFormat.get(interval) || '',- locale,- )}+ {monthUtils.format(startDate, intervalFormat, locale)}+ {monthUtils.format(startDate, intervalFormat, locale) !==+ monthUtils.format(endDate, intervalFormat, locale) &&+ ` ${t('to')} ` + monthUtils.format(endDate, intervalFormat, locale)}</Text></View><Viewdiff --git a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsxindex 781617a5a3..417cd44cba 100644--- a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx+++ b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx@@ -25,6 +25,8 @@ import {} from '#components/reports/chart-theme';import { Container } from '#components/reports/Container';import { numberFormatterTooltip } from '#components/reports/numberFormatter';+import { getIntervalFormat } from '#components/reports/ReportOptions';+import { useDateFormat } from '#hooks/useDateFormat';import { useFormat } from '#hooks/useFormat';import type { UseFormatResult } from '#hooks/useFormat';import { usePrivacyMode } from '#hooks/usePrivacyMode';@@ -250,6 +252,7 @@ export function NetWorthGraph({const privacyMode = usePrivacyMode();const id = useId();const format = useFormat();+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';const animationProps = useRechartsAnimation({ animationDuration: 1000 });const [isTooltipActive, setIsTooltipActive] = useState(false);const [hoveredAccountId, setHoveredAccountId] = useState<string | null>(null);@@ -320,18 +323,22 @@ export function NetWorthGraph({);}, [sortedAccounts, mode]);- // Generate weekly tick positions when viewing Daily data+ // Generate weekly tick positions when viewing Daily data.+ // `point.x` is a display label, so it has to be parsed back with the same+ // format that produced it in net-worth-spreadsheet -- otherwise `parse`+ // returns Invalid Date, `getDay` returns NaN, and the ticks vanish silently.const weeklyTicks = useMemo(() => {if (interval !== 'Daily') {return undefined;}+ const pointFormat = getIntervalFormat(interval, dateFormat);return graphData.data.filter(point => {- const date = parse(point.x, 'yy-MM-dd', new Date());+ const date = parse(point.x, pointFormat, new Date());return getDay(date) === 1; // Monday}).map(point => point.x);- }, [interval, graphData.data]);+ }, [interval, dateFormat, graphData.data]);return (<Containerdiff --git a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx b/packages/desktop-client/src/components/reports/reports/CustomReport.tsxindex 4e41e6cca2..73d23cf009 100644--- a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx+++ b/packages/desktop-client/src/components/reports/reports/CustomReport.tsx@@ -42,6 +42,7 @@ import { LoadingIndicator } from '#components/reports/LoadingIndicator';import { ReportLegend } from '#components/reports/ReportLegend';import {defaultReport,+ getIntervalFormat,ReportOptions,} from '#components/reports/ReportOptions';import type { dateRangeProps } from '#components/reports/ReportOptions';@@ -56,6 +57,7 @@ import { useReport } from '#components/reports/useReport';import { calculateHasWarning, fromDateRepr } from '#components/reports/util';import { useAccounts } from '#hooks/useAccounts';import { useCategories } from '#hooks/useCategories';+import { useDateFormat } from '#hooks/useDateFormat';import { useFormat } from '#hooks/useFormat';import { useLocale } from '#hooks/useLocale';import { useLocalPref } from '#hooks/useLocalPref';@@ -145,6 +147,7 @@ function CustomReportInner({const locale = useLocale();const { t } = useTranslation();const format = useFormat();+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';const { data: categories = { grouped: [], list: [] } } = useCategories();const { isNarrowWidth } = useResponsive();@@ -386,7 +389,7 @@ function CustomReportInner({name: inter,pretty: monthUtils.format(inter,- ReportOptions.intervalFormat.get(interval) || '',+ getIntervalFormat(interval, dateFormat),locale,),}))@@ -455,6 +458,10 @@ function CustomReportInner({report.conditionsOp,includeCurrentInterval,savedStatus,+ // onSetAllIntervals formats the interval labels with the date preference,+ // and being an effect event it reads it without re-triggering -- so the+ // labels would stay stale until another dependency happened to change.+ dateFormat,]);useEffect(() => {@@ -561,6 +568,7 @@ function CustomReportInner({accounts,graphType,firstDayOfWeekIdx,+ dateFormat,});}, [startDate,@@ -582,6 +590,7 @@ function CustomReportInner({sortByOp,graphType,firstDayOfWeekIdx,+ dateFormat,]);const graphData = useReport('default', getGraphData);const groupedData = useReport('grouped', getGroupData);diff --git a/packages/desktop-client/src/components/reports/reports/GetCardData.tsx b/packages/desktop-client/src/components/reports/reports/GetCardData.tsxindex 6509db92e1..9cf2cc3388 100644--- a/packages/desktop-client/src/components/reports/reports/GetCardData.tsx+++ b/packages/desktop-client/src/components/reports/reports/GetCardData.tsx@@ -23,6 +23,7 @@ import { ReportOptions } from '#components/reports/ReportOptions';import { createCustomSpreadsheet } from '#components/reports/spreadsheets/custom-spreadsheet';import { createGroupedSpreadsheet } from '#components/reports/spreadsheets/grouped-spreadsheet';import { useReport } from '#components/reports/useReport';+import { useDateFormat } from '#hooks/useDateFormat';import { useSyncedPref } from '#hooks/useSyncedPref';function ErrorFallback() {@@ -85,6 +86,7 @@ export function GetCardData({}) {const { isNarrowWidth } = useResponsive();const [budgetType = 'envelope'] = useSyncedPref('budgetType');+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';let startDate = report.startDate;let endDate = report.endDate;@@ -161,6 +163,7 @@ export function GetCardData({graphType: report.graphType,firstDayOfWeekIdx,sortByOp: report.sortBy,+ dateFormat,});}, [report,@@ -171,6 +174,9 @@ export function GetCardData({endDate,firstDayOfWeekIdx,budgetType,+ // Load-bearing: without this the card keeps its old interval labels after+ // the date format preference changes, until something else invalidates it.+ dateFormat,]);const graphData = useReport('default' + report.name, getGraphData);const groupedData = useReport('grouped' + report.name, getGroupData);diff --git a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx b/packages/desktop-client/src/components/reports/reports/NetWorth.tsxindex 7a28cc1350..7e83eb5b63 100644--- a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx+++ b/packages/desktop-client/src/components/reports/reports/NetWorth.tsx@@ -38,6 +38,7 @@ import { useReport } from '#components/reports/useReport';import { fromDateRepr } from '#components/reports/util';import { useAccounts } from '#hooks/useAccounts';import { useDashboardWidget } from '#hooks/useDashboardWidget';+import { useDateFormat } from '#hooks/useDateFormat';import { useFormat } from '#hooks/useFormat';import { useLocale } from '#hooks/useLocale';import { useNavigate } from '#hooks/useNavigate';@@ -123,6 +124,7 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';const reportParams = useMemo(() =>@@ -136,6 +138,7 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {interval,firstDayOfWeekIdx,format,+ dateFormat,),[start,@@ -147,6 +150,7 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {interval,firstDayOfWeekIdx,format,+ dateFormat,],);const data = useReport('net_worth', reportParams);diff --git a/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx b/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsxindex c14067e6db..a65b9ed7e6 100644--- a/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx@@ -23,6 +23,7 @@ import { ReportCardName } from '#components/reports/ReportCardName';import { calculateTimeRange } from '#components/reports/reportRanges';import { createSpreadsheet as netWorthSpreadsheet } from '#components/reports/spreadsheets/net-worth-spreadsheet';import { useReport } from '#components/reports/useReport';+import { useDateFormat } from '#hooks/useDateFormat';import { useFormat } from '#hooks/useFormat';import { useLocale } from '#hooks/useLocale';import { useSyncedPref } from '#hooks/useSyncedPref';@@ -48,6 +49,7 @@ export function NetWorthCard({const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';const format = useFormat();+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';const [latestTransaction, setLatestTransaction] = useState<string>('');const [nameMenuOpen, setNameMenuOpen] = useState(false);@@ -83,6 +85,7 @@ export function NetWorthCard({meta?.interval || 'Monthly',firstDayOfWeekIdx,format,+ dateFormat,),[start,@@ -94,6 +97,7 @@ export function NetWorthCard({meta?.interval,firstDayOfWeekIdx,format,+ dateFormat,],);const data = useReport('net_worth', params);diff --git a/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.tsindex b744487b4d..59a4adf763 100644--- a/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts+++ b/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts@@ -17,6 +17,7 @@ import * as d from 'date-fns';import {categoryLists,+ getIntervalFormat,groupBySelections,ReportOptions,} from '#components/reports/ReportOptions';@@ -58,6 +59,7 @@ export type createCustomSpreadsheetProps = {accounts?: AccountEntity[];graphType?: string;firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'];+ dateFormat?: SyncedPrefs['dateFormat'];};export function createCustomSpreadsheet({@@ -80,6 +82,7 @@ export function createCustomSpreadsheet({accounts = [],graphType,firstDayOfWeekIdx,+ dateFormat,}: createCustomSpreadsheetProps) {const [categoryList, categoryGroup] = categoryLists(categories);@@ -245,7 +248,7 @@ export function createCustomSpreadsheet({arr.push({date: d.format(d.parseISO(intervalItem),- ReportOptions.intervalFormat.get(interval) || '',+ getIntervalFormat(interval, dateFormat),),...stacked,intervalStartDate: index === 0 ? startDate : intervalItem,diff --git a/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.tsindex a0cce68f92..ff4e8031e2 100644--- a/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts+++ b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts@@ -9,7 +9,7 @@ import * as d from 'date-fns';import type { Locale } from 'date-fns';import { keyBy } from 'es-toolkit';-import { ReportOptions } from '#components/reports/ReportOptions';+import { getIntervalFormat } from '#components/reports/ReportOptions';import type { FormatType } from '#hooks/useFormat';import type { useSpreadsheet } from '#hooks/useSpreadsheet';import { aqlQuery } from '#queries/aqlQuery';@@ -29,6 +29,7 @@ export function createSpreadsheet(interval: string = 'Monthly',firstDayOfWeekIdx: string = '0',format: (value: unknown, type?: FormatType) => string,+ dateFormat?: string,) {return async (spreadsheet: ReturnType<typeof useSpreadsheet>,@@ -178,6 +179,7 @@ export function createSpreadsheet(interval,firstDayOfWeekIdx,format,+ dateFormat,),);};@@ -196,6 +198,7 @@ function recalculate(interval: string = 'Monthly',firstDayOfWeekIdx: string = '0',format: (value: unknown, type?: FormatType) => string,+ dateFormat?: string,) {// Get intervals using the same pattern as other working spreadsheetsconst intervals =@@ -281,9 +284,9 @@ function recalculate(}endNetWorth = total;- // Use standardized format from ReportOptions- const displayFormat =- ReportOptions.intervalFormat.get(interval) ?? "MMM ''yy";+ // Use standardized format from ReportOptions, following the user's date+ // format preference for the day-level intervals.+ const displayFormat = getIntervalFormat(interval, dateFormat) || "MMM ''yy";const tooltipFormat =interval === 'Daily'diff --git a/upcoming-release-notes/fix-report-interval-date-format.md b/upcoming-release-notes/fix-report-interval-date-format.mdnew file mode 100644index 0000000000..07e8e28d88--- /dev/null+++ b/upcoming-release-notes/fix-report-interval-date-format.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [Divergent-Code]+---++Show daily and weekly report dates using your chosen date format