Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(sankey): draw transfers that fund a deficit account in the account view (#4180)

scragnog4197f7132e20
diff --git a/app/models/income_statement/account_sankey.rb b/app/models/income_statement/account_sankey.rb
index 2a53455630..266c768401 100644
--- a/app/models/income_statement/account_sankey.rb
+++ b/app/models/income_statement/account_sankey.rb
@@ -3,8 +3,11 @@
# CategoryNetting, scoped to that account. What an account takes in beyond what
# it spends flows on to Surplus; an account that spends more than it takes in
# (a credit card paid off by transfer, savings being drawn down) is fed from
-# Deficit. Transfers between accounts are neither income nor spending, so they
-# never appear as flows between accounts.
+# Deficit. Transfers between accounts are neither income nor spending, but where
+# an account in surplus paid one in deficit, that transfer is drawn between the
+# two accounts (see #transfer_funding), so a card paid off from a current
+# account shows where its money came from instead of a Surplus on one side and
+# an equal Deficit on the other.
#
# Same schema as IncomeStatement::Sankey, with basis "net_by_account" and an
# "account" node kind in place of the single Cash Flow node.
@@ -24,7 +27,9 @@ class IncomeStatement::AccountSankey
capacity = [ income, spending + invested ].max
unless capacity.zero?
subcategory_flows = Hash.new(0.to_d)
- flows.each { |flow| add_account(flow, income, spending, capacity, subcategory_flows) }
+ funding = transfer_funding(flows)
+ flows.each { |flow| add_account(flow, income, spending, capacity, subcategory_flows, funding) }
+ add_transfers(funding, capacity)
add_subcategories(subcategory_flows)
end
{ basis: "net_by_account", income: decimal(income), spending: decimal(spending), invested: decimal(invested),
@@ -48,7 +53,7 @@ class IncomeStatement::AccountSankey
end
end
- def add_account(flow, income, spending, capacity, subcategory_flows)
+ def add_account(flow, income, spending, capacity, subcategory_flows, funding)
account = flow[:account]
size = [ flow[:income], flow[:spending] + flow[:invested] ].max
center = node("account_#{account.id}", account.name, :account, color: ACCOUNT_COLOR)
@@ -79,7 +84,10 @@ class IncomeStatement::AccountSankey
link(center, node_invested, flow[:invested], percentage(flow[:invested], capacity))
end
- net = flow[:income] - flow[:spending] - flow[:invested]
+ id = account.id
+ net = flow[:income] - flow[:spending] - flow[:invested] +
+ funding.sum { |(_, to), value| to == id ? value : 0 } -
+ funding.sum { |(from, _), value| from == id ? value : 0 }
return if net.zero?
kind = net.positive? ? :surplus : :deficit
@@ -89,6 +97,68 @@ class IncomeStatement::AccountSankey
link(*(net.positive? ? [ center, balance ] : [ balance, center ]), net.abs, percentage(net.abs, capacity))
end
+ # How much of each deficit account's shortfall was paid by a surplus
+ # account, as { [from_id, to_id] => amount }. Uses the period's confirmed
+ # transfers (funds movements and card payments) between the accounts in
+ # the graph, netted per pair, largest first. Each amount is capped by what
+ # the payer has left over and what the payee still needs, so every pound
+ # drawn takes the same off Surplus and Deficit (the net is unchanged) and
+ # links only run from surplus to deficit accounts, which keeps the graph
+ # acyclic.
+ def transfer_funding(flows)
+ balance = flows.to_h { |flow| [ flow[:account].id, flow[:income] - flow[:spending] - flow[:invested] ] }
+ surplus = balance.select { |_, net| net.positive? }
+ deficit = balance.select { |_, net| net.negative? }.transform_values(&:abs)
+ return {} if surplus.empty? || deficit.empty?
+
+ moved = Hash.new(0.to_d)
+ transfers_between(balance.keys).each do |from, to, amount|
+ moved[[ from, to ]] += amount
+ moved[[ to, from ]] -= amount
+ end
+
+ moved.select { |(from, to), amount| amount.positive? && surplus.key?(from) && deficit.key?(to) }
+ .sort_by { |_, amount| -amount }
+ .each_with_object({}) do |((from, to), amount), funding|
+ value = [ amount, surplus[from], deficit[to] ].min
+ next unless value.positive?
+
+ funding[[ from, to ]] = value
+ surplus[from] -= value
+ deficit[to] -= value
+ end
+ end
+
+ # [from_account_id, to_account_id, amount in the family currency] for each
+ # confirmed transfer between two of the given accounts with either leg in
+ # the period (legs can be days apart, so one may fall just outside it).
+ # Neither leg may be excluded.
+ def transfers_between(account_ids)
+ currency = @statement.family.currency
+ legs = Transaction.joins(:entry).where(entries: { account_id: account_ids, excluded: false })
+ outflows = legs.where(kind: %w[funds_movement cc_payment])
+ in_period = legs.where(entries: { date: @[email protected]_date })
+
+ between = Transfer.confirmed.where(outflow_transaction_id: outflows.select(:id), inflow_transaction_id: legs.select(:id))
+
+ between.where(outflow_transaction_id: in_period.select(:id))
+ .or(between.where(inflow_transaction_id: in_period.select(:id)))
+ .includes(outflow_transaction: :entry, inflow_transaction: :entry)
+ .filter_map do |transfer|
+ outflow = transfer.outflow_transaction.entry
+ amount = outflow.amount_money.abs.exchange_to(currency, date: outflow.date).amount.to_d
+ [ outflow.account_id, transfer.inflow_transaction.entry.account_id, amount ]
+ rescue Money::ConversionError
+ nil
+ end
+ end
+
+ def add_transfers(funding, capacity)
+ funding.each do |(from, to), value|
+ link(@node_index.fetch("account_#{from}"), @node_index.fetch("account_#{to}"), value, percentage(value, capacity))
+ end
+ end
+
# Subcategories are summed across accounts, then hang off their parent.
def add_subcategories(subcategory_flows)
subcategory_flows.each do |(side, root_id, category), value|
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 303c6b3825..3ba0091aae 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -3396,7 +3396,9 @@ components:
- net_by_category
- net_by_account
description: net_by_account (group_by=account) replaces the Cash Flow node
- with one account node per account, each balanced by Surplus or Deficit
+ with one account node per account, each balanced by Surplus or Deficit.
+ Where an account in surplus paid one in deficit by confirmed transfer
+ in the period, that amount is a link between the two account nodes instead
income:
type: string
spending:
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 9bb95f4306..87090ae347 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -1835,7 +1835,7 @@ RSpec.configure do |config|
type: :object, required: %w[basis income spending net_savings nodes links],
description: 'Refunds net within each category. Parent direct amounts exclude child totals before partitioning by direction. Graph income/spending may differ from gross monthly totals; net savings agrees. Decimal strings retain FX precision. Empty flow has empty nodes and links.',
properties: {
- basis: { type: :string, enum: %w[net_by_category net_by_account], description: 'net_by_account (group_by=account) replaces the Cash Flow node with one account node per account, each balanced by Surplus or Deficit' },
+ basis: { type: :string, enum: %w[net_by_category net_by_account], description: 'net_by_account (group_by=account) replaces the Cash Flow node with one account node per account, each balanced by Surplus or Deficit. Where an account in surplus paid one in deficit by confirmed transfer in the period, that amount is a link between the two account nodes instead' },
income: { type: :string }, spending: { type: :string }, net_savings: { type: :string },
invested: { type: :string, description: "Money moved into investment accounts, shown as its own node. Zero unless the family does not count investing as spending" },
nodes: { type: :array, items: {
diff --git a/test/models/income_statement/account_sankey_test.rb b/test/models/income_statement/account_sankey_test.rb
index ae6e95eea8..cb2529f488 100644
--- a/test/models/income_statement/account_sankey_test.rb
+++ b/test/models/income_statement/account_sankey_test.rb
@@ -47,6 +47,70 @@ class IncomeStatement::AccountSankeyTest < ActiveSupport::TestCase
assert_balanced result
end
+ test "a card paid off from a surplus account is drawn as a flow between the accounts" do
+ transaction(@checking, -1000, @salary)
+ transaction(@card, 250, @shopping)
+ create_transfer(from_account: @checking, to_account: @card, amount: 250, date: @month + 5)
+ result = graph
+
+ assert_link result, "account_#{@checking.id}", "account_#{@card.id}", "250.0"
+ assert_link result, "account_#{@checking.id}", "surplus_node", "750.0"
+ assert_nil node(result, "deficit_node")
+ assert_equal "750.0", result[:net_savings]
+ assert_balanced result
+ end
+
+ test "only the transferred part of a shortfall is drawn, the rest still comes from Deficit" do
+ transaction(@checking, -1000, @salary)
+ transaction(@card, 250, @shopping)
+ create_transfer(from_account: @checking, to_account: @card, amount: 100, date: @month + 5)
+ result = graph
+
+ assert_link result, "account_#{@checking.id}", "account_#{@card.id}", "100.0"
+ assert_link result, "deficit_node", "account_#{@card.id}", "150.0"
+ assert_link result, "account_#{@checking.id}", "surplus_node", "900.0"
+ assert_balanced result
+ end
+
+ test "transfers are netted per pair and capped at the shortfall" do
+ transaction(@checking, -1000, @salary)
+ transaction(@card, 250, @shopping)
+ create_transfer(from_account: @checking, to_account: @card, amount: 400, date: @month + 5)
+ create_transfer(from_account: @card, to_account: @checking, amount: 50, date: @month + 6)
+ create_transfer(from_account: @checking, to_account: @card, amount: 999, date: @month - 10)
+ result = graph
+
+ assert_link result, "account_#{@checking.id}", "account_#{@card.id}", "250.0"
+ assert_nil node(result, "deficit_node")
+ assert_link result, "account_#{@checking.id}", "surplus_node", "750.0"
+ assert_balanced result
+ end
+
+ test "a transfer counts when either leg is in the period, and not when a leg is excluded" do
+ transaction(@checking, -1000, @salary)
+ transaction(@card, 250, @shopping)
+ straddling = create_transfer(from_account: @checking, to_account: @card, amount: 100, date: @month - 2)
+ straddling.inflow_transaction.reload.entry.update!(date: @month + 1)
+ excluded = create_transfer(from_account: @checking, to_account: @card, amount: 60, date: @month + 5)
+ excluded.inflow_transaction.reload.entry.update!(excluded: true)
+ result = graph
+
+ assert_link result, "account_#{@checking.id}", "account_#{@card.id}", "100.0"
+ assert_link result, "deficit_node", "account_#{@card.id}", "150.0"
+ assert_balanced result
+ end
+
+ test "a transfer out of an account in deficit is not drawn" do
+ transaction(@checking, -1000, @salary)
+ transaction(@card, 250, @shopping)
+ create_transfer(from_account: @card, to_account: @checking, amount: 250, date: @month + 5)
+ result = graph
+
+ assert_empty(result[:links].select { |link| result[:nodes][link[:source]][:kind] == "account" && result[:nodes][link[:target]][:kind] == "account" })
+ assert_link result, "deficit_node", "account_#{@card.id}", "250.0"
+ assert_balanced result
+ end
+
test "money invested leaves each account for Invested when investing is not spending" do
@family.update!(investment_contributions_as_spending: false)
transaction(@checking, -1000, @salary)
@@ -60,6 +124,21 @@ class IncomeStatement::AccountSankeyTest < ActiveSupport::TestCase
assert_balanced result
end
+ test "money invested comes out of an account's surplus before it can fund another account" do
+ @family.update!(investment_contributions_as_spending: false)
+ transaction(@checking, -1000, @salary)
+ transaction(@card, 250, @shopping)
+ create_transaction(account: @checking, amount: 900, category: nil, date: @month, kind: "investment_contribution")
+ create_transfer(from_account: @checking, to_account: @card, amount: 250, date: @month + 5)
+ result = graph
+
+ assert_link result, "account_#{@checking.id}", "invested_node", "900.0"
+ assert_link result, "account_#{@checking.id}", "account_#{@card.id}", "100.0"
+ assert_link result, "deficit_node", "account_#{@card.id}", "150.0"
+ assert_nil node(result, "surplus_node")
+ assert_balanced result
+ end
+
test "accounts without income or spending are left out, and an empty period is empty" do
transaction(@checking, 50, @shopping)
assert_nil node(graph, "account_#{@card.id}")
diff --git a/test/system/cash_flow_group_by_test.rb b/test/system/cash_flow_group_by_test.rb
index 6c0e72b959..ac0e9de955 100644
--- a/test/system/cash_flow_group_by_test.rb
+++ b/test/system/cash_flow_group_by_test.rb
@@ -30,4 +30,28 @@ class CashFlowGroupByTest < ApplicationSystemTestCase
.assert_selector "svg text", text: "Group By Checking"
assert_equal "account", @user.reload.cashflow_sankey_group_by
end
+
+ test "the account view draws a card paid off from another account as a flow between them" do
+ family = @user.family
+ salary = family.categories.create!(name: "Group By Salary", color: "#00aa00")
+ checking = family.accounts.find_by!(name: "Group By Checking")
+ card = family.accounts.create!(name: "Group By Card", currency: "USD", balance: 0, accountable: CreditCard.new)
+ create_transaction(account: checking, category: salary, amount: -1000, date: @month)
+ create_transaction(account: card, category: family.categories.find_by!(name: "Group By Shopping"), amount: 250, date: @month)
+ create_transfer(from_account: checking, to_account: card, amount: 250, date: @month)
+ @user.update!(preferences: @user.preferences.merge("cashflow_sankey_group_by" => "account"))
+
+ sign_in @user
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ chart = find("#cashflow-preview [data-preview-sankey-chart-target='chart']", match: :first)
+
+ chart.assert_selector "svg text", text: "Group By Card"
+ flows = page.evaluate_script(<<~JS)
+ Array.from(document.querySelectorAll("#cashflow-preview svg .sankey-link"))
+ .map((path) => path.__data__)
+ .map((link) => [link.source.name, link.target.name, link.value])
+ JS
+ assert_includes flows, [ "Group By Checking", "Group By Card", 250 ]
+ assert_not(flows.any? { |source, target, _| source == "Deficit" && target == "Group By Card" }, "the card is paid from Checking, not Deficit")
+ end
end