Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix: scope account chart history and align inception dates (#3508)

Teju Nareddy22d8bbd45b51
diff --git a/app/components/UI/account/chart.rb b/app/components/UI/account/chart.rb
index 9b14715512..64794049ae 100644
--- a/app/components/UI/account/chart.rb
+++ b/app/components/UI/account/chart.rb
@@ -8,7 +8,15 @@ class UI::Account::Chart < ApplicationComponent
end
def period
- @period ||= Period.last_30_days
+ @effective_period ||= begin
+ p = @period || Period.last_30_days
+ acc_start = account.history_start_date
+ if p.key == "all_time" && acc_start.present? && acc_start > p.start_date
+ Period.new(key: "all_time", start_date: acc_start, end_date: p.end_date)
+ else
+ p
+ end
+ end
end
def holdings_value_money
diff --git a/app/models/account/anchorable.rb b/app/models/account/anchorable.rb
index bb797c8515..5983a9b3bc 100644
--- a/app/models/account/anchorable.rb
+++ b/app/models/account/anchorable.rb
@@ -27,6 +27,18 @@ module Account::Anchorable
opening_balance_manager.has_opening_anchor?
end
+ def history_start_date
+ if linked? && balance_type == :investment
+ Balance::LinkedInvestmentSeriesNormalizer.supported_history_start_date(self)
+ else
+ [
+ (opening_anchor_date if has_opening_anchor?),
+ entries.excluding_pending.minimum(:date),
+ balances.minimum(:date)
+ ].compact.min
+ end
+ end
+
def set_current_balance(balance)
result = current_balance_manager.set_current_balance(balance)
sync_later if result.success?
diff --git a/app/models/account/chartable.rb b/app/models/account/chartable.rb
index d84b43d9c7..12a804b4a2 100644
--- a/app/models/account/chartable.rb
+++ b/app/models/account/chartable.rb
@@ -23,7 +23,7 @@ module Account::Chartable
interval: interval
))
- normalize_linked_investment_series(builder.send("#{view}_series"))
+ normalize_linked_investment_series(builder.send("#{view}_series"), view: view)
end
def sparkline_series
@@ -35,7 +35,7 @@ module Account::Chartable
end
private
- def normalize_linked_investment_series(series)
- Balance::LinkedInvestmentSeriesNormalizer.new(account: self, series: series).normalize
+ def normalize_linked_investment_series(series, view: :balance)
+ Balance::LinkedInvestmentSeriesNormalizer.new(account: self, series: series, view: view).normalize
end
end
diff --git a/app/models/balance/linked_investment_series_normalizer.rb b/app/models/balance/linked_investment_series_normalizer.rb
index f0fc414228..544b3eae70 100644
--- a/app/models/balance/linked_investment_series_normalizer.rb
+++ b/app/models/balance/linked_investment_series_normalizer.rb
@@ -1,5 +1,5 @@
class Balance::LinkedInvestmentSeriesNormalizer
- attr_reader :account, :series
+ attr_reader :account, :series, :view
class << self
def aggregate_accounts(accounts:, currency:, period:, favorable_direction:, interval: "1 day")
@@ -37,9 +37,13 @@ class Balance::LinkedInvestmentSeriesNormalizer
)
end
+ def supported_history_start_date(account)
+ new(account: account, series: nil).supported_history_start_date
+ end
+
private
def common_supported_history_start_date(account_ids)
- account_ids = Array(account_ids)
+ account_ids = Array(account_ids).compact
return if account_ids.empty?
activity_dates = Entry.where(account_id: account_ids)
@@ -77,34 +81,72 @@ class Balance::LinkedInvestmentSeriesNormalizer
end
end
- def initialize(account:, series:)
+ # Normalizes chart series for linked investment accounts by trimming unsupported
+ # history and aligning the inception boundary.
+ def initialize(account:, series:, view: :balance)
@account = account
@series = series
+ @view = view
end
+ # Trims points before supported provider history and prepends an anchor point at inception
+ # if coarse sampling missed the opening date within the requested period.
def normalize
return series unless account.linked? && account.balance_type == :investment
first_supported_history_date = supported_history_start_date
return series unless first_supported_history_date.present?
- trimmed_values = series.values.select { |value| value.date >= first_supported_history_date }
- return series if trimmed_values.blank? || trimmed_values.length == series.values.length
+ active_points = series.values.select { |value| value.date >= first_supported_history_date }
+ return series if active_points.blank?
+
+ # If periodic sampling missed the exact opening date (e.g. coarse 1-month or 1-week intervals),
+ # prepend an anchor point on the exact opening date with the initial balance (e.g. $0)
+ # only when the inception date falls within the requested series date range.
+ if first_supported_history_date >= series.start_date && active_points.first.date > first_supported_history_date
+ currency = active_points.first.value.currency
+ initial_amount = case view.to_sym
+ when :gains, :holdings_balance
+ 0
+ when :cash_balance, :balance
+ if account.has_opening_anchor? && first_supported_history_date == account.opening_anchor_date
+ account.opening_anchor_balance || 0
+ else
+ 0
+ end
+ else
+ 0
+ end
+ opening_money = Money.new(initial_amount, currency)
+ anchor_value = Series::Value.new(
+ date: first_supported_history_date,
+ date_formatted: I18n.l(first_supported_history_date, format: :long),
+ value: opening_money,
+ trend: Trend.new(
+ current: opening_money,
+ previous: nil,
+ favorable_direction: series.favorable_direction
+ )
+ )
+ active_points = [ anchor_value, *active_points ]
+ end
+
+ return series if active_points.first&.date == series.values.first&.date && active_points.length == series.values.length
Series.new(
- start_date: trimmed_values.first.date,
+ start_date: active_points.first.date,
end_date: series.end_date,
interval: series.interval,
- values: trimmed_values,
+ values: active_points,
favorable_direction: series.favorable_direction
)
end
- private
+ def supported_history_start_date
+ [ first_provider_activity_date, stable_provider_holding_start_date ].compact.min
+ end
- def supported_history_start_date
- [ first_provider_activity_date, stable_provider_holding_start_date ].compact.min
- end
+ private
def first_provider_activity_date
@first_provider_activity_date ||= account.entries
diff --git a/test/components/UI/account/chart_test.rb b/test/components/UI/account/chart_test.rb
index 8245ff20b6..57c930db3a 100644
--- a/test/components/UI/account/chart_test.rb
+++ b/test/components/UI/account/chart_test.rb
@@ -40,6 +40,126 @@ class UI::Account::ChartTest < ViewComponent::TestCase
assert_equal "+$110.00", component.converted_balance_display
end
+ test "scopes all_time period to account history_start_date when history postdates family oldest entry date" do
+ account_opening = 60.days.ago.to_date
+ @account.stubs(:history_start_date).returns(account_opening)
+
+ family_oldest = 5.years.ago.to_date
+ all_time_period = Period.new(key: "all_time", start_date: family_oldest, end_date: Date.current)
+
+ component = UI::Account::Chart.new(account: @account, period: all_time_period)
+
+ assert_equal "all_time", component.period.key
+ assert_equal account_opening, component.period.start_date
+ assert_equal Date.current, component.period.end_date
+ assert_equal "1 day", component.period.interval
+ end
+
+ test "does not clamp non-all_time periods even if account opening postdates period start" do
+ account_opening = 10.days.ago.to_date
+ @account.stubs(:history_start_date).returns(account_opening)
+
+ last_30_days = Period.from_key("last_30_days")
+ component = UI::Account::Chart.new(account: @account, period: last_30_days)
+
+ assert_equal "last_30_days", component.period.key
+ assert_equal 30.days.ago.to_date, component.period.start_date
+ end
+
+ test "unlinked account with trade 2 years ago clamps all_time to 2 years with 1 week interval" do
+ two_years_ago = 2.years.ago.to_date
+ @account.stubs(:history_start_date).returns(two_years_ago)
+
+ family_oldest = 10.years.ago.to_date
+ all_time_period = Period.new(key: "all_time", start_date: family_oldest, end_date: Date.current)
+
+ component = UI::Account::Chart.new(account: @account, period: all_time_period)
+
+ assert_equal "all_time", component.period.key
+ assert_equal two_years_ago, component.period.start_date
+ assert_equal "1 week", component.period.interval
+ end
+
+ test "unlinked account with trade 10 years ago clamps all_time to 10 years with 1 month interval" do
+ ten_years_ago = 10.years.ago.to_date
+ @account.stubs(:history_start_date).returns(ten_years_ago)
+
+ family_oldest = 15.years.ago.to_date
+ all_time_period = Period.new(key: "all_time", start_date: family_oldest, end_date: Date.current)
+
+ component = UI::Account::Chart.new(account: @account, period: all_time_period)
+
+ assert_equal "all_time", component.period.key
+ assert_equal ten_years_ago, component.period.start_date
+ assert_equal "1 month", component.period.interval
+ end
+
+ test "unlinked account on 5Y period does not clamp period and shows full timeframe comparison" do
+ two_years_ago = 2.years.ago.to_date
+ @account.stubs(:history_start_date).returns(two_years_ago)
+
+ last_5_years = Period.from_key("last_5_years")
+ component = UI::Account::Chart.new(account: @account, period: last_5_years)
+
+ assert_equal "last_5_years", component.period.key
+ assert_equal 5.years.ago.to_date, component.period.start_date
+ assert_equal "1 week", component.period.interval
+
+ last_10_years = Period.from_key("last_10_years")
+ ten_year_component = UI::Account::Chart.new(account: @account, period: last_10_years)
+ assert_equal "last_10_years", ten_year_component.period.key
+ assert_equal 10.years.ago.to_date, ten_year_component.period.start_date
+ assert_equal "1 month", ten_year_component.period.interval
+
+ # When series covers full period (unlinked account showing 0 baseline)
+ mock_series = Series.new(
+ start_date: 5.years.ago.to_date,
+ end_date: Date.current,
+ interval: "1 month",
+ values: [
+ Series::Value.new(date: 5.years.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(100, "USD"))
+ ],
+ favorable_direction: @account.favorable_direction
+ )
+ component.stubs(:series).returns(mock_series)
+ assert_equal "vs. 5 years ago", component.comparison_label
+ end
+
+ test "linked account on 5Y period with trimmed history shows vs available history comparison" do
+ two_years_ago = 2.years.ago.to_date
+ @account.stubs(:history_start_date).returns(two_years_ago)
+
+ last_5_years = Period.from_key("last_5_years")
+ component = UI::Account::Chart.new(account: @account, period: last_5_years)
+
+ # Series normalized to 2 years ago (trimmed from 5 years ago)
+ mock_series = Series.new(
+ start_date: two_years_ago,
+ end_date: Date.current,
+ interval: "1 month",
+ values: [
+ Series::Value.new(date: two_years_ago, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(100, "USD"))
+ ],
+ favorable_direction: @account.favorable_direction
+ )
+ component.stubs(:series).returns(mock_series)
+ assert_equal I18n.t("UI.account.chart.vs_available_history"), component.comparison_label
+ end
+
+ test "empty account with nil history_start_date leaves all_time period unchanged" do
+ @account.stubs(:history_start_date).returns(nil)
+
+ family_oldest = 5.years.ago.to_date
+ all_time_period = Period.new(key: "all_time", start_date: family_oldest, end_date: Date.current)
+
+ component = UI::Account::Chart.new(account: @account, period: all_time_period)
+
+ assert_equal "all_time", component.period.key
+ assert_equal family_oldest, component.period.start_date
+ end
+
private
# 10 shares at $100 market price; gain = 1000 - cost_basis * 10
def create_holding(cost_basis:)
diff --git a/test/models/account/chartable_test.rb b/test/models/account/chartable_test.rb
index cb7b524d0b..5cb9da0842 100644
--- a/test/models/account/chartable_test.rb
+++ b/test/models/account/chartable_test.rb
@@ -165,4 +165,285 @@ class Account::ChartableTest < ActiveSupport::TestCase
assert_equal Date.current, series.start_date
assert_equal [ Date.current ], series.values.map(&:date)
end
+
+ test "prepends inception anchor point when coarse periodic sampling misses opening date" do
+ account = accounts(:investment)
+ account.entries.destroy_all
+ account.holdings.destroy_all
+
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ opening_date = 8.days.ago.to_date
+ account.set_opening_anchor_balance(balance: 0, date: opening_date)
+ account.entries.create!(
+ name: "Opening Trade",
+ date: opening_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 10.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 3.days.ago.to_date, date_formatted: "", value: Money.new(100, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(110, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ builder = mock
+ Balance::ChartSeriesBuilder.expects(:new).returns(builder)
+ builder.expects(:balance_series).returns(raw_series)
+
+ series = account.balance_series
+
+ assert_equal opening_date, series.start_date
+ assert_equal [ opening_date, 3.days.ago.to_date, Date.current ], series.values.map(&:date)
+ assert_equal Money.new(0, "USD"), series.values.first.value
+ end
+
+ test "does not normalize balance series for unlinked accounts" do
+ account = accounts(:depository) # Unlinked account
+
+ raw_series = Series.new(
+ start_date: 5.years.ago.to_date,
+ end_date: Date.current,
+ interval: "1 month",
+ values: [
+ Series::Value.new(date: 5.years.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(100, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ builder = mock
+ Balance::ChartSeriesBuilder.expects(:new).returns(builder)
+ builder.expects(:balance_series).returns(raw_series)
+
+ series = account.balance_series(period: Period.from_key("last_5_years"))
+ assert_same raw_series, series
+ end
+
+ test "prepends opening anchor with non-zero balance when coarse sampling misses opening date" do
+ account = accounts(:investment)
+ account.entries.destroy_all
+ account.holdings.destroy_all
+
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ opening_date = 8.days.ago.to_date
+ account.set_opening_anchor_balance(balance: 1500, date: opening_date)
+ account.entries.create!(
+ name: "Opening Trade",
+ date: opening_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 10.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 3.days.ago.to_date, date_formatted: "", value: Money.new(1600, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(1700, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ builder = mock
+ Balance::ChartSeriesBuilder.expects(:new).returns(builder)
+ builder.expects(:balance_series).returns(raw_series)
+
+ series = account.balance_series
+
+ assert_equal opening_date, series.start_date
+ assert_equal [ opening_date, 3.days.ago.to_date, Date.current ], series.values.map(&:date)
+ assert_equal Money.new(1500, "USD"), series.values.first.value
+ end
+
+ test "prepends anchor at 0 on trade date when linked account has no opening valuation" do
+ account = accounts(:investment)
+ account.entries.destroy_all
+ account.holdings.destroy_all
+
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ trade_date = 8.days.ago.to_date
+ account.entries.create!(
+ name: "First Trade Without Anchor",
+ date: trade_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 10.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 3.days.ago.to_date, date_formatted: "", value: Money.new(100, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(110, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ builder = mock
+ Balance::ChartSeriesBuilder.expects(:new).returns(builder)
+ builder.expects(:balance_series).returns(raw_series)
+
+ series = account.balance_series
+
+ assert_equal trade_date, series.start_date
+ assert_equal [ trade_date, 3.days.ago.to_date, Date.current ], series.values.map(&:date)
+ assert_equal Money.new(0, "USD"), series.values.first.value
+ end
+
+ test "balance_series with view :gains synthesizes 0 gains for prepended anchor point" do
+ account = accounts(:investment)
+ account.entries.destroy_all
+ account.holdings.destroy_all
+
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ opening_date = 8.days.ago.to_date
+ account.set_opening_anchor_balance(balance: 5000, date: opening_date)
+ account.entries.create!(
+ name: "Opening Trade",
+ date: opening_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_gains_series = Series.new(
+ start_date: 10.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 3.days.ago.to_date, date_formatted: "", value: Money.new(200, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(250, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ builder = mock
+ Balance::ChartSeriesBuilder.expects(:new).returns(builder)
+ builder.expects(:gains_series).returns(raw_gains_series)
+
+ series = account.balance_series(view: :gains)
+
+ assert_equal opening_date, series.start_date
+ assert_equal [ opening_date, 3.days.ago.to_date, Date.current ], series.values.map(&:date)
+ assert_equal Money.new(0, "USD"), series.values.first.value
+ end
+
+ test "balance_series does not prepend anchor outside requested period for older linked account" do
+ account = accounts(:investment)
+ account.entries.destroy_all
+ account.holdings.destroy_all
+
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ opening_date = 2.years.ago.to_date
+ account.set_opening_anchor_balance(balance: 0, date: opening_date)
+ account.entries.create!(
+ name: "Old Trade",
+ date: opening_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ thirty_days_ago = 30.days.ago.to_date
+ raw_series = Series.new(
+ start_date: thirty_days_ago,
+ end_date: Date.current,
+ interval: "1 day",
+ values: [
+ Series::Value.new(date: thirty_days_ago, date_formatted: "", value: Money.new(500, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(550, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ builder = mock
+ Balance::ChartSeriesBuilder.expects(:new).returns(builder)
+ builder.expects(:balance_series).returns(raw_series)
+
+ series = account.balance_series(period: Period.last_30_days)
+
+ assert_equal thirty_days_ago, series.start_date
+ assert_equal [ thirty_days_ago, Date.current ], series.values.map(&:date)
+ assert_equal Money.new(500, "USD"), series.values.first.value
+ end
+
+ test "balance_series assigns 0 to prepended anchor when trade predates later opening anchor" do
+ account = accounts(:investment)
+ account.entries.destroy_all
+ account.holdings.destroy_all
+
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ early_trade_date = 15.days.ago.to_date
+ later_anchor_date = 8.days.ago.to_date
+
+ account.set_opening_anchor_balance(balance: 5000, date: later_anchor_date)
+ account.entries.create!(
+ name: "Early Trade",
+ date: early_trade_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 20.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 20.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(100, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(5100, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ builder = mock
+ Balance::ChartSeriesBuilder.expects(:new).returns(builder)
+ builder.expects(:balance_series).returns(raw_series)
+
+ series = account.balance_series
+
+ assert_equal early_trade_date, series.start_date
+ assert_equal [ early_trade_date, 10.days.ago.to_date, Date.current ], series.values.map(&:date)
+ assert_equal Money.new(0, "USD"), series.values.first.value
+ end
end
diff --git a/test/models/account_test.rb b/test/models/account_test.rb
index 9360c7beee..646e898e25 100644
--- a/test/models/account_test.rb
+++ b/test/models/account_test.rb
@@ -679,4 +679,214 @@ class AccountTest < ActiveSupport::TestCase
assert_empty queries.grep(/SELECT "transactions"\.\* FROM "transactions" WHERE "transactions"\."id" =/)
assert transfers.all? { |transfer| !Transfer.exists?(transfer.id) }
end
+
+ test "history_start_date resolves to the earliest of opening anchor, entries, and balances" do
+ account = @family.accounts.create!(
+ owner: @admin,
+ name: "History Test Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Depository.new
+ )
+ account.entries.destroy_all
+ account.balances.destroy_all
+
+ assert_nil account.history_start_date
+
+ anchor_date = 30.days.ago.to_date
+ account.set_opening_anchor_balance(balance: 100, date: anchor_date)
+ assert_equal anchor_date, account.history_start_date
+
+ earlier_entry_date = 45.days.ago.to_date
+ account.entries.create!(
+ name: "Past Entry",
+ date: earlier_entry_date,
+ amount: 50,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+ assert_equal earlier_entry_date, account.history_start_date
+ end
+
+ test "history_start_date returns nil when account has no opening anchor, entries, or balances" do
+ account = @family.accounts.create!(
+ owner: @admin,
+ name: "Empty History Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Depository.new
+ )
+ account.entries.destroy_all
+ account.balances.destroy_all
+
+ assert_nil account.history_start_date
+ end
+
+ test "history_start_date resolves to transaction date when there is no opening valuation" do
+ account = @family.accounts.create!(
+ owner: @admin,
+ name: "Transaction Only Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Depository.new
+ )
+ account.entries.destroy_all
+ account.balances.destroy_all
+
+ trade_date = 2.years.ago.to_date
+ account.entries.create!(
+ name: "Old Trade",
+ date: trade_date,
+ amount: 500,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ assert_equal trade_date, account.history_start_date
+ end
+
+ test "history_start_date resolves to balance date when there are no entries or opening valuation" do
+ account = @family.accounts.create!(
+ owner: @admin,
+ name: "Balance Only Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Depository.new
+ )
+ account.entries.destroy_all
+ account.balances.destroy_all
+
+ balance_date = 1.year.ago.to_date
+ account.balances.create!(
+ date: balance_date,
+ balance: 1000,
+ currency: "USD"
+ )
+
+ assert_equal balance_date, account.history_start_date
+ end
+
+ test "history_start_date prefers earlier transaction when valuation is added much later" do
+ account = @family.accounts.create!(
+ owner: @admin,
+ name: "Late Valuation Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Depository.new
+ )
+ account.entries.destroy_all
+ account.balances.destroy_all
+
+ trade_date = 2.years.ago.to_date
+ account.entries.create!(
+ name: "Initial Buy",
+ date: trade_date,
+ amount: 100,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ # Later reconciliation valuation added 6 months ago
+ account.set_opening_anchor_balance(balance: 500, date: 6.months.ago.to_date)
+
+ assert_equal trade_date, account.history_start_date
+ end
+
+ test "history_start_date handles transaction from 10 years ago" do
+ account = @family.accounts.create!(
+ owner: @admin,
+ name: "Decade Old Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Depository.new
+ )
+ account.entries.destroy_all
+ account.balances.destroy_all
+
+ ten_years_ago = 10.years.ago.to_date
+ account.entries.create!(
+ name: "Decade Ago Trade",
+ date: ten_years_ago,
+ amount: 250,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ assert_equal ten_years_ago, account.history_start_date
+ end
+
+ test "history_start_date ignores pending transactions" do
+ account = @family.accounts.create!(
+ owner: @admin,
+ name: "Pending Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Depository.new
+ )
+ account.entries.destroy_all
+ account.balances.destroy_all
+
+ posted_date = 5.days.ago.to_date
+ account.entries.create!(
+ name: "Posted Entry",
+ date: posted_date,
+ amount: 100,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ account.entries.create!(
+ name: "Pending Entry",
+ date: 10.days.ago.to_date,
+ amount: 50,
+ currency: "USD",
+ entryable: Transaction.new(extra: { "plaid" => { "pending" => true } })
+ )
+
+ assert_equal posted_date, account.history_start_date
+ end
+
+ test "history_start_date on linked investment account resolves to provider activity ignoring default anchor" do
+ account = @family.accounts.create!(
+ owner: @admin,
+ name: "Linked Investment Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new,
+ plaid_account: plaid_accounts(:one)
+ )
+ assert account.linked?
+
+ default_anchor_date = 2.years.ago.to_date
+ account.set_opening_anchor_balance(balance: 0, date: default_anchor_date)
+
+ recent_trade_date = 14.days.ago.to_date
+ account.entries.create!(
+ name: "Recent Provider Trade",
+ date: recent_trade_date,
+ amount: 100,
+ currency: "USD",
+ source: "plaid",
+ entryable: Transaction.new
+ )
+
+ assert_equal recent_trade_date, account.history_start_date
+ end
+
+ test "history_start_date on linked investment account returns nil when no provider activity exists" do
+ account = @family.accounts.create!(
+ owner: @admin,
+ name: "Fresh Linked Investment",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new,
+ plaid_account: plaid_accounts(:one)
+ )
+ assert account.linked?
+
+ default_anchor_date = 2.years.ago.to_date
+ account.set_opening_anchor_balance(balance: 0, date: default_anchor_date)
+
+ assert_nil account.history_start_date
+ end
end
diff --git a/test/models/balance/linked_investment_series_normalizer_test.rb b/test/models/balance/linked_investment_series_normalizer_test.rb
index a3113beb01..8c75e06d18 100644
--- a/test/models/balance/linked_investment_series_normalizer_test.rb
+++ b/test/models/balance/linked_investment_series_normalizer_test.rb
@@ -33,4 +33,434 @@ class Balance::LinkedInvestmentSeriesNormalizerTest < ActiveSupport::TestCase
assert_equal posted_date, start_date
end
+
+ test "common_supported_history_start_date ignores unlinked manual accounts in mixed portfolio" do
+ linked_account = families(:empty).accounts.create!(
+ name: "Linked Investment",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ manual_account = families(:empty).accounts.create!(
+ name: "Manual Investment",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+
+ linked_activity_date = 20.days.ago.to_date
+ manual_anchor_date = 5.days.ago.to_date
+
+ linked_account.entries.create!(
+ date: linked_activity_date,
+ name: "Trade",
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+ manual_account.set_opening_anchor_balance(balance: 50, date: manual_anchor_date)
+
+ start_date = Balance::LinkedInvestmentSeriesNormalizer
+ .send(:common_supported_history_start_date, [ linked_account.id, manual_account.id ])
+
+ assert_equal linked_activity_date, start_date
+ end
+
+ test "common_supported_history_start_date returns nil when no accounts have provider history" do
+ manual_account = families(:empty).accounts.create!(
+ name: "Manual Investment",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ manual_account.set_opening_anchor_balance(balance: 50, date: 5.days.ago.to_date)
+
+ start_date = Balance::LinkedInvestmentSeriesNormalizer
+ .send(:common_supported_history_start_date, [ manual_account.id ])
+
+ assert_nil start_date
+ end
+
+ test "common_supported_history_start_date prefers trade date over later valuation" do
+ account = families(:empty).accounts.create!(
+ name: "Linked Investment Trade First",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ trade_date = 2.years.ago.to_date
+ later_valuation_date = 6.months.ago.to_date
+
+ account.entries.create!(
+ date: trade_date,
+ name: "Early Trade",
+ amount: 50,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ account.entries.create!(
+ date: later_valuation_date,
+ name: "Reconciliation Valuation",
+ amount: 500,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Valuation.new(kind: "reconciliation")
+ )
+
+ start_date = Balance::LinkedInvestmentSeriesNormalizer
+ .send(:common_supported_history_start_date, [ account.id ])
+
+ assert_equal trade_date, start_date
+ end
+
+ test "normalizer leaves series untouched for unlinked accounts" do
+ account = families(:empty).accounts.create!(
+ name: "Unlinked Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ assert account.unlinked?
+
+ raw_series = Series.new(
+ start_date: 5.years.ago.to_date,
+ end_date: Date.current,
+ interval: "1 month",
+ values: [
+ Series::Value.new(date: 5.years.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(100, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ normalizer = Balance::LinkedInvestmentSeriesNormalizer.new(account: account, series: raw_series)
+ assert_same raw_series, normalizer.normalize
+ end
+
+ test "normalizer prepends opening anchor with non-zero opening balance when coarse sampling misses date" do
+ account = families(:empty).accounts.create!(
+ name: "Linked With Anchor Balance",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ opening_date = 8.days.ago.to_date
+ account.set_opening_anchor_balance(balance: 500, date: opening_date)
+ account.entries.create!(
+ name: "Trade",
+ date: opening_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 10.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 3.days.ago.to_date, date_formatted: "", value: Money.new(600, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(650, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ normalizer = Balance::LinkedInvestmentSeriesNormalizer.new(account: account, series: raw_series)
+ normalized = normalizer.normalize
+
+ assert_equal opening_date, normalized.start_date
+ assert_equal [ opening_date, 3.days.ago.to_date, Date.current ], normalized.values.map(&:date)
+ assert_equal Money.new(500, "USD"), normalized.values.first.value
+ end
+
+ test "normalizer does not duplicate anchor point when coarse sample lands on exact opening date" do
+ account = families(:empty).accounts.create!(
+ name: "Linked Exact Date",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ opening_date = 7.days.ago.to_date
+ account.set_opening_anchor_balance(balance: 0, date: opening_date)
+ account.entries.create!(
+ name: "Trade",
+ date: opening_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 14.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 14.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: opening_date, date_formatted: "", value: Money.new(100, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(110, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ normalizer = Balance::LinkedInvestmentSeriesNormalizer.new(account: account, series: raw_series)
+ normalized = normalizer.normalize
+
+ assert_equal opening_date, normalized.start_date
+ assert_equal [ opening_date, Date.current ], normalized.values.map(&:date)
+ assert_equal Money.new(100, "USD"), normalized.values.first.value
+ end
+
+ test "normalizer returns series unmodified when linked account has no history" do
+ account = families(:empty).accounts.create!(
+ name: "Empty Linked Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ raw_series = Series.new(
+ start_date: 30.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 day",
+ values: [
+ Series::Value.new(date: 30.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(0, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ normalizer = Balance::LinkedInvestmentSeriesNormalizer.new(account: account, series: raw_series)
+ assert_same raw_series, normalizer.normalize
+ end
+
+ test "normalizer does not prepend anchor when account inception predates series start_date" do
+ account = families(:empty).accounts.create!(
+ name: "Established Linked Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ two_years_ago = 2.years.ago.to_date
+ account.set_opening_anchor_balance(balance: 0, date: two_years_ago)
+ account.entries.create!(
+ name: "Old Trade",
+ date: two_years_ago,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ # 30-day series
+ thirty_days_ago = 30.days.ago.to_date
+ raw_series = Series.new(
+ start_date: thirty_days_ago,
+ end_date: Date.current,
+ interval: "1 day",
+ values: [
+ Series::Value.new(date: thirty_days_ago, date_formatted: "", value: Money.new(500, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(550, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ normalizer = Balance::LinkedInvestmentSeriesNormalizer.new(account: account, series: raw_series)
+ normalized = normalizer.normalize
+
+ assert_equal thirty_days_ago, normalized.start_date
+ assert_equal [ thirty_days_ago, Date.current ], normalized.values.map(&:date)
+ assert_equal Money.new(500, "USD"), normalized.values.first.value
+ end
+
+ test "normalizer synthesizes 0 gains for gains view even if opening anchor balance is positive" do
+ account = families(:empty).accounts.create!(
+ name: "Gains View Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ opening_date = 8.days.ago.to_date
+ account.set_opening_anchor_balance(balance: 5000, date: opening_date)
+ account.entries.create!(
+ name: "Trade",
+ date: opening_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 10.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 3.days.ago.to_date, date_formatted: "", value: Money.new(200, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(250, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ normalizer = Balance::LinkedInvestmentSeriesNormalizer.new(account: account, series: raw_series, view: :gains)
+ normalized = normalizer.normalize
+
+ assert_equal opening_date, normalized.start_date
+ assert_equal [ opening_date, 3.days.ago.to_date, Date.current ], normalized.values.map(&:date)
+ assert_equal Money.new(0, "USD"), normalized.values.first.value
+ end
+
+ test "normalizer synthesizes 0 holdings for holdings_balance view even if opening anchor balance is positive" do
+ account = families(:empty).accounts.create!(
+ name: "Holdings View Account",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ opening_date = 8.days.ago.to_date
+ account.set_opening_anchor_balance(balance: 5000, date: opening_date)
+ account.entries.create!(
+ name: "Trade",
+ date: opening_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 10.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 3.days.ago.to_date, date_formatted: "", value: Money.new(4500, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(4800, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ normalizer = Balance::LinkedInvestmentSeriesNormalizer.new(account: account, series: raw_series, view: :holdings_balance)
+ normalized = normalizer.normalize
+
+ assert_equal opening_date, normalized.start_date
+ assert_equal [ opening_date, 3.days.ago.to_date, Date.current ], normalized.values.map(&:date)
+ assert_equal Money.new(0, "USD"), normalized.values.first.value
+ end
+
+ test "normalizer uses 0 balance when earlier provider activity predates later opening anchor" do
+ account = families(:empty).accounts.create!(
+ name: "Early Trade Later Anchor",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ early_trade_date = 15.days.ago.to_date
+ later_anchor_date = 8.days.ago.to_date
+
+ account.set_opening_anchor_balance(balance: 5000, date: later_anchor_date)
+ account.entries.create!(
+ name: "Early Trade",
+ date: early_trade_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 20.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 20.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(100, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(5100, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ normalizer = Balance::LinkedInvestmentSeriesNormalizer.new(account: account, series: raw_series, view: :balance)
+ normalized = normalizer.normalize
+
+ assert_equal early_trade_date, normalized.start_date
+ assert_equal [ early_trade_date, 10.days.ago.to_date, Date.current ], normalized.values.map(&:date)
+ assert_equal Money.new(0, "USD"), normalized.values.first.value
+ end
+
+ test "normalizer uses opening anchor balance when opening anchor matches earliest supported history date" do
+ account = families(:empty).accounts.create!(
+ name: "Anchor Is Earliest",
+ balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ coinstats_item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ account.account_providers.create!(provider: coinstats_account)
+
+ anchor_date = 15.days.ago.to_date
+
+ account.set_opening_anchor_balance(balance: 5000, date: anchor_date)
+ account.entries.create!(
+ name: "Trade on Anchor Date",
+ date: anchor_date,
+ amount: 100,
+ currency: "USD",
+ source: "snaptrade",
+ entryable: Transaction.new
+ )
+
+ raw_series = Series.new(
+ start_date: 20.days.ago.to_date,
+ end_date: Date.current,
+ interval: "1 week",
+ values: [
+ Series::Value.new(date: 20.days.ago.to_date, date_formatted: "", value: Money.new(0, "USD")),
+ Series::Value.new(date: 10.days.ago.to_date, date_formatted: "", value: Money.new(5000, "USD")),
+ Series::Value.new(date: Date.current, date_formatted: "", value: Money.new(5100, "USD"))
+ ],
+ favorable_direction: account.favorable_direction
+ )
+
+ normalizer = Balance::LinkedInvestmentSeriesNormalizer.new(account: account, series: raw_series, view: :balance)
+ normalized = normalizer.normalize
+
+ assert_equal anchor_date, normalized.start_date
+ assert_equal [ anchor_date, 10.days.ago.to_date, Date.current ], normalized.values.map(&:date)
+ assert_equal Money.new(5000, "USD"), normalized.values.first.value
+ end
end