Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Show positions that went below zero on the holdings tab (#4185)

GFRd5c12026281a
diff --git a/app/controllers/holdings_controller.rb b/app/controllers/holdings_controller.rb
index c3e0ba6008..a02c1eae7a 100644
--- a/app/controllers/holdings_controller.rb
+++ b/app/controllers/holdings_controller.rb
@@ -7,6 +7,7 @@ class HoldingsController < ApplicationController
def index
@account = accessible_accounts.find(params[:account_id])
@current_holdings = @account.current_holdings.includes(:security)
+ @negative_positions = @account.negative_positions
@trade_republic_categories = trade_republic_categories_for(@account)
end
diff --git a/app/models/account.rb b/app/models/account.rb
index 4f63cc5bfc..ef1d35fcfc 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -917,6 +917,31 @@ class Account < ApplicationRecord
.order(:ticker)
end
+ NegativePosition = Data.define(:security, :first_date, :lowest_qty)
+
+ # Securities whose calculated position dropped below zero on some day, for
+ # example after a sale without its purchase or after deleting a purchase.
+ # The holdings tab shows them instead of hiding the gap.
+ # Linked accounts are left out entirely: their provider's holdings are the
+ # truth, so a negative quantity there (reported, or carried back by the
+ # reverse calculator) is a short position, not missing data.
+ def negative_positions
+ return [] if linked?
+
+ rows = holdings
+ .joins(:security)
+ .merge(Security.standard)
+ .where(account_provider_id: nil)
+ .where("holdings.qty < 0")
+ .group(:security_id)
+ .pluck(:security_id, Arel.sql("MIN(holdings.date)"), Arel.sql("MIN(holdings.qty)"))
+ return [] if rows.empty?
+
+ securities = Security.where(id: rows.map(&:first)).index_by(&:id)
+ rows.map { |security_id, first_date, lowest_qty| NegativePosition.new(securities[security_id], first_date, lowest_qty) }
+ .sort_by { |position| [ position.first_date, position.security.ticker, position.security.id ] }
+ end
+
# The balance type determines which "component" of balance is being tracked.
# This is primarily used for balance related calculations and updates.
#
diff --git a/app/views/holdings/index.html.erb b/app/views/holdings/index.html.erb
index 297f6be5b8..16c879ad7f 100644
--- a/app/views/holdings/index.html.erb
+++ b/app/views/holdings/index.html.erb
@@ -13,6 +13,21 @@
<% end %>
</div>
+ <% if @negative_positions.any? %>
+ <%= render DS::Alert.new(title: t(".negative_positions_title"), variant: :warning) do %>
+ <% @negative_positions.each do |position| %>
+ <p class="privacy-sensitive">
+ <%= t(".negative_position",
+ name: position.security.name.presence || position.security.ticker,
+ ticker: position.security.ticker,
+ date: l(position.first_date),
+ qty: number_with_precision(position.lowest_qty, precision: 18, strip_insignificant_zeros: true)) %>
+ </p>
+ <% end %>
+ <p class="text-secondary"><%= t(".negative_positions_hint") %></p>
+ <% end %>
+ <% end %>
+
<% if @trade_republic_categories.present? %>
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
<% @trade_republic_categories.each do |category, summary| %>
diff --git a/config/locales/views/holdings/ca.yml b/config/locales/views/holdings/ca.yml
index b7bbb0ba80..8bcc372aed 100644
--- a/config/locales/views/holdings/ca.yml
+++ b/config/locales/views/holdings/ca.yml
@@ -36,6 +36,9 @@ ca:
holdings: Posicions
name: Nom
new_holding: Nova activitat
+ negative_position: "%{name} (%{ticker}): per sota de zero des del %{date}, mínim %{qty}."
+ negative_positions_hint: "Probablement falta una compra o un traspàs. Afegeix-la o corregeix les operacions que han deixat la posició per sota de zero."
+ negative_positions_title: "Algunes posicions han quedat per sota de zero"
no_holdings: No hi ha posicions per mostrar.
return: Rendiment total
weight: Pes
diff --git a/config/locales/views/holdings/de.yml b/config/locales/views/holdings/de.yml
index bef1ee2f79..23f7c816eb 100644
--- a/config/locales/views/holdings/de.yml
+++ b/config/locales/views/holdings/de.yml
@@ -42,6 +42,9 @@ de:
holdings: Positionen
name: Name
new_holding: Neue Transaktion
+ negative_position: "%{name} (%{ticker}): ab %{date} unter null, niedrigster Stand %{qty}."
+ negative_positions_hint: Vermutlich fehlt ein Kauf oder ein Übertrag. Lege ihn an oder korrigiere die Trades, die den Bestand unter null gebracht haben.
+ negative_positions_title: Bestände unter null
no_holdings: Keine Positionen vorhanden
positions:
one: "%{count} Position"
diff --git a/config/locales/views/holdings/en.yml b/config/locales/views/holdings/en.yml
index 8099b6c1aa..88399be4df 100644
--- a/config/locales/views/holdings/en.yml
+++ b/config/locales/views/holdings/en.yml
@@ -46,6 +46,9 @@ en:
holdings: Holdings
name: Name
new_holding: New activity
+ negative_position: "%{name} (%{ticker}): below zero from %{date}, lowest %{qty}."
+ negative_positions_hint: A purchase or transfer is probably missing. Add it, or correct the trades that took the position below zero.
+ negative_positions_title: Some positions went below zero
no_holdings: No holdings to show.
positions:
one: "%{count} position"
diff --git a/config/locales/views/holdings/es.yml b/config/locales/views/holdings/es.yml
index 3380bdd35f..79a58547ea 100644
--- a/config/locales/views/holdings/es.yml
+++ b/config/locales/views/holdings/es.yml
@@ -49,6 +49,9 @@ es:
holdings: Posiciones
name: Nombre
new_holding: Nueva transacción
+ negative_position: "%{name} (%{ticker}): por debajo de cero desde el %{date}, mínimo %{qty}."
+ negative_positions_hint: "Probablemente falta una compra o un traspaso. Añádela o corrige las operaciones que dejaron la posición por debajo de cero."
+ negative_positions_title: "Algunas posiciones quedaron por debajo de cero"
no_holdings: No hay posiciones para mostrar.
return: Rendimiento total
weight: Peso
diff --git a/config/locales/views/holdings/fr.yml b/config/locales/views/holdings/fr.yml
index 439f864591..19ce9aa670 100644
--- a/config/locales/views/holdings/fr.yml
+++ b/config/locales/views/holdings/fr.yml
@@ -36,6 +36,9 @@ fr:
holdings: Holdings
name: Nom
new_holding: Nouvelle activité
+ negative_position: "%{name} (%{ticker}) : sous zéro depuis le %{date}, au plus bas %{qty}."
+ negative_positions_hint: "Il manque probablement un achat ou un transfert. Ajoutez-le ou corrigez les opérations qui ont fait passer la position sous zéro."
+ negative_positions_title: "Certaines positions sont passées sous zéro"
no_holdings: Aucun holding à afficher.
return: Rendement total
weight: Poids
diff --git a/config/locales/views/holdings/hu.yml b/config/locales/views/holdings/hu.yml
index 025ebcf4eb..e1bef01f86 100644
--- a/config/locales/views/holdings/hu.yml
+++ b/config/locales/views/holdings/hu.yml
@@ -49,6 +49,9 @@ hu:
holdings: Pozíciók
name: Név
new_holding: Új tevékenység
+ negative_position: "%{name} (%{ticker}): %{date} óta nulla alatt, legalacsonyabb %{qty}."
+ negative_positions_hint: "Valószínűleg hiányzik egy vétel vagy átvezetés. Vedd fel, vagy javítsd azokat a tranzakciókat, amelyek nulla alá vitték a pozíciót."
+ negative_positions_title: "Néhány pozíció nulla alá került"
no_holdings: Nincs megjeleníthető pozíció.
return: Teljes hozam
weight: Súly
diff --git a/config/locales/views/holdings/id.yml b/config/locales/views/holdings/id.yml
index fa9d1178e5..a176a01846 100644
--- a/config/locales/views/holdings/id.yml
+++ b/config/locales/views/holdings/id.yml
@@ -46,6 +46,9 @@ id:
holdings: Kepemilikan
name: Nama
new_holding: Aktivitas baru
+ negative_position: "%{name} (%{ticker}): di bawah nol sejak %{date}, terendah %{qty}."
+ negative_positions_hint: Kemungkinan ada pembelian atau transfer yang belum dicatat. Tambahkan, atau perbaiki transaksi yang membuat posisi di bawah nol.
+ negative_positions_title: Beberapa posisi berada di bawah nol
no_holdings: Tidak ada kepemilikan untuk ditampilkan.
positions:
one: "%{count} posisi"
diff --git a/config/locales/views/holdings/it.yml b/config/locales/views/holdings/it.yml
index a800b80c01..ea71a195d8 100644
--- a/config/locales/views/holdings/it.yml
+++ b/config/locales/views/holdings/it.yml
@@ -49,6 +49,9 @@ it:
holdings: Portafoglio
name: Nome
new_holding: Nuova attività
+ negative_position: "%{name} (%{ticker}): sotto zero dal %{date}, minimo %{qty}."
+ negative_positions_hint: "Probabilmente manca un acquisto o un trasferimento. Aggiungilo o correggi le operazioni che hanno portato la posizione sotto zero."
+ negative_positions_title: "Alcune posizioni sono scese sotto zero"
no_holdings: Nessuna posizione da mostrare.
return: Rendimento totale
weight: Peso
diff --git a/config/locales/views/holdings/nb.yml b/config/locales/views/holdings/nb.yml
index 66339a4d9b..ae1d496dac 100644
--- a/config/locales/views/holdings/nb.yml
+++ b/config/locales/views/holdings/nb.yml
@@ -16,6 +16,9 @@ nb:
holdings: Beholdninger
name: Navn
new_holding: Ny transaksjon
+ negative_position: "%{name} (%{ticker}): under null fra %{date}, lavest %{qty}."
+ negative_positions_hint: "Sannsynligvis mangler et kjøp eller en overføring. Legg det til, eller rett transaksjonene som tok beholdningen under null."
+ negative_positions_title: "Noen beholdninger gikk under null"
no_holdings: Ingen beholdninger å vise.
return: Total avkastning
weight: Vekt
diff --git a/config/locales/views/holdings/nl.yml b/config/locales/views/holdings/nl.yml
index 4b8f550036..bd1f5fcf51 100644
--- a/config/locales/views/holdings/nl.yml
+++ b/config/locales/views/holdings/nl.yml
@@ -52,6 +52,9 @@ nl:
other: "%{count} posities"
return: "Totaal rendement"
weight: "Gewicht"
+ negative_position: "%{name} (%{ticker}): onder nul sinds %{date}, laagste %{qty}."
+ negative_positions_hint: "Waarschijnlijk ontbreekt een aankoop of overboeking. Voeg die toe of corrigeer de transacties die de positie onder nul brachten."
+ negative_positions_title: "Sommige posities zijn onder nul gekomen"
missing_price_tooltip:
description: "Deze belegging heeft ontbrekende waarden en we konden het rendement of de waarde niet berekenen."
missing_data: "Ontbrekende gegevens"
diff --git a/config/locales/views/holdings/pl.yml b/config/locales/views/holdings/pl.yml
index 2a8a2b723c..f8174412cd 100644
--- a/config/locales/views/holdings/pl.yml
+++ b/config/locales/views/holdings/pl.yml
@@ -34,6 +34,9 @@ pl:
holdings: Pozycje
name: Nazwa
new_holding: Nowa aktywność
+ negative_position: "%{name} (%{ticker}): poniżej zera od %{date}, najniżej %{qty}."
+ negative_positions_hint: "Prawdopodobnie brakuje zakupu lub przeniesienia. Dodaj je albo popraw transakcje, które sprowadziły pozycję poniżej zera."
+ negative_positions_title: "Niektóre pozycje spadły poniżej zera"
no_holdings: Brak pozycji do wyświetlenia.
positions:
few: "%{count} pozycje"
diff --git a/config/locales/views/holdings/pt-BR.yml b/config/locales/views/holdings/pt-BR.yml
index 86f79f47aa..0018aac68a 100644
--- a/config/locales/views/holdings/pt-BR.yml
+++ b/config/locales/views/holdings/pt-BR.yml
@@ -16,6 +16,9 @@ pt-BR:
holdings: Posições
name: Nome
new_holding: Nova transação
+ negative_position: "%{name} (%{ticker}): abaixo de zero desde %{date}, mínimo %{qty}."
+ negative_positions_hint: "Provavelmente falta uma compra ou transferência. Adicione-a ou corrija as operações que deixaram a posição abaixo de zero."
+ negative_positions_title: "Algumas posições ficaram abaixo de zero"
no_holdings: Nenhuma posição para mostrar.
return: Retorno total
weight: Peso
diff --git a/config/locales/views/holdings/pt-PT.yml b/config/locales/views/holdings/pt-PT.yml
index 73bdffe5cb..8dda343980 100644
--- a/config/locales/views/holdings/pt-PT.yml
+++ b/config/locales/views/holdings/pt-PT.yml
@@ -46,6 +46,9 @@ pt-PT:
holdings: Posições
name: Designação
new_holding: Nova atividade
+ negative_position: "%{name} (%{ticker}): abaixo de zero desde %{date}, mínimo %{qty}."
+ negative_positions_hint: "Provavelmente falta uma compra ou transferência. Adicione-a ou corrija as operações que deixaram a posição abaixo de zero."
+ negative_positions_title: "Algumas posições ficaram abaixo de zero"
no_holdings: Nenhuma posição para mostrar.
return: Retorno total
weight: Peso
diff --git a/config/locales/views/holdings/ro.yml b/config/locales/views/holdings/ro.yml
index f4fc26ec7b..4c88428a50 100644
--- a/config/locales/views/holdings/ro.yml
+++ b/config/locales/views/holdings/ro.yml
@@ -16,6 +16,9 @@ ro:
holdings: Dețineri
name: Nume
new_holding: Tranzacție nouă
+ negative_position: "%{name} (%{ticker}): sub zero din %{date}, minim %{qty}."
+ negative_positions_hint: "Probabil lipsește o cumpărare sau un transfer. Adaug-o sau corectează tranzacțiile care au adus poziția sub zero."
+ negative_positions_title: "Unele poziții au scăzut sub zero"
no_holdings: Nu există dețineri de afișat.
return: Randament total
weight: Pondere
diff --git a/config/locales/views/holdings/ru.yml b/config/locales/views/holdings/ru.yml
index b541a50268..1ae59d8b92 100644
--- a/config/locales/views/holdings/ru.yml
+++ b/config/locales/views/holdings/ru.yml
@@ -38,6 +38,9 @@ ru:
holdings: Активы
name: Название
new_holding: Новая активность
+ negative_position: "%{name} (%{ticker}): ниже нуля с %{date}, минимум %{qty}."
+ negative_positions_hint: "Вероятно, не хватает покупки или перевода. Добавьте её или исправьте сделки, из-за которых позиция ушла ниже нуля."
+ negative_positions_title: "Некоторые позиции ушли ниже нуля"
no_holdings: Нет активов для отображения.
return: Общая доходность
weight: Доля
diff --git a/config/locales/views/holdings/tr.yml b/config/locales/views/holdings/tr.yml
index f00327145d..5495913ba4 100644
--- a/config/locales/views/holdings/tr.yml
+++ b/config/locales/views/holdings/tr.yml
@@ -36,6 +36,9 @@ tr:
holdings: Varlıklar
name: İsim
new_holding: Yeni işlem
+ negative_position: "%{name} (%{ticker}): %{date} tarihinden beri sıfırın altında, en düşük %{qty}."
+ negative_positions_hint: "Muhtemelen bir alım veya transfer eksik. Ekleyin ya da pozisyonu sıfırın altına düşüren işlemleri düzeltin."
+ negative_positions_title: "Bazı pozisyonlar sıfırın altına düştü"
no_holdings: Gösterilecek varlık yok.
return: Toplam getiri
weight: Ağırlık
diff --git a/config/locales/views/holdings/uk.yml b/config/locales/views/holdings/uk.yml
index ce78e0c032..6e212c5ab1 100644
--- a/config/locales/views/holdings/uk.yml
+++ b/config/locales/views/holdings/uk.yml
@@ -51,6 +51,9 @@ uk:
holdings: "Активи"
name: "Назва"
new_holding: "Нова активність"
+ negative_position: "%{name} (%{ticker}): нижче нуля з %{date}, мінімум %{qty}."
+ negative_positions_hint: "Імовірно, бракує купівлі або переказу. Додайте її або виправте операції, через які позиція стала від'ємною."
+ negative_positions_title: "Деякі позиції стали від'ємними"
no_holdings: "Немає активів для відображення."
return: "Загальна дохідність"
weight: "Вага"
diff --git a/config/locales/views/holdings/vi.yml b/config/locales/views/holdings/vi.yml
index 28891d70cf..fa21cd2a3d 100644
--- a/config/locales/views/holdings/vi.yml
+++ b/config/locales/views/holdings/vi.yml
@@ -49,6 +49,9 @@ vi:
holdings: Danh mục nắm giữ
name: Tên
new_holding: Hoạt động mới
+ negative_position: "%{name} (%{ticker}): dưới 0 từ %{date}, thấp nhất %{qty}."
+ negative_positions_hint: "Có thể thiếu một giao dịch mua hoặc chuyển khoản. Hãy thêm vào hoặc sửa các giao dịch đã đưa vị thế xuống dưới 0."
+ negative_positions_title: "Một số vị thế đã xuống dưới 0"
no_holdings: Không có danh mục nắm giữ.
return: Tổng lợi nhuận
weight: Tỷ trọng
diff --git a/config/locales/views/holdings/zh-CN.yml b/config/locales/views/holdings/zh-CN.yml
index d1ead336ea..2798eae8ce 100644
--- a/config/locales/views/holdings/zh-CN.yml
+++ b/config/locales/views/holdings/zh-CN.yml
@@ -49,6 +49,9 @@ zh-CN:
holdings: 持仓
name: 名称
new_holding: 新活动
+ negative_position: "%{name} (%{ticker}):自 %{date} 起低于零,最低 %{qty}。"
+ negative_positions_hint: "可能缺少一笔买入或转入。请补上,或更正使持仓低于零的交易。"
+ negative_positions_title: "部分持仓低于零"
no_holdings: 没有可显示的持仓。
return: 总回报
weight: 权重
diff --git a/config/locales/views/holdings/zh-TW.yml b/config/locales/views/holdings/zh-TW.yml
index 4e0aac9fa8..0fbb5854ee 100644
--- a/config/locales/views/holdings/zh-TW.yml
+++ b/config/locales/views/holdings/zh-TW.yml
@@ -49,6 +49,9 @@ zh-TW:
holdings: 持股
name: 名稱
new_holding: 新增活動
+ negative_position: "%{name} (%{ticker}):自 %{date} 起低於零,最低 %{qty}。"
+ negative_positions_hint: "可能缺少一筆買入或轉入。請補上,或更正使持倉低於零的交易。"
+ negative_positions_title: "部分持倉低於零"
no_holdings: 沒有可顯示的持股。
return: 總報酬
weight: 占比
diff --git a/test/controllers/holdings_controller_test.rb b/test/controllers/holdings_controller_test.rb
index 5b295cd7f1..73def80b46 100644
--- a/test/controllers/holdings_controller_test.rb
+++ b/test/controllers/holdings_controller_test.rb
@@ -12,6 +12,28 @@ class HoldingsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
end
+ test "warns about positions that went below zero" do
+ # An import that records a sale without its purchase, as a provider or CSV can.
+ @account.entries.create!(
+ name: "Sell 3 shares of MSFT", date: 3.days.ago.to_date, amount: -1200, currency: "USD",
+ entryable: Trade.new(security: securities(:msft), qty: -3, price: 400, currency: "USD", investment_activity_label: "Sell")
+ )
+ Holding::Materializer.new(@account, strategy: :forward).materialize_holdings
+
+ get holdings_url(account_id: @account.id)
+
+ assert_response :success
+ assert_match "Some positions went below zero", response.body
+ assert_match "Microsoft (MSFT): below zero from", response.body
+ end
+
+ test "shows no below-zero warning for a normal portfolio" do
+ get holdings_url(account_id: @account.id)
+
+ assert_response :success
+ assert_no_match "Some positions went below zero", response.body
+ end
+
test "gets holding" do
get holding_path(@holding)
diff --git a/test/i18n_test.rb b/test/i18n_test.rb
index 64c361078d..3f1f557fbb 100644
--- a/test/i18n_test.rb
+++ b/test/i18n_test.rb
@@ -145,6 +145,23 @@ class I18nTest < ActiveSupport::TestCase
assert_empty missing, "bills.index.notices_heading is missing for: #{missing.join(", ")}"
end
+ # The below-zero warning speaks wherever the holdings tab is translated.
+ def test_negative_position_keys_exist_wherever_the_holdings_tab_is_translated
+ {
+ "holdings.index.new_holding" => %w[
+ holdings.index.negative_position holdings.index.negative_positions_hint holdings.index.negative_positions_title
+ ]
+ }.each do |sibling, keys|
+ locales = I18n.available_locales.select { |locale| I18n.t(sibling, locale: locale, fallback: false, default: nil) }
+ assert_includes locales, :de
+
+ locales.each do |locale|
+ missing = keys.reject { |key| I18n.t(key, locale: locale, fallback: false, default: nil) }
+ assert_empty missing, "#{locale} translates #{sibling} but is missing #{missing.join(", ")}"
+ end
+ end
+ end
+
# The All bills default status option. Every bills locale must translate it,
# or the default filter falls back to English.
def test_bills_current_bills_label_exists_for_each_bills_locale
diff --git a/test/models/account_test.rb b/test/models/account_test.rb
index 1420698483..2069b06533 100644
--- a/test/models/account_test.rb
+++ b/test/models/account_test.rb
@@ -10,6 +10,35 @@ class AccountTest < ActiveSupport::TestCase
@member = users(:family_member)
end
+ test "negative_positions lists calculated positions below zero" do
+ account = accounts(:investment)
+ msft = securities(:msft)
+ # A sale without its purchase, as an import or a deleted buy can leave behind.
+ account.entries.create!(
+ name: "Sell 3 shares of MSFT", date: 3.days.ago.to_date, amount: -1200, currency: "USD",
+ entryable: Trade.new(security: msft, qty: -3, price: 400, currency: "USD", investment_activity_label: "Sell")
+ )
+ Holding::Materializer.new(account, strategy: :forward).materialize_holdings
+
+ positions = account.negative_positions
+
+ assert_equal [ msft ], positions.map(&:security)
+ assert_equal 3.days.ago.to_date, positions.first.first_date
+ assert_equal(-3, positions.first.lowest_qty)
+ end
+
+ test "negative_positions ignores linked accounts" do
+ account = accounts(:investment)
+ account.entries.create!(
+ name: "Sell 3 shares of MSFT", date: 3.days.ago.to_date, amount: -1200, currency: "USD",
+ entryable: Trade.new(security: securities(:msft), qty: -3, price: 400, currency: "USD", investment_activity_label: "Sell")
+ )
+ Holding::Materializer.new(account, strategy: :forward).materialize_holdings
+ account.stubs(:linked?).returns(true)
+
+ assert_empty account.negative_positions
+ end
+
test "linked cash and investment accounts hide balance updates by default" do
assert accounts(:connected).hides_balance_updates_by_default?