Skip to content

A local-first personal finance app

Add Crossover Report (#5554)

scojob80c2d002bf0
diff --git a/packages/desktop-client/src/components/reports/AccountSelector.tsx b/packages/desktop-client/src/components/reports/AccountSelector.tsx
new file mode 100644
index 0000000000..857c5c9125
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/AccountSelector.tsx
@@ -0,0 +1,421 @@
+import React, { useMemo, useState } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+
+import { Button } from '@actual-app/components/button';
+import {
+ SvgCheckAll,
+ SvgUncheckAll,
+ SvgViewHide,
+ SvgViewShow,
+} from '@actual-app/components/icons/v2';
+import { Text } from '@actual-app/components/text';
+import { View } from '@actual-app/components/view';
+
+import { type AccountEntity } from 'loot-core/types/models';
+
+import { GraphButton } from './GraphButton';
+
+import { Checkbox } from '@desktop-client/components/forms';
+
+type AccountSelectorProps = {
+ accounts: AccountEntity[];
+ selectedAccountIds: string[];
+ setSelectedAccountIds: (selectedAccountIds: string[]) => void;
+};
+
+export function AccountSelector({
+ accounts,
+ selectedAccountIds,
+ setSelectedAccountIds,
+}: AccountSelectorProps) {
+ const { t } = useTranslation();
+ const [uncheckedHidden, setUncheckedHidden] = useState(false);
+
+ // Group accounts by on-budget, off-budget, and closed
+ const groupedAccounts = useMemo(() => {
+ const onBudget = accounts.filter(
+ account => !account.offbudget && !account.closed,
+ );
+ const offBudget = accounts.filter(
+ account => account.offbudget && !account.closed,
+ );
+ const closed = accounts.filter(account => account.closed);
+ return { onBudget, offBudget, closed };
+ }, [accounts]);
+
+ const selectedAccountMap = useMemo(
+ () => new Set(selectedAccountIds),
+ [selectedAccountIds],
+ );
+
+ // Calculate selection states for each group
+ const onBudgetSelected = groupedAccounts.onBudget.every(account =>
+ selectedAccountMap.has(account.id),
+ );
+ const offBudgetSelected = groupedAccounts.offBudget.every(account =>
+ selectedAccountMap.has(account.id),
+ );
+ const closedSelected = groupedAccounts.closed.every(account =>
+ selectedAccountMap.has(account.id),
+ );
+
+ const allAccountsSelected =
+ onBudgetSelected && offBudgetSelected && closedSelected;
+ const allAccountsUnselected = !selectedAccountIds.length;
+
+ return (
+ <View>
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ marginBottom: 5,
+ flexShrink: 0,
+ }}
+ >
+ <Button
+ variant="bare"
+ onPress={() => setUncheckedHidden(state => !state)}
+ style={{ padding: 8 }}
+ >
+ <View>
+ {uncheckedHidden ? (
+ <View style={{ flexDirection: 'row', alignItems: 'center' }}>
+ <SvgViewShow
+ width={15}
+ height={15}
+ style={{ marginRight: 5 }}
+ />
+ <Text>
+ <Trans>Show unchecked</Trans>
+ </Text>
+ </View>
+ ) : (
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ }}
+ >
+ <SvgViewHide
+ width={15}
+ height={15}
+ style={{ marginRight: 5 }}
+ />
+ <Text
+ style={{
+ maxWidth: 100,
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ }}
+ >
+ <Trans>Hide unchecked</Trans>
+ </Text>
+ </View>
+ )}
+ </View>
+ </Button>
+ <View style={{ flex: 1 }} />
+ <View style={{ flexDirection: 'row', alignItems: 'center' }}>
+ <GraphButton
+ selected={allAccountsSelected}
+ title={t('Select All')}
+ onSelect={() => {
+ setSelectedAccountIds(accounts.map(account => account.id));
+ }}
+ style={{ marginRight: 5, padding: 8 }}
+ >
+ <SvgCheckAll width={15} height={15} />
+ </GraphButton>
+ <GraphButton
+ selected={allAccountsUnselected}
+ title={t('Unselect All')}
+ onSelect={() => {
+ setSelectedAccountIds([]);
+ }}
+ style={{ padding: 8 }}
+ >
+ <SvgUncheckAll width={15} height={15} />
+ </GraphButton>
+ </View>
+ </View>
+
+ <ul
+ style={{
+ listStyle: 'none',
+ marginLeft: 0,
+ paddingLeft: 0,
+ paddingRight: 10,
+ flexGrow: 1,
+ overflowY: 'auto',
+ }}
+ >
+ {/* On Budget Accounts */}
+ {groupedAccounts.onBudget.length > 0 && (
+ <>
+ <li
+ style={{
+ display: !onBudgetSelected && uncheckedHidden ? 'none' : 'flex',
+ flexDirection: 'row',
+ marginBottom: 8,
+ marginTop: 8,
+ }}
+ >
+ <Checkbox
+ id="onbudget_group"
+ checked={onBudgetSelected}
+ onChange={() => {
+ const onBudgetAccountIds = groupedAccounts.onBudget.map(
+ account => account.id,
+ );
+ const allOnBudgetSelected = onBudgetAccountIds.every(id =>
+ selectedAccountIds.includes(id),
+ );
+
+ if (allOnBudgetSelected) {
+ // Deselect all on-budget accounts
+ setSelectedAccountIds(
+ selectedAccountIds.filter(
+ id => !onBudgetAccountIds.includes(id),
+ ),
+ );
+ } else {
+ // Select all on-budget accounts
+ const newSelection = [...selectedAccountIds];
+ onBudgetAccountIds.forEach(id => {
+ if (!newSelection.includes(id)) {
+ newSelection.push(id);
+ }
+ });
+ setSelectedAccountIds(newSelection);
+ }
+ }}
+ />
+ <label
+ htmlFor="onbudget_group"
+ style={{ userSelect: 'none', fontWeight: 'bold' }}
+ >
+ <Trans>On Budget</Trans>
+ </label>
+ </li>
+ {groupedAccounts.onBudget.map(account => {
+ const isChecked = selectedAccountMap.has(account.id);
+ return (
+ <li
+ key={account.id}
+ style={{
+ display: !isChecked && uncheckedHidden ? 'none' : 'flex',
+ flexDirection: 'row',
+ marginBottom: 4,
+ marginLeft: 16,
+ }}
+ >
+ <Checkbox
+ id={`account_${account.id}`}
+ checked={isChecked}
+ onChange={() => {
+ if (isChecked) {
+ setSelectedAccountIds(
+ selectedAccountIds.filter(id => id !== account.id),
+ );
+ } else {
+ setSelectedAccountIds([
+ ...selectedAccountIds,
+ account.id,
+ ]);
+ }
+ }}
+ />
+ <label
+ htmlFor={`account_${account.id}`}
+ style={{ userSelect: 'none' }}
+ >
+ {account.name}
+ </label>
+ </li>
+ );
+ })}
+ </>
+ )}
+
+ {/* Off Budget Accounts */}
+ {groupedAccounts.offBudget.length > 0 && (
+ <>
+ <li
+ style={{
+ display:
+ !offBudgetSelected && uncheckedHidden ? 'none' : 'flex',
+ flexDirection: 'row',
+ marginBottom: 8,
+ marginTop: 16,
+ }}
+ >
+ <Checkbox
+ id="offbudget_group"
+ checked={offBudgetSelected}
+ onChange={() => {
+ const offBudgetAccountIds = groupedAccounts.offBudget.map(
+ account => account.id,
+ );
+ const allOffBudgetSelected = offBudgetAccountIds.every(id =>
+ selectedAccountIds.includes(id),
+ );
+
+ if (allOffBudgetSelected) {
+ // Deselect all off-budget accounts
+ setSelectedAccountIds(
+ selectedAccountIds.filter(
+ id => !offBudgetAccountIds.includes(id),
+ ),
+ );
+ } else {
+ // Select all off-budget accounts
+ const newSelection = [...selectedAccountIds];
+ offBudgetAccountIds.forEach(id => {
+ if (!newSelection.includes(id)) {
+ newSelection.push(id);
+ }
+ });
+ setSelectedAccountIds(newSelection);
+ }
+ }}
+ />
+ <label
+ htmlFor="offbudget_group"
+ style={{ userSelect: 'none', fontWeight: 'bold' }}
+ >
+ <Trans>Off Budget</Trans>
+ </label>
+ </li>
+ {groupedAccounts.offBudget.map(account => {
+ const isChecked = selectedAccountMap.has(account.id);
+ return (
+ <li
+ key={account.id}
+ style={{
+ display: !isChecked && uncheckedHidden ? 'none' : 'flex',
+ flexDirection: 'row',
+ marginBottom: 4,
+ marginLeft: 16,
+ }}
+ >
+ <Checkbox
+ id={`account_${account.id}`}
+ checked={isChecked}
+ onChange={() => {
+ if (isChecked) {
+ setSelectedAccountIds(
+ selectedAccountIds.filter(id => id !== account.id),
+ );
+ } else {
+ setSelectedAccountIds([
+ ...selectedAccountIds,
+ account.id,
+ ]);
+ }
+ }}
+ />
+ <label
+ htmlFor={`account_${account.id}`}
+ style={{ userSelect: 'none' }}
+ >
+ {account.name}
+ </label>
+ </li>
+ );
+ })}
+ </>
+ )}
+
+ {/* Closed Accounts */}
+ {groupedAccounts.closed.length > 0 && (
+ <>
+ <li
+ style={{
+ display: !closedSelected && uncheckedHidden ? 'none' : 'flex',
+ flexDirection: 'row',
+ marginBottom: 8,
+ marginTop: 16,
+ }}
+ >
+ <Checkbox
+ id="closed_group"
+ checked={closedSelected}
+ onChange={() => {
+ const closedAccountIds = groupedAccounts.closed.map(
+ account => account.id,
+ );
+ const allClosedSelected = closedAccountIds.every(id =>
+ selectedAccountIds.includes(id),
+ );
+
+ if (allClosedSelected) {
+ // Deselect all closed accounts
+ setSelectedAccountIds(
+ selectedAccountIds.filter(
+ id => !closedAccountIds.includes(id),
+ ),
+ );
+ } else {
+ // Select all closed accounts
+ const newSelection = [...selectedAccountIds];
+ closedAccountIds.forEach(id => {
+ if (!newSelection.includes(id)) {
+ newSelection.push(id);
+ }
+ });
+ setSelectedAccountIds(newSelection);
+ }
+ }}
+ />
+ <label
+ htmlFor="closed_group"
+ style={{ userSelect: 'none', fontWeight: 'bold' }}
+ >
+ <Trans>Closed</Trans>
+ </label>
+ </li>
+ {groupedAccounts.closed.map(account => {
+ const isChecked = selectedAccountMap.has(account.id);
+ return (
+ <li
+ key={account.id}
+ style={{
+ display: !isChecked && uncheckedHidden ? 'none' : 'flex',
+ flexDirection: 'row',
+ marginBottom: 4,
+ marginLeft: 16,
+ }}
+ >
+ <Checkbox
+ id={`account_${account.id}`}
+ checked={isChecked}
+ onChange={() => {
+ if (isChecked) {
+ setSelectedAccountIds(
+ selectedAccountIds.filter(id => id !== account.id),
+ );
+ } else {
+ setSelectedAccountIds([
+ ...selectedAccountIds,
+ account.id,
+ ]);
+ }
+ }}
+ />
+ <label
+ htmlFor={`account_${account.id}`}
+ style={{ userSelect: 'none' }}
+ >
+ {account.name}
+ </label>
+ </li>
+ );
+ })}
+ </>
+ )}
+ </ul>
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/Overview.tsx b/packages/desktop-client/src/components/reports/Overview.tsx
index e7a04faa66..c64de9d49a 100644
--- a/packages/desktop-client/src/components/reports/Overview.tsx
+++ b/packages/desktop-client/src/components/reports/Overview.tsx
@@ -25,6 +25,7 @@ import { NON_DRAGGABLE_AREA_CLASS_NAME } from './constants';
import { LoadingIndicator } from './LoadingIndicator';
import { CalendarCard } from './reports/CalendarCard';
import { CashFlowCard } from './reports/CashFlowCard';
+import { CrossoverCard } from './reports/CrossoverCard';
import { CustomReportListCards } from './reports/CustomReportListCards';
import { FormulaCard } from './reports/FormulaCard';
import { MarkdownCard } from './reports/MarkdownCard';
@@ -63,6 +64,7 @@ export function Overview() {
const dispatch = useDispatch();
const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');
const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';
+ const crossoverReportEnabled = useFeatureFlag('crossoverReport');
const formulaMode = useFeatureFlag('formulaMode');
@@ -420,6 +422,14 @@ export function Overview() {
name: 'net-worth-card' as const,
text: t('Net worth graph'),
},
+ ...(crossoverReportEnabled
+ ? [
+ {
+ name: 'crossover-card' as const,
+ text: t('Crossover point'),
+ },
+ ]
+ : []),
{
name: 'spending-card' as const,
text: t('Spending analysis'),
@@ -564,6 +574,16 @@ export function Overview() {
onMetaChange={newMeta => onMetaChange(item, newMeta)}
onRemove={() => onRemoveWidget(item.i)}
/>
+ ) : item.type === 'crossover-card' &&
+ crossoverReportEnabled ? (
+ <CrossoverCard
+ widgetId={item.i}
+ isEditing={isEditing}
+ accounts={accounts}
+ meta={item.meta}
+ onMetaChange={newMeta => onMetaChange(item, newMeta)}
+ onRemove={() => onRemoveWidget(item.i)}
+ />
) : item.type === 'cash-flow-card' ? (
<CashFlowCard
widgetId={item.i}
diff --git a/packages/desktop-client/src/components/reports/ReportRouter.tsx b/packages/desktop-client/src/components/reports/ReportRouter.tsx
index 00ec41b8ae..2d46bbe6ea 100644
--- a/packages/desktop-client/src/components/reports/ReportRouter.tsx
+++ b/packages/desktop-client/src/components/reports/ReportRouter.tsx
@@ -4,18 +4,29 @@ import { Route, Routes } from 'react-router';
import { Overview } from './Overview';
import { Calendar } from './reports/Calendar';
import { CashFlow } from './reports/CashFlow';
+import { Crossover } from './reports/Crossover';
import { CustomReport } from './reports/CustomReport';
import { Formula } from './reports/Formula';
import { NetWorth } from './reports/NetWorth';
import { Spending } from './reports/Spending';
import { Summary } from './reports/Summary';
+import { useFeatureFlag } from '@desktop-client/hooks/useFeatureFlag';
+
export function ReportRouter() {
+ const crossoverReportEnabled = useFeatureFlag('crossoverReport');
+
return (
<Routes>
<Route path="/" element={<Overview />} />
<Route path="/net-worth" element={<NetWorth />} />
<Route path="/net-worth/:id" element={<NetWorth />} />
+ {crossoverReportEnabled && (
+ <>
+ <Route path="/crossover" element={<Crossover />} />
+ <Route path="/crossover/:id" element={<Crossover />} />
+ </>
+ )}
<Route path="/cash-flow" element={<CashFlow />} />
<Route path="/cash-flow/:id" element={<CashFlow />} />
<Route path="/custom" element={<CustomReport />} />
diff --git a/packages/desktop-client/src/components/reports/graphs/CrossoverGraph.tsx b/packages/desktop-client/src/components/reports/graphs/CrossoverGraph.tsx
new file mode 100644
index 0000000000..a6379b7cb9
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/graphs/CrossoverGraph.tsx
@@ -0,0 +1,195 @@
+import { Trans, useTranslation } from 'react-i18next';
+
+import { type CSSProperties } from '@actual-app/components/styles';
+import { theme } from '@actual-app/components/theme';
+import { View } from '@actual-app/components/view';
+import { css } from '@emotion/css';
+import {
+ LineChart,
+ Line,
+ CartesianGrid,
+ XAxis,
+ YAxis,
+ Tooltip,
+ ResponsiveContainer,
+ ReferenceLine,
+} from 'recharts';
+
+import { Container } from '@desktop-client/components/reports/Container';
+import { useFormat } from '@desktop-client/hooks/useFormat';
+import { usePrivacyMode } from '@desktop-client/hooks/usePrivacyMode';
+
+type CrossoverGraphProps = {
+ style?: CSSProperties;
+ graphData: {
+ data: Array<{
+ x: string;
+ investmentIncome: number;
+ expenses: number;
+ isProjection?: boolean;
+ }>;
+ start: string;
+ end: string;
+ crossoverXLabel?: string | null;
+ };
+ compact?: boolean;
+ showTooltip?: boolean;
+};
+
+export function CrossoverGraph({
+ style,
+ graphData,
+ compact = false,
+ showTooltip = true,
+}: CrossoverGraphProps) {
+ const { t } = useTranslation();
+ const privacyMode = usePrivacyMode();
+ const format = useFormat();
+
+ const tickFormatter = (tick: number) => {
+ if (privacyMode) {
+ return '...';
+ }
+ return `${format(Math.round(tick), 'financial-no-decimals')}`;
+ };
+
+ type PayloadItem = {
+ payload: {
+ x: string;
+ investmentIncome: number | string;
+ expenses: number | string;
+ isProjection?: boolean;
+ };
+ };
+
+ type CustomTooltipProps = {
+ active?: boolean;
+ payload?: PayloadItem[];
+ };
+
+ // eslint-disable-next-line react/no-unstable-nested-components
+ const CustomTooltip = ({ active, payload }: CustomTooltipProps) => {
+ if (active && payload && payload.length) {
+ return (
+ <div
+ className={css({
+ zIndex: 1000,
+ pointerEvents: 'none',
+ borderRadius: 2,
+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',
+ backgroundColor: theme.menuBackground,
+ color: theme.menuItemText,
+ padding: 10,
+ })}
+ >
+ <div>
+ <div style={{ marginBottom: 10 }}>
+ <strong>{payload[0].payload.x}</strong>
+ {payload[0].payload.isProjection ? (
+ <span style={{ marginLeft: 8, opacity: 0.7 }}>
+ {t('(projected)')}
+ </span>
+ ) : null}
+ </div>
+ <div style={{ lineHeight: 1.5 }}>
+ <View
+ className={css({
+ display: 'flex',
+ justifyContent: 'space-between',
+ })}
+ >
+ <div>
+ <Trans>Monthly investment income:</Trans>
+ </div>
+ <div>
+ {format(payload[0].payload.investmentIncome, 'financial')}
+ </div>
+ </View>
+ <View
+ className={css({
+ display: 'flex',
+ justifyContent: 'space-between',
+ })}
+ >
+ <div>
+ <Trans>Monthly expenses:</Trans>
+ </div>
+ <div>{format(payload[0].payload.expenses, 'financial')}</div>
+ </View>
+ </div>
+ </div>
+ </div>
+ );
+ }
+ };
+
+ return (
+ <Container
+ style={{
+ ...style,
+ ...(compact && { height: 'auto' }),
+ }}
+ >
+ {(width, height) => (
+ <ResponsiveContainer>
+ <div style={{ ...(!compact && { marginTop: '15px' }) }}>
+ <LineChart
+ width={width}
+ height={height}
+ data={graphData.data}
+ margin={{
+ top: 0,
+ right: 0,
+ left: compact ? 0 : 20,
+ bottom: compact ? 0 : 10,
+ }}
+ >
+ {!compact && <CartesianGrid strokeDasharray="3 3" />}
+ <XAxis
+ dataKey="x"
+ hide={compact}
+ tick={{ fill: theme.pageText }}
+ tickLine={{ stroke: theme.pageText }}
+ />
+ <YAxis
+ hide={compact}
+ tickFormatter={tickFormatter}
+ tick={{ fill: theme.pageText }}
+ tickLine={{ stroke: theme.pageText }}
+ />
+ {showTooltip && (
+ <Tooltip
+ content={<CustomTooltip />}
+ isAnimationActive={false}
+ />
+ )}
+ {graphData.crossoverXLabel && (
+ <ReferenceLine
+ x={graphData.crossoverXLabel}
+ stroke={theme.noticeText}
+ strokeDasharray="4 4"
+ />
+ )}
+ <Line
+ type="monotone"
+ dataKey="investmentIncome"
+ dot={false}
+ stroke={theme.reportsBlue}
+ strokeWidth={2}
+ animationDuration={0}
+ />
+ <Line
+ type="monotone"
+ dataKey="expenses"
+ dot={false}
+ stroke={theme.reportsRed}
+ strokeWidth={2}
+ animationDuration={0}
+ />
+ </LineChart>
+ </div>
+ </ResponsiveContainer>
+ )}
+ </Container>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/reports/Crossover.tsx b/packages/desktop-client/src/components/reports/reports/Crossover.tsx
new file mode 100644
index 0000000000..b3a3e00ecd
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/Crossover.tsx
@@ -0,0 +1,848 @@
+import React, { useEffect, useMemo, useState, useCallback } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import { Button } from '@actual-app/components/button';
+import { useResponsive } from '@actual-app/components/hooks/useResponsive';
+import { SvgQuestion } from '@actual-app/components/icons/v1';
+import { SvgViewHide, SvgViewShow } from '@actual-app/components/icons/v2';
+import { Input } from '@actual-app/components/input';
+import { Paragraph } from '@actual-app/components/paragraph';
+import { Select } from '@actual-app/components/select';
+import { styles } from '@actual-app/components/styles';
+import { Text } from '@actual-app/components/text';
+import { theme } from '@actual-app/components/theme';
+import { Tooltip } from '@actual-app/components/tooltip';
+import { View } from '@actual-app/components/view';
+import * as d from 'date-fns';
+
+import { send } from 'loot-core/platform/client/fetch';
+import * as monthUtils from 'loot-core/shared/months';
+import {
+ type CrossoverWidget,
+ type TimeFrame,
+ type CategoryEntity,
+} from 'loot-core/types/models';
+
+import { Link } from '@desktop-client/components/common/Link';
+import { EditablePageHeaderTitle } from '@desktop-client/components/EditablePageHeaderTitle';
+import { MobileBackButton } from '@desktop-client/components/mobile/MobileBackButton';
+import {
+ MobilePageHeader,
+ Page,
+ PageHeader,
+} from '@desktop-client/components/Page';
+import { PrivacyFilter } from '@desktop-client/components/PrivacyFilter';
+import { AccountSelector } from '@desktop-client/components/reports/AccountSelector';
+import { CategorySelector } from '@desktop-client/components/reports/CategorySelector';
+import { CrossoverGraph } from '@desktop-client/components/reports/graphs/CrossoverGraph';
+import { Header } from '@desktop-client/components/reports/Header';
+import { LoadingIndicator } from '@desktop-client/components/reports/LoadingIndicator';
+import { createCrossoverSpreadsheet } from '@desktop-client/components/reports/spreadsheets/crossover-spreadsheet';
+import { useReport } from '@desktop-client/components/reports/useReport';
+import { fromDateRepr } from '@desktop-client/components/reports/util';
+import { useAccounts } from '@desktop-client/hooks/useAccounts';
+import { useCategories } from '@desktop-client/hooks/useCategories';
+import { useFormat } from '@desktop-client/hooks/useFormat';
+import { useNavigate } from '@desktop-client/hooks/useNavigate';
+import { type useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+import { useWidget } from '@desktop-client/hooks/useWidget';
+import { addNotification } from '@desktop-client/notifications/notificationsSlice';
+import { useDispatch } from '@desktop-client/redux';
+
+// Type for the return value of the recalculate function
+type CrossoverData = {
+ graphData: {
+ data: Array<{
+ x: string;
+ investmentIncome: number;
+ expenses: number;
+ isProjection?: boolean;
+ }>;
+ start: string;
+ end: string;
+ crossoverXLabel: string | null;
+ };
+ lastKnownBalance: number;
+ lastKnownMonthlyIncome: number;
+ lastKnownMonthlyExpenses: number;
+ historicalReturn: number | null;
+ yearsToRetire: number | null;
+ targetMonthlyIncome: number | null;
+};
+
+export function Crossover() {
+ const params = useParams();
+ const { data: widget, isLoading } = useWidget<CrossoverWidget>(
+ params.id ?? '',
+ 'crossover-card',
+ );
+
+ if (isLoading) {
+ return <LoadingIndicator />;
+ }
+
+ return <CrossoverInner widget={widget} />;
+}
+
+type CrossoverInnerProps = { widget?: CrossoverWidget };
+
+function CrossoverInner({ widget }: CrossoverInnerProps) {
+ const { t } = useTranslation();
+ const dispatch = useDispatch();
+ const accounts = useAccounts();
+ const categories = useCategories();
+ const format = useFormat();
+
+ const expenseCategoryGroups = categories.grouped.filter(
+ group => !group.is_income,
+ );
+ const expenseCategories = categories.list.filter(c => !c.is_income);
+
+ const [allMonths, setAllMonths] = useState<Array<{
+ name: string;
+ pretty: string;
+ }> | null>(null);
+
+ // Date range state
+ const [start, setStart] = useState<string>('');
+ const [end, setEnd] = useState<string>('');
+ const [mode, setMode] = useState<TimeFrame['mode']>('static');
+ const [earliestTransactionDate, setEarliestTransactionDate] =
+ useState<string>('');
+
+ const [selectedExpenseCategories, setSelectedExpenseCategories] =
+ useState<Array<CategoryEntity>>(expenseCategories);
+ const [selectedIncomeAccountIds, setSelectedIncomeAccountIds] = useState<
+ string[]
+ >(accounts.map(a => a.id));
+
+ const [swr, setSwr] = useState(0.04);
+ const [estimatedReturn, setEstimatedReturn] = useState<number | null>(null);
+ const [projectionType, setProjectionType] = useState<'trend' | 'hampel'>(
+ 'trend',
+ );
+ const [showHiddenCategories, setShowHiddenCategories] = useState(false);
+ const [selectionsInitialized, setSelectionsInitialized] = useState(false);
+
+ // reset when widget changes
+ useEffect(() => {
+ setSelectionsInitialized(false);
+ }, [widget?.id]);
+
+ // initialize once when data is available
+ useEffect(() => {
+ if (
+ selectionsInitialized ||
+ accounts.length === 0 ||
+ categories.list.length === 0
+ ) {
+ return;
+ }
+
+ const initialExpenseCategories = widget?.meta?.expenseCategoryIds?.length
+ ? categories.list.filter(c =>
+ widget.meta!.expenseCategoryIds!.includes(c.id),
+ )
+ : categories.list.filter(c => !c.is_income);
+
+ const initialIncomeAccountIds = widget?.meta?.incomeAccountIds?.length
+ ? widget.meta!.incomeAccountIds!
+ : accounts.map(a => a.id);
+
+ setSelectedExpenseCategories(initialExpenseCategories);
+ setSelectedIncomeAccountIds(initialIncomeAccountIds);
+ setSwr(widget?.meta?.safeWithdrawalRate ?? 0.04);
+ setEstimatedReturn(widget?.meta?.estimatedReturn ?? null);
+ setProjectionType(widget?.meta?.projectionType ?? 'trend');
+ setShowHiddenCategories(widget?.meta?.showHiddenCategories ?? false);
+
+ setSelectionsInitialized(true);
+ }, [selectionsInitialized, accounts, categories.list, widget?.meta]);
+
+ useEffect(() => {
+ async function run() {
+ const trans = await send('get-earliest-transaction');
+ const currentMonth = monthUtils.currentMonth();
+ const earliestMonth = trans
+ ? monthUtils.monthFromDate(d.parseISO(fromDateRepr(trans.date)))
+ : currentMonth;
+ const latestMonth = monthUtils.subMonths(currentMonth, 1);
+
+ // Initialize date range from widget meta or use default range
+ let startMonth = earliestMonth;
+ let endMonth = monthUtils.isBefore(startMonth, latestMonth)
+ ? latestMonth
+ : startMonth;
+ let timeMode: TimeFrame['mode'] = 'static';
+
+ if (widget?.meta?.timeFrame?.start && widget?.meta?.timeFrame?.end) {
+ startMonth = widget.meta.timeFrame.start;
+ endMonth = widget.meta.timeFrame.end;
+ timeMode = widget.meta.timeFrame.mode || 'static';
+ }
+
+ setStart(startMonth);
+ setEnd(endMonth);
+ setMode(timeMode);
+ setEarliestTransactionDate(earliestMonth);
+
+ const months = monthUtils
+ .rangeInclusive(earliestMonth, latestMonth)
+ .map(month => ({
+ name: month,
+ pretty: monthUtils.format(month, 'MMMM, yyyy'),
+ }))
+ .reverse();
+
+ setAllMonths(months);
+ }
+ run();
+ }, [widget?.meta?.timeFrame]);
+
+ function onChangeDates(start: string, end: string, mode: TimeFrame['mode']) {
+ if (mode === 'sliding-window') {
+ // This is because we don't include the current month in the sliding window
+ start = monthUtils.subMonths(start, 1);
+ end = monthUtils.subMonths(end, 1);
+ }
+ setStart(start);
+ setEnd(end);
+ setMode(mode);
+ }
+
+ async function onSaveWidget() {
+ if (!widget) {
+ dispatch(
+ addNotification({
+ notification: {
+ type: 'error',
+ message: t('Save failed: No widget found to save.'),
+ },
+ }),
+ );
+ return;
+ }
+
+ await send('dashboard-update-widget', {
+ id: widget.id,
+ meta: {
+ ...(widget.meta ?? {}),
+ expenseCategoryIds: selectedExpenseCategories.map(c => c.id),
+ incomeAccountIds: selectedIncomeAccountIds,
+ safeWithdrawalRate: swr,
+ estimatedReturn,
+ projectionType,
+ showHiddenCategories,
+ timeFrame: { start, end, mode },
+ },
+ });
+ dispatch(
+ addNotification({
+ notification: {
+ type: 'message',
+ message: t('Dashboard widget successfully saved.'),
+ },
+ }),
+ );
+ }
+
+ // Memoize the derived values to avoid recreating them on every render
+ const expenseCategoryIds = useMemo(
+ () =>
+ selectedExpenseCategories
+ .filter(c => showHiddenCategories || !c.hidden)
+ .map(c => c.id),
+ [selectedExpenseCategories, showHiddenCategories],
+ );
+
+ const params = useCallback(
+ async (
+ spreadsheet: ReturnType<typeof useSpreadsheet>,
+ setData: (data: CrossoverData) => void,
+ ) => {
+ // Don't run if dates are not yet initialized
+ if (!start || !end) {
+ return;
+ }
+
+ const crossoverSpreadsheet = createCrossoverSpreadsheet({
+ start,
+ end,
+ expenseCategoryIds,
+ incomeAccountIds: selectedIncomeAccountIds,
+ safeWithdrawalRate: swr,
+ estimatedReturn,
+ projectionType,
+ });
+ await crossoverSpreadsheet(spreadsheet, setData);
+ },
+ [
+ start,
+ end,
+ swr,
+ estimatedReturn,
+ projectionType,
+ expenseCategoryIds,
+ selectedIncomeAccountIds,
+ ],
+ );
+
+ const data = useReport<CrossoverData>('crossover', params);
+
+ // Get the default estimated return from the spreadsheet data
+ const historicalReturn = data?.historicalReturn ?? null;
+
+ // Get years to retire from spreadsheet data
+ const yearsToRetire = data?.yearsToRetire ?? null;
+
+ // Get target monthly income from spreadsheet data
+ const targetMonthlyIncome = data?.targetMonthlyIncome ?? null;
+
+ const navigate = useNavigate();
+ const { isNarrowWidth } = useResponsive();
+
+ const title = widget?.meta?.name || t('Crossover Point');
+ const onSaveWidgetName = async (newName: string) => {
+ if (!widget) {
+ dispatch(
+ addNotification({
+ notification: {
+ type: 'error',
+ message: t('Save failed: No widget found to save.'),
+ },
+ }),
+ );
+ return;
+ }
+
+ const name = newName || t('Crossover Point');
+ await send('dashboard-update-widget', {
+ id: widget.id,
+ meta: {
+ ...(widget.meta ?? {}),
+ name,
+ },
+ });
+ };
+
+ if (
+ !allMonths ||
+ !data ||
+ !start ||
+ !end ||
+ categories.list.length === 0 ||
+ accounts.length === 0
+ ) {
+ return <LoadingIndicator />;
+ }
+
+ return (
+ <Page
+ header={
+ isNarrowWidth ? (
+ <MobilePageHeader
+ title={title}
+ leftContent={
+ <MobileBackButton onPress={() => navigate('/reports')} />
+ }
+ />
+ ) : (
+ <PageHeader
+ title={
+ widget ? (
+ <EditablePageHeaderTitle
+ title={title}
+ onSave={onSaveWidgetName}
+ />
+ ) : (
+ title
+ )
+ }
+ />
+ )
+ }
+ padding={0}
+ >
+ <Header
+ start={start}
+ end={end}
+ mode={mode}
+ allMonths={allMonths || []}
+ earliestTransaction={earliestTransactionDate}
+ onChangeDates={onChangeDates}
+ conditionsOp="and"
+ onUpdateFilter={() => {}}
+ onDeleteFilter={() => {}}
+ onConditionsOpChange={() => {}}
+ latestTransaction=""
+ >
+ {widget && (
+ <Button variant="primary" onPress={onSaveWidget}>
+ <Trans>Save widget</Trans>
+ </Button>
+ )}
+ </Header>
+
+ <View
+ style={{
+ flexDirection: 'row',
+ paddingLeft: !isNarrowWidth ? 20 : undefined,
+ flex: 1,
+ }}
+ >
+ {/* Left sidebar */}
+ {!isNarrowWidth && (
+ <View
+ style={{
+ minWidth: 225,
+ maxWidth: 250,
+ paddingTop: 10,
+ paddingRight: 10,
+ flexShrink: 0,
+ overflowY: 'auto',
+ }}
+ >
+ <View style={{ flexShrink: 0 }}>
+ <div style={{ fontWeight: 600, marginBottom: 8 }}>
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}
+ >
+ <Text>
+ <Trans>Expenses categories</Trans>
+ </Text>
+ <Tooltip
+ content={
+ <View style={{ maxWidth: 300 }}>
+ <Text>
+ <Trans>
+ Used to estimate your future expenses.
+ <br />
+ <br />
+ Select the budget categories that reflect your
+ living expenses in retirement.
+ <br />
+ Ex: Food, Utilities, Entertainment, Medical
+ <br />
+ <br />
+ Exclude categories that will not continue in
+ retirement.
+ <br />
+ Ex: Retirement Savings
+ </Trans>
+ </Text>
+ </View>
+ }
+ placement="right top"
+ style={{
+ ...styles.tooltip,
+ }}
+ >
+ <SvgQuestion height={12} width={12} cursor="pointer" />
+ </Tooltip>
+ </View>
+ </div>
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ marginBottom: 5,
+ flexShrink: 0,
+ }}
+ >
+ <Button
+ variant="bare"
+ onPress={() => setShowHiddenCategories(!showHiddenCategories)}
+ style={{ padding: 8 }}
+ >
+ <View>
+ {showHiddenCategories ? (
+ <View
+ style={{ flexDirection: 'row', alignItems: 'center' }}
+ >
+ <SvgViewHide
+ width={15}
+ height={15}
+ style={{ marginRight: 5 }}
+ />
+ <Text>
+ <Trans>Hide hidden</Trans>
+ </Text>
+ </View>
+ ) : (
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ }}
+ >
+ <SvgViewShow
+ width={15}
+ height={15}
+ style={{ marginRight: 5 }}
+ />
+ <Text
+ style={{
+ maxWidth: 100,
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ }}
+ >
+ <Trans>Show hidden</Trans>
+ </Text>
+ </View>
+ )}
+ </View>
+ </Button>
+ <View style={{ flex: 1 }} />
+ </View>
+ <div
+ style={{ maxHeight: 220, overflowY: 'auto', marginBottom: 12 }}
+ >
+ <CategorySelector
+ categoryGroups={expenseCategoryGroups}
+ selectedCategories={selectedExpenseCategories}
+ setSelectedCategories={setSelectedExpenseCategories}
+ showHiddenCategories={showHiddenCategories}
+ />
+ </div>
+
+ <div style={{ fontWeight: 600, marginBottom: 8 }}>
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}
+ >
+ <Text>
+ <Trans>Income accounts</Trans>
+ </Text>
+ <Tooltip
+ content={
+ <View style={{ maxWidth: 300 }}>
+ <Text>
+ <Trans>
+ Used to estimate your future income.
+ <br />
+ <br />
+ Select the accounts that will be used to fund your
+ retirement.
+ <br />
+ Ex: Retirement Accounts, Savings Accounts
+ <br />
+ <br />
+ Exclude accounts that will not.
+ <br />
+ Ex: Mortgage Accounts, Child Education Accounts
+ </Trans>
+ </Text>
+ </View>
+ }
+ placement="right top"
+ style={{
+ ...styles.tooltip,
+ }}
+ >
+ <SvgQuestion height={12} width={12} cursor="pointer" />
+ </Tooltip>
+ </View>
+ </div>
+ <div
+ style={{ maxHeight: 220, overflowY: 'auto', marginBottom: 12 }}
+ >
+ <AccountSelector
+ accounts={accounts}
+ selectedAccountIds={selectedIncomeAccountIds}
+ setSelectedAccountIds={setSelectedIncomeAccountIds}
+ />
+ </div>
+
+ <View style={{ marginBottom: 12 }}>
+ <div style={{ fontWeight: 600, marginBottom: 8 }}>
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}
+ >
+ <Text>{t('Safe withdrawal rate (%)')}</Text>
+ <Tooltip
+ content={
+ <View style={{ maxWidth: 300 }}>
+ <Text>
+ <Trans>
+ The amount you plan to withdraw from your Income
+ Accounts each year to fund your living expenses.
+ <br />
+ <Link
+ variant="external"
+ to="https://en.wikipedia.org/wiki/Retirement_spend-down#Withdrawal_rate"
+ >
+ More info.
+ </Link>
+ </Trans>
+ </Text>
+ </View>
+ }
+ placement="right top"
+ style={{
+ ...styles.tooltip,
+ }}
+ >
+ <SvgQuestion height={12} width={12} cursor="pointer" />
+ </Tooltip>
+ </View>
+ </div>
+ <Input
+ type="number"
+ min={0}
+ max={100}
+ step={0.1}
+ value={swr == null ? '' : Number((swr * 100).toFixed(2))}
+ onChange={e =>
+ setSwr(
+ isNaN(e.target.valueAsNumber)
+ ? 0
+ : e.target.valueAsNumber / 100,
+ )
+ }
+ style={{ width: 120, marginBottom: 12 }}
+ />
+ </View>
+
+ <View style={{ marginBottom: 12 }}>
+ <div style={{ fontWeight: 600, marginBottom: 8 }}>
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}
+ >
+ <Text>{t('Expense Projection Type')}</Text>
+ <Tooltip
+ content={
+ <View style={{ maxWidth: 300 }}>
+ <Text>
+ <Trans>
+ How past expenses are projected into the future.
+ <br />
+ <br />
+ Linear Trend: Projects expenses using a linear
+ regression of historical data.
+ <br />
+ <br />
+ Hampel Filtered Median: Filters out outliers
+ before calculating the median expense.
+ </Trans>
+ </Text>
+ </View>
+ }
+ placement="right top"
+ style={{
+ ...styles.tooltip,
+ }}
+ >
+ <SvgQuestion height={12} width={12} cursor="pointer" />
+ </Tooltip>
+ </View>
+ </div>
+ <Select
+ value={projectionType}
+ onChange={value =>
+ setProjectionType(value as 'trend' | 'hampel')
+ }
+ options={[
+ ['trend', t('Linear Trend')],
+ ['hampel', t('Hampel Filtered Median')],
+ ]}
+ style={{ width: 200, marginBottom: 12 }}
+ />
+ </View>
+
+ <View style={{ marginBottom: 12 }}>
+ <div style={{ fontWeight: 600, marginBottom: 8 }}>
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}
+ >
+ <Text>{t('Estimated return (annual %, optional)')}</Text>
+ <Tooltip
+ content={
+ <View style={{ maxWidth: 300 }}>
+ <Text>
+ <Trans>
+ The expected annual return rate for your
+ investments, used to project growth of Income
+ Accounts. If not specified, the historical return
+ from your Income Accounts will be used instead.
+ <br />
+ <br />
+ Note: Historical return calculation includes
+ contributions and may not reflect actual
+ investment performance.
+ </Trans>
+ </Text>
+ </View>
+ }
+ placement="right top"
+ style={{
+ ...styles.tooltip,
+ }}
+ >
+ <SvgQuestion height={12} width={12} cursor="pointer" />
+ </Tooltip>
+ </View>
+ </div>
+ <Input
+ type="number"
+ min={0}
+ max={100}
+ step={0.1}
+ value={
+ estimatedReturn == null
+ ? ''
+ : Number((estimatedReturn * 100).toFixed(2))
+ }
+ onChange={e =>
+ setEstimatedReturn(
+ isNaN(e.target.valueAsNumber)
+ ? null
+ : e.target.valueAsNumber / 100,
+ )
+ }
+ style={{ width: 120 }}
+ />
+ {estimatedReturn == null && historicalReturn != null && (
+ <div
+ style={{
+ fontSize: 12,
+ color: theme.pageTextSubdued,
+ marginTop: 4,
+ }}
+ >
+ <Trans>
+ Using historical return:{' '}
+ {(historicalReturn * 100).toFixed(1)}%
+ </Trans>
+ </div>
+ )}
+ </View>
+ </View>
+ </View>
+ )}
+
+ {/* Right content */}
+ <View
+ style={{
+ flex: 1,
+ }}
+ >
+ {/* Header stats */}
+ <View
+ style={{
+ backgroundColor: theme.tableBackground,
+ padding: 20,
+ paddingTop: 10,
+ marginBottom: 10,
+ }}
+ >
+ <View style={{ textAlign: 'right' }}>
+ <View
+ style={{
+ ...styles.largeText,
+ fontWeight: 400,
+ marginBottom: 8,
+ whiteSpace: 'nowrap',
+ }}
+ >
+ <span>
+ <Trans>Years to Retire</Trans>:{' '}
+ <PrivacyFilter>
+ {yearsToRetire != null
+ ? t('{{years}} years', {
+ years: format(yearsToRetire, 'number'),
+ })
+ : t('N/A')}
+ </PrivacyFilter>
+ </span>
+ </View>
+ <View
+ style={{
+ whiteSpace: 'nowrap',
+ }}
+ >
+ <span>
+ <Trans>Target Monthly Income</Trans>:{' '}
+ <PrivacyFilter>
+ {targetMonthlyIncome != null && !isNaN(targetMonthlyIncome)
+ ? format(targetMonthlyIncome, 'financial')
+ : t('N/A')}
+ </PrivacyFilter>
+ </span>
+ </View>
+ </View>
+ </View>
+
+ {/* Graph area */}
+ <View
+ style={{
+ backgroundColor: theme.tableBackground,
+ flexDirection: 'row',
+ flex: '1 0 auto',
+ minHeight: 400,
+ }}
+ >
+ <View
+ style={{
+ flex: 1,
+ padding: 10,
+ height: '100%',
+ }}
+ >
+ <CrossoverGraph
+ graphData={data.graphData}
+ style={{ height: '100%', flex: 1 }}
+ />
+ </View>
+ </View>
+
+ {/* Description */}
+ <View
+ style={{
+ backgroundColor: theme.tableBackground,
+ marginTop: 10,
+ padding: 20,
+ userSelect: 'none',
+ }}
+ >
+ <Paragraph>
+ <strong>
+ <Trans>What is the Crossover Point?</Trans>
+ </strong>
+ </Paragraph>
+ <Paragraph>
+ <Trans>
+ The crossover point is when your monthly investment income (from
+ selected accounts using the safe withdrawal rate) meets or
+ exceeds your total monthly expenses (from selected categories).
+ The chart projects into the future using your estimated return
+ until the lines cross.
+ </Trans>
+ </Paragraph>
+ </View>
+ </View>
+ </View>
+ </Page>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/reports/CrossoverCard.tsx b/packages/desktop-client/src/components/reports/reports/CrossoverCard.tsx
new file mode 100644
index 0000000000..6c9a7267c4
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/CrossoverCard.tsx
@@ -0,0 +1,240 @@
+import React, { useMemo, useState, useCallback, useEffect } from 'react';
+import { useTranslation, Trans } from 'react-i18next';
+
+import { Block } from '@actual-app/components/block';
+import { useResponsive } from '@actual-app/components/hooks/useResponsive';
+import { styles } from '@actual-app/components/styles';
+import { theme } from '@actual-app/components/theme';
+import { View } from '@actual-app/components/view';
+import * as d from 'date-fns';
+
+import { send } from 'loot-core/platform/client/fetch';
+import * as monthUtils from 'loot-core/shared/months';
+import {
+ type AccountEntity,
+ type CrossoverWidget,
+} from 'loot-core/types/models';
+
+import { PrivacyFilter } from '@desktop-client/components/PrivacyFilter';
+import { CrossoverGraph } from '@desktop-client/components/reports/graphs/CrossoverGraph';
+import { LoadingIndicator } from '@desktop-client/components/reports/LoadingIndicator';
+import { ReportCard } from '@desktop-client/components/reports/ReportCard';
+import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';
+import { createCrossoverSpreadsheet } from '@desktop-client/components/reports/spreadsheets/crossover-spreadsheet';
+import { useReport } from '@desktop-client/components/reports/useReport';
+import { fromDateRepr } from '@desktop-client/components/reports/util';
+import { useFormat } from '@desktop-client/hooks/useFormat';
+
+// Type for the return value of the recalculate function
+type CrossoverData = {
+ graphData: {
+ data: Array<{
+ x: string;
+ investmentIncome: number;
+ expenses: number;
+ isProjection?: boolean;
+ }>;
+ start: string;
+ end: string;
+ crossoverXLabel: string | null;
+ };
+ lastKnownBalance: number;
+ lastKnownMonthlyIncome: number;
+ lastKnownMonthlyExpenses: number;
+ historicalReturn: number | null;
+ yearsToRetire: number | null;
+ targetMonthlyIncome: number | null;
+};
+
+type CrossoverCardProps = {
+ widgetId: string;
+ isEditing?: boolean;
+ accounts: AccountEntity[];
+ meta?: CrossoverWidget['meta'];
+ onMetaChange: (newMeta: CrossoverWidget['meta']) => void;
+ onRemove: () => void;
+};
+
+export function CrossoverCard({
+ widgetId,
+ isEditing,
+ accounts,
+ meta = {},
+ onMetaChange,
+ onRemove,
+}: CrossoverCardProps) {
+ const { t } = useTranslation();
+ const { isNarrowWidth } = useResponsive();
+
+ const [nameMenuOpen, setNameMenuOpen] = useState(false);
+
+ // Calculate date range from meta or use default range
+ const [start, setStart] = useState<string>('');
+ const [end, setEnd] = useState<string>('');
+
+ const format = useFormat();
+
+ useEffect(() => {
+ let isMounted = true;
+ async function calculateDateRange() {
+ if (meta?.timeFrame?.start && meta?.timeFrame?.end) {
+ setStart(meta.timeFrame.start);
+ setEnd(meta.timeFrame.end);
+ return;
+ }
+
+ const trans = await send('get-earliest-transaction');
+ if (!isMounted) return;
+
+ const currentMonth = monthUtils.currentMonth();
+ const startMonth = trans
+ ? monthUtils.monthFromDate(d.parseISO(fromDateRepr(trans.date)))
+ : currentMonth;
+
+ const previousMonth = monthUtils.subMonths(currentMonth, 1);
+ const endMonth = monthUtils.isBefore(startMonth, previousMonth)
+ ? previousMonth
+ : startMonth;
+
+ // Use saved timeFrame from meta or default range
+ setStart(startMonth);
+ setEnd(endMonth);
+ }
+ calculateDateRange();
+ return () => {
+ isMounted = false;
+ };
+ }, [meta?.timeFrame]);
+
+ const [isCardHovered, setIsCardHovered] = useState(false);
+ const onCardHover = useCallback(() => setIsCardHovered(true), []);
+ const onCardHoverEnd = useCallback(() => setIsCardHovered(false), []);
+
+ // Memoize these to prevent unnecessary re-renders
+ const expenseCategoryIds = useMemo(
+ () => meta?.expenseCategoryIds ?? [],
+ [meta?.expenseCategoryIds],
+ );
+
+ const incomeAccountIds = useMemo(
+ () => meta?.incomeAccountIds ?? accounts.map(a => a.id),
+ [meta?.incomeAccountIds, accounts],
+ );
+
+ const swr = meta?.safeWithdrawalRate ?? 0.04;
+ const estimatedReturn = meta?.estimatedReturn ?? null;
+ const projectionType = meta?.projectionType ?? 'trend';
+
+ const params = useMemo(
+ () =>
+ createCrossoverSpreadsheet({
+ start,
+ end,
+ expenseCategoryIds,
+ incomeAccountIds,
+ safeWithdrawalRate: swr,
+ estimatedReturn: estimatedReturn == null ? null : estimatedReturn,
+ projectionType,
+ }),
+ [
+ start,
+ end,
+ expenseCategoryIds,
+ incomeAccountIds,
+ swr,
+ estimatedReturn,
+ projectionType,
+ ],
+ );
+
+ const data = useReport<CrossoverData>('crossover', params);
+
+ // Get years to retire from spreadsheet data
+ const yearsToRetire = data?.yearsToRetire ?? null;
+
+ return (
+ <ReportCard
+ isEditing={isEditing}
+ disableClick={nameMenuOpen}
+ to={`/reports/crossover/${widgetId}`}
+ menuItems={[
+ { name: 'rename', text: t('Rename') },
+ { name: 'remove', text: t('Remove') },
+ ]}
+ onMenuSelect={item => {
+ switch (item) {
+ case 'rename':
+ setNameMenuOpen(true);
+ break;
+ case 'remove':
+ onRemove();
+ break;
+ default:
+ throw new Error(`Unrecognized selection: ${item}`);
+ }
+ }}
+ >
+ <View
+ style={{ flex: 1 }}
+ onPointerEnter={onCardHover}
+ onPointerLeave={onCardHoverEnd}
+ >
+ <View style={{ flexDirection: 'row', padding: 20 }}>
+ <View style={{ flex: 1 }}>
+ <ReportCardName
+ name={meta?.name || t('Crossover Point')}
+ isEditing={nameMenuOpen}
+ onChange={newName => {
+ onMetaChange({
+ ...meta,
+ name: newName,
+ });
+ setNameMenuOpen(false);
+ }}
+ onClose={() => setNameMenuOpen(false)}
+ />
+ {/* Date range is now fixed and not configurable */}
+ </View>
+ {data && (
+ <View style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
+ <Block
+ style={{
+ ...styles.mediumText,
+ fontWeight: 500,
+ marginBottom: 5,
+ }}
+ >
+ <PrivacyFilter activationFilters={[!isCardHovered]}>
+ {yearsToRetire != null
+ ? t('{{years}} years', {
+ years: format(yearsToRetire, 'number'),
+ })
+ : t('N/A')}
+ </PrivacyFilter>
+ </Block>
+ <Block
+ style={{
+ fontSize: 12,
+ color: theme.pageTextSubdued,
+ }}
+ >
+ <Trans>Years to Retire</Trans>
+ </Block>
+ </View>
+ )}
+ </View>
+
+ {data ? (
+ <CrossoverGraph
+ graphData={data.graphData}
+ compact={true}
+ showTooltip={!isEditing && !isNarrowWidth}
+ style={{ height: 'auto', flex: 1 }}
+ />
+ ) : (
+ <LoadingIndicator />
+ )}
+ </View>
+ </ReportCard>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/crossover-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/crossover-spreadsheet.ts
new file mode 100644
index 0000000000..b722ee0cc1
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/crossover-spreadsheet.ts
@@ -0,0 +1,410 @@
+import * as d from 'date-fns';
+
+import * as monthUtils from 'loot-core/shared/months';
+import { q } from 'loot-core/shared/query';
+import { type AccountEntity } from 'loot-core/types/models';
+
+import { type useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+import { aqlQuery } from '@desktop-client/queries/aqlQuery';
+
+type MonthlyAgg = { date: string; amount: number };
+
+// Utility functions for Hampel identifier
+function calculateMedian(values: number[]): number {
+ if (values.length === 0) return 0;
+ if (values.length === 1) return values[0];
+
+ const sorted = [...values].sort((a, b) => a - b);
+ const mid = Math.floor(sorted.length / 2);
+ return sorted.length % 2 === 0
+ ? (sorted[mid - 1] + sorted[mid]) / 2
+ : sorted[mid];
+}
+
+function calculateMAD(values: number[], median: number): number {
+ const deviations = values.map(v => Math.abs(v - median));
+ return calculateMedian(deviations);
+}
+
+function calculateHampelFilteredMedian(expenses: number[]): number {
+ if (expenses.length === 0) return 0;
+ if (expenses.length === 1) return expenses[0];
+
+ const median = calculateMedian(expenses);
+ const mad = calculateMAD(expenses, median);
+ const threshold = 3; // Standard threshold for outlier detection
+
+ const filteredExpenses = expenses.filter(expense => {
+ const lowerBound = median - 1.4826 * mad * threshold;
+ const upperBound = median + 1.4826 * mad * threshold;
+ return expense >= lowerBound && expense <= upperBound;
+ });
+
+ return calculateMedian(filteredExpenses);
+}
+
+export type CrossoverParams = {
+ start: string;
+ end: string;
+ expenseCategoryIds: string[]; // which categories count as expenses
+ incomeAccountIds: AccountEntity['id'][]; // selected accounts for both historical returns and projections
+ safeWithdrawalRate: number; // annual percent, e.g. 0.04 for 4%
+ estimatedReturn?: number | null; // optional annual return to project future balances
+ projectionType: 'trend' | 'hampel'; // expense projection method
+};
+
+export function createCrossoverSpreadsheet({
+ start,
+ end,
+ expenseCategoryIds,
+ incomeAccountIds,
+ safeWithdrawalRate,
+ estimatedReturn,
+ projectionType,
+}: CrossoverParams) {
+ return async (
+ _spreadsheet: ReturnType<typeof useSpreadsheet>,
+ setData: (data: ReturnType<typeof recalculate>) => void,
+ ) => {
+ if (!start || !end || incomeAccountIds.length === 0) {
+ setData({
+ graphData: {
+ data: [],
+ start: start || '',
+ end: end || '',
+ crossoverXLabel: null,
+ },
+ lastKnownBalance: 0,
+ lastKnownMonthlyIncome: 0,
+ lastKnownMonthlyExpenses: 0,
+ historicalReturn: null,
+ yearsToRetire: null,
+ targetMonthlyIncome: null,
+ });
+ return;
+ }
+
+ // Aggregate monthly expenses for selected categories (expenses are negative amounts)
+ const expensesPromise = (async () => {
+ if (!expenseCategoryIds.length) {
+ return monthUtils
+ .rangeInclusive(start, end)
+ .map(date => ({ date, amount: 0 }));
+ }
+
+ const query = q('transactions')
+ .filter({
+ $and: [
+ { $or: expenseCategoryIds.map(id => ({ category: id })) },
+ { date: { $gte: monthUtils.firstDayOfMonth(start) } },
+ { date: { $lte: monthUtils.lastDayOfMonth(end) } },
+ ],
+ })
+ .groupBy({ $month: '$date' })
+ .select([
+ { date: { $month: '$date' } },
+ { amount: { $sum: '$amount' } },
+ ]);
+
+ const { data } = await aqlQuery(query);
+ return data as MonthlyAgg[];
+ })();
+
+ // Compute monthly balances for selected accounts (historical returns)
+ const historicalBalancesPromise = Promise.all(
+ incomeAccountIds.map(async accountId => {
+ // Get the account balance at the end of the first month (start month)
+ const startingBalance = await aqlQuery(
+ q('transactions')
+ .filter({ account: accountId })
+ .filter({
+ date: { $lte: monthUtils.lastDayOfMonth(start) },
+ })
+ .calculate({ $sum: '$amount' }),
+ ).then(({ data }) => (typeof data === 'number' ? data : 0));
+ // Get all transactions from the start month onwards for balance calculations
+ // We need to exclude the first month since we already have its ending balance as starting
+ // Instead of adding months (which can cause invalid month strings), we'll filter out the first month later
+ const balances = await aqlQuery(
+ q('transactions')
+ .filter({
+ account: accountId,
+ date: { $gte: monthUtils.firstDayOfMonth(start) },
+ })
+ .filter({
+ $and: [{ date: { $lte: monthUtils.lastDayOfMonth(end) } }],
+ })
+ .groupBy({ $month: '$date' })
+ .select([
+ { date: { $month: '$date' } },
+ { amount: { $sum: '$amount' } },
+ ]),
+ ).then(({ data }) => data as MonthlyAgg[]);
+
+ // Filter out the first month since we already have its ending balance as starting
+ const filteredBalances = balances.filter(b => b.date !== start);
+
+ return {
+ accountId,
+ starting: startingBalance,
+ balances: filteredBalances,
+ };
+ }),
+ );
+
+ const [expenses, historicalBalances] = await Promise.all([
+ expensesPromise,
+ historicalBalancesPromise,
+ ]);
+
+ setData(
+ recalculate(
+ {
+ start,
+ end,
+ expenseCategoryIds,
+ incomeAccountIds,
+ safeWithdrawalRate,
+ estimatedReturn,
+ projectionType,
+ },
+ expenses,
+ historicalBalances,
+ ),
+ );
+ };
+}
+
+function recalculate(
+ params: Pick<
+ CrossoverParams,
+ | 'start'
+ | 'end'
+ | 'expenseCategoryIds'
+ | 'incomeAccountIds'
+ | 'safeWithdrawalRate'
+ | 'estimatedReturn'
+ | 'projectionType'
+ >,
+ expenses: MonthlyAgg[],
+ historicalAccounts: Array<{
+ accountId: string;
+ starting: number;
+ balances: MonthlyAgg[];
+ }>,
+) {
+ const months = monthUtils.rangeInclusive(params.start, params.end);
+
+ // Build total expenses per month (positive number for visualization)
+ const expenseMap = new Map<string, number>();
+ for (const e of expenses) {
+ // amounts for expenses are negative; flip sign to positive monthly spend
+ expenseMap.set(e.date, (expenseMap.get(e.date) || 0) + -e.amount);
+ }
+
+ // Build total balances across selected accounts per month for CAGR calculation (historical returns)
+ const historicalBalances: number[] = months.map(() => 0);
+
+ for (const acct of historicalAccounts) {
+ // Calculate running balance for each month
+ // Start with the account's starting balance (balance at the end of the first month)
+ let runningBalance = acct.starting;
+
+ // Process each month in order
+ const byMonth = new Map(acct.balances.map(b => [b.date, b.amount]));
+ for (let i = 0; i < months.length; i++) {
+ const month = months[i];
+ const delta = byMonth.get(month) ?? 0;
+
+ runningBalance += delta;
+
+ // Add this account's balance to the total for this month
+ historicalBalances[i] += runningBalance;
+ }
+ }
+
+ // Determine historical monthly investment income using safe withdrawal rate: annual rate -> monthly
+ const monthlySWR = params.safeWithdrawalRate / 12; // e.g. 0.04 / 12
+
+ // Prepare historical data points and compute last known month data for projection seeds
+ const data: Array<{
+ x: string;
+ investmentIncome: number;
+ expenses: number;
+ isProjection?: boolean;
+ }> = [];
+
+ let lastBalance = 0;
+ let lastExpense = 0;
+ let crossoverIndex: number | null = null;
+ months.forEach((month, idx) => {
+ const balance = historicalBalances[idx]; // Use historical balances for data generation
+ const monthlyIncome = balance * monthlySWR;
+ const spend = expenseMap.get(month) || 0;
+ data.push({
+ x: d.format(d.parseISO(month + '-01'), 'MMM yyyy'),
+ investmentIncome: Math.round(monthlyIncome),
+ expenses: spend,
+ });
+ lastBalance = balance;
+ lastExpense = spend;
+
+ if (crossoverIndex == null && Math.round(monthlyIncome) >= spend) {
+ crossoverIndex = idx;
+ } else if (crossoverIndex != null && Math.round(monthlyIncome) < spend) {
+ crossoverIndex = null;
+ }
+ });
+
+ // If estimatedReturn provided, project future months until investment income exceeds expenses
+ // Use either provided estimatedReturn or simple trailing growth from balances
+ // Determine default return from historical balances if not provided
+ const annualReturn = params.estimatedReturn ?? null; // e.g. 0.05
+ let monthlyReturn =
+ annualReturn != null ? Math.pow(1 + annualReturn, 1 / 12) - 1 : null;
+
+ // Always calculate the default return for display purposes
+ let defaultMonthlyReturn: number | null = null;
+ if (historicalBalances.length >= 2) {
+ // Use the starting balance (end of first month) and final balance (end of last month) for CAGR calculation
+ // The starting balance represents the account balance at the end of the first month
+ let startingBalance = historicalBalances[0];
+ const finalBalance = historicalBalances[historicalBalances.length - 1];
+ const n = historicalBalances.length - 1; // Number of months between start and end
+
+ if (startingBalance === 0) {
+ for (let i = 1; i < historicalBalances.length; i++) {
+ if (historicalBalances[i] !== 0) {
+ startingBalance = historicalBalances[i];
+ break;
+ }
+ }
+ }
+
+ if (startingBalance > 0 && finalBalance > 0 && n > 0) {
+ // Calculate monthly CAGR: (final/starting)^(1/n) - 1
+ const cagrMonthly = Math.pow(finalBalance / startingBalance, 1 / n) - 1;
+
+ if (isFinite(cagrMonthly) && !isNaN(cagrMonthly)) {
+ defaultMonthlyReturn = cagrMonthly;
+ } else {
+ defaultMonthlyReturn = 0;
+ }
+ } else {
+ defaultMonthlyReturn = 0;
+ }
+ }
+
+ if (months.length > 0 && crossoverIndex == null) {
+ // If no explicit return provided, use the calculated default
+ if (monthlyReturn == null) {
+ // not quite right. Need a better approximation
+ monthlyReturn = defaultMonthlyReturn;
+ }
+ // Project up to 600 months max to avoid infinite loops (50 years)
+ const maxProjectionMonths = 600;
+ let projectedBalance = lastBalance;
+ let monthCursor = d.parseISO(months[months.length - 1] + '-01');
+ // Calculate expense projection parameters based on projection type
+ let expenseSlope = 0;
+ let expenseIntercept = lastExpense;
+ let hampelFilteredExpense = 0;
+
+ if (expenseMap.size >= 2) {
+ const y: number[] = months.map(m => expenseMap.get(m) || 0);
+
+ if (params.projectionType === 'trend') {
+ // Linear trend calculation: y = a + b * t
+ const x: number[] = months.map((_m, i) => i);
+ const n = x.length;
+ const sumX = x.reduce((a, b) => a + b, 0);
+ const sumY = y.reduce((a, b) => a + b, 0);
+ const sumXY = x.reduce((a, xi, idx) => a + xi * y[idx], 0);
+ const sumX2 = x.reduce((a, xi) => a + xi * xi, 0);
+ const denom = n * sumX2 - sumX * sumX;
+ if (denom !== 0) {
+ expenseSlope = (n * sumXY - sumX * sumY) / denom;
+ expenseIntercept = (sumY - expenseSlope * sumX) / n;
+ }
+ } else if (params.projectionType === 'hampel') {
+ // Hampel filtered median calculation
+ hampelFilteredExpense = calculateHampelFilteredMedian(y);
+ }
+ }
+
+ for (let i = 1; i <= maxProjectionMonths; i++) {
+ monthCursor = d.addMonths(monthCursor, 1);
+ // grow balance
+ if (monthlyReturn != null) {
+ projectedBalance = projectedBalance * (1 + monthlyReturn);
+ }
+ const projectedIncome = projectedBalance * monthlySWR;
+
+ // Project expenses based on projection type
+ let projectedExpenses: number;
+ if (params.projectionType === 'trend') {
+ projectedExpenses = Math.max(
+ 0,
+ expenseIntercept + expenseSlope * (months.length - 1 + i),
+ );
+ } else {
+ // Hampel filtered median - flat projection
+ projectedExpenses = Math.max(0, hampelFilteredExpense);
+ }
+
+ data.push({
+ x: d.format(monthCursor, 'MMM yyyy'),
+ investmentIncome: Math.round(projectedIncome),
+ expenses: Math.round(projectedExpenses),
+ isProjection: true,
+ });
+
+ if (
+ crossoverIndex == null &&
+ Math.round(projectedIncome) >= Math.round(projectedExpenses)
+ ) {
+ crossoverIndex = months.length + (i - 1);
+ break;
+ }
+ }
+ }
+ // Calculate years to retire based on crossover point
+ let yearsToRetire: number | null = null;
+ let targetMonthlyIncome: number | null = null;
+
+ if (crossoverIndex != null && crossoverIndex < data.length) {
+ const crossoverData = data[crossoverIndex];
+ if (crossoverData) {
+ const currentDate = new Date();
+ const crossoverDate = d.parse(crossoverData.x, 'MMM yyyy', currentDate);
+ const monthsDiff = d.differenceInMonths(crossoverDate, currentDate);
+ yearsToRetire = monthsDiff > 0 ? monthsDiff / 12 : 0;
+ targetMonthlyIncome = crossoverData.expenses;
+ }
+ }
+
+ return {
+ graphData: {
+ data,
+ start: params.start,
+ end: params.end,
+ crossoverXLabel:
+ crossoverIndex != null ? (data[crossoverIndex]?.x ?? null) : null,
+ },
+ // Provide some summary numbers
+ lastKnownBalance: historicalBalances[historicalBalances.length - 1] || 0,
+ lastKnownMonthlyIncome: Math.round(
+ (historicalBalances[historicalBalances.length - 1] || 0) * monthlySWR,
+ ),
+ lastKnownMonthlyExpenses: lastExpense,
+ // Return the calculated default return for display purposes
+ historicalReturn:
+ defaultMonthlyReturn != null
+ ? Math.pow(1 + defaultMonthlyReturn, 12) - 1
+ : null,
+ // Years to retire calculation
+ yearsToRetire,
+ // Target monthly income at crossover point
+ targetMonthlyIncome,
+ };
+}
diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsx
index c18ddbc1c1..01e32f9b14 100644
--- a/packages/desktop-client/src/components/settings/Experimental.tsx
+++ b/packages/desktop-client/src/components/settings/Experimental.tsx
@@ -164,6 +164,13 @@ export function ExperimentalFeatures() {
>
<Trans>Currency support</Trans>
</FeatureToggle>
+
+ <FeatureToggle
+ flag="crossoverReport"
+ feedbackLink="https://github.com/actualbudget/actual/pull/5554"
+ >
+ <Trans>Crossover Report</Trans>
+ </FeatureToggle>
<GlobalFeatureToggle
prefName="plugins"
disableToggle={true}
diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.ts
index e8d4af29b0..0976854517 100644
--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts
+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts
@@ -8,6 +8,7 @@ const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {
actionTemplating: false,
formulaMode: false,
currency: false,
+ crossoverReport: false,
plugins: false,
};
diff --git a/packages/loot-core/src/server/dashboard/app.ts b/packages/loot-core/src/server/dashboard/app.ts
index 8fc7258248..e821239bd8 100644
--- a/packages/loot-core/src/server/dashboard/app.ts
+++ b/packages/loot-core/src/server/dashboard/app.ts
@@ -76,6 +76,7 @@ const exportModel = {
'net-worth-card',
'cash-flow-card',
'spending-card',
+ 'crossover-card',
'custom-report',
'markdown-card',
'summary-card',
diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.ts
index d8b0b98414..26f85d792b 100644
--- a/packages/loot-core/src/types/models/dashboard.ts
+++ b/packages/loot-core/src/types/models/dashboard.ts
@@ -63,6 +63,19 @@ export type CustomReportWidget = AbstractWidget<
'custom-report',
{ id: string }
>;
+export type CrossoverWidget = AbstractWidget<
+ 'crossover-card',
+ {
+ name?: string;
+ expenseCategoryIds?: string[];
+ incomeAccountIds?: string[];
+ timeFrame?: TimeFrame;
+ safeWithdrawalRate?: number; // 0.04 default
+ estimatedReturn?: number | null; // annual
+ projectionType?: 'trend' | 'hampel'; // expense projection method
+ showHiddenCategories?: boolean; // show hidden categories in selector
+ } | null
+>;
export type MarkdownWidget = AbstractWidget<
'markdown-card',
{ content: string; text_align?: 'left' | 'right' | 'center' }
@@ -72,6 +85,7 @@ type SpecializedWidget =
| NetWorthWidget
| CashFlowWidget
| SpendingWidget
+ | CrossoverWidget
| MarkdownWidget
| SummaryWidget
| CalendarWidget
diff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.ts
index fd25ad315b..94ab7cd0d7 100644
--- a/packages/loot-core/src/types/prefs.ts
+++ b/packages/loot-core/src/types/prefs.ts
@@ -4,6 +4,7 @@ export type FeatureFlag =
| 'actionTemplating'
| 'formulaMode'
| 'currency'
+ | 'crossoverReport'
| 'plugins';
/**
diff --git a/upcoming-release-notes/5554.md b/upcoming-release-notes/5554.md
new file mode 100644
index 0000000000..e390e0da27
--- /dev/null
+++ b/upcoming-release-notes/5554.md
@@ -0,0 +1,6 @@
+---
+category: Features
+authors: [sjones512]
+---
+
+Add a Crossover Report for tracking progress towards financial independence.