A local-first personal finance app
add trend line to line graphs (#7954)
Matt Fiddamanf7d159514869
diff --git a/packages/desktop-client/src/components/reports/ChooseGraph.tsx b/packages/desktop-client/src/components/reports/ChooseGraph.tsxindex 64784ee135..f9da791e3c 100644--- a/packages/desktop-client/src/components/reports/ChooseGraph.tsx+++ b/packages/desktop-client/src/components/reports/ChooseGraph.tsx@@ -30,6 +30,7 @@ type ChooseGraphProps = {style?: CSSProperties;showHiddenCategories?: boolean;showOffBudget?: boolean;+ showTrendLines?: boolean;showTooltip?: boolean;intervalsCount: number;};@@ -48,6 +49,7 @@ export function ChooseGraph({style,showHiddenCategories = false,showOffBudget = false,+ showTrendLines = false,showTooltip = true,intervalsCount,}: ChooseGraphProps) {@@ -161,6 +163,7 @@ export function ChooseGraph({balanceTypeOp={balanceTypeOp}showHiddenCategories={showHiddenCategories}showOffBudget={showOffBudget}+ showTrendLines={showTrendLines}showTooltip={showTooltip}interval={interval}/>diff --git a/packages/desktop-client/src/components/reports/ReportOptions.ts b/packages/desktop-client/src/components/reports/ReportOptions.tsindex bc44a8bd9d..b61f3df5bf 100644--- a/packages/desktop-client/src/components/reports/ReportOptions.ts+++ b/packages/desktop-client/src/components/reports/ReportOptions.ts@@ -28,6 +28,7 @@ export const defaultReport: CustomReportEntity = {includeCurrentInterval: true,showUncategorized: true,trimIntervals: false,+ showTrendLines: false,graphType: 'BarGraph',conditions: [],conditionsOp: 'and',diff --git a/packages/desktop-client/src/components/reports/ReportSidebar.tsx b/packages/desktop-client/src/components/reports/ReportSidebar.tsxindex bd70b52cc9..fde06b4a69 100644--- a/packages/desktop-client/src/components/reports/ReportSidebar.tsx+++ b/packages/desktop-client/src/components/reports/ReportSidebar.tsx@@ -58,6 +58,7 @@ type ReportSidebarProps = {value: CustomReportEntity['showUncategorized'],) => void;setTrimIntervals: (value: CustomReportEntity['trimIntervals']) => void;+ setShowTrendLines: (value: CustomReportEntity['showTrendLines']) => void;setIncludeCurrentInterval: (value: CustomReportEntity['includeCurrentInterval'],) => void;@@ -97,6 +98,7 @@ export function ReportSidebar({setIncludeCurrentInterval,setShowUncategorized,setTrimIntervals,+ setShowTrendLines,setSelectedCategories,onChangeDates,onReportChange,@@ -459,6 +461,12 @@ export function ReportSidebar({!customReportItems.trimIntervals,);setTrimIntervals(!customReportItems.trimIntervals);+ } else if (type === 'show-trend-lines') {+ setSessionReport(+ 'showTrendLines',+ !customReportItems.showTrendLines,+ );+ setShowTrendLines(!customReportItems.showTrendLines);}}}items={[@@ -505,6 +513,13 @@ export function ReportSidebar({),toggle: customReportItems.trimIntervals,},+ {+ name: 'show-trend-lines',+ text: t('Show trend lines'),+ tooltip: t('Add a trend line per series (line graphs only)'),+ toggle: customReportItems.showTrendLines,+ disabled: customReportItems.graphType !== 'LineGraph',+ },]}/></Popover>diff --git a/packages/desktop-client/src/components/reports/graphs/LineGraph.tsx b/packages/desktop-client/src/components/reports/graphs/LineGraph.tsxindex 337024cb71..ce49140b72 100644--- a/packages/desktop-client/src/components/reports/graphs/LineGraph.tsx+++ b/packages/desktop-client/src/components/reports/graphs/LineGraph.tsx@@ -16,6 +16,7 @@ import {CartesianGrid,Line,LineChart,+ ReferenceLine,Tooltip,XAxis,YAxis,@@ -34,6 +35,7 @@ import { useNavigate } from '#hooks/useNavigate';import { usePrivacyMode } from '#hooks/usePrivacyMode';import { showActivity } from './showActivity';+import { computeTrendLines } from './util/computeTrendLines';type PayloadItem = {dataKey: string;@@ -149,6 +151,7 @@ type LineGraphProps = {balanceTypeOp: balanceTypeOpType;showHiddenCategories?: boolean;showOffBudget?: boolean;+ showTrendLines?: boolean;showTooltip?: boolean;interval?: string;};@@ -162,6 +165,7 @@ export function LineGraph({balanceTypeOp,showHiddenCategories,showOffBudget,+ showTrendLines = false,showTooltip = true,interval,}: LineGraphProps) {@@ -181,6 +185,10 @@ export function LineGraph({const leftMargin = Math.abs(largestValue) > 1000000 ? 20 : 5;+ const trendLines = showTrendLines+ ? computeTrendLines(data.intervalData, data.legend)+ : [];+const onShowActivity = (item, id, payload) => {showActivity({navigate,@@ -253,6 +261,16 @@ export function LineGraph({tickSize={0}/>)}+ {trendLines.map(t => (+ <ReferenceLine+ key={`trend-${t.id}`}+ segment={[t.start, t.end]}+ stroke={t.color}+ strokeDasharray="4 4"+ strokeOpacity={0.6}+ ifOverflow="extendDomain"+ />+ ))}{data.legend.map((entry, index) => {return (<Linediff --git a/packages/desktop-client/src/components/reports/graphs/util/computeTrendLines.test.ts b/packages/desktop-client/src/components/reports/graphs/util/computeTrendLines.test.tsnew file mode 100644index 0000000000..337238fd5e--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/util/computeTrendLines.test.ts@@ -0,0 +1,99 @@+import type { DataEntity, LegendEntity } from '@actual-app/core/types/models';++import { computeTrendLines } from './computeTrendLines';++function point(date: string, values: Record<string, number>) {+ return {+ date,+ totalAssets: 0,+ totalDebts: 0,+ netAssets: 0,+ netDebts: 0,+ totalTotals: 0,+ totalBudgeted: 0,+ ...values,+ } satisfies DataEntity['intervalData'][number];+}++const series = (overrides: Partial<LegendEntity> = {}): LegendEntity => ({+ name: 'A',+ id: 'a',+ color: '#000',+ dataKey: 'a',+ ...overrides,+});++describe('computeTrendLines', () => {+ it('returns an empty list when there are fewer than two intervals', () => {+ expect(computeTrendLines([], [series()])).toEqual([]);+ expect(computeTrendLines([point('Jan', { a: 1 })], [series()])).toEqual([]);+ });++ it('fits a perfect line for a perfectly linear series', () => {+ const result = computeTrendLines(+ [+ point('Jan', { a: 0 }),+ point('Feb', { a: 10 }),+ point('Mar', { a: 20 }),+ point('Apr', { a: 30 }),+ ],+ [series()],+ );++ expect(result).toEqual([+ {+ id: 'a',+ color: '#000',+ start: { x: 'Jan', y: 0 },+ end: { x: 'Apr', y: 30 },+ },+ ]);+ });++ it('produces a flat line at the mean for a constant series', () => {+ const result = computeTrendLines(+ [point('Jan', { a: 5 }), point('Feb', { a: 5 }), point('Mar', { a: 5 })],+ [series()],+ );++ expect(result[0].start.y).toBeCloseTo(5);+ expect(result[0].end.y).toBeCloseTo(5);+ });++ it('falls back to zero when a series has missing values', () => {+ const result = computeTrendLines(+ [point('Jan', {}), point('Feb', {}), point('Mar', {})],+ [series()],+ );++ expect(result[0].start.y).toBeCloseTo(0);+ expect(result[0].end.y).toBeCloseTo(0);+ });++ it('falls back to the dataKey when a series has no id', () => {+ const [line] = computeTrendLines(+ [point('Jan', { a: 1 }), point('Feb', { a: 2 })],+ [series({ id: null })],+ );++ expect(line.id).toBe('a');+ });++ it('computes a separate trend for each series', () => {+ const result = computeTrendLines(+ [+ point('Jan', { a: 0, b: 100 }),+ point('Feb', { a: 10, b: 80 }),+ point('Mar', { a: 20, b: 60 }),+ ],+ [+ series({ id: 'a', dataKey: 'a', color: '#a' }),+ series({ id: 'b', dataKey: 'b', color: '#b' }),+ ],+ );++ expect(result).toHaveLength(2);+ expect(result[0].end.y).toBeCloseTo(20);+ expect(result[1].end.y).toBeCloseTo(60);+ });+});diff --git a/packages/desktop-client/src/components/reports/graphs/util/computeTrendLines.ts b/packages/desktop-client/src/components/reports/graphs/util/computeTrendLines.tsnew file mode 100644index 0000000000..c68bcfbde5--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/util/computeTrendLines.ts@@ -0,0 +1,50 @@+import type { DataEntity, LegendEntity } from '@actual-app/core/types/models';++export type TrendLineSegment = {+ id: string;+ color: string;+ start: { x: string; y: number };+ end: { x: string; y: number };+};++export function computeTrendLines(+ intervalData: DataEntity['intervalData'],+ legend: LegendEntity[],+): TrendLineSegment[] {+ const n = intervalData.length;+ if (n < 2) return [];++ const sumX = sumRange(n);+ const denom = n * sumSquares(n) - sumX ** 2;+ if (denom === 0) return [];++ const rows = intervalData as unknown as ReadonlyArray<+ Record<string, number | undefined>+ >;++ return legend.map(entry => {+ let sumY = 0;+ let sumXY = 0;+ for (let x = 0; x < n; x++) {+ const y = rows[x][entry.dataKey] ?? 0;+ sumY += y;+ sumXY += x * y;+ }+ const slope = (n * sumXY - sumX * sumY) / denom;+ const intercept = (sumY - slope * sumX) / n;+ return {+ id: entry.id ?? entry.dataKey,+ color: entry.color,+ start: { x: intervalData[0].date, y: intercept },+ end: { x: intervalData[n - 1].date, y: intercept + slope * (n - 1) },+ };+ });+}++function sumRange(n: number) {+ return (n * (n - 1)) / 2;+}++function sumSquares(n: number) {+ return ((n - 1) * n * (2 * n - 1)) / 6;+}diff --git a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx b/packages/desktop-client/src/components/reports/reports/CustomReport.tsxindex 4209bc5dc7..0b9be267c1 100644--- a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx+++ b/packages/desktop-client/src/components/reports/reports/CustomReport.tsx@@ -284,6 +284,9 @@ function CustomReportInner({loadReport.showUncategorized,);const [trimIntervals, setTrimIntervals] = useState(loadReport.trimIntervals);+ const [showTrendLines, setShowTrendLines] = useState(+ loadReport.showTrendLines,+ );const [graphType, setGraphType] = useState(loadReport.graphType);const [dateRange, setDateRange] = useState(loadReport.dateRange);@@ -623,6 +626,7 @@ function CustomReportInner({includeCurrentInterval,showUncategorized,trimIntervals,+ showTrendLines,graphType,conditions,conditionsOp,@@ -769,6 +773,7 @@ function CustomReportInner({setIncludeCurrentInterval(input.includeCurrentInterval);setShowUncategorized(input.showUncategorized);setTrimIntervals(input.trimIntervals);+ setShowTrendLines(input.showTrendLines);setGraphType(input.graphType);onApplyFilter(null);(input.conditions || []).forEach(condition => {@@ -913,6 +918,7 @@ function CustomReportInner({setIncludeCurrentInterval={setIncludeCurrentInterval}setShowUncategorized={setShowUncategorized}setTrimIntervals={setTrimIntervals}+ setShowTrendLines={setShowTrendLines}setSelectedCategories={setSelectedCategories}onChangeDates={onChangeDates}onReportChange={onReportChange}@@ -1055,6 +1061,7 @@ function CustomReportInner({compact={false}showHiddenCategories={showHiddenCategories}showOffBudget={showOffBudget}+ showTrendLines={showTrendLines}intervalsCount={intervals.length}/>) : (diff --git a/packages/desktop-client/src/components/reports/reports/GetCardData.tsx b/packages/desktop-client/src/components/reports/reports/GetCardData.tsxindex 3281072148..6509db92e1 100644--- a/packages/desktop-client/src/components/reports/reports/GetCardData.tsx+++ b/packages/desktop-client/src/components/reports/reports/GetCardData.tsx@@ -190,6 +190,7 @@ export function GetCardData({compactstyle={{ height: 'auto', flex: 1 }}intervalsCount={intervals.length}+ showTrendLines={report.showTrendLines}showTooltip={!isNarrowWidth && showTooltip}/></ErrorBoundary>diff --git a/packages/desktop-client/src/components/reports/spreadsheets/calculateLegend.ts b/packages/desktop-client/src/components/reports/spreadsheets/calculateLegend.tsindex f65e77a8e7..9d7b2cd676 100644--- a/packages/desktop-client/src/components/reports/spreadsheets/calculateLegend.ts+++ b/packages/desktop-client/src/components/reports/spreadsheets/calculateLegend.ts@@ -25,7 +25,7 @@ export function calculateLegend(return { name: c.name, id: c.id, data: c };});- function getColor(data: IntervalEntity, index: number) {+ function getColor(data: IntervalEntity | GroupedEntity, index: number) {if (graphType === 'DonutGraph') {return colorScale[index % colorScale.length];}diff --git a/packages/desktop-client/src/components/reports/spreadsheets/recalculate.ts b/packages/desktop-client/src/components/reports/spreadsheets/recalculate.tsindex 4486280b83..84266aafd4 100644--- a/packages/desktop-client/src/components/reports/spreadsheets/recalculate.ts+++ b/packages/desktop-client/src/components/reports/spreadsheets/recalculate.ts@@ -83,6 +83,7 @@ export function recalculate({const change = last ? intervalTotals - last.totalTotals : 0;arr.push({+ date: intervalItem,totalAssets: intervalAssets,totalDebts: intervalDebts,netAssets: intervalTotals > 0 ? intervalTotals : 0,diff --git a/packages/loot-core/migrations/1780099200000_add_show_trend_lines_report_setting.sql b/packages/loot-core/migrations/1780099200000_add_show_trend_lines_report_setting.sqlnew file mode 100644index 0000000000..c2eb0652b9--- /dev/null+++ b/packages/loot-core/migrations/1780099200000_add_show_trend_lines_report_setting.sql@@ -0,0 +1,5 @@+BEGIN TRANSACTION;++ALTER TABLE custom_reports ADD COLUMN show_trend_lines INTEGER DEFAULT 0;++COMMIT;diff --git a/packages/loot-core/src/server/aql/schema/index.ts b/packages/loot-core/src/server/aql/schema/index.tsindex 7a10b21ab9..3303cc37df 100644--- a/packages/loot-core/src/server/aql/schema/index.ts+++ b/packages/loot-core/src/server/aql/schema/index.ts@@ -162,6 +162,7 @@ export const schema = {show_hidden: f('integer', { default: 0 }),show_uncategorized: f('integer', { default: 0 }),trim_intervals: f('integer', { default: 0 }),+ show_trend_lines: f('integer', { default: 0 }),include_current: f('integer', { default: 0 }),graph_type: f('string', { default: 'BarGraph' }),conditions: f('json'),diff --git a/packages/loot-core/src/server/reports/app.ts b/packages/loot-core/src/server/reports/app.tsindex 20ef9c6bd0..de16dedcaf 100644--- a/packages/loot-core/src/server/reports/app.ts+++ b/packages/loot-core/src/server/reports/app.ts@@ -46,6 +46,7 @@ export const reportModel = {showHiddenCategories: row.show_hidden === 1,showUncategorized: row.show_uncategorized === 1,trimIntervals: row.trim_intervals === 1,+ showTrendLines: row.show_trend_lines === 1,includeCurrentInterval: row.include_current === 1,graphType: row.graph_type,conditions: row.conditions ?? [],@@ -72,6 +73,7 @@ export const reportModel = {show_hidden: report.showHiddenCategories ? 1 : 0,show_uncategorized: report.showUncategorized ? 1 : 0,trim_intervals: report.trimIntervals ? 1 : 0,+ show_trend_lines: report.showTrendLines ? 1 : 0,include_current: report.includeCurrentInterval ? 1 : 0,graph_type: report.graphType,conditions: report.conditions,diff --git a/packages/loot-core/src/types/models/reports.ts b/packages/loot-core/src/types/models/reports.tsindex acac9b99c4..b283e51b6f 100644--- a/packages/loot-core/src/types/models/reports.ts+++ b/packages/loot-core/src/types/models/reports.ts@@ -18,6 +18,7 @@ export type CustomReportEntity = {includeCurrentInterval: boolean;showUncategorized: boolean;trimIntervals: boolean;+ showTrendLines: boolean;graphType: string;conditions?: RuleConditionEntity[];conditionsOp: 'and' | 'or';@@ -92,7 +93,7 @@ export type LegendEntity = {};export type IntervalEntity = {- date?: string;+ date: string;change?: number;intervalStartDate?: string;intervalEndDate?: string;@@ -139,6 +140,7 @@ export type CustomReportData = {include_current: number;show_uncategorized: number;trim_intervals: number;+ show_trend_lines: number;graph_type: string;conditions?: RuleConditionEntity[];conditions_op: 'and' | 'or';diff --git a/upcoming-release-notes/7954.md b/upcoming-release-notes/7954.mdnew file mode 100644index 0000000000..e25a0dcaa1--- /dev/null+++ b/upcoming-release-notes/7954.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [matt-fidd]+---++Add trend line to line reports