Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Support multi-currency goal funding (#3974)

Artem Danilov8482357a5d29
diff --git a/app/components/goals/card_component.html.erb b/app/components/goals/card_component.html.erb
index f5b10fe28a..dbe537c899 100644
--- a/app/components/goals/card_component.html.erb
+++ b/app/components/goals/card_component.html.erb
@@ -46,6 +46,12 @@
<% if pace_line %>
<p class="text-xs text-subdued tabular-nums mt-1 privacy-sensitive"><%= pace_line %></p>
<% end %>
+ <%# A marker, not an alert: the full explanation lives on the goal page. %>
+ <% if goal.currency_conversion_incomplete? %>
+ <p class="mt-1 flex items-center gap-1 text-xs text-secondary">
+ <%= helpers.icon "alert-triangle", size: "xs", color: "warning" %><%= t("goals.goal_card.partial_total") %>
+ </p>
+ <% end %>
</div>
<%# flex-wrap + gap so the account label and the footer line wrap onto
diff --git a/app/components/goals/funding_accounts_breakdown_component.html.erb b/app/components/goals/funding_accounts_breakdown_component.html.erb
index f98118fb47..43e1b67432 100644
--- a/app/components/goals/funding_accounts_breakdown_component.html.erb
+++ b/app/components/goals/funding_accounts_breakdown_component.html.erb
@@ -32,16 +32,22 @@
<p class="text-sm font-medium text-primary truncate"><%= account.name %></p>
<p class="text-sm text-subdued tabular-nums privacy-sensitive">
<% if row[:earmarked] %>
- <%= t("goals.show.funding_accounts.earmarked_of", earmarked: row[:backing_money].format(precision: 0), balance: row[:balance_money].format(precision: 0)) %>
+ <%= t("goals.show.funding_accounts.earmarked_of", earmarked: row[:native_backing_money].format(precision: 0), balance: row[:balance_money].format(precision: 0)) %>
<% else %>
- <%= accountable_label(account) %> · <%= row[:backing_money].format(precision: 0) %>
+ <%= accountable_label(account) %> · <%= row[:native_backing_money].format(precision: 0) %>
+ <% end %>
+ <% if row[:converted] && !row[:rate_missing] %>
+ · <%= t("goals.show.funding_accounts.converted", amount: row[:backing_money].format(precision: 0)) %>
<% end %>
</p>
+ <% if row[:rate_missing] %>
+ <p class="text-xs text-secondary"><%= t("goals.show.funding_accounts.rate_unavailable") %></p>
+ <% end %>
</div>
<% if rows.size > 1 %>
<p class="hidden sm:block text-sm text-secondary tabular-nums text-right privacy-sensitive">
- <%= percent_for(row[:backing]) %>%
+ <%= row[:rate_missing] ? "—" : "#{percent_for(row[:backing])}%" %>
</p>
<% else %>
<span class="hidden sm:block"></span>
@@ -49,11 +55,11 @@
<div class="text-right space-y-0.5">
<div class="flex items-baseline justify-end gap-1.5">
- <p class="text-sm font-medium text-primary tabular-nums privacy-sensitive"><%= row[:last_30_money].format(precision: 0) %></p>
+ <p class="text-sm font-medium text-primary tabular-nums privacy-sensitive"><%= row[:rate_missing] ? "—" : row[:last_30_money].format(precision: 0) %></p>
<p class="text-xs text-subdued"><%= t("goals.show.funding_last_30d") %></p>
</div>
<div class="flex items-baseline justify-end gap-1.5">
- <p class="text-xs text-secondary tabular-nums privacy-sensitive"><%= row[:last_90_money].format(precision: 0) %></p>
+ <p class="text-xs text-secondary tabular-nums privacy-sensitive"><%= row[:rate_missing] ? "—" : row[:last_90_money].format(precision: 0) %></p>
<p class="text-xs text-subdued"><%= t("goals.show.funding_last_90d") %></p>
</div>
</div>
diff --git a/app/components/goals/funding_accounts_breakdown_component.rb b/app/components/goals/funding_accounts_breakdown_component.rb
index 6917bf47c4..c5658192b4 100644
--- a/app/components/goals/funding_accounts_breakdown_component.rb
+++ b/app/components/goals/funding_accounts_breakdown_component.rb
@@ -12,12 +12,17 @@ class Goals::FundingAccountsBreakdownComponent < ApplicationComponent
@rows ||= goal.linked_accounts.sort_by { |a| -goal.account_backing(a).amount.to_d }.map do |account|
totals = inflow_totals_for(account)
backing = goal.account_backing(account).amount.to_d
+ native = goal.account_native_backing(account)
goal_account = goal_account_by_id[account.id]
{
account: account,
backing: backing,
backing_money: Money.new(backing, goal.currency),
- balance_money: Money.new(account.balance.to_d, goal.currency),
+ balance_money: Money.new(account.balance.to_d, account.currency),
+ native_backing_money: native,
+ converted: account.currency != goal.currency,
+ # Zero converts without a rate, so only a nonzero share can be left out.
+ rate_missing: !native.zero? && goal.missing_exchange_rate_currencies.include?(account.currency),
earmarked: goal_account&.allocated_amount.present?,
last_30_money: Money.new(totals[:last_30], goal.currency),
last_90_money: Money.new(totals[:last_90], goal.currency)
@@ -60,13 +65,13 @@ class Goals::FundingAccountsBreakdownComponent < ApplicationComponent
@goal_account_by_id ||= goal.goal_accounts.index_by(&:account_id)
end
- # Per-account net inflow for both windows in one pass over the 90-day
- # entries set. Entry amount sign in Sure: inflow is negative; flip and
- # clamp ≥ 0.
def inflow_totals_for(account)
inflow_totals_map[account.id] || { last_30: 0.to_d, last_90: 0.to_d }
end
+ # Per-account net inflow for both windows in one pass over the 90-day
+ # entries set. Entry amount sign in Sure: inflow is negative; flip and
+ # clamp ≥ 0. Converted at today's rate, like Goal#pace.
def inflow_totals_map
@inflow_totals_map ||= begin
account_ids = goal.linked_accounts.map(&:id)
@@ -79,11 +84,12 @@ class Goals::FundingAccountsBreakdownComponent < ApplicationComponent
.where(account_id: account_ids, date: TREND_WINDOW_DAYS.days.ago.to_date..Date.current)
.where(excluded: false)
.merge(Transaction.excluding_pending)
- .pluck(:account_id, :date, :amount)
+ .pluck(:account_id, :date, :amount, :currency)
result = Hash.new { |h, k| h[k] = { last_30: 0.to_d, last_90: 0.to_d } }
- rows.each do |aid, date, amount|
- inflow = (-amount.to_d).clamp(0..)
+ accounts_by_id = goal.linked_accounts.index_by(&:id)
+ rows.each do |aid, date, amount, currency|
+ inflow = goal.convert_money(Money.new((-amount.to_d).clamp(0..), currency.presence || accounts_by_id.fetch(aid).currency)).amount
result[aid][:last_90] += inflow
result[aid][:last_30] += inflow if date >= cutoff_30
end
diff --git a/app/controllers/goals_controller.rb b/app/controllers/goals_controller.rb
index 917a8b538e..f897b37a3f 100644
--- a/app/controllers/goals_controller.rb
+++ b/app/controllers/goals_controller.rb
@@ -58,7 +58,8 @@ class GoalsController < ApplicationController
def create
@goal = Current.family.goals.new(goal_params)
accounts = lookup_accounts(params.dig(:goal, :account_ids))
- @goal.currency = (accounts.first&.currency || Current.family.primary_currency_code) if @goal.currency.blank?
+ # The family currency is what the form shows next to the target.
+ @goal.currency = Current.family.primary_currency_code if @goal.currency.blank?
allocations = submitted_allocations
Goal.transaction do
@@ -173,11 +174,13 @@ class GoalsController < ApplicationController
def record_consumption
txn = consumption_transaction
- amount = txn ? txn.entry.amount.to_d : params[:amount].to_d
+ amount = txn ? @goal.convert_money!(txn.entry.amount_money, date: txn.entry.date).amount : params[:amount].to_d
@goal.consume!(amount, account: consumption_account(txn), transaction: txn)
redirect_to goal_path(@goal),
notice: t("goals.consume.success", amount: Money.new(amount, @goal.currency).format)
+ rescue Money::ConversionError
+ redirect_to goal_path(@goal), alert: t("goals.consume.errors.missing_exchange_rate")
rescue Goal::ConsumptionRefused => e
redirect_to goal_path(@goal), alert: t("goals.consume.errors.#{e.reason}")
rescue ActiveRecord::RecordInvalid => e
diff --git a/app/helpers/goals_helper.rb b/app/helpers/goals_helper.rb
index 2c1fb225e2..4ad6ab54db 100644
--- a/app/helpers/goals_helper.rb
+++ b/app/helpers/goals_helper.rb
@@ -47,6 +47,20 @@ module GoalsHelper
other_goal_rows(account, pooled, current_goal).any? { |row| row[:allocated_amount].nil? }
end
+ # The amount fields in the spend and pledge dialogs are in goal currency, so
+ # an account in another currency says which one it holds.
+ def goal_account_label(account, goal)
+ account.currency == goal.currency ? account.name : "#{account.name} · #{account.currency}"
+ end
+
+ # Today's account-to-goal rate, so the earmark hint can show the goal-currency
+ # equivalent while typing. nil when the currencies match or no rate exists.
+ def earmark_conversion_rate(goal, account, currency)
+ return if account.currency == currency
+
+ goal.convert_money(Money.new(1, account.currency), to: currency).amount.nonzero?
+ end
+
private
def other_goal_rows(account, pooled, current_goal)
(pooled[account.id] || [])
diff --git a/app/javascript/controllers/goal_earmark_controller.js b/app/javascript/controllers/goal_earmark_controller.js
index 5267221443..517afa9665 100644
--- a/app/javascript/controllers/goal_earmark_controller.js
+++ b/app/javascript/controllers/goal_earmark_controller.js
@@ -1,4 +1,4 @@
-import { Controller } from "@hotwired/stimulus"
+import { Controller } from "@hotwired/stimulus";
// Tells the user what each funding account still has room for, as they type.
//
@@ -12,7 +12,7 @@ import { Controller } from "@hotwired/stimulus"
// against the 7 the project guidelines suggest. Three here, and no shared
// state between them.
export default class extends Controller {
- static targets = ["allocationInput", "warning", "checkbox"]
+ static targets = ["allocationInput", "warning", "checkbox"];
static values = {
currency: String,
locale: String,
@@ -20,44 +20,45 @@ export default class extends Controller {
prorata: String,
headroom: String,
wholeBalanceAlone: String,
- }
+ converted: String,
+ };
// A complete number, optionally with one decimal separator and digits after
// it. `Number.parseFloat` alone accepts prefixes — "500abc" becomes 500 —
// and a bare comma-to-dot swap turns the thousands-separated "1,500" into
// 1.5, so a typo or a habit from another locale silently changed the amount
// the preview was based on.
- static ALLOCATION_PATTERN = /^\d+(?:[.,]\d+)?$/
+ static ALLOCATION_PATTERN = /^\d+(?:[.,]\d+)?$/;
connect() {
- this.refresh()
+ this.refresh();
}
refresh() {
- this.allocationInputTargets.forEach((input) => this.#refreshRow(input))
+ this.allocationInputTargets.forEach((input) => this.#refreshRow(input));
}
#refreshRow(input) {
- const row = input.closest("[data-balance]")
- if (!row) return
+ const row = input.closest("[data-balance]");
+ if (!row) return;
- const warning = row.querySelector('[data-goal-earmark-target="warning"]')
- const checkbox = row.querySelector('input[type="checkbox"]')
- if (!warning) return
+ const warning = row.querySelector('[data-goal-earmark-target="warning"]');
+ const checkbox = row.querySelector('input[type="checkbox"]');
+ if (!warning) return;
// An unchecked account funds nothing, so it has nothing to say.
- if (checkbox && !checkbox.checked) return this.#hide(warning)
+ if (checkbox && !checkbox.checked) return this.#hide(warning);
- const balance = Number.parseFloat(row.dataset.balance || "0")
- const others = Number.parseFloat(row.dataset.earmarkedByOthers || "0")
+ const balance = Number.parseFloat(row.dataset.balance || "0");
+ const others = Number.parseFloat(row.dataset.earmarkedByOthers || "0");
// A whole-account link elsewhere sums to zero above, so the amount alone
// cannot tell "nobody else claims this" from "somebody claims all of it".
- const claimedWhole = row.dataset.wholeAccountClaimed === "true"
- const raw = input.value.trim()
+ const claimedWhole = row.dataset.wholeAccountClaimed === "true";
+ const raw = input.value.trim();
// A number input reports text it cannot parse as "", which would read as
// a blank amount and claim the whole balance for what the user typed.
- if (input.validity?.badInput) return this.#hide(warning)
+ if (input.validity?.badInput) return this.#hide(warning);
// "whatever is left after the other earmarks" describes nothing when there
// are none — and this is where a first-time user meets the word, pointed
@@ -65,47 +66,66 @@ export default class extends Controller {
if (raw === "") {
return this.#show(
warning,
- others > 0 || claimedWhole ? this.wholeBalanceValue : this.wholeBalanceAloneValue,
- )
+ others > 0 || claimedWhole
+ ? this.wholeBalanceValue
+ : this.wholeBalanceAloneValue,
+ );
}
- if (!this.constructor.ALLOCATION_PATTERN.test(raw)) return this.#hide(warning)
+ if (!this.constructor.ALLOCATION_PATTERN.test(raw))
+ return this.#hide(warning);
- const entered = Number.parseFloat(raw.replace(",", "."))
- if (Number.isNaN(entered)) return this.#hide(warning)
+ const entered = Number.parseFloat(raw.replace(",", "."));
+ if (Number.isNaN(entered)) return this.#hide(warning);
- const total = others + entered
+ const total = others + entered;
+ // Only foreign-currency rows with a known rate carry one. Past the
+ // balance the goal counts its pro-rata share, not the typed amount.
+ const rate = Number.parseFloat(row.dataset.rate);
+ const counted =
+ total > balance ? Math.max((entered * balance) / total, 0) : entered;
+ const converted =
+ rate > 0
+ ? ` ${this.convertedValue.replace("{amount}", this.#money(counted * rate))}`
+ : "";
if (total > balance) {
this.#show(
warning,
this.prorataValue
- .replace("{total}", this.#money(total))
- .replace("{balance}", this.#money(balance)),
- )
+ .replace("{total}", this.#money(total, row.dataset.currency))
+ .replace("{balance}", this.#money(balance, row.dataset.currency)) +
+ converted,
+ );
} else {
- this.#show(warning, this.headroomValue.replace("{left}", this.#money(balance - total)))
+ this.#show(
+ warning,
+ this.headroomValue.replace(
+ "{left}",
+ this.#money(balance - total, row.dataset.currency),
+ ) + converted,
+ );
}
}
#show(element, text) {
- element.textContent = text
- element.classList.remove("hidden")
+ element.textContent = text;
+ element.classList.remove("hidden");
}
#hide(element) {
- element.classList.add("hidden")
+ element.classList.add("hidden");
}
- #money(value) {
+ #money(value, currency = this.currencyValue || "USD") {
try {
return new Intl.NumberFormat(this.localeValue || undefined, {
style: "currency",
- currency: this.currencyValue || "USD",
+ currency,
maximumFractionDigits: 0,
- }).format(value)
+ }).format(value);
} catch {
- return `${this.currencyValue || "$"}${Math.round(value).toLocaleString()}`
+ return `${currency}${Math.round(value).toLocaleString()}`;
}
}
}
diff --git a/app/models/assistant/function/create_goal.rb b/app/models/assistant/function/create_goal.rb
index 18c679dba8..b528464b6b 100644
--- a/app/models/assistant/function/create_goal.rb
+++ b/app/models/assistant/function/create_goal.rb
@@ -19,7 +19,9 @@ class Assistant::Function::CreateGoal < Assistant::Function
Constraints:
- The goal must link to at least one of the user's Depository
accounts (checking, savings, HSA, CD, money-market).
- - All linked accounts must share the same currency.
+ - The target is in the family's primary currency. Accounts in other
+ currencies are converted to it; earmarks stay in each account's
+ own currency.
- Use account names exactly as listed in the user's Depository
accounts.
@@ -44,7 +46,7 @@ class Assistant::Function::CreateGoal < Assistant::Function
},
target_amount: {
type: "number",
- description: "Total amount to save, in the linked accounts' currency."
+ description: "Total amount to save, in the family's primary currency."
},
target_date: {
type: "string",
@@ -57,7 +59,7 @@ class Assistant::Function::CreateGoal < Assistant::Function
},
earmarks: {
type: "object",
- description: "Optional map of account name to the amount to reserve from that account, e.g. {\"Livret A\": 2000}. Required for an account already claimed in full by another goal — the available accounts list says which, and how much room is left. Accounts left out of this map reserve whatever the account has spare.",
+ description: "Optional map of account name to the amount to reserve from that account, in that account's currency, e.g. {\"Livret A\": 2000}. Required for an account already claimed in full by another goal — the available accounts list says which, and how much room is left. Accounts left out of this map reserve whatever the account has spare.",
additionalProperties: { type: "number" }
},
notes: {
@@ -115,14 +117,6 @@ class Assistant::Function::CreateGoal < Assistant::Function
matched = linked_account_names.map { |name| grouped[name].first }
- currencies = matched.map(&:currency).uniq
- if currencies.size > 1
- return error(
- "currency_mismatch",
- "All linked accounts must share the same currency. Found: #{currencies.join(', ')}."
- )
- end
-
# Named before the save, so the assistant gets a reason it can act on
# rather than a generic validation failure it can only relay. Claiming an
# account in full is exclusive; joining one that is already claimed needs
@@ -144,7 +138,7 @@ class Assistant::Function::CreateGoal < Assistant::Function
name: name,
target_amount: target_amount,
target_date: target_date,
- currency: currencies.first,
+ currency: family.primary_currency_code,
notes: notes.presence,
color: Goal::COLORS.sample
)
diff --git a/app/models/balance/chart_series_builder.rb b/app/models/balance/chart_series_builder.rb
index ae24e9cbaa..1daeaf1e30 100644
--- a/app/models/balance/chart_series_builder.rb
+++ b/app/models/balance/chart_series_builder.rb
@@ -1,6 +1,7 @@
class Balance::ChartSeriesBuilder
def initialize(account_ids:, currency:, period: Period.last_30_days, interval: nil,
- favorable_direction: "up", account_active_until_dates: {})
+ favorable_direction: "up", account_active_until_dates: {}, strict_currency_conversion: false)
+ @strict_currency_conversion = strict_currency_conversion
@account_ids = account_ids
@currency = currency
@period = period
@@ -70,6 +71,9 @@ class Balance::ChartSeriesBuilder
def build_series_for(column)
values = query_data.map do |datum|
+ if @strict_currency_conversion && datum[:missing_currency].present?
+ raise Money::ConversionError.new(from_currency: datum[:missing_currency], to_currency: currency, date: datum.date)
+ end
# Map column names to their start equivalents
previous_column = case column
when :end_balance then :start_balance
@@ -143,6 +147,10 @@ class Balance::ChartSeriesBuilder
favorable_direction == "down" ? -1 : 1
end
+ def balance_rate_sql
+ @strict_currency_conversion ? "CASE WHEN accounts.currency = :target_currency THEN 1 WHEN er.rate > 0 THEN er.rate END" : "COALESCE(er.rate, 1)"
+ end
+
def query
<<~SQL
WITH dates AS (
@@ -165,24 +173,28 @@ class Balance::ChartSeriesBuilder
)
SELECT
d.date,
+ MIN(accounts.currency) FILTER (
+ WHERE accounts.currency <> :target_currency
+ AND last_bal.end_balance <> 0 AND (er.rate IS NULL OR er.rate <= 0)
+ ) AS missing_currency,
-- Use flows_factor: already handles asset (+1) vs liability (-1)
- COALESCE(SUM(last_bal.end_balance * last_bal.flows_factor * COALESCE(er.rate, 1) * :sign_multiplier::integer), 0) AS end_balance,
- COALESCE(SUM(last_bal.end_cash_balance * last_bal.flows_factor * COALESCE(er.rate, 1) * :sign_multiplier::integer), 0) AS end_cash_balance,
+ COALESCE(SUM(last_bal.end_balance * last_bal.flows_factor * #{balance_rate_sql} * :sign_multiplier::integer), 0) AS end_balance,
+ COALESCE(SUM(last_bal.end_cash_balance * last_bal.flows_factor * #{balance_rate_sql} * :sign_multiplier::integer), 0) AS end_cash_balance,
-- Holdings only for assets (flows_factor = 1)
COALESCE(SUM(
CASE WHEN last_bal.flows_factor = 1
THEN last_bal.end_non_cash_balance
ELSE 0
- END * COALESCE(er.rate, 1) * :sign_multiplier::integer
+ END * #{balance_rate_sql} * :sign_multiplier::integer
), 0) AS end_holdings_balance,
-- Previous balances
- COALESCE(SUM(last_bal.start_balance * last_bal.flows_factor * COALESCE(er.rate, 1) * :sign_multiplier::integer), 0) AS start_balance,
- COALESCE(SUM(last_bal.start_cash_balance * last_bal.flows_factor * COALESCE(er.rate, 1) * :sign_multiplier::integer), 0) AS start_cash_balance,
+ COALESCE(SUM(last_bal.start_balance * last_bal.flows_factor * #{balance_rate_sql} * :sign_multiplier::integer), 0) AS start_balance,
+ COALESCE(SUM(last_bal.start_cash_balance * last_bal.flows_factor * #{balance_rate_sql} * :sign_multiplier::integer), 0) AS start_cash_balance,
COALESCE(SUM(
CASE WHEN last_bal.flows_factor = 1
THEN last_bal.start_non_cash_balance
ELSE 0
- END * COALESCE(er.rate, 1) * :sign_multiplier::integer
+ END * #{balance_rate_sql} * :sign_multiplier::integer
), 0) AS start_holdings_balance
FROM dates d
LEFT JOIN selected_accounts accounts
diff --git a/app/models/budget.rb b/app/models/budget.rb
index d7381ab536..b3dd5dba75 100644
--- a/app/models/budget.rb
+++ b/app/models/budget.rb
@@ -235,11 +235,17 @@ class Budget < ApplicationRecord
# a USD budget would read 1,200 available, 1,000 earmarked and 200
# free, when none of it is free.
Goal.prepared_for(family, scope: family.goals.where.not(state: Goal::RELEASED_STATES))
- .sum { |goal| convert_to_budget_currency(goal.backing_within(ids), goal.currency) }
+ .sum { |goal| goal.backing_within(ids, currency: currency) }
end
end
end
+ # Currencies whose balances available_cash left out for want of a rate.
+ def missing_cash_currencies
+ available_cash
+ @missing_cash_currencies ||= Set.new
+ end
+
def free_cash
[ available_cash - earmarked_for_goals, 0 ].max
end
@@ -505,17 +511,16 @@ class Budget < ApplicationRecord
end
private
- # `find_or_fetch_rate`, not `find_rate` — the latter does not exist, and
- # every multi-currency family opening this page hit a NoMethodError.
- #
- # No rate for the day leaves the amount as it stands. A cash panel that
- # renders with one figure unconverted is wrong by the spread; one that
- # raises takes the whole budget page down with it.
+ # Use the same known-subtotal policy as goal backing. A foreign balance
+ # without a rate is unavailable, never newly "free" cash at a 1:1 rate.
def convert_to_budget_currency(amount, from_currency)
- return amount.to_d if from_currency == currency
+ return amount.to_d if from_currency == currency || amount.to_d.zero?
rate = ExchangeRate.find_or_fetch_rate(from: from_currency, to: currency, date: Date.current)&.rate
- rate ? amount.to_d * rate : amount.to_d
+ return amount.to_d * rate if rate && rate.to_d.positive?
+
+ (@missing_cash_currencies ||= Set.new) << from_currency
+ 0.to_d
end
def income_statement
@income_statement ||= family.income_statement(user: current_user, accounts: income_statement_accounts)
diff --git a/app/models/goal.rb b/app/models/goal.rb
index 9b77d80abd..06e886b7de 100644
--- a/app/models/goal.rb
+++ b/app/models/goal.rb
@@ -64,7 +64,6 @@ class Goal < ApplicationRecord
validate :must_have_at_least_one_linked_account
validate :linked_accounts_must_be_fundable
- validate :linked_accounts_must_match_goal_currency
validate :linked_accounts_must_belong_to_family
validate :currency_locked_once_linked
validate :restore_must_not_recreate_whole_account_conflict
@@ -77,6 +76,11 @@ class Goal < ApplicationRecord
# cannot see.
before_validation :clear_target_date_for_maintained
+ # Warm conversion rates before taking account-claim locks. Completing a goal
+ # freezes its balance, so an unavailable rate must refuse the write rather
+ # than permanently snapshot a partial subtotal.
+ before_validation :prepare_completion_conversion, if: -> { state_changed? && completed? }
+
# Autosave validates each link separately, so each would otherwise take its
# own account lock in association order. Two goals saving links on the same
# two accounts in opposite orders would then hold one lock each and wait on
@@ -257,11 +261,12 @@ class Goal < ApplicationRecord
attr_writer :market_flows
# Family-wide map of each linked account's net inflow over the trailing
- # 90 days (account_id => net Entry#amount sum) — the same aggregate #pace
- # computes per goal. Injected alongside pooled_allocations/market_flows so
- # sorting/rendering N goals (active_display_sort calls goal.status, which
- # reaches #pace for any goal with a target_date) fires one grouped query
- # instead of one Entry.sum per goal.
+ # 90 days, per entry currency (account_id => { currency => net Entry#amount
+ # sum }) — the same aggregate #pace computes per goal. Injected alongside
+ # pooled_allocations/market_flows so sorting/rendering N goals
+ # (active_display_sort calls goal.status, which reaches #pace for any goal
+ # with a target_date) fires one grouped query instead of one Entry.sum per
+ # goal.
def self.pace_for(family)
account_ids = GoalAccount.joins(:goal).where(goals: { family_id: family.id }).distinct.pluck(:account_id)
return {} if account_ids.empty?
@@ -271,8 +276,11 @@ class Goal < ApplicationRecord
.where(account_id: account_ids, date: 90.days.ago.to_date..Date.current)
.where(excluded: false)
.merge(Transaction.excluding_pending)
- .group(:account_id)
+ .group(:account_id, :currency)
.sum(:amount)
+ .each_with_object({}) do |((account_id, currency), amount), totals|
+ (totals[account_id] ||= {})[currency] = amount
+ end
end
attr_writer :pooled_pace
@@ -296,7 +304,9 @@ class Goal < ApplicationRecord
pooled = pooled_allocations_for(family)
flows = market_flows_for(family)
pace_map = pace_for(family)
+ converter = CurrencyConverter.new
goals.each do |goal|
+ goal.currency_converter = converter
goal.pooled_allocations = pooled
goal.market_flows = flows
goal.pooled_pace = pace_map
@@ -376,14 +386,9 @@ class Goal < ApplicationRecord
end
end
- # Balance is this goal's backing across its linked depository accounts that
- # match the goal's currency. Each linked account contributes either its
- # earmarked slice (goal_accounts.allocated_amount) or — when unallocated —
- # the whole balance left after other goals' earmarks (see
- # #backing_balance_for). The model validates the currency invariant at write
- # time, but the defensive filter + telemetry here guards against drift from
- # direct DB writes, account-currency edits outside goal validation, or
- # future code that bypasses the validation chain.
+ # Allocate in each account's native currency first, then convert the goal's
+ # share. Goals with different currencies can share fixed earmarks without
+ # interpreting one goal's dollars as another goal's euros.
def current_balance
# A closed goal reports what it reached, not what its accounts hold now.
# The guard is `present?`, never `completed?`: `archive` accepts a goal
@@ -392,14 +397,7 @@ class Goal < ApplicationRecord
# shapes coexist in the database.
return completed_amount.to_d if completed_amount.present?
- @current_balance ||= begin
- matching = linked_accounts.select { |a| a.currency == currency }
- if matching.size != linked_accounts.size
- Rails.logger.warn("Goal##{id} linked-account currency drift: #{linked_accounts.size - matching.size} of #{linked_accounts.size} mismatched (expected #{currency})")
- Sentry.capture_message("Goal linked-account currency drift", level: :warning, extra: { goal_id: id, expected_currency: currency }) if defined?(Sentry)
- end
- matching.sum { |account| account_amount_for(account) }
- end
+ @current_balance ||= linked_accounts.sum { |account| account_backing(account).amount }
end
def current_balance_money
@@ -416,11 +414,11 @@ class Goal < ApplicationRecord
# Goes through the same `backing_share_for` as everything else, so a
# whole-account link is counted for the remainder it actually claims rather
# than the zero its nil allocation would suggest.
- def backing_within(account_ids)
+ def backing_within(account_ids, currency: self.currency)
ids = Array(account_ids).to_set
linked_accounts
- .select { |account| account.currency == currency && ids.include?(account.id) }
- .sum { |account| account_amount_for(account) }
+ .select { |account| ids.include?(account.id) }
+ .sum { |account| convert_money(Money.new(account_amount_for(account), account.currency), to: currency).amount }
end
# Whether this reader can record a spend against this goal. Two doors lead to
@@ -431,8 +429,52 @@ class Goal < ApplicationRecord
one_off? && active? && backing_within(account_ids).to_d.positive?
end
+ # A missing rate counts as zero and is recorded for the warning.
def account_backing(account)
- Money.new(account_amount_for(account), currency)
+ convert_money(account_native_backing(account))
+ end
+
+ def account_native_backing(account)
+ Money.new(account_amount_for(account), account.currency)
+ end
+
+ attr_writer :currency_converter
+
+ # Strict conversion is used for writes, so an unavailable rate cannot record
+ # a pledge match or release an incorrectly sized earmark.
+ def convert_money!(money, to: currency, date: Date.current)
+ currency_converter.convert(money, to: to, date: date)
+ end
+
+ # Read surfaces show the known subtotal with an explicit missing-rate warning.
+ # Never relabel a foreign amount as goal currency or assume a 1:1 rate.
+ def convert_money(money, to: currency, date: Date.current)
+ convert_money!(money, to: to, date: date)
+ rescue Money::ConversionError => e
+ # Logged once a day per family and pair: reads run on every page view, and
+ # a family without a rate provider would otherwise log on each one.
+ if missing_exchange_rate_currencies.add?(e.from_currency) &&
+ Rails.cache.write([ "goal_fx_missing", family_id, e.from_currency, e.to_currency ], true, expires_in: 1.day, unless_exist: true)
+ DebugLogEntry.capture(
+ category: "goal_currency_conversion", level: "warn", source: "Goal",
+ message: "Goal amount could not be converted", family: family,
+ metadata: { goal_id: id, from: e.from_currency, to: e.to_currency, date: e.date }
+ )
+ end
+ Money.new(0, to)
+ end
+
+ def missing_exchange_rate_currencies
+ @missing_exchange_rate_currencies ||= Set.new
+ end
+
+ # Runs the backing, pace and market-value conversions up front, so the
+ # warning can render above those figures instead of after them.
+ def currency_conversion_incomplete?
+ current_balance
+ pace
+ market_value_money
+ missing_exchange_rate_currencies.any?
end
def contributions_basis?
@@ -533,7 +575,9 @@ class Goal < ApplicationRecord
# progress basis — the "what it's worth today" figure shown next to
# contributions on an investment-backed goal.
def market_value_money
- amount = linked_accounts.select { |a| a.currency == currency }.sum { |a| backing_share_for(a, a.balance.to_d) }
+ amount = linked_accounts.sum do |account|
+ convert_money(Money.new(backing_share_for(account, account.balance.to_d), account.currency)).amount
+ end
Money.new(amount, currency)
end
@@ -571,6 +615,11 @@ class Goal < ApplicationRecord
raise ConsumptionRefused.new(:maintained) if maintained?
link = consumption_link_for(account)
+ # The submitted amount and consumed_amount are in goal currency; earmarks
+ # remain in account currency. Reuse the forward rate instead of requiring
+ # a separately cached inverse rate.
+ rate = convert_money!(Money.new(1, link.account.currency), date: transaction&.entry&.date || Date.current).amount
+ native_amount = amount / rate
# The GOAL is locked, not just the link. `consumed_amount` lives here, and
# two concurrent requests locking only their own links would both read the
@@ -589,11 +638,11 @@ class Goal < ApplicationRecord
# held while `consumed_amount` took the full figure, so the two sides
# silently disagreed: money counted as spent that was never released,
# and still reserved against every sibling goal on the account.
- if amount > link.allocated_amount.to_d
+ if native_amount > link.allocated_amount.to_d
raise ConsumptionRefused.new(:exceeds_earmark)
end
- link.update!(allocated_amount: link.allocated_amount.to_d - amount)
+ link.update!(allocated_amount: link.allocated_amount.to_d - native_amount)
else
# A whole-account link has no slice to shrink, so `consumed_amount`
# would be added to a backing that has not moved: the goal reads 6,000
@@ -611,15 +660,15 @@ class Goal < ApplicationRecord
# twice reports 4,000 of a 5,000 goal that is whole. Capping at what
# is left to reach is the same answer in both orders, with nothing to
# infer.
- backed = backing_within([ link.account_id ]).to_d
+ backed = account_amount_for(link.account).to_d
# Same refusal a fixed earmark gives, for the same reason: the link
# cannot have supplied money it never backed. `still_needed` cannot go
# negative — the target check above has already refused that.
- raise ConsumptionRefused.new(:exceeds_earmark) if amount > backed
+ raise ConsumptionRefused.new(:exceeds_earmark) if native_amount > backed
still_needed = target_amount.to_d - consumed_amount.to_d - amount
- link.update!(allocated_amount: [ backed, still_needed ].min)
+ link.update!(allocated_amount: [ backed, still_needed / rate ].min)
end
update!(consumed_amount: consumed_amount.to_d + amount)
@@ -631,6 +680,8 @@ class Goal < ApplicationRecord
reload
reset_state_dependent_caches!
self
+ rescue Money::ConversionError
+ raise ConsumptionRefused.new(:missing_exchange_rate)
end
def remaining_amount_money
@@ -720,7 +771,14 @@ class Goal < ApplicationRecord
@pace = if linked_accounts.empty?
0
else
- net = linked_accounts.sum { |account| pooled_pace.fetch(account.id, 0).to_d }
+ # Today's rate, not each entry's: pace is an estimate, and a rate per
+ # entry date could reach the provider up to 90 times per currency on
+ # every render.
+ net = linked_accounts.sum do |account|
+ pooled_pace.fetch(account.id, {}).sum do |entry_currency, amount|
+ convert_money(Money.new(amount, entry_currency.presence || account.currency)).amount
+ end
+ end
(-net.to_d / 3).round(2)
end
end
@@ -767,7 +825,9 @@ class Goal < ApplicationRecord
# instead of dropping off a cliff for earmarked goals. Assumes the earmark
# ratio held over the window (an approximation); exact for unallocated
# goals, where ratio == 1 and the series is unchanged.
- whole_total = linked_accounts.select { |a| a.currency == currency }.sum { |a| a.balance.to_d }
+ whole_total = linked_accounts.sum do |account|
+ convert_money(Money.new(account.balance.to_d, account.currency)).amount
+ end
# 0 when the linked-account total is non-positive: current_balance is forced
# to 0 there, so the saved series must end at 0 too (no stray non-zero tail).
#
@@ -1109,6 +1169,10 @@ class Goal < ApplicationRecord
goal_accounts.find { |ga| ga.account_id == account.id }&.allocated_amount
end
+ def currency_converter
+ @currency_converter ||= CurrencyConverter.new
+ end
+
# Family-wide map of non-archived goal earmarks. Injected once per request
# by the controller on index (one query for the whole page); falls back to
# a single query for the standalone (show) case.
@@ -1124,6 +1188,12 @@ class Goal < ApplicationRecord
@pooled_pace ||= self.class.pace_for(family)
end
+ def prepare_completion_conversion
+ linked_accounts.each { |account| convert_money!(account_native_backing(account)) }
+ rescue Money::ConversionError
+ errors.add(:base, :missing_exchange_rate)
+ end
+
def apply_state_change_side_effects
previous_state, next_state = saved_change_to_state
@@ -1137,7 +1207,8 @@ class Goal < ApplicationRecord
# nothing, but its amount would still be recomputed from the live
# balance — so spending the money would walk the finished goal back
# down and rewrite its own history.
- update_columns(completed_amount: current_balance, completed_at: Time.current)
+ closing_balance = linked_accounts.sum { |account| convert_money!(account_native_backing(account)).amount }
+ update_columns(completed_amount: closing_balance, completed_at: Time.current)
elsif previous_state.in?(RELEASED_STATES) && !next_state.in?(RELEASED_STATES)
thaw_completed_amount!
end
@@ -1244,7 +1315,7 @@ class Goal < ApplicationRecord
@remaining_amount @remaining_amount_money
@progress_percent @monthly_target_amount
@progress_amount_money @consumed_amount_money
- @pace @pace_money @status @pooled_allocations
+ @pace @pace_money @status @pooled_allocations @missing_exchange_rate_currencies
].each do |ivar|
remove_instance_variable(ivar) if instance_variable_defined?(ivar)
end
@@ -1274,8 +1345,12 @@ class Goal < ApplicationRecord
Balance::ChartSeriesBuilder.new(
account_ids: linked_accounts.map(&:id),
currency: currency,
- period: Period.last_90_days
+ period: Period.last_90_days,
+ strict_currency_conversion: true
).balance_series.values
+ rescue Money::ConversionError => e
+ missing_exchange_rate_currencies << e.from_currency
+ []
rescue StandardError => e
# Degrade gracefully (chart drops to target-line-only) but surface
# the failure; silent fallbacks here masked real Builder bugs.
@@ -1309,17 +1384,6 @@ class Goal < ApplicationRecord
self.progress_basis = "contributions"
end
- def linked_accounts_must_match_goal_currency
- return if currency.blank?
-
- mismatched = goal_accounts.reject(&:marked_for_destruction?).reject do |sga|
- sga.account.nil? || sga.account.currency == currency
- end
- return if mismatched.empty?
-
- errors.add(:linked_accounts, :currency_mismatch)
- end
-
def linked_accounts_must_belong_to_family
return if family.nil?
diff --git a/app/models/goal/currency_converter.rb b/app/models/goal/currency_converter.rb
new file mode 100644
index 0000000000..83b06536c1
--- /dev/null
+++ b/app/models/goal/currency_converter.rb
@@ -0,0 +1,29 @@
+class Goal::CurrencyConverter
+ # Shared by goals prepared for one page. Cache missing rates too: an unavailable
+ # provider must not be called again for every balance, row and status pill.
+ def initialize
+ @rates = {}
+ end
+
+ def convert(money, to:, date: Date.current)
+ to = Money::Currency.new(to).iso_code
+ return Money.new(0, to) if money.zero?
+
+ money.exchange_to(to, date: date, custom_rate: rate_for(money.currency.iso_code, to, date))
+ end
+
+ private
+ def rate_for(from, to, date)
+ return 1.to_d if from == to
+
+ key = [ from, to, date ]
+ unless @rates.key?(key)
+ @rates[key] = ExchangeRate.find_or_fetch_rate(from: from, to: to, date: date)&.rate
+ end
+ rate = @rates[key]
+ unless rate&.positive?
+ raise Money::ConversionError.new(from_currency: from, to_currency: to, date: date)
+ end
+ rate
+ end
+end
diff --git a/app/models/goal_pledge.rb b/app/models/goal_pledge.rb
index 052e6c9d19..82160c2fe4 100644
--- a/app/models/goal_pledge.rb
+++ b/app/models/goal_pledge.rb
@@ -73,13 +73,16 @@ class GoalPledge < ApplicationRecord
latest = [ created_at.to_date + MATCH_DATE_TOLERANCE_DAYS.days, expires_at.to_date ].max
return false unless entry.date >= earliest && entry.date <= latest
- txn_amount = (is_valuation ? valuation_delta.to_d : entry.amount.to_d).abs
+ native_amount = (is_valuation ? valuation_delta.to_d : entry.amount.to_d).abs
+ txn_amount = goal.convert_money!(Money.new(native_amount, entry.currency.presence || account.currency), date: entry.date).amount
pledge_amount = amount.to_d
diff_abs = (txn_amount - pledge_amount).abs
return true if diff_abs <= MATCH_AMOUNT_TOLERANCE_ABSOLUTE
return true if pledge_amount.positive? && (diff_abs / pledge_amount) <= MATCH_AMOUNT_TOLERANCE_RATIO
+ false
+ rescue Money::ConversionError
false
end
diff --git a/app/models/insight/generators/maintained_goal_depleted_generator.rb b/app/models/insight/generators/maintained_goal_depleted_generator.rb
index 9584218ebf..e5cb398512 100644
--- a/app/models/insight/generators/maintained_goal_depleted_generator.rb
+++ b/app/models/insight/generators/maintained_goal_depleted_generator.rb
@@ -51,9 +51,12 @@ class Insight::Generators::MaintainedGoalDepletedGenerator < Insight::Generator
#
# Ordered by shortfall so a tight MAX_INSIGHTS spends itself on the reserves
# furthest from their floor, and stays stable between nightly runs.
+ #
+ # A reserve whose foreign balance has no exchange rate reads as short only
+ # because that balance is left out. The goal page says so; this feed cannot.
def depleted_reserves
Goal.prepared_for(family, scope: family.goals.where(kind: "maintained", state: "active"))
- .select { |goal| goal.status == :depleted }
+ .select { |goal| goal.status == :depleted && !goal.currency_conversion_incomplete? }
.sort_by { |goal| -goal.remaining_amount.to_d }
end
end
diff --git a/app/views/budgets/_available_cash.html.erb b/app/views/budgets/_available_cash.html.erb
index 92b23baa79..f5838381ed 100644
--- a/app/views/budgets/_available_cash.html.erb
+++ b/app/views/budgets/_available_cash.html.erb
@@ -42,4 +42,10 @@
</dd>
</div>
</dl>
+ <% if budget.missing_cash_currencies.any? %>
+ <div class="mt-3">
+ <%= render DS::Alert.new(variant: "warning",
+ message: t(".currency_warning", currencies: budget.missing_cash_currencies.to_a.to_sentence, currency: budget.currency)) %>
+ </div>
+ <% end %>
</div>
diff --git a/app/views/goal_pledges/new.html.erb b/app/views/goal_pledges/new.html.erb
index a7143a777d..f5099676a1 100644
--- a/app/views/goal_pledges/new.html.erb
+++ b/app/views/goal_pledges/new.html.erb
@@ -11,7 +11,7 @@
# off the pledge kind actually saved (default_pledge_kind), so a manual
# investment account — which pledges via transfer — shows the transfer
# helper, not the manual one.
- [ a.name, a.id, { data: { manual: (a.default_pledge_kind == "manual_save").to_s } } ]
+ [ goal_account_label(a, @goal), a.id, { data: { manual: (a.default_pledge_kind == "manual_save").to_s } } ]
end
%>
diff --git a/app/views/goals/_currency_warning.html.erb b/app/views/goals/_currency_warning.html.erb
new file mode 100644
index 0000000000..6e31f51db4
--- /dev/null
+++ b/app/views/goals/_currency_warning.html.erb
@@ -0,0 +1,13 @@
+<%# locals: (goal:) %>
+<% if goal.currency_conversion_incomplete? %>
+ <% missing = goal.missing_exchange_rate_currencies %>
+ <%= render DS::Alert.new(variant: "warning", title: t("goals.currency_warning.title")) do %>
+ <p><%= t("goals.currency_warning.body", count: missing.size, from: missing.to_a.to_sentence, to: goal.currency) %></p>
+ <%# Rates come from the exchange rate provider; only a self-hosted admin can change it. %>
+ <% if self_hosted? && Current.user&.admin? %>
+ <div class="mt-2">
+ <%= render DS::Link.new(text: t("goals.currency_warning.settings_link"), variant: :default, href: settings_hosting_path) %>
+ </div>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/goals/_form.html.erb b/app/views/goals/_form.html.erb
index ddf7ad77e7..e202601419 100644
--- a/app/views/goals/_form.html.erb
+++ b/app/views/goals/_form.html.erb
@@ -5,7 +5,7 @@
targets inside its own element. Scoped to the selector, dateFieldTargets
came back empty and picking "Reserve to maintain" never hid the date. %>
<div data-controller="goal-form goal-kind"
- data-goal-form-currency-value="<%= Current.family.primary_currency_code %>"
+ data-goal-form-currency-value="<%= goal.currency.presence || Current.family.primary_currency_code %>"
data-goal-form-require-account-value="<%= !goal.persisted? %>"
data-goal-form-suggested-with-date-value="<%= t("goals.form.suggested_with_date") %>"
data-goal-form-suggested-no-date-value="<%= t("goals.form.suggested_no_date") %>"
@@ -113,13 +113,17 @@
<span class="block text-sm font-medium text-primary"><%= t("goals.form.fields.funding_accounts") %></span>
<p class="text-xs text-secondary mt-0.5"><%= t("goals.form.fields.funding_accounts_hint") %></p>
<p class="text-xs text-subdued mt-0.5"><%= t("goals.form.fields.earmark_hint") %></p>
+ <% goal_currency = goal.currency.presence || Current.family.primary_currency_code %>
+ <% if (linkable_accounts.map(&:currency) | [ goal_currency ]).size > 1 %>
+ <p class="text-xs text-secondary mt-0.5"><%= t("goals.form.fields.currency_conversion_hint", currency: goal_currency) %></p>
+ <% end %>
</div>
<%# Its own controller, not goal-form: that one is already at 10 targets
against the 7 the project guidelines suggest, and this needs none of
its state. Three targets here. %>
<div class="bg-container-inset rounded-lg p-1"
data-controller="goal-earmark"
- data-goal-earmark-currency-value="<%= goal.currency.presence || Current.family.primary_currency_code %>"
+ data-goal-earmark-currency-value="<%= goal_currency %>"
<%# The APPLICATION locale, not the browser's. `Intl.NumberFormat`
with `undefined` lets the browser pick, so a French user on an
English-locale browser read separators and symbol placement that
@@ -130,7 +134,8 @@
data-goal-earmark-whole-balance-value="<%= t("goals.form.earmark.whole_balance") %>"
data-goal-earmark-whole-balance-alone-value="<%= t("goals.form.earmark.whole_balance_alone") %>"
data-goal-earmark-prorata-value="<%= t("goals.form.earmark.prorata") %>"
- data-goal-earmark-headroom-value="<%= t("goals.form.earmark.headroom") %>">
+ data-goal-earmark-headroom-value="<%= t("goals.form.earmark.headroom") %>"
+ data-goal-earmark-converted-value="<%= t("goals.form.earmark.converted") %>">
<% linked_allocation_by_account = goal.goal_accounts.index_by(&:account_id) %>
<% grouped = linkable_accounts.group_by { |a| a.subtype.to_s.presence || "other" } %>
<% grouped.each_with_index do |(subtype, accts), group_idx| %>
@@ -140,6 +145,8 @@
<% linked_ga = linked_allocation_by_account[account.id] %>
<div class="px-3 py-2.5 hover:bg-surface-hover <%= "border-t border-subdued" if idx > 0 %>"
data-balance="<%= account.balance.to_d %>"
+ data-currency="<%= account.currency %>"
+ data-rate="<%= earmark_conversion_rate(goal, account, goal_currency) %>"
data-earmarked-by-others="<%= earmarked_by_other_goals(account, pooled: pooled_allocations, current_goal: goal) %>"
data-whole-account-claimed="<%= whole_account_claimed_by_other_goals?(account, pooled: pooled_allocations, current_goal: goal) %>">
<div class="flex items-center gap-3">
diff --git a/app/views/goals/consume.html.erb b/app/views/goals/consume.html.erb
index 4f4da5bed3..daca1e5027 100644
--- a/app/views/goals/consume.html.erb
+++ b/app/views/goals/consume.html.erb
@@ -22,6 +22,9 @@
<p class="text-xs text-secondary privacy-sensitive">
<%= t(".amount_hint", saved: @goal.current_balance_money.format(precision: 0)) %>
</p>
+ <% if @consumption_accounts.any? { |account| account.currency != @goal.currency } %>
+ <p class="text-xs text-secondary"><%= t(".goal_currency_hint", currency: @goal.currency) %></p>
+ <% end %>
</div>
<%# Only asked when there is a choice to make. With one link the model
@@ -36,7 +39,7 @@
<%= render DS::Select.new(
form: f,
method: :account_id,
- items: @consumption_accounts.map { |account| { label: account.name, value: account.id } },
+ items: @consumption_accounts.map { |account| { label: goal_account_label(account, @goal), value: account.id } },
label: t(".account_label")
) %>
<% end %>
diff --git a/app/views/goals/show.html.erb b/app/views/goals/show.html.erb
index 8c170f51e5..100080c66d 100644
--- a/app/views/goals/show.html.erb
+++ b/app/views/goals/show.html.erb
@@ -131,6 +131,9 @@
<% end %>
<% end %>
+ <%# Above the ring: the headline figures are what a partial total misleads. %>
+ <%= render "goals/currency_warning", goal: @goal %>
+
<%# Top row: ring panel (status, no elevation) + projection chart card %>
<section class="grid grid-cols-1 lg:grid-cols-[320px_minmax(0,1fr)] gap-3">
<div class="rounded-xl p-5 flex flex-col items-center justify-center text-center">
diff --git a/app/views/plans/_goals_card.html.erb b/app/views/plans/_goals_card.html.erb
index 7530d14c5e..441728d451 100644
--- a/app/views/plans/_goals_card.html.erb
+++ b/app/views/plans/_goals_card.html.erb
@@ -115,6 +115,14 @@
<% end %>
</div>
+ <%# Every goal, not only the five listed: the saved total above covers them all. %>
+ <% affected = goals.select(&:currency_conversion_incomplete?) %>
+ <% if affected.any? %>
+ <div class="mt-4">
+ <%= render DS::Alert.new(variant: "warning", message: t(".currency_warning", count: affected.size,
+ currencies: affected.flat_map { |goal| goal.missing_exchange_rate_currencies.to_a }.uniq.to_sentence)) %>
+ </div>
+ <% end %>
<% end %>
<% if family_has_goals %>
diff --git a/config/locales/models/goal/ca.yml b/config/locales/models/goal/ca.yml
index 4646dbbb9c..7445066134 100644
--- a/config/locales/models/goal/ca.yml
+++ b/config/locales/models/goal/ca.yml
@@ -25,7 +25,6 @@ ca:
only_with_months_mode: Els mesos de despeses només s'apliquen quan l'objectiu es defineix d'aquesta manera.
linked_accounts:
must_be_fundable: Tots els comptes enllaçats han de ser comptes d'efectiu o d'inversió.
- currency_mismatch: Tots els comptes enllaçats han de tenir la mateixa moneda.
must_belong_to_family: Els comptes enllaçats han de pertànyer a la mateixa família que l'objectiu.
kind:
locked_while_released: Torna a obrir aquest objectiu abans de convertir-lo en una reserva.
diff --git a/config/locales/models/goal/de.yml b/config/locales/models/goal/de.yml
index 0d81b27534..80a37cf4b4 100644
--- a/config/locales/models/goal/de.yml
+++ b/config/locales/models/goal/de.yml
@@ -20,6 +20,5 @@ de:
currency:
locked_after_linked: Die Währung lässt sich nicht mehr ändern, sobald das Ziel mit Konten verknüpft ist.
linked_accounts:
- currency_mismatch: Alle verknüpften Konten müssen dieselbe Währung haben.
must_be_fundable: Alle verknüpften Konten müssen Bank- oder Investmentkonten sein.
must_belong_to_family: Verknüpfte Konten müssen zur selben Familie gehören wie das Ziel.
diff --git a/config/locales/models/goal/en.yml b/config/locales/models/goal/en.yml
index 6f10e80613..3b1797a097 100644
--- a/config/locales/models/goal/en.yml
+++ b/config/locales/models/goal/en.yml
@@ -16,6 +16,7 @@ en:
goal:
attributes:
base:
+ missing_exchange_rate: No exchange rate is available yet for one of this goal's accounts, so it can't be completed.
at_least_one_linked_account_required: Pick at least one account to fund this goal.
whole_account_conflict_on_restore: "Can't restore this goal: “%{account_name}” is now fully earmarked for “%{goal_name}”. Enter an amount on one of them first."
target_mode:
@@ -25,7 +26,6 @@ en:
only_with_months_mode: Months of expenses only apply when the target is set that way.
linked_accounts:
must_be_fundable: All linked accounts must be cash or investment accounts.
- currency_mismatch: All linked accounts must share the same currency.
must_belong_to_family: Linked accounts must belong to the same family as the goal.
kind:
locked_while_released: Reopen this goal before turning it into a reserve.
diff --git a/config/locales/models/goal/es.yml b/config/locales/models/goal/es.yml
index 52d5d37f48..8178cbd24e 100644
--- a/config/locales/models/goal/es.yml
+++ b/config/locales/models/goal/es.yml
@@ -19,7 +19,6 @@ es:
at_least_one_linked_account_required: Elige al menos una cuenta para financiar este objetivo.
linked_accounts:
must_be_fundable: Todas las cuentas vinculadas deben ser cuentas de efectivo o de inversión.
- currency_mismatch: Todas las cuentas vinculadas deben compartir la misma moneda.
must_belong_to_family: Las cuentas vinculadas deben pertenecer a la misma familia que el objetivo.
currency:
locked_after_linked: No se puede cambiar la moneda cuando el objetivo ya está vinculado a cuentas.
diff --git a/config/locales/models/goal/fr.yml b/config/locales/models/goal/fr.yml
index c6b547a522..65f7b94788 100644
--- a/config/locales/models/goal/fr.yml
+++ b/config/locales/models/goal/fr.yml
@@ -31,6 +31,5 @@ fr:
blank: Indiquez combien de mois de dépenses cette réserve doit couvrir.
only_with_months_mode: Les mois de dépenses ne s'appliquent que si la cible est exprimée ainsi.
linked_accounts:
- currency_mismatch: Tous les comptes liés doivent partager la même devise.
must_be_fundable: Tous les comptes liés doivent être des comptes de trésorerie ou d'investissement.
must_belong_to_family: Les comptes liés doivent appartenir au même foyer que l'objectif.
diff --git a/config/locales/models/goal/it.yml b/config/locales/models/goal/it.yml
index a7e1d01ab3..8a7c144def 100644
--- a/config/locales/models/goal/it.yml
+++ b/config/locales/models/goal/it.yml
@@ -19,7 +19,6 @@ it:
at_least_one_linked_account_required: Scegli almeno un conto per finanziare questo obiettivo.
linked_accounts:
must_be_fundable: Tutti i conti collegati devono essere conti correnti o conti di investimento.
- currency_mismatch: Tutti i conti collegati devono avere la stessa valuta.
must_belong_to_family: I conti collegati devono appartenere alla stessa famiglia dell'obiettivo.
currency:
locked_after_linked: Impossibile cambiare la valuta dopo che l'obiettivo è stato collegato ai conti.
diff --git a/config/locales/models/goal/pl.yml b/config/locales/models/goal/pl.yml
index 7d1bdd5859..b7c064c3ce 100644
--- a/config/locales/models/goal/pl.yml
+++ b/config/locales/models/goal/pl.yml
@@ -29,7 +29,6 @@ pl:
locked_while_released: Otwórz ponownie ten cel, zanim zmienisz go w
rezerwę.
linked_accounts:
- currency_mismatch: Wszystkie połączone konta muszą mieć tę samą walutę.
must_be_fundable: Wszystkie połączone konta muszą być kontami gotówkowymi
lub inwestycyjnymi.
must_belong_to_family: Połączone konta muszą należeć do tej samej rodziny
diff --git a/config/locales/models/goal/pt-PT.yml b/config/locales/models/goal/pt-PT.yml
index 7ebf435baf..ea420c8bb1 100644
--- a/config/locales/models/goal/pt-PT.yml
+++ b/config/locales/models/goal/pt-PT.yml
@@ -25,7 +25,6 @@ pt-PT:
only_with_months_mode: Os meses de despesas só se aplicam quando o objetivo é definido dessa forma.
linked_accounts:
must_be_fundable: Todas as contas associadas têm de ser contas de dinheiro ou de investimento.
- currency_mismatch: Todas as contas associadas têm de partilhar a mesma moeda.
must_belong_to_family: As contas associadas têm de pertencer à mesma família que o objetivo.
kind:
locked_while_released: Reabra este objetivo antes de o transformar numa reserva.
diff --git a/config/locales/models/goal/ru.yml b/config/locales/models/goal/ru.yml
index 964ba6bce0..95035e28fe 100644
--- a/config/locales/models/goal/ru.yml
+++ b/config/locales/models/goal/ru.yml
@@ -22,7 +22,6 @@ ru:
currency:
locked_after_linked: Нельзя изменить валюту после привязки счетов к цели.
linked_accounts:
- currency_mismatch: Все связанные счета должны быть в одной валюте.
must_be_fundable: Все связанные счета должны быть денежными или
инвестиционными.
must_belong_to_family: Связанные счета должны принадлежать той же семье/группе,
diff --git a/config/locales/models/goal/tr.yml b/config/locales/models/goal/tr.yml
index 282ae5c72e..611b6a1226 100644
--- a/config/locales/models/goal/tr.yml
+++ b/config/locales/models/goal/tr.yml
@@ -23,7 +23,6 @@ tr:
locked_after_linked: Hedef hesaplara bağlandıktan sonra para birimi
değiştirilemez.
linked_accounts:
- currency_mismatch: Bağlı tüm hesaplar aynı para birimini kullanmalıdır.
must_be_fundable: Bağlı tüm hesaplar nakit veya yatırım hesabı olmalıdır.
must_belong_to_family: Bağlı hesaplar, hedefle aynı aileye ait olmalıdır.
target_mode:
diff --git a/config/locales/models/goal/uk.yml b/config/locales/models/goal/uk.yml
index 4e153e14e2..b09602c7da 100644
--- a/config/locales/models/goal/uk.yml
+++ b/config/locales/models/goal/uk.yml
@@ -20,7 +20,6 @@ uk:
whole_account_conflict_on_restore: 'Неможливо відновити цю ціль: рахунок «%{account_name}» тепер повністю виділено для цілі «%{goal_name}». Спершу вкажіть суму для однієї з них.'
linked_accounts:
must_be_fundable: "Всі прив'язані рахунки мають бути грошовими або інвестиційними."
- currency_mismatch: "Всі прив'язані рахунки повинні мати однакову валюту."
must_belong_to_family: "Прив'язані рахунки повинні належати до тієї ж сім'ї, що й ціль."
currency:
locked_after_linked: "Неможливо змінити валюту після прив'язки цілі до рахунків."
diff --git a/config/locales/models/goal/zh-CN.yml b/config/locales/models/goal/zh-CN.yml
index a49e8fddec..3852b143c2 100644
--- a/config/locales/models/goal/zh-CN.yml
+++ b/config/locales/models/goal/zh-CN.yml
@@ -19,7 +19,6 @@ zh-CN:
at_least_one_linked_account_required: 请至少选择一个账户为此目标提供资金。
linked_accounts:
must_be_fundable: 所有关联账户必须是现金或投资账户。
- currency_mismatch: 所有关联账户必须使用同一货币。
must_belong_to_family: 关联账户必须属于与目标相同的家庭。
currency:
locked_after_linked: 目标关联账户后不能更改货币。
diff --git a/config/locales/models/goal/zh-TW.yml b/config/locales/models/goal/zh-TW.yml
index ac7305dd58..2bb6ae550f 100644
--- a/config/locales/models/goal/zh-TW.yml
+++ b/config/locales/models/goal/zh-TW.yml
@@ -19,7 +19,6 @@ zh-TW:
at_least_one_linked_account_required: 請至少選擇一個帳戶來支應這個目標。
linked_accounts:
must_be_fundable: 所有已連結的帳戶都必須是現金或投資帳戶。
- currency_mismatch: 所有已連結的帳戶必須使用相同的幣別。
must_belong_to_family: 已連結的帳戶必須和這個目標屬於同一個家庭。
currency:
locked_after_linked: 目標連結帳戶之後就不能再更改幣別了。
diff --git a/config/locales/views/budgets/en.yml b/config/locales/views/budgets/en.yml
index 3fddcce35e..ff397d2a7e 100644
--- a/config/locales/views/budgets/en.yml
+++ b/config/locales/views/budgets/en.yml
@@ -45,6 +45,7 @@ en:
earmarked: Already earmarked for goals
free: Really free
goals_link: View goals
+ currency_warning: "%{currencies} balances aren't included because no exchange rate to %{currency} is available yet."
show:
categories:
amount: Amount
diff --git a/config/locales/views/goals/en.yml b/config/locales/views/goals/en.yml
index 3b917e6ecc..8ac2e6a55e 100644
--- a/config/locales/views/goals/en.yml
+++ b/config/locales/views/goals/en.yml
@@ -1,6 +1,12 @@
---
en:
goals:
+ currency_warning:
+ title: Some balances aren't counted
+ body:
+ one: "No %{from} → %{to} exchange rate is available yet, so %{from} balances are left out of this total."
+ other: "No exchange rates from %{from} to %{to} are available yet, so those balances are left out of this total."
+ settings_link: Exchange rate provider settings
color_picker:
trigger_label: Choose color and icon
color_heading: Color
@@ -102,10 +108,12 @@ en:
amount_hint: "%{saved} is currently backing this goal."
account_label: From which account?
earmark_note: The amount you record stops being reserved for this goal, so your other goals on that account get their share back.
+ goal_currency_hint: "Enter the amount in %{currency}. For an account in another currency, it's converted at today's rate before it comes off that account's earmark."
cancel: Cancel
submit: Record it
success: "%{amount} recorded as used."
errors:
+ missing_exchange_rate: No exchange rate is available yet for this account's currency, so this spending can't be recorded.
non_positive: Enter an amount greater than zero.
maintained: A reserve is drawn down and refilled, not spent — its shortfall already shows on the goal.
exceeds_target: That is more than this goal ever set out to save.
@@ -139,6 +147,8 @@ en:
funding_accounts_heading: Funding accounts
funding_accounts:
earmarked_of: "%{earmarked} earmarked of %{balance}"
+ converted: "≈ %{amount}"
+ rate_unavailable: No exchange rate yet, so this account isn't counted.
empty:
heading: No funding accounts linked yet
body: Edit the goal to link the depository accounts you save into.
@@ -262,6 +272,7 @@ en:
add_account: Add an account
goal_card:
including_used: "Including %{amount} already used"
+ partial_total: Some balances aren't counted (no exchange rate yet)
no_accounts: No linked accounts
n_accounts: "%{first} +%{count}"
left: left
@@ -314,6 +325,7 @@ en:
accounts_required: Pick at least one funding account.
earmark:
headroom: "{left} left to earmark on this account."
+ converted: "This earmark ≈ {amount}."
prorata: "Your goals on this account come to {total} for a balance of {balance} — they will progress pro rata."
whole_balance: This account will fund whatever is left after the other earmarks.
whole_balance_alone: "This goal will use this account's whole balance."
@@ -336,6 +348,7 @@ en:
whole_balance: "Blank: whole balance"
earmark_for: Earmark amount for %{account}
earmark_hint: Leave an amount blank to dedicate that account's whole balance.
+ currency_conversion_hint: "Accounts can use different currencies. Totals are converted to %{currency}; account earmarks stay in each account's currency."
subtypes:
checking: Checking
savings: Savings
diff --git a/config/locales/views/plans/en.yml b/config/locales/views/plans/en.yml
index 563ccd93d2..bcab4a07f1 100644
--- a/config/locales/views/plans/en.yml
+++ b/config/locales/views/plans/en.yml
@@ -18,6 +18,9 @@ en:
set_up: Set up this month's budget
goals_card:
title: Your goals
+ currency_warning:
+ one: "1 goal leaves out %{currencies} balances (no exchange rate yet)."
+ other: "%{count} goals leave out %{currencies} balances (no exchange rate yet)."
new_goal: New goal
active_count:
one: 1 active
diff --git a/docs/llm-guides/goals.md b/docs/llm-guides/goals.md
index ccd6966c3b..48ed075e0d 100644
--- a/docs/llm-guides/goals.md
+++ b/docs/llm-guides/goals.md
@@ -92,18 +92,46 @@ Locales:
A goal records a name, target amount, optional target date, color, optional
icon, optional notes, currency, and an AASM `state` (`active` / `paused` /
-`completed` / `archived`). It links to depository accounts via the join
+`completed` / `archived`). It links cash and investment accounts via the join
table `goal_accounts`.
-The goal's *progress* is the live balance of every linked account. There
-is no ledger of contributions. `Goal#current_balance` reads
-`linked_accounts.sum(:balance)` at request time.
+The goal's *progress* is its allocated share of linked accounts, converted to
+its currency at request time. `Goal#current_balance` preserves native account
+allocations and shared-pool limits before conversion. Investment-backed goals
+default to contribution progress, excluding cumulative market gains from their
+backing; `market_value_money` separately shows the current market value.
A `GoalPledge` is an intent: amount, account, kind, status, expires_at.
The status enum is `open` / `matched` / `cancelled` / `expired`. The kind
enum is `transfer` / `manual_save`; kind is decided at create time from
the selected account's connection state.
+## Currencies and account allocations
+
+A goal can link cash and investment accounts in different currencies. New goals
+use the family's display currency, matching the target field; an existing goal's
+currency remains locked. Target, progress, consumed amount and pledges use goal
+currency. Each `GoalAccount#allocated_amount` remains in its account's currency.
+Shared-pool allocation and pro-rata scaling happen before conversion, so goals
+with different currencies cannot double-count the same account.
+
+`Goal::CurrencyConverter` uses `ExchangeRate.find_or_fetch_rate` through `Money`,
+with a request-scoped rate cache shared by prepared goals. Current backing, pace
+and funding inflows use today's rate (pace is an estimate, and a rate per entry
+date would reach the provider on every render); consumption and pledge matches
+use the entry date. Budget
+cash reservations convert native earmarks directly to budget currency rather
+than going through an intermediate goal currency. Consumption converts the
+entered goal-currency amount back into native units before releasing an earmark.
+
+Unavailable rates never become 1:1 conversions. Read surfaces show the known
+subtotal and a missing-rate warning (`Goal#currency_conversion_incomplete?`
+runs the backing, pace and market-value conversions first, so the warning can
+render above them); writes that require conversion are refused,
+and pledge matches wait for a rate. Goal history charts opt into strict currency
+conversion and omit the saved line when it cannot be converted. Existing stored
+balances and transactions are unchanged; no migration is required.
+
## Status semantics
`Goal#status` is computed at render time:
@@ -277,10 +305,9 @@ calls it. Things to watch:
## Gotchas
-The same depository account can fund two goals. Both will read the
-full balance and double-count progress toward their targets. This is a
-known limitation; an allocation primitive that splits the balance
-proportionally (or by explicit user weights) would be the way out.
+Accounts can fund multiple goals using fixed native-currency allocations.
+Whole-account links are exclusive while their goal remains active or paused;
+completed and archived goals release their reservation.
`Goal#pace` includes paychecks, rent, debit-card spend — anything on
the linked account. For a goal linked to primary checking, the metric
diff --git a/test/controllers/goal_pledges_controller_test.rb b/test/controllers/goal_pledges_controller_test.rb
index 9395cad323..b9bf791eae 100644
--- a/test/controllers/goal_pledges_controller_test.rb
+++ b/test/controllers/goal_pledges_controller_test.rb
@@ -25,6 +25,17 @@ class GoalPledgesControllerTest < ActionDispatch::IntegrationTest
assert_response :success
end
+ test "new labels a foreign-currency account with its currency" do
+ eur = Account.create!(family: @user.family, accountable: Depository.new,
+ name: "Euro Savings", currency: "EUR", balance: 1_000)
+ @goal.goal_accounts.create!(account: eur, allocated_amount: 500)
+
+ get new_goal_pledge_url(@goal), headers: { "Turbo-Frame" => "modal" }
+
+ assert_select "option", text: "Euro Savings · EUR"
+ assert_select "option", text: @account.name
+ end
+
test "new redirects to the goal show page on a non-frame GET" do
get new_goal_pledge_url(@goal)
assert_redirected_to goal_path(@goal)
diff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rb
index a624644092..4fb8ca2e85 100644
--- a/test/controllers/goals_controller_test.rb
+++ b/test/controllers/goals_controller_test.rb
@@ -149,6 +149,20 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest
assert_select "label[for=amount]", text: /#{I18n.t("goals.consume.amount_label")}/
end
+ # The amount is in goal currency even when it comes off a euro earmark, so
+ # the dialog says which currency it wants and which account holds which.
+ test "the consumption dialog names a foreign account's currency" do
+ eur = Account.create!(family: @user.family, accountable: Depository.new,
+ name: "Euro Savings", currency: "EUR", balance: 1_000)
+ @goal.goal_accounts.create!(account: eur, allocated_amount: 500)
+
+ get consume_goal_url(@goal)
+
+ assert_response :success
+ assert_includes response.body, "Euro Savings · EUR"
+ assert_select "p", text: I18n.t("goals.consume.goal_currency_hint", currency: "USD")
+ end
+
# Both figures in the dialog blur under privacy mode, as they do on the goal
# page. The amount also stays clickable: it is the one field the reader fills.
test "the consumption dialog blurs its figures under privacy mode and the amount stays editable" do
@@ -256,22 +270,70 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest
assert_not_empty @goal.reload.goal_accounts
end
- test "update rejects a cross-currency account attachment" do
- # Regression: sync_linked_accounts! used to call goal_accounts.create!
- # directly, bypassing Goal#linked_accounts_must_match_goal_currency.
+ test "update accepts a foreign-currency account and converts its backing" do
eur_account = Account.create!(
- family: @goal.family,
- accountable: Depository.new,
- name: "EUR Checking",
- currency: "EUR",
- balance: 100
+ family: @goal.family, accountable: Depository.new,
+ name: "EUR Checking", currency: "EUR", balance: 100
)
- before_ids = @goal.goal_accounts.pluck(:account_id).sort
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.current, rate: 1.2)
patch goal_url(@goal), params: { goal: { account_ids: [ eur_account.id ] } }
- assert_response :unprocessable_entity
- assert_equal before_ids, @goal.reload.goal_accounts.pluck(:account_id).sort
+ assert_redirected_to goal_path(@goal)
+ assert_equal [ eur_account.id ], @goal.reload.goal_accounts.pluck(:account_id)
+ assert_equal "USD", @goal.currency
+ assert_equal 120, Goal.find(@goal.id).current_balance
+ end
+
+ test "create with mixed currencies uses the currency shown for the target" do
+ usd = unclaimed_account("USD pot")
+ eur = Account.create!(family: @user.family, accountable: Depository.new,
+ name: "EUR pot", currency: "EUR", balance: 100)
+ post goals_url, params: { goal: { name: "Mixed", target_amount: 1_000, account_ids: [ eur.id, usd.id ] } }
+
+ goal = Goal.order(created_at: :desc).first
+ assert_redirected_to goal_path(goal)
+ assert_equal @user.family.primary_currency_code, goal.currency
+ assert_equal [ eur.id, usd.id ].sort, goal.linked_accounts.pluck(:id).sort
+ end
+
+ test "show and index disclose an unavailable account conversion" do
+ eur = Account.create!(family: @user.family, accountable: Depository.new,
+ name: "EUR reserve", currency: "EUR", balance: 100)
+ @goal.goal_accounts.build(account: eur)
+ @goal.save!
+ ExchangeRate.stubs(:provider).returns(nil)
+
+ warning = I18n.t("goals.currency_warning.body", count: 1, from: "EUR", to: @goal.currency)
+
+ get goal_url(@goal)
+ assert_response :success
+ assert_select "p", text: I18n.t("goals.show.funding_accounts.rate_unavailable")
+ assert_includes response.body, warning
+ # Above the headline figures, not below the funding breakdown.
+ assert_operator response.body.index(warning), :<, response.body.index(I18n.t("goals.show.funding_accounts_heading"))
+
+ get goals_url
+ assert_response :success
+ assert_select "p", text: I18n.t("goals.goal_card.partial_total")
+ end
+
+ test "detected foreign spending is converted on its date and releases native units" do
+ eur = Account.create!(family: @user.family, accountable: Depository.new,
+ name: "EUR spending", currency: "EUR", balance: 1_000)
+ @goal.goal_accounts.build(account: eur, allocated_amount: 500)
+ @goal.save!
+ date = 20.days.ago.to_date
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: date, rate: 2)
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.current, rate: 3)
+ entry = eur.entries.create!(name: "Travel", date: date, amount: 100, currency: "EUR", entryable: Transaction.new)
+
+ post consume_goal_url(@goal), params: { transaction_id: entry.entryable_id }
+
+ assert_redirected_to goal_path(@goal)
+ assert_equal 200, @goal.reload.consumed_amount
+ assert_equal 400, @goal.goal_accounts.find_by!(account: eur).allocated_amount
+ assert_equal @goal.id, entry.entryable.reload.extra.dig("goal", "consumed_goal_id")
end
test "pause/resume/complete/archive/unarchive flow" do
diff --git a/test/controllers/plans_controller_test.rb b/test/controllers/plans_controller_test.rb
index cfb1bf7fc9..6c098dacb2 100644
--- a/test/controllers/plans_controller_test.rb
+++ b/test/controllers/plans_controller_test.rb
@@ -37,6 +37,22 @@ class PlansControllerTest < ActionDispatch::IntegrationTest
"the depleted reserve's bar stayed neutral"
end
+ test "goals missing an exchange rate share one warning line" do
+ 2.times do |i|
+ account = @user.family.accounts.create!(name: "Euro reserve #{i}", accountable: Depository.new,
+ currency: "EUR", balance: 100)
+ @user.family.goals.create!(name: "Trip #{i}", target_amount: 1_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: account)
+ end
+ end
+ ExchangeRate.stubs(:provider).returns(nil)
+
+ get plan_url
+
+ assert_response :success
+ assert_equal 1, response.body.scan(I18n.t("plans.goals_card.currency_warning", count: 2, currencies: "EUR")).size
+ end
+
test "redirects users without preview access to budgets" do
@user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => false))
diff --git a/test/models/assistant/function/create_goal_test.rb b/test/models/assistant/function/create_goal_test.rb
index 2f999a8d6a..c7012b3cbf 100644
--- a/test/models/assistant/function/create_goal_test.rb
+++ b/test/models/assistant/function/create_goal_test.rb
@@ -70,15 +70,17 @@ class Assistant::Function::CreateGoalTest < ActiveSupport::TestCase
assert_includes result[:unknown_names], "Nonexistent Account"
end
- test "soft error when currencies differ across linked accounts" do
- eur = Account.create!(family: @family, accountable: Depository.new, name: "EUR Account", currency: "EUR", balance: 100)
+ test "mixed-currency accounts fund one goal in the family currency" do
+ usd = Account.create!(family: @family, accountable: Depository.new, name: "USD Pot", currency: "USD", balance: 100)
+ eur = Account.create!(family: @family, accountable: Depository.new, name: "EUR Pot", currency: "EUR", balance: 100)
result = @fn.call(
"name" => "Mixed",
"target_amount" => 100,
- "linked_account_names" => [ @depository.name, eur.name ]
+ "linked_account_names" => [ usd.name, eur.name ]
)
- assert_equal false, result[:success]
- assert_equal "currency_mismatch", result[:error]
+ assert result[:success]
+ assert_equal @family.primary_currency_code, result[:currency]
+ assert_equal [ usd.id, eur.id ].sort, Goal.find(result[:goal_id]).linked_accounts.pluck(:id).sort
end
test "scopes to the user's family" do
diff --git a/test/models/balance/chart_series_builder_test.rb b/test/models/balance/chart_series_builder_test.rb
index 5ae56071f5..a78aa117db 100644
--- a/test/models/balance/chart_series_builder_test.rb
+++ b/test/models/balance/chart_series_builder_test.rb
@@ -64,6 +64,61 @@ class Balance::ChartSeriesBuilderTest < ActiveSupport::TestCase
assert_equal expected, builder.balance_series.map { |v| v.value.amount }
end
+ test "strict currency conversion refuses a missing rate instead of assuming one" do
+ account = accounts(:depository)
+ account.balances.destroy_all
+ create_balance(account: account, date: Date.current, balance: 100)
+ builder = Balance::ChartSeriesBuilder.new(
+ account_ids: [ account.id ], currency: "EUR",
+ period: Period.custom(start_date: Date.current, end_date: Date.current),
+ strict_currency_conversion: true
+ )
+
+ error = assert_raises(Money::ConversionError) { builder.balance_series }
+ assert_equal "USD", error.from_currency
+ assert_equal "EUR", error.to_currency
+ end
+
+ test "strict currency conversion keeps history when a foreign balance is zero without a usable rate" do
+ foreign = accounts(:depository)
+ native = accounts(:credit_card)
+ foreign.balances.destroy_all
+ native.balances.destroy_all
+ native.update!(currency: "EUR")
+ create_balance(account: foreign, date: Date.current, balance: 0)
+ create_balance(account: native, date: Date.current, balance: 50)
+
+ # Zero and negative rates are rejected at write time, so absent is the only unusable rate.
+ ExchangeRate.where(from_currency: "USD", to_currency: "EUR").delete_all
+ builder = Balance::ChartSeriesBuilder.new(
+ account_ids: [ foreign.id, native.id ], currency: "EUR",
+ period: Period.custom(start_date: Date.current, end_date: Date.current),
+ strict_currency_conversion: true
+ )
+
+ series = builder.balance_series
+ assert_equal 1, series.size
+ assert_equal(-50, series.first.value.amount)
+ assert_equal(-50, series.first.trend.previous.amount)
+ end
+
+ test "strict currency conversion uses historical rates without changing native balances" do
+ account = accounts(:depository)
+ account.balances.destroy_all
+ create_balance(account: account, date: 1.day.ago.to_date, balance: 100)
+ create_balance(account: account, date: Date.current, balance: 100)
+ ExchangeRate.create!(date: 1.day.ago.to_date, from_currency: "USD", to_currency: "EUR", rate: 2)
+ ExchangeRate.create!(date: Date.current, from_currency: "USD", to_currency: "EUR", rate: 3)
+ builder = Balance::ChartSeriesBuilder.new(
+ account_ids: [ account.id ], currency: "EUR",
+ period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),
+ strict_currency_conversion: true
+ )
+
+ assert_equal [ 200, 300 ], builder.balance_series.map { |value| value.value.amount }
+ assert_equal [ 100, 100 ], account.balances.order(:date).pluck(:end_balance)
+ end
+
test "combines asset and liability accounts properly" do
asset_account = accounts(:depository)
liability_account = accounts(:credit_card)
diff --git a/test/models/budget_available_cash_test.rb b/test/models/budget_available_cash_test.rb
index a37a2e8cb2..8423a8958d 100644
--- a/test/models/budget_available_cash_test.rb
+++ b/test/models/budget_available_cash_test.rb
@@ -118,17 +118,18 @@ class BudgetAvailableCashTest < ActiveSupport::TestCase
assert_equal 1_200, @budget.available_cash
end
- # A missing rate leaves the amount as it stands rather than raising: a panel
- # wrong by the spread beats the whole budget page failing to render.
- test "a missing rate leaves the figure standing rather than raising" do
- Account.create!(
- family: @family, accountable: Depository.new,
- name: "EUR pot", currency: "EUR", balance: 1_000
- )
-
+ test "missing rates cannot turn a reserved foreign balance into free cash" do
+ account = Account.create!(family: @family, accountable: Depository.new,
+ name: "EUR pot", currency: "EUR", balance: 1_000)
+ @family.goals.create!(name: "Mixed", target_amount: 1_000, currency: "USD") do |goal|
+ goal.goal_accounts.build(account: account)
+ end
ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)
- assert_equal 1_000, @budget.available_cash
+ assert_equal 0, @budget.available_cash
+ assert_equal 0, @budget.earmarked_for_goals
+ assert_equal 0, @budget.free_cash
+ assert_equal [ "EUR" ], @budget.missing_cash_currencies.to_a
end
private
diff --git a/test/models/goal/currency_conversion_test.rb b/test/models/goal/currency_conversion_test.rb
new file mode 100644
index 0000000000..e2366654e5
--- /dev/null
+++ b/test/models/goal/currency_conversion_test.rb
@@ -0,0 +1,253 @@
+require "test_helper"
+
+class Goal::CurrencyConversionTest < ActiveSupport::TestCase
+ include BalanceTestHelper
+ setup do
+ @family = families(:empty)
+ ExchangeRate.stubs(:provider).returns(nil)
+ end
+
+ test "mixed balances and fixed earmarks are converted after native allocation" do
+ usd = cash("USD", 500)
+ eur = cash("EUR", 1_000)
+ rate("EUR", "USD", 1.2)
+ goal = goal_on("USD", [ [ usd, nil ], [ eur, 400 ] ])
+
+ assert_equal 980, goal.current_balance
+ assert_equal 400, goal.account_native_backing(eur).amount
+ assert_equal 480, goal.account_backing(eur).amount
+ assert_equal "USD", goal.account_backing(eur).currency.iso_code
+ assert_equal 980, goal.market_value_money.amount
+ assert_equal 480, goal.backing_within([ eur.id ])
+ assert_equal 400, goal.backing_within([ eur.id ], currency: "EUR")
+ end
+
+ test "goals in different currencies share native earmarks without double counting" do
+ eur = cash("EUR", 1_000)
+ rate("EUR", "USD", 1.2)
+ first = goal_on("USD", [ [ eur, 800 ] ])
+ second = goal_on("EUR", [ [ eur, 800 ] ])
+
+ assert_equal 600, first.current_balance
+ assert_equal 500, second.current_balance
+ assert_equal 1_000, first.account_native_backing(eur).amount + second.account_native_backing(eur).amount
+ end
+
+ test "whole-account exclusivity applies across goal currencies" do
+ eur = cash("EUR", 100)
+ goal_on("USD", [ [ eur, nil ] ])
+ other = @family.goals.new(name: "Other", target_amount: 1_000, currency: "EUR")
+ other.goal_accounts.build(account: eur)
+
+ assert_not other.valid?
+ assert other.errors.any?
+ end
+
+ test "missing rates exclude the unknown amount and report an incomplete total" do
+ goal = goal_on("USD", [ [ cash("USD", 200), nil ], [ cash("EUR", 900), nil ] ])
+ ExchangeRate.expects(:find_or_fetch_rate).with(from: "EUR", to: "USD", date: Date.current).once.returns(nil)
+
+ assert_equal 200, goal.current_balance
+ assert goal.currency_conversion_incomplete?
+ assert_equal [ "EUR" ], goal.missing_exchange_rate_currencies.to_a
+ assert_equal 200, goal.market_value_money.amount
+ assert_equal 1, DebugLogEntry.where(category: "goal_currency_conversion").count
+ end
+
+ test "a missing rate is logged once a day, not on every page view" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ eur = cash("EUR", 900)
+ goal_on("USD", [ [ eur, 400 ] ])
+ goal_on("USD", [ [ eur, 400 ] ])
+
+ 2.times { Goal.prepared_for(@family).each(&:currency_conversion_incomplete?) }
+
+ assert_equal 1, DebugLogEntry.where(category: "goal_currency_conversion").count
+ assert Goal.prepared_for(@family).all?(&:currency_conversion_incomplete?), "the warning must not depend on the log"
+ end
+
+ test "zero foreign balances do not need a rate" do
+ goal = goal_on("USD", [ [ cash("EUR", 0), nil ] ])
+ ExchangeRate.expects(:find_or_fetch_rate).never
+
+ assert_equal 0, goal.current_balance
+ assert_not goal.currency_conversion_incomplete?
+ end
+
+ test "pace converts the 90-day net at today's rate" do
+ eur = cash("EUR", 1_000)
+ goal = goal_on("USD", [ [ eur, nil ] ])
+ past = 20.days.ago.to_date
+ rate("EUR", "USD", 1.1, date: past)
+ rate("EUR", "USD", 1.5)
+ eur.entries.create!(name: "Deposit", date: past, amount: -300, currency: "EUR", entryable: Transaction.new)
+ eur.entries.create!(name: "Pending", date: past, amount: -900, currency: "EUR",
+ entryable: Transaction.new(extra: { plaid: { pending: true } }))
+
+ assert_equal 150, goal.pace
+ assert_equal 1_500, goal.current_balance
+ end
+
+ test "the incomplete-conversion check covers pace before it is rendered" do
+ eur = cash("EUR", 0)
+ goal = goal_on("USD", [ [ eur, nil ] ])
+ eur.entries.create!(name: "Deposit", date: 5.days.ago.to_date, amount: -300, currency: "EUR", entryable: Transaction.new)
+
+ assert Goal.find(goal.id).currency_conversion_incomplete?
+ end
+
+ test "investment contributions are converted after excluding market gains" do
+ eur = @family.accounts.create!(name: "EUR investments", accountable: Investment.new, currency: "EUR", balance: 1_000)
+ goal = goal_on("USD", [ [ eur, nil ] ])
+ goal.market_flows = { eur.id => 200 }
+ rate("EUR", "USD", 1.2)
+
+ assert goal.contributions_basis?
+ assert_equal 960, goal.current_balance
+ assert_equal 1_200, goal.market_value_money.amount
+ end
+
+ test "consumption releases a native earmark and credits goal-currency progress" do
+ eur = cash("EUR", 1_000)
+ goal = goal_on("USD", [ [ eur, 500 ] ])
+ rate("EUR", "USD", 2)
+
+ goal.consume!(200, account: eur)
+
+ assert_equal 400, goal.goal_accounts.first.reload.allocated_amount
+ assert_equal 200, goal.consumed_amount
+ assert_equal 800, goal.current_balance
+ assert_equal 1_000, goal.progress_amount
+ assert_equal 1_000, eur.reload.balance
+ end
+
+ test "whole-account consumption caps the remaining earmark in native units" do
+ eur = cash("EUR", 1_000)
+ goal = goal_on("USD", [ [ eur, nil ] ], target: 2_000)
+ rate("EUR", "USD", 2)
+
+ goal.consume!(200, account: eur)
+
+ assert_equal 900, goal.goal_accounts.first.reload.allocated_amount
+ assert_equal 2_000, goal.progress_amount
+ end
+
+ test "missing consumption rates cannot change progress or earmarks" do
+ eur = cash("EUR", 1_000)
+ goal = goal_on("USD", [ [ eur, 500 ] ])
+
+ error = assert_raises(Goal::ConsumptionRefused) { goal.consume!(100, account: eur) }
+
+ assert_equal :missing_exchange_rate, error.reason
+ assert_equal 0, goal.reload.consumed_amount
+ assert_equal 500, goal.goal_accounts.first.allocated_amount
+ end
+
+ test "pledges match a foreign deposit using the entry date exchange rate" do
+ eur = cash("EUR", 100)
+ goal = goal_on("USD", [ [ eur, nil ] ])
+ pledge = goal.goal_pledges.create!(account: eur, amount: 120, kind: "transfer")
+ rate("EUR", "USD", 1.2)
+ entry = eur.entries.create!(name: "Deposit", date: Date.current, amount: -100, currency: "EUR", entryable: Transaction.new)
+
+ assert pledge.matches?(entry)
+ entry.amount = -120
+ assert_not pledge.matches?(entry), "120 EUR must not be matched as 120 USD"
+ end
+
+ test "missing pledge rates do not produce false matches" do
+ eur = cash("EUR", 100)
+ goal = goal_on("USD", [ [ eur, nil ] ])
+ pledge = goal.goal_pledges.create!(account: eur, amount: 100, kind: "transfer")
+ entry = eur.entries.create!(name: "Deposit", date: Date.current, amount: -100, currency: "EUR", entryable: Transaction.new)
+
+ assert_not pledge.matches?(entry)
+ assert pledge.status_open?
+ end
+
+ test "budget cash reservations convert directly into budget currency" do
+ eur = cash("EUR", 1_000)
+ usd = cash("USD", 500)
+ goal_on("GBP", [ [ eur, 400 ], [ usd, 200 ] ])
+ rate("EUR", "USD", 1.2)
+ budget = Budget.find_or_bootstrap(@family, start_date: Date.current)
+
+ assert_equal 1_700, budget.available_cash
+ assert_equal 680, budget.earmarked_for_goals
+ assert_equal 1_020, budget.free_cash
+ end
+
+ test "converted projection history meets the allocated current balance" do
+ usd = cash("USD", 500)
+ eur = cash("EUR", 1_000)
+ rate("EUR", "USD", 1.2)
+ goal = goal_on("USD", [ [ usd, nil ], [ eur, 400 ] ])
+ create_balance(account: usd, date: Date.current, balance: 500)
+ create_balance(account: eur, date: Date.current, balance: 1_000)
+
+ assert_in_delta 980, goal.projection_payload[:saved_series].last[:value], 0.01
+ end
+
+ test "funding rows preserve native values while converting inflows at today's rate" do
+ eur = cash("EUR", 1_000)
+ goal = goal_on("USD", [ [ eur, 400 ] ])
+ past = 20.days.ago.to_date
+ rate("EUR", "USD", 1.1, date: past)
+ rate("EUR", "USD", 1.2)
+ eur.entries.create!(name: "Deposit", date: past, amount: -100, currency: "EUR", entryable: Transaction.new)
+ row = Goals::FundingAccountsBreakdownComponent.new(goal: goal).rows.first
+
+ assert_equal 480, row[:backing_money].amount
+ assert_equal "USD", row[:backing_money].currency.iso_code
+ assert_equal 400, row[:native_backing_money].amount
+ assert_equal "EUR", row[:balance_money].currency.iso_code
+ assert_equal 120, row[:last_30_money].amount
+ assert_not row[:rate_missing]
+ end
+
+ test "funding rows flag a nonzero share that could not be converted" do
+ funded = cash("EUR", 1_000)
+ empty = cash("EUR", 0)
+ goal = goal_on("USD", [ [ funded, 400 ], [ empty, nil ] ])
+ flags = Goals::FundingAccountsBreakdownComponent.new(goal: goal).rows.to_h { |row| [ row[:account], row[:rate_missing] ] }
+
+ assert flags[funded]
+ assert_not flags[empty]
+ end
+
+ test "completion freezes the converted balance" do
+ eur = cash("EUR", 1_000)
+ goal = goal_on("USD", [ [ eur, nil ] ])
+ rate("EUR", "USD", 1.2)
+
+ assert goal.complete!
+ assert_equal 1_200, goal.reload.completed_amount
+ eur.update!(balance: 0)
+ assert_equal 1_200, Goal.find(goal.id).current_balance
+ end
+
+ test "missing rates cannot freeze a partial completion balance" do
+ goal = goal_on("USD", [ [ cash("EUR", 1_000), nil ] ])
+
+ assert_not goal.complete!
+ assert goal.reload.active?
+ assert_nil goal.completed_amount
+ end
+
+ private
+ def cash(currency, balance)
+ @family.accounts.create!(name: "#{currency} #{SecureRandom.hex(3)}", accountable: Depository.new,
+ currency: currency, balance: balance)
+ end
+
+ # `accounts` pairs each account with its native earmark; nil links the whole balance.
+ def goal_on(currency, accounts, target: 5_000)
+ @family.goals.create!(name: "Mixed goal", target_amount: target, currency: currency) do |goal|
+ accounts.each { |account, amount| goal.goal_accounts.build(account: account, allocated_amount: amount) }
+ end
+ end
+
+ def rate(from, to, value, date: Date.current)
+ ExchangeRate.create!(from_currency: from, to_currency: to, rate: value, date: date)
+ end
+end
diff --git a/test/models/goal_test.rb b/test/models/goal_test.rb
index 0e491315ae..78883e1edc 100644
--- a/test/models/goal_test.rb
+++ b/test/models/goal_test.rb
@@ -176,7 +176,7 @@ class GoalTest < ActiveSupport::TestCase
assert_includes new_goal.errors[:linked_accounts], "Linked accounts must belong to the same family as the goal."
end
- test "linked accounts must share currency with goal" do
+ test "linked accounts may use a different currency from the goal" do
eur_account = Account.create!(
family: @family,
accountable: Depository.new,
@@ -186,8 +186,7 @@ class GoalTest < ActiveSupport::TestCase
)
new_goal = @family.goals.new(name: "T", target_amount: 100, currency: "USD")
new_goal.goal_accounts.build(account: eur_account)
- assert_not new_goal.valid?
- assert_includes new_goal.errors[:linked_accounts], "All linked accounts must share the same currency."
+ assert new_goal.valid?
end
test "currency can't change once linked accounts exist" do
diff --git a/test/models/insight/generators/maintained_goal_depleted_generator_test.rb b/test/models/insight/generators/maintained_goal_depleted_generator_test.rb
index c45b5b1576..16e5e3a991 100644
--- a/test/models/insight/generators/maintained_goal_depleted_generator_test.rb
+++ b/test/models/insight/generators/maintained_goal_depleted_generator_test.rb
@@ -45,6 +45,16 @@ class Insight::Generators::MaintainedGoalDepletedGeneratorTest < ActiveSupport::
assert_empty generate
end
+ test "says nothing about a reserve that only looks short for want of a rate" do
+ ExchangeRate.stubs(:provider).returns(nil)
+ reserve = @family.goals.create!(name: "Euro pot", target_amount: 6_000, currency: "USD", kind: "maintained") do |g|
+ g.goal_accounts.build(account: fresh_account(6_000, currency: "EUR"))
+ end
+ assert_equal :depleted, Goal.find(reserve.id).status
+
+ assert_empty generate
+ end
+
test "ignores one-off goals, however short they are" do
account = fresh_account(0)
@family.goals.create!(name: "Trip", target_amount: 5_000, currency: "USD") do |g|
@@ -84,10 +94,10 @@ class Insight::Generators::MaintainedGoalDepletedGeneratorTest < ActiveSupport::
# A dedicated account each time: the fixtures already have goals claiming
# `depository`, and a shared one would drag the pro-rata haircut into every
# shortfall figure asserted here.
- def fresh_account(balance)
+ def fresh_account(balance, currency: "USD")
Account.create!(
family: @family, accountable: Depository.new,
- name: "Pot #{SecureRandom.hex(4)}", currency: "USD", balance: balance
+ name: "Pot #{SecureRandom.hex(4)}", currency: currency, balance: balance
)
end
diff --git a/test/system/goal_multi_currency_test.rb b/test/system/goal_multi_currency_test.rb
new file mode 100644
index 0000000000..e7e520d3f9
--- /dev/null
+++ b/test/system/goal_multi_currency_test.rb
@@ -0,0 +1,41 @@
+require "application_system_test_case"
+
+class GoalMultiCurrencyTest < ApplicationSystemTestCase
+ setup do
+ @user = users(:family_admin)
+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))
+ @usd = @user.family.accounts.create!(name: "Dollar reserve", accountable: Depository.new, currency: "USD", balance: 500)
+ @eur = @user.family.accounts.create!(name: "Euro reserve", accountable: Depository.new, currency: "EUR", balance: 1_000)
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.current, rate: 1.2)
+ end
+
+ test "create a goal backed by mixed currencies and show the converted total" do
+ sign_in @user
+ visit goals_path
+ click_link I18n.t("goals.index.new_goal")
+
+ within "turbo-frame#modal" do
+ fill_in I18n.t("goals.form.fields.name"), with: "Travel reserve"
+ fill_in I18n.t("goals.form.fields.target_amount"), with: "2000"
+ check "goal_account_ids_#{@usd.id}"
+ check "goal_account_ids_#{@eur.id}"
+ earmark = I18n.t("goals.form.fields.earmark_for", account: @eur.name)
+ fill_in earmark, with: "500"
+ assert_text I18n.t("goals.form.earmark.converted").sub("{amount}", Money.new(600, "USD").format(precision: 0))
+ # Past the €1,000 balance the goal counts its pro-rata share, not the typed amount.
+ fill_in earmark, with: "2000"
+ assert_text I18n.t("goals.form.earmark.converted").sub("{amount}", Money.new(1_200, "USD").format(precision: 0))
+ fill_in earmark, with: ""
+ click_button I18n.t("goals.form.create")
+ end
+
+ assert_text "Travel reserve"
+ goal = @user.family.goals.find_by!(name: "Travel reserve")
+ assert_current_path goal_path(goal)
+ assert_equal "USD", goal.currency
+ assert_equal 1_700, goal.current_balance
+ assert_text Money.new(1_700, "USD").format(precision: 0)
+ assert_text Money.new(1_000, "EUR").format(precision: 0)
+ assert_text I18n.t("goals.show.funding_accounts.converted", amount: Money.new(1_200, "USD").format(precision: 0))
+ end
+end