Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(reports): add net worth chart with breakdown tooltip (#2716)

kianrafiee40b18e848458
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb
index 11fa20c3ff..7568a29496 100644
--- a/app/controllers/reports_controller.rb
+++ b/app/controllers/reports_controller.rb
@@ -598,13 +598,19 @@ class ReportsController < ApplicationController
{ name: group.name, total: Money.new(group.total, currency) }
end.reject { |g| g[:total].zero? }
+ # Monthly net worth series with per-account-group breakdown for the chart
+ breakdown_series = BalanceSheet::NetWorthBreakdownSeriesBuilder
+ .new(Current.family, user: Current.user)
+ .breakdown_series(period: @period)
+
{
current_net_worth: Money.new(current_net_worth, currency),
total_assets: Money.new(total_assets, currency),
total_liabilities: Money.new(total_liabilities, currency),
trend: trend,
asset_groups: asset_groups,
- liability_groups: liability_groups
+ liability_groups: liability_groups,
+ breakdown_series: breakdown_series
}
end
diff --git a/app/javascript/controllers/net_worth_chart_controller.js b/app/javascript/controllers/net_worth_chart_controller.js
new file mode 100644
index 0000000000..738f808390
--- /dev/null
+++ b/app/javascript/controllers/net_worth_chart_controller.js
@@ -0,0 +1,79 @@
+import TimeSeriesChartController from "controllers/time_series_chart_controller";
+
+// Net worth chart for the Reports page. Inherits all drawing behavior from
+// the time series chart and extends the tooltip with a per-account-group
+// breakdown of assets and liabilities at the hovered point.
+export default class extends TimeSeriesChartController {
+ static values = {
+ assetsLabel: { type: String, default: "Assets" },
+ liabilitiesLabel: { type: String, default: "Liabilities" },
+ };
+
+ _normalizeDataPoints() {
+ super._normalizeDataPoints();
+
+ const rawValues = this.dataValue.values || [];
+ this._normalDataPoints = this._normalDataPoints.map((point, i) => ({
+ ...point,
+ assets: rawValues[i]?.assets,
+ liabilities: rawValues[i]?.liabilities,
+ groups: rawValues[i]?.groups || [],
+ }));
+ }
+
+ _tooltipTemplate(datum) {
+ return `${super._tooltipTemplate(datum)}${this._breakdownTemplate(datum)}`;
+ }
+
+ _breakdownTemplate(datum) {
+ const assetGroups = datum.groups.filter(
+ (group) => group.classification === "asset",
+ );
+ const liabilityGroups = datum.groups.filter(
+ (group) => group.classification === "liability",
+ );
+
+ const sections = [
+ this._sectionTemplate(this.assetsLabelValue, datum.assets, assetGroups),
+ this._sectionTemplate(
+ this.liabilitiesLabelValue,
+ datum.liabilities,
+ liabilityGroups,
+ ),
+ ]
+ .filter(Boolean)
+ .join("");
+
+ if (!sections) return "";
+
+ return `<div class="mt-2 pt-2 border-t border-secondary space-y-2">${sections}</div>`;
+ }
+
+ _sectionTemplate(label, total, groups) {
+ if (groups.length === 0) return "";
+
+ const rows = groups
+ .map(
+ (group) => `
+ <div class="flex items-center justify-between gap-4">
+ <div class="flex items-center gap-1.5 text-secondary">
+ <span class="w-2 h-2 rounded-full shrink-0" style="background-color: ${group.color};"></span>
+ ${group.name}
+ </div>
+ <span class="text-primary tabular-nums">${this._extractFormattedValue(group.value)}</span>
+ </div>
+ `,
+ )
+ .join("");
+
+ return `
+ <div class="space-y-1 text-xs">
+ <div class="flex items-center justify-between gap-4 font-medium">
+ <span class="text-secondary uppercase">${label}</span>
+ <span class="text-primary tabular-nums">${this._extractFormattedValue(total)}</span>
+ </div>
+ ${rows}
+ </div>
+ `;
+ }
+}
diff --git a/app/models/balance_sheet/net_worth_breakdown_series_builder.rb b/app/models/balance_sheet/net_worth_breakdown_series_builder.rb
new file mode 100644
index 0000000000..06397c4a5b
--- /dev/null
+++ b/app/models/balance_sheet/net_worth_breakdown_series_builder.rb
@@ -0,0 +1,139 @@
+class BalanceSheet::NetWorthBreakdownSeriesBuilder
+ # Monthly interval regardless of period length so the reports chart always
+ # shows one point per month in the selected range.
+ INTERVAL = "1 month"
+
+ def initialize(family, user: nil)
+ @family = family
+ @user = user
+ end
+
+ # Returns a chart payload where each monthly point carries the net worth
+ # value plus a per-account-group breakdown (grouped by accountable type)
+ # split into assets and liabilities, for rendering in chart tooltips.
+ def breakdown_series(period:)
+ Rails.cache.fetch(cache_key(period)) do
+ net_series = series_for(historical_accounts, favorable_direction: "up", period: period)
+ groups = group_series(period)
+
+ {
+ start_date: period.start_date,
+ end_date: period.end_date,
+ interval: INTERVAL,
+ trend: net_series.trend,
+ values: [ nil, *net_series.values ].each_cons(2).map do |previous, value|
+ breakdown_value(value, previous, groups)
+ end
+ }
+ end
+ end
+
+ private
+ attr_reader :family, :user
+
+ def breakdown_value(value, previous, groups)
+ point_groups = groups.map do |group|
+ {
+ name: group[:name],
+ color: group[:color],
+ classification: group[:classification],
+ value: group[:values_by_date][value.date] || Money.new(0, family.currency)
+ }
+ end
+
+ {
+ date: value.date,
+ date_formatted: value.date_formatted,
+ value: value.value,
+ # Month-over-month change between chart points. The trend on the raw
+ # series value compares the underlying balance row's own start/end,
+ # which at a monthly interval reflects only the last balance update
+ # before the sample date. The first point has no prior month, so it
+ # gets a flat trend.
+ trend: Trend.new(
+ current: value.value,
+ previous: previous&.value || value.value,
+ favorable_direction: "up"
+ ),
+ assets: classification_total(point_groups, "asset"),
+ liabilities: classification_total(point_groups, "liability"),
+ groups: point_groups
+ }
+ end
+
+ def classification_total(point_groups, classification)
+ total = point_groups
+ .select { |group| group[:classification] == classification }
+ .sum { |group| group[:value].amount }
+
+ Money.new(total, family.currency)
+ end
+
+ def group_series(period)
+ grouped_accounts.filter_map do |(classification, accountable), accounts|
+ direction = classification == "asset" ? "up" : "down"
+ series = series_for(accounts, favorable_direction: direction, period: period)
+ values_by_date = series.values.index_by(&:date).transform_values(&:value)
+
+ next if values_by_date.values.all? { |money| money.amount.zero? }
+
+ {
+ name: accountable.display_name,
+ color: accountable.color,
+ classification: classification,
+ values_by_date: values_by_date
+ }
+ end
+ end
+
+ def grouped_accounts
+ historical_accounts
+ .group_by { |account| [ account.classification, Accountable.from_type(account.accountable_type) ] }
+ .sort_by do |(classification, accountable), _accounts|
+ [
+ classification == "asset" ? 0 : 1,
+ Accountable::TYPES.index(accountable.name) || Float::INFINITY
+ ]
+ end
+ end
+
+ def series_for(accounts, favorable_direction:, period:)
+ Balance::ChartSeriesBuilder.new(
+ account_ids: accounts.map(&:id),
+ account_active_until_dates: disabled_account_active_until_dates(accounts),
+ currency: family.currency,
+ period: period,
+ interval: INTERVAL,
+ favorable_direction: favorable_direction
+ ).balance_series
+ end
+
+ def historical_accounts
+ @historical_accounts ||= BalanceSheet::HistoricalAccountScope.new(family, user: user).relation.to_a
+ end
+
+ def disabled_account_active_until_dates(accounts)
+ accounts.each_with_object({}) do |account, dates|
+ next unless account.disabled?
+
+ disabled_on = (account.disabled_at || account.updated_at).to_date
+ dates[account.id] = disabled_on - 1.day
+ end
+ end
+
+ def cache_key(period)
+ shares_version = user ? AccountShare.where(user: user).maximum(:updated_at)&.to_i : nil
+ key = [
+ "balance_sheet_net_worth_breakdown_series",
+ user&.id,
+ shares_version,
+ period.start_date,
+ period.end_date
+ ].compact.join("_")
+
+ family.build_cache_key(
+ key,
+ invalidate_on_data_updates: true
+ )
+ end
+end
diff --git a/app/views/reports/_net_worth.html.erb b/app/views/reports/_net_worth.html.erb
index 93f979983d..0d6bc74b00 100644
--- a/app/views/reports/_net_worth.html.erb
+++ b/app/views/reports/_net_worth.html.erb
@@ -36,6 +36,18 @@
</div>
</div>
+ <%# Net Worth Over Time chart %>
+ <% breakdown_series = net_worth_metrics[:breakdown_series] %>
+ <% if breakdown_series && breakdown_series[:values].size >= 2 %>
+ <div
+ id="reportsNetWorthChart"
+ class="w-full h-72 privacy-sensitive"
+ data-controller="net-worth-chart"
+ data-net-worth-chart-data-value="<%= breakdown_series.to_json %>"
+ data-net-worth-chart-assets-label-value="<%= t("reports.net_worth.total_assets") %>"
+ data-net-worth-chart-liabilities-label-value="<%= t("reports.net_worth.total_liabilities") %>"></div>
+ <% end %>
+
<%# Asset/Liability Breakdown %>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<%# Assets Summary %>
diff --git a/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb b/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb
new file mode 100644
index 0000000000..e6169884b3
--- /dev/null
+++ b/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb
@@ -0,0 +1,69 @@
+require "test_helper"
+
+class BalanceSheet::NetWorthBreakdownSeriesBuilderTest < ActiveSupport::TestCase
+ include BalanceTestHelper
+
+ setup do
+ @family = families(:dylan_family)
+ @family.accounts.each { |account| account.balances.destroy_all }
+
+ @asset_account = accounts(:depository)
+ @liability_account = accounts(:credit_card)
+ end
+
+ test "builds monthly points with group breakdown that sums to net worth" do
+ period = Period.custom(start_date: 3.months.ago.to_date, end_date: Date.current)
+
+ create_balance(account: @asset_account, date: period.start_date, balance: 5000)
+ create_balance(account: @asset_account, date: Date.current, balance: 6000)
+ create_balance(account: @liability_account, date: period.start_date, balance: 1000)
+ create_balance(account: @liability_account, date: Date.current, balance: 1500)
+
+ series = builder.breakdown_series(period: period)
+
+ # One point per month in the period, end date included
+ assert_equal 4, series[:values].size
+ assert_equal period.start_date, series[:values].first[:date]
+ assert_equal period.end_date, series[:values].last[:date]
+
+ last_point = series[:values].last
+
+ # Liabilities are reported as positive magnitudes
+ assert_equal 6000, last_point[:assets].amount
+ assert_equal 1500, last_point[:liabilities].amount
+ assert_equal 4500, last_point[:value].amount
+
+ # Every point's net worth equals assets minus liabilities
+ series[:values].each do |point|
+ assert_equal point[:value].amount, point[:assets].amount - point[:liabilities].amount
+ end
+
+ # Each point's trend is the month-over-month change from the previous
+ # point; the first point has no prior month so its trend is flat
+ assert_equal 0, series[:values].first[:trend].value.amount
+ series[:values].each_cons(2) do |previous, point|
+ assert_equal point[:value].amount - previous[:value].amount, point[:trend].value.amount
+ end
+ end
+
+ test "includes group metadata and excludes groups with no balances" do
+ period = Period.custom(start_date: 1.month.ago.to_date, end_date: Date.current)
+
+ create_balance(account: @asset_account, date: Date.current, balance: 5000)
+ create_balance(account: @liability_account, date: Date.current, balance: 1000)
+
+ series = builder.breakdown_series(period: period)
+ groups = series[:values].last[:groups]
+
+ # Only account types with balances appear; assets sort before liabilities
+ assert_equal [ "asset", "liability" ], groups.map { |g| g[:classification] }
+ assert_equal Depository.display_name, groups.first[:name]
+ assert_equal CreditCard.display_name, groups.last[:name]
+ assert groups.all? { |g| g[:color].present? }
+ end
+
+ private
+ def builder
+ BalanceSheet::NetWorthBreakdownSeriesBuilder.new(@family)
+ end
+end