Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Feature/dashboard Add "Money In / Out" dashboard widget with monthly bar chart (#2594)

Anthonye3a7107271d4
diff --git a/app/components/DS/menu.html.erb b/app/components/DS/menu.html.erb
index 07828a01c4..d4297b901e 100644
--- a/app/components/DS/menu.html.erb
+++ b/app/components/DS/menu.html.erb
@@ -7,7 +7,7 @@
<div id="<%= menu_id %>" data-DS--menu-target="content" class="px-2 lg:px-0 max-w-full hidden z-50" role="menu">
<%= tag.div class: "mx-auto min-w-[200px] shadow-border-lg bg-container rounded-lg", style: ("max-width: #{max_width}" if max_width) do %>
- <%= tag.div class: class_names("py-1" => !no_padding) do %>
+ <%= tag.div class: class_names("py-1" => !no_padding, "overflow-y-auto" => max_height), style: ("max-height: #{max_height}" if max_height) do %>
<% items.each do |item| %>
<%= item %>
<% end %>
diff --git a/app/components/DS/menu.rb b/app/components/DS/menu.rb
index 778d487022..0c63ae3eba 100644
--- a/app/components/DS/menu.rb
+++ b/app/components/DS/menu.rb
@@ -10,7 +10,7 @@
# content? Use `DS::Popover` — `role="menu"` restricts AT users to
# menuitem-only navigation and breaks anything that isn't an action.
class DS::Menu < DesignSystemComponent
- attr_reader :variant, :placement, :offset, :icon_vertical, :no_padding, :testid, :mobile_fullwidth, :max_width, :menu_id
+ attr_reader :variant, :placement, :offset, :icon_vertical, :no_padding, :testid, :mobile_fullwidth, :max_width, :max_height, :menu_id
renders_one :button, ->(**button_options, &block) do
options_with_target = button_options.deep_dup
@@ -33,7 +33,7 @@ class DS::Menu < DesignSystemComponent
VARIANTS = %i[icon icon_sm button].freeze
- def initialize(variant: "icon", placement: "bottom-end", offset: 12, icon_vertical: false, no_padding: false, testid: nil, mobile_fullwidth: true, max_width: nil)
+ def initialize(variant: "icon", placement: "bottom-end", offset: 12, icon_vertical: false, no_padding: false, testid: nil, mobile_fullwidth: true, max_width: nil, max_height: nil)
@variant = variant.to_sym
@placement = placement
@offset = offset
@@ -42,6 +42,7 @@ class DS::Menu < DesignSystemComponent
@testid = testid
@mobile_fullwidth = mobile_fullwidth
@max_width = max_width
+ @max_height = max_height
@menu_id = "menu-#{SecureRandom.hex(4)}"
raise ArgumentError, "Invalid variant: #{@variant}. DS::Menu is for action lists only; use DS::Popover for mixed content (forms, pickers, account dropdowns)." unless VARIANTS.include?(@variant)
diff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rb
index e157dbba86..da42560650 100644
--- a/app/controllers/pages_controller.rb
+++ b/app/controllers/pages_controller.rb
@@ -14,12 +14,17 @@ class PagesController < ApplicationController
# to fit beside it, and none is). Users who pair it manually can go half.
"insights_feed" => { col_span: "full", grow: false, min_height: 0, width_toggle: true },
"cashflow_sankey" => { col_span: "full", grow: false, min_height: 384, width_toggle: true },
+ "money_flow" => { col_span: "single", grow: false, min_height: 0, width_toggle: true },
"outflows_donut" => { col_span: "single", grow: false, min_height: 0 },
"investment_summary" => { col_span: "single", grow: false, min_height: 0, width_toggle: true },
"net_worth_chart" => { col_span: "single", grow: true, min_height: 208, width_toggle: true },
"balance_sheet" => { col_span: "single", grow: false, min_height: 0, width_toggle: true }
}.freeze
+ # Number of consecutive months (ending at the selected month) shown as
+ # bars in the "money_flow" dashboard widget.
+ MONEY_FLOW_CHART_MONTHS = 6
+
# Selectable height presets (px) for grow widgets.
DASHBOARD_HEIGHT_PRESETS = { "compact" => 208, "auto" => 288, "tall" => 416 }.freeze
DEFAULT_HEIGHT_PRESET = "auto"
@@ -48,6 +53,11 @@ class PagesController < ApplicationController
@outflows_data = build_outflows_donut_data(net_totals)
@feed_insights = Current.family.insights.visible.ordered.limit(3)
+ @money_flow_accounts = income_statement.eligible_accounts
+ @money_flow_month = money_flow_month_param
+ @money_flow_account_ids = money_flow_account_ids_param
+ @money_flow_data = build_money_flow_data(income_statement, @money_flow_month, @money_flow_account_ids)
+
@dashboard_sections = build_dashboard_sections
@breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("breadcrumbs.dashboard"), nil ] ]
@@ -128,6 +138,15 @@ class PagesController < ApplicationController
visible: @accounts.any?,
collapsible: true
},
+ {
+ key: "money_flow",
+ title: "pages.dashboard.money_flow.title",
+ partial: "pages/dashboard/money_flow",
+ layout: section_layout("money_flow"),
+ locals: { money_flow_data: @money_flow_data, accounts: @money_flow_accounts, col_span: section_layout("money_flow")[:col_span] },
+ visible: @accounts.any?,
+ collapsible: true
+ },
{
key: "outflows_donut",
title: "pages.dashboard.outflows_donut.title",
@@ -400,6 +419,64 @@ class PagesController < ApplicationController
{ categories: categories, total: total.to_f.round(2), currency: net_totals.currency, currency_symbol: currency_symbol }
end
+ def money_flow_month_param
+ current_month = Date.current.beginning_of_month
+ month = Date.strptime(params[:money_flow_month], "%Y-%m-%d").beginning_of_month
+ # Clamp future months: build_money_flow_data caps each bar's end_date at
+ # Date.current, which would otherwise be earlier than a future month's
+ # start_date and blow up Period.custom's date-range validation.
+ month > current_month ? current_month : month
+ rescue ArgumentError, TypeError
+ current_month
+ end
+
+ # nil means "all accessible accounts" (the widget's default, unfiltered state)
+ def money_flow_account_ids_param
+ ids = Array(params[:money_flow_account_ids]).reject(&:blank?)
+ eligible_ids = @money_flow_accounts.map { |a| a.id.to_s }
+ ids &= eligible_ids
+ ids.presence
+ end
+
+ def build_money_flow_data(income_statement, selected_month, account_ids)
+ months = (MONEY_FLOW_CHART_MONTHS - 1).downto(0).map { |i| selected_month - i.months }
+
+ selected_period = nil
+ selected_totals = nil
+
+ bars = months.map do |month_start|
+ # Cap at today so an in-progress month (most commonly the current one)
+ # doesn't report totals for its not-yet-arrived days.
+ end_date = [ month_start.end_of_month, Date.current ].min
+ period = Period.custom(start_date: month_start, end_date: end_date)
+ totals = income_statement.totals_for(period, account_ids: account_ids)
+
+ if month_start == selected_month
+ selected_period = period
+ selected_totals = totals
+ end
+
+ {
+ date: month_start,
+ label: I18n.l(month_start, format: :short_month_year),
+ income: totals.income_money.amount.to_f.round(2),
+ expense: totals.expense_money.amount.to_f.round(2),
+ highlighted: month_start == selected_month,
+ partial: end_date < month_start.end_of_month
+ }
+ end
+
+ {
+ bars: bars,
+ period: selected_period,
+ month: selected_month,
+ income: selected_totals.income_money,
+ expense: selected_totals.expense_money,
+ balance: selected_totals.income_money - selected_totals.expense_money,
+ account_ids: account_ids
+ }
+ end
+
def ensure_intro_guest!
return if Current.user&.guest?
diff --git a/app/javascript/controllers/bar_chart_controller.js b/app/javascript/controllers/bar_chart_controller.js
new file mode 100644
index 0000000000..673030ad55
--- /dev/null
+++ b/app/javascript/controllers/bar_chart_controller.js
@@ -0,0 +1,159 @@
+import { Controller } from "@hotwired/stimulus";
+import * as d3 from "d3";
+import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";
+
+// Grouped bar chart used by the dashboard "money flow" widget — each month
+// shows an expense bar (red) and an income bar (green) side by side.
+// Modeled after time_series_chart_controller's lifecycle (install/teardown,
+// ResizeObserver, turbo:load reinstall, page-relative tooltip positioning)
+// but with scaleBand/scaleLinear instead of a line.
+export default class extends Controller {
+ static values = {
+ data: Array,
+ currency: { type: String, default: "USD" },
+ incomeLabel: { type: String, default: "Income" },
+ expenseLabel: { type: String, default: "Expenses" },
+ };
+
+ _resizeObserver = null;
+
+ connect() {
+ this._install();
+ document.addEventListener("turbo:load", this._reinstall);
+ this._resizeObserver = new ResizeObserver(() => this._reinstall());
+ this._resizeObserver.observe(this.element);
+ }
+
+ disconnect() {
+ this._teardown();
+ document.removeEventListener("turbo:load", this._reinstall);
+ this._resizeObserver?.disconnect();
+ }
+
+ _reinstall = () => {
+ this._teardown();
+ this._install();
+ };
+
+ _teardown() {
+ d3.select(this.element).selectAll("*").remove();
+ }
+
+ _install() {
+ const width = this.element.clientWidth;
+ const height = this.element.clientHeight;
+ const data = this.dataValue || [];
+
+ if (width < 50 || height < 50 || data.length === 0) return;
+
+ const margin = { top: 16, right: 4, bottom: 24, left: 4 };
+ const innerWidth = width - margin.left - margin.right;
+ const innerHeight = height - margin.top - margin.bottom;
+
+ const svg = d3
+ .select(this.element)
+ .append("svg")
+ .attr("width", width)
+ .attr("height", height)
+ .attr("viewBox", [0, 0, width, height]);
+
+ const group = svg
+ .append("g")
+ .attr("transform", `translate(${margin.left},${margin.top})`);
+
+ const series = ["income", "expense"];
+ const seriesColor = { expense: "var(--color-gray-400)", income: "var(--color-success)" };
+
+ const x0 = d3
+ .scaleBand()
+ .domain(data.map((d) => d.label))
+ .range([0, innerWidth])
+ .padding(0.3);
+
+ const x1 = d3.scaleBand().domain(series).range([0, x0.bandwidth()]).padding(0.15);
+
+ const maxValue = d3.max(data, (d) => Math.max(d.income, d.expense)) || 1;
+ const y = d3.scaleLinear().domain([0, maxValue * 1.1]).range([innerHeight, 0]);
+ // Floor tiny-but-nonzero bars (e.g. an in-progress month) at 2px so they stay visible.
+ const barHeight = (v) => (v > 0 ? Math.max(2, innerHeight - y(v)) : 0);
+
+ const tooltip = d3
+ .select(this.element)
+ .append("div")
+ .attr("class", `${CHART_TOOLTIP_CLASSES} opacity-0 top-0`);
+
+ const showTooltip = (event, month, key) => {
+ const estimatedTooltipWidth = 200;
+ const pageWidth = document.body.clientWidth;
+ const tooltipX = event.pageX + 10;
+ const overflowX = tooltipX + estimatedTooltipWidth - pageWidth;
+ const adjustedX = overflowX > 0 ? event.pageX - overflowX - 20 : tooltipX;
+
+ tooltip
+ .html(this._tooltipTemplate(month, key))
+ .style("opacity", 1)
+ .style("left", `${adjustedX}px`)
+ .style("top", `${event.pageY - 10}px`);
+ };
+
+ const hideTooltip = () => tooltip.style("opacity", 0);
+
+ const monthGroups = group
+ .selectAll("g.month")
+ .data(data)
+ .join("g")
+ .attr("class", "month")
+ .attr("transform", (d) => `translate(${x0(d.label)},0)`);
+
+ monthGroups
+ .selectAll("rect")
+ .data((d) => series.map((key) => ({ key, value: d[key], month: d })))
+ .join("rect")
+ .attr("x", (d) => x1(d.key))
+ .attr("y", (d) => innerHeight - barHeight(d.value))
+ .attr("width", x1.bandwidth())
+ .attr("height", (d) => barHeight(d.value))
+ .attr("rx", 3)
+ .attr("fill", (d) => seriesColor[d.key])
+ // In-progress month (period capped at today) reads as provisional.
+ .attr("fill-opacity", (d) => (d.month.partial ? 0.5 : 1))
+ .on("mousemove", (event, d) => showTooltip(event, d.month, d.key))
+ .on("mouseleave", hideTooltip);
+
+ group
+ .append("g")
+ .attr("transform", `translate(0,${innerHeight})`)
+ .call(d3.axisBottom(x0).tickSize(0))
+ .call((g) => g.select(".domain").remove())
+ .selectAll("text")
+ .attr("class", (_d, i) => (data[i].highlighted ? "text-primary fill-current" : "text-secondary fill-current"))
+ .style("font-size", "12px")
+ .style("font-weight", (_d, i) => (data[i].highlighted ? 600 : 500));
+ }
+
+ _tooltipTemplate(month, key) {
+ const label = key === "income" ? this.incomeLabelValue : this.expenseLabelValue;
+ // Match the bar/legend palette — expenses render gray, not destructive red.
+ const color = key === "income" ? "var(--color-success)" : "var(--color-gray-400)";
+
+ return `
+ <div class="text-xs text-secondary mb-1">${month.label}</div>
+ <div class="flex items-center gap-1.5 text-primary font-medium tabular-nums">
+ <span class="inline-block w-2 h-2 rounded-full" style="background-color: ${color};"></span>
+ ${label}: ${this._formatCurrency(month[key])}
+ </div>
+ `;
+ }
+
+ _formatCurrency(value) {
+ try {
+ return new Intl.NumberFormat(undefined, {
+ style: "currency",
+ currency: this.currencyValue,
+ maximumFractionDigits: 0,
+ }).format(value);
+ } catch {
+ return value;
+ }
+ }
+}
diff --git a/app/models/income_statement.rb b/app/models/income_statement.rb
index 1101df93e9..e81bbf8b04 100644
--- a/app/models/income_statement.rb
+++ b/app/models/income_statement.rb
@@ -107,6 +107,34 @@ class IncomeStatement
)
end
+ # Income/expense totals for an arbitrary period, optionally scoped to a
+ # subset of accounts (e.g. a dashboard widget's account filter). Unlike
+ # `income_totals`/`expense_totals`, this isn't memoized per-period since
+ # callers (e.g. a monthly bar chart) typically query several distinct
+ # periods and account combinations in one request.
+ def totals_for(period, account_ids: nil)
+ scope = family.transactions.visible.excluding_pending.in_period(period)
+ scope = scope.where(entries: { account_id: account_ids }) if account_ids.present?
+
+ totals(transactions_scope: scope, date_range: period.date_range)
+ end
+
+ # Accounts actually reflected in totals/totals_for: visible, not excluded
+ # from reports, not tax-advantaged, and (when scoped to a user) included in
+ # that user's finances. Callers offering an account filter (e.g. a
+ # dashboard widget) should build their options from this, not a broader
+ # "accessible accounts" list, or selecting an ineligible account silently
+ # computes to zero instead of the totals it actually appears in elsewhere.
+ def eligible_accounts
+ @eligible_accounts ||= begin
+ scope = family.accounts.visible.included_in_reports
+ tax_advantaged_ids = family.tax_advantaged_account_ids
+ scope = scope.where.not(id: tax_advantaged_ids) if tax_advantaged_ids.present?
+ scope = scope.merge(Account.included_in_finances_for(user)) if user
+ scope
+ end
+ end
+
def median_expense(interval: "month", category: nil)
if category.present?
category_stats(interval: interval).find { |stat| stat.classification == "expense" && stat.category_id == category.id }&.median || 0
diff --git a/app/views/pages/dashboard/_money_flow.html.erb b/app/views/pages/dashboard/_money_flow.html.erb
new file mode 100644
index 0000000000..297df32257
--- /dev/null
+++ b/app/views/pages/dashboard/_money_flow.html.erb
@@ -0,0 +1,137 @@
+<%# locals: (money_flow_data:, accounts:, col_span: "single") %>
+<%
+ pill_button_class = "inline-flex items-center gap-1.5 bg-container border border-secondary font-medium rounded-lg pl-3 pr-2 py-2 text-sm cursor-pointer text-primary hover:bg-container-inset-hover focus:outline-hidden focus:ring-0 whitespace-nowrap"
+ selected_account_ids = money_flow_data[:account_ids] || accounts.map { |a| a.id.to_s }
+ all_accounts_selected = selected_account_ids.size == accounts.size
+ period = money_flow_data[:period]
+ # At full width the chart and summary sit side by side; at single/half width
+ # they stack so the chart gets the full column and the month labels don't crowd.
+ stacked = col_span != "full"
+%>
+<div id="money-flow-section" class="px-4 space-y-4">
+ <div class="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-3">
+ <p class="text-sm text-secondary">
+ <%= t(".date_range", start_date: l(period.date_range.begin, format: :long), end_date: l(period.date_range.end, format: :long)) %>
+ </p>
+
+ <div class="flex items-center gap-2">
+ <%= render DS::Tooltip.new(text: t(".period_scope_hint"), placement: "top-start") %>
+
+ <%= render DS::Menu.new(variant: :button, placement: "bottom-end", max_height: "18rem") do |menu| %>
+ <% menu.with_button(type: "button", class: pill_button_class, aria: { label: t(".month_picker_aria_label") }) do %>
+ <span class="capitalize"><%= I18n.l(money_flow_data[:month], format: :month_year) %></span>
+ <%= icon("chevron-down", size: "sm") %>
+ <% end %>
+
+ <% (0..11).each do |i| %>
+ <% month = Date.current.beginning_of_month - i.months %>
+ <% menu.with_item(
+ variant: :link,
+ text: I18n.l(month, format: :month_year).capitalize,
+ href: root_path({ money_flow_month: month.iso8601, money_flow_account_ids: money_flow_data[:account_ids] }.compact),
+ frame: "dashboard_sections",
+ selected: month == money_flow_data[:month]
+ ) %>
+ <% end %>
+ <% end %>
+
+ <%= render DS::Popover.new(variant: :button, no_padding: true) do |popover| %>
+ <% popover.with_button(
+ type: "button",
+ text: all_accounts_selected ? t(".filter_accounts_all") : t(".filter_accounts", count: selected_account_ids.size),
+ variant: "outline",
+ icon: "list-filter"
+ ) %>
+
+ <% popover.with_custom_content do %>
+ <%= form_with url: root_path, method: :get, data: { turbo_frame: "dashboard_sections" }, class: "p-3 w-56 space-y-2" do %>
+ <%= hidden_field_tag :money_flow_month, money_flow_data[:month].iso8601 %>
+
+ <div data-controller="list-filter">
+ <%= render DS::SearchInput.new(
+ variant: :embedded,
+ placeholder: t(".search_accounts"),
+ aria_label: t(".search_accounts"),
+ data: { list_filter_target: "input", action: "input->list-filter#filter" }
+ ) %>
+
+ <div class="my-2 max-h-64 overflow-y-auto space-y-1" data-list-filter-target="list">
+ <% accounts.each do |account| %>
+ <label class="filterable-item flex items-center gap-2 p-1.5 rounded-md hover:bg-container-inset-hover cursor-pointer" data-filter-name="<%= account.name %>">
+ <%= check_box_tag "money_flow_account_ids[]", account.id, selected_account_ids.include?(account.id.to_s), id: nil, class: "checkbox checkbox--light" %>
+ <span class="text-sm text-primary truncate"><%= account.name %></span>
+ </label>
+ <% end %>
+ </div>
+ </div>
+
+ <%= render DS::Button.new(type: "submit", text: t(".apply"), variant: "primary", full_width: true) %>
+ <% end %>
+ <% end %>
+ <% end %>
+ </div>
+ </div>
+
+ <div class="flex flex-col gap-6<%= " xl:flex-row" unless stacked %>">
+ <div class="w-full space-y-2<%= " xl:w-3/5" unless stacked %>">
+ <div class="flex items-center justify-between gap-4 px-1">
+ <div class="flex items-center gap-4">
+ <span class="flex items-center gap-1.5 text-xs text-secondary">
+ <span class="w-2 h-2 rounded-full bg-success"></span>
+ <%= t(".income") %>
+ </span>
+ <span class="flex items-center gap-1.5 text-xs text-secondary">
+ <span class="w-2 h-2 rounded-full bg-gray-400"></span>
+ <%= t(".expenses") %>
+ </span>
+ </div>
+ <span class="text-xs text-secondary"><%= t(".chart_span", count: money_flow_data[:bars].size) %></span>
+ </div>
+
+ <div class="w-full h-44 privacy-sensitive"
+ data-controller="bar-chart"
+ data-bar-chart-data-value="<%= money_flow_data[:bars].to_json %>"
+ data-bar-chart-currency-value="<%= Current.family.currency %>"
+ data-bar-chart-income-label-value="<%= t(".income") %>"
+ data-bar-chart-expense-label-value="<%= t(".expenses") %>">
+ </div>
+ </div>
+
+ <div class="w-full space-y-4<%= " xl:w-2/5" unless stacked %>">
+ <p class="text-sm font-medium text-primary capitalize"><%= I18n.l(money_flow_data[:month], format: :month_year) %></p>
+
+ <div class="flex items-center justify-between text-sm">
+ <span class="text-secondary"><%= t(".balance") %></span>
+ <span class="font-medium text-lg tabular-nums privacy-sensitive <%= money_flow_data[:balance].negative? ? "text-destructive" : (money_flow_data[:balance].zero? ? "text-primary" : "text-success") %>">
+ <%= format_money money_flow_data[:balance] %>
+ </span>
+ </div>
+
+ <%= link_to transactions_path(q: { types: [ "income" ], status: [ "confirmed" ], start_date: period.date_range.begin, end_date: period.date_range.end, account_ids: selected_account_ids }.compact),
+ class: "flex items-center justify-between p-3 border border-secondary rounded-lg hover:bg-container-inset-hover transition-colors group",
+ data: { turbo_frame: "_top" } do %>
+ <span class="flex items-center gap-2 text-sm text-primary">
+ <span class="w-2.5 h-2.5 rounded-full bg-success"></span>
+ <%= t(".income") %>
+ </span>
+ <span class="flex items-center gap-2">
+ <span class="font-medium tabular-nums text-success privacy-sensitive"><%= format_money money_flow_data[:income] %></span>
+ <%= icon("chevron-right", size: "sm", class: "text-secondary group-hover:text-primary transition-colors") %>
+ </span>
+ <% end %>
+
+ <%= link_to transactions_path(q: { types: [ "expense" ], status: [ "confirmed" ], start_date: period.date_range.begin, end_date: period.date_range.end, account_ids: selected_account_ids }.compact),
+ class: "flex items-center justify-between p-3 border border-secondary rounded-lg hover:bg-container-inset-hover transition-colors group",
+ data: { turbo_frame: "_top" } do %>
+ <span class="flex items-center gap-2 text-sm text-primary">
+ <span class="w-2.5 h-2.5 rounded-full bg-gray-400"></span>
+ <%= t(".expenses") %>
+ </span>
+ <span class="flex items-center gap-2">
+ <span class="font-medium tabular-nums text-primary privacy-sensitive"><%= format_money money_flow_data[:expense] %></span>
+ <%= icon("chevron-right", size: "sm", class: "text-secondary group-hover:text-primary transition-colors") %>
+ </span>
+ <% end %>
+ </div>
+ </div>
+</div>
diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.yml
index 5b6e6aa74d..6d5876284e 100644
--- a/config/locales/views/pages/en.yml
+++ b/config/locales/views/pages/en.yml
@@ -105,3 +105,16 @@ en:
trades: "Trades"
no_investments: "No investment accounts"
add_investment: "Add an investment account to track your portfolio"
+ money_flow:
+ title: "Money In / Out"
+ date_range: "%{start_date} to %{end_date}"
+ month_picker_aria_label: "Select month"
+ filter_accounts: "Filter accounts (%{count})"
+ filter_accounts_all: "All accounts"
+ period_scope_hint: "Shows the months you pick here — independent of the dashboard's time period at the top."
+ search_accounts: "Search accounts"
+ apply: "Apply"
+ balance: "Transaction balance"
+ chart_span: "Last %{count} months"
+ income: "Income"
+ expenses: "Expenses"
diff --git a/config/locales/views/pages/fr.yml b/config/locales/views/pages/fr.yml
index fed78fe876..480b74a05b 100644
--- a/config/locales/views/pages/fr.yml
+++ b/config/locales/views/pages/fr.yml
@@ -40,6 +40,19 @@ fr:
value: Valeur
weight: Poids
withdrawals: Retraits
+ money_flow:
+ apply: Appliquer
+ balance: Balance des opérations
+ chart_span: "%{count} derniers mois"
+ date_range: Du %{start_date} au %{end_date}
+ expenses: Sorties
+ filter_accounts: Filtrer les comptes (%{count})
+ filter_accounts_all: Tous les comptes
+ income: Entrées
+ month_picker_aria_label: Sélectionner un mois
+ period_scope_hint: Affiche les mois que vous sélectionnez ici — indépendant de la période du tableau de bord en haut.
+ search_accounts: Rechercher un compte
+ title: Entrées / sorties d'argent
net_worth_chart:
data_not_available: Données indisponibles pour la période sélectionnée
title: Patrimoine net
diff --git a/test/controllers/pages_controller_test.rb b/test/controllers/pages_controller_test.rb
index cb3d451b41..0159730ed3 100644
--- a/test/controllers/pages_controller_test.rb
+++ b/test/controllers/pages_controller_test.rb
@@ -124,6 +124,137 @@ class PagesControllerTest < ActionDispatch::IntegrationTest
assert sankey_data.fetch("nodes").any? { |node| node.fetch("id").start_with?("expense_") }
end
+ test "dashboard renders money flow widget" do
+ get root_path
+
+ assert_response :ok
+ assert_select "[data-controller='bar-chart']"
+ end
+
+ test "dashboard scopes money flow widget to selected month and accounts" do
+ # Dedicated account (rather than @family.accounts.first) so fixture
+ # transactions on other accounts can't skew the computed totals.
+ account = @family.accounts.create!(name: "Money Flow Test Checking", currency: @family.currency, balance: 0, accountable: Depository.new)
+ selected_month = 1.month.ago.beginning_of_month.to_date
+ create_transaction(account: account, name: "Groceries", amount: 50, date: selected_month + 1.day)
+ create_transaction(account: account, name: "Paycheck", amount: -200, date: selected_month + 2.days)
+
+ get root_path, params: {
+ money_flow_month: selected_month.iso8601,
+ money_flow_account_ids: [ account.id ]
+ }
+
+ assert_response :ok
+ bars = money_flow_bars
+
+ assert_equal 6, bars.size
+ highlighted = bars.find { |bar| bar["highlighted"] }
+ assert_equal selected_month.iso8601, highlighted["date"]
+ assert_equal 50.0, highlighted["expense"]
+ assert_equal 200.0, highlighted["income"]
+ end
+
+ test "dashboard money flow widget ignores account ids not accessible to the current user" do
+ other_family = Family.create!(name: "Other Family", currency: "USD")
+ other_account = other_family.accounts.create!(name: "Other Family Checking", currency: "USD", balance: 0, accountable: Depository.new)
+ create_transaction(account: other_account, name: "Not mine", amount: 999)
+
+ get root_path
+ default_bars = money_flow_bars
+
+ get root_path, params: { money_flow_account_ids: [ other_account.id ] }
+
+ assert_response :ok
+ filtered_bars = money_flow_bars
+
+ # An id outside the current user's accessible accounts is dropped entirely
+ # (money_flow_account_ids_param intersects against accessible ids), so the
+ # widget falls back to its unfiltered "all accessible accounts" state
+ # rather than scoping to a foreign account or erroring.
+ assert_equal default_bars, filtered_bars
+ end
+
+ test "dashboard money flow widget excludes accounts ineligible for cashflow totals from its account filter" do
+ excluded_account = @family.accounts.create!(
+ name: "Excluded From Reports",
+ currency: @family.currency,
+ balance: 0,
+ exclude_from_reports: true,
+ accountable: Depository.new
+ )
+
+ get root_path
+
+ assert_response :ok
+ assert_select "input[type='checkbox'][value=?]", excluded_account.id.to_s, count: 0
+ end
+
+ test "dashboard money flow widget ignores account ids excluded from cashflow totals" do
+ excluded_account = @family.accounts.create!(
+ name: "Excluded From Reports",
+ currency: @family.currency,
+ balance: 0,
+ exclude_from_reports: true,
+ accountable: Depository.new
+ )
+ create_transaction(account: excluded_account, name: "Not counted", amount: 999)
+
+ get root_path
+ default_bars = money_flow_bars
+
+ get root_path, params: { money_flow_account_ids: [ excluded_account.id ] }
+
+ assert_response :ok
+ filtered_bars = money_flow_bars
+
+ # An account excluded from reports is visible/accessible but not eligible
+ # for cashflow totals, so selecting only it must fall back to the
+ # unfiltered state instead of silently computing to zero.
+ assert_equal default_bars, filtered_bars
+ end
+
+ test "dashboard clamps a future money flow month instead of erroring" do
+ get root_path, params: { money_flow_month: 1.month.from_now.beginning_of_month.iso8601 }
+
+ assert_response :ok
+ bars = money_flow_bars
+
+ assert_equal Date.current.beginning_of_month.iso8601, bars.last["date"]
+ end
+
+ test "dashboard money flow income/expense links exclude pending transactions" do
+ get root_path
+
+ assert_response :ok
+ assert_select "a[href*='q%5Btypes%5D%5B%5D=income'][href*='q%5Bstatus%5D%5B%5D=confirmed']"
+ assert_select "a[href*='q%5Btypes%5D%5B%5D=expense'][href*='q%5Bstatus%5D%5B%5D=confirmed']"
+ end
+
+ test "dashboard money flow income/expense links stay scoped to eligible accounts by default" do
+ excluded_account = @family.accounts.create!(
+ name: "Excluded From Reports",
+ currency: @family.currency,
+ balance: 0,
+ exclude_from_reports: true,
+ accountable: Depository.new
+ )
+
+ get root_path
+
+ assert_response :ok
+ income_href = css_select("a[href*='q%5Btypes%5D%5B%5D=income']").first["href"]
+ expense_href = css_select("a[href*='q%5Btypes%5D%5B%5D=expense']").first["href"]
+
+ # The default (unfiltered) state must still pin the drill-down links to
+ # the eligible accounts backing the displayed totals, not the broader
+ # accessible-accounts set transactions_path defaults to when account_ids
+ # is absent.
+ assert_includes income_href, "q%5Baccount_ids%5D%5B%5D="
+ assert_not_includes income_href, excluded_account.id
+ assert_includes expense_href, "q%5Baccount_ids%5D%5B%5D="
+ assert_not_includes expense_href, excluded_account.id
+ end
+
test "changelog" do
VCR.use_cassette("git_repository_provider/fetch_latest_release_notes") do
get changelog_path
@@ -161,4 +292,9 @@ class PagesControllerTest < ActionDispatch::IntegrationTest
assert_select "h2", text: "Test Release"
# Should not crash even with nil values
end
+
+ private
+ def money_flow_bars
+ JSON.parse(css_select("[data-controller='bar-chart']").first["data-bar-chart-data-value"])
+ end
end
diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rb
index 73feefc57f..00c9ca9c82 100644
--- a/test/models/income_statement_test.rb
+++ b/test/models/income_statement_test.rb
@@ -76,6 +76,30 @@ class IncomeStatementTest < ActiveSupport::TestCase
assert_equal expected_total_income, income_totals.category_totals.find { |ct| ct.category.id == @income_category.id }.total
end
+ test "totals_for scopes totals to a period and optional account ids" do
+ income_statement = IncomeStatement.new(@family)
+ period = Period.last_30_days
+
+ all_totals = income_statement.totals_for(period)
+ assert_equal Money.new(1000, @family.currency), all_totals.income_money
+ assert_equal Money.new(200 + 300 + 400, @family.currency), all_totals.expense_money
+
+ checking_only_totals = income_statement.totals_for(period, account_ids: [ @checking_account.id ])
+ assert_equal Money.new(1000, @family.currency), checking_only_totals.income_money
+ assert_equal Money.new(200, @family.currency), checking_only_totals.expense_money
+ end
+
+ test "eligible_accounts excludes accounts not reflected in totals" do
+ tax_advantaged_account = @family.accounts.create! name: "401k", currency: @family.currency, balance: 10000, accountable: Investment.new(subtype: "401k")
+ excluded_account = @family.accounts.create! name: "Excluded", currency: @family.currency, balance: 0, exclude_from_reports: true, accountable: Depository.new
+
+ eligible_ids = IncomeStatement.new(@family).eligible_accounts.pluck(:id)
+
+ assert_includes eligible_ids, @checking_account.id
+ assert_not_includes eligible_ids, tax_advantaged_account.id
+ assert_not_includes eligible_ids, excluded_account.id
+ end
+
test "calculates median expense" do
income_statement = IncomeStatement.new(@family)
assert_equal 200 + 300 + 400, income_statement.expense_totals(period: Period.last_30_days).total