The personal finance app for everyone (by everyone)
Ruby
Show account data-quality problems next to the sync state (#5363)
David Gil20d63ac0ad9b
diff --git a/app/components/UI/account/health_status.html.erb b/app/components/UI/account/health_status.html.erbnew file mode 100644index 0000000000..cfa85cff07--- /dev/null+++ b/app/components/UI/account/health_status.html.erb@@ -0,0 +1,15 @@+<div class="px-3 space-y-2" data-testid="account-health-status">+ <% issues.each do |issue| %>+ <%= render DS::Alert.new(title: issue.message, variant: issue.severity) do %>+ <% issue.details.each do |detail| %>+ <p class="privacy-sensitive"><%= detail_text(detail) %></p>+ <% end %>+ <% if issue.hint %>+ <p class="text-secondary"><%= issue.hint %></p>+ <% end %>+ <% if issue.link %>+ <p><%= render DS::Link.new(text: issue.link[:text], href: issue.link[:href], variant: :default, frame: :_top) %></p>+ <% end %>+ <% end %>+ <% end %>+</div>diff --git a/app/components/UI/account/health_status.rb b/app/components/UI/account/health_status.rbnew file mode 100644index 0000000000..1be3765841--- /dev/null+++ b/app/components/UI/account/health_status.rb@@ -0,0 +1,26 @@+# The account's data-quality problems (Account::HealthStatus), shown under its+# header, where the page shows the sync state.+class UI::Account::HealthStatus < ApplicationComponent+ def initialize(account:)+ @account = account+ end++ def issues+ @issues ||= Account::HealthStatus.new(@account).issues+ end++ def render?+ issues.any?+ end++ # Only the negative-positions issue lists details: one Account::NegativePosition each.+ def detail_text(position)+ t(+ "accounts.health_status.negative_positions.detail",+ name: position.security.name.presence || position.security.ticker,+ ticker: position.security.ticker,+ date: helpers.format_date(position.first_date),+ qty: helpers.format_quantity(position.lowest_qty, exact: true)+ )+ end+enddiff --git a/app/components/UI/account_page.html.erb b/app/components/UI/account_page.html.erbindex 53273ef1c7..ba4172c887 100644--- a/app/components/UI/account_page.html.erb+++ b/app/components/UI/account_page.html.erb@@ -4,6 +4,8 @@<%= tag.div class: "space-y-4 pb-5 lg:pb-32" do %><%= render "accounts/show/header", account: account, title: title, subtitle: subtitle, reconciliation_indicator: reconciliation_indicator %>+ <%= render UI::Account::HealthStatus.new(account: account) %>+<%= render UI::Account::Chart.new(account: account, period: chart_period, view: chart_view, loan_chart: loan_chart,extra_repayment: extra_repayment) %>diff --git a/app/controllers/holdings_controller.rb b/app/controllers/holdings_controller.rbindex f63b7f9753..9a170738cd 100644--- a/app/controllers/holdings_controller.rb+++ b/app/controllers/holdings_controller.rb@@ -9,7 +9,6 @@ class HoldingsController < ApplicationController# Every row shows its average cost; load them together, not per row.@current_holdings = @account.current_holdings.includes(:security).to_aHolding.preload_avg_costs(@current_holdings)- @negative_positions = @account.negative_positions@trade_republic_categories = trade_republic_categories_for(@account)enddiff --git a/app/models/account.rb b/app/models/account.rbindex 799a5e7b47..be61dcdd99 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -924,12 +924,12 @@ class Account < ApplicationRecord# 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.+ # The account status (Account::HealthStatus) 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?+ return [] if linked? || balance_type != :investmentrows = holdings.joins(:security)diff --git a/app/models/account/health_status.rb b/app/models/account/health_status.rbnew file mode 100644index 0000000000..0dd8ff9e84--- /dev/null+++ b/app/models/account/health_status.rb@@ -0,0 +1,54 @@+# Data-quality problems on one account, shown next to its sync state on the+# account page. Each check returns an Issue or nil; a new one is a private+# `*_issue` method added to `issues`. Details stay data (negative positions);+# UI::Account::HealthStatus formats them for the viewer's family.+#+# Computed for the account the viewer opened, so it is only ever shown to+# someone who can see that account.+class Account::HealthStatus+ Issue = Data.define(:severity, :message, :details, :hint, :link) do+ def initialize(severity:, message:, details: [], hint: nil, link: nil)+ super+ end+ end++ attr_reader :account++ def initialize(account)+ @account = account+ end++ def issues+ @issues ||= [ sync_issue, negative_positions_issue ].compact+ end++ private+ # The account's own latest sync: a later one that went through clears it.+ # One still pending past Sync::VISIBLE_FOR lost its job; Sync.clean only+ # marks it stale a day later.+ def sync_issue+ sync = account.latest_sync_record+ return unless sync+ return unless sync.failed? || sync.stale? || (sync.in_progress? && !sync.visible?)++ key = sync.failed? ? :sync_failed : :sync_stale+ Issue.new(+ severity: sync.failed? ? :error : :warning,+ message: I18n.t("accounts.health_status.#{key}.message"),+ hint: I18n.t("accounts.health_status.sync_hint")+ )+ end++ def negative_positions_issue+ positions = account.negative_positions+ return if positions.empty?++ Issue.new(+ severity: :warning,+ message: I18n.t("accounts.health_status.negative_positions.message"),+ details: positions,+ hint: I18n.t("accounts.health_status.negative_positions.hint"),+ link: { text: I18n.t("accounts.health_status.negative_positions.link"), href: Rails.application.routes.url_helpers.account_path(account, tab: "holdings") }+ )+ end+enddiff --git a/app/views/holdings/index.html.erb b/app/views/holdings/index.html.erbindex 16c879ad7f..297f6be5b8 100644--- a/app/views/holdings/index.html.erb+++ b/app/views/holdings/index.html.erb@@ -13,21 +13,6 @@<% 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/accounts/ca.yml b/config/locales/views/accounts/ca.ymlindex a021a6e8b5..97a93075fc 100644--- a/config/locales/views/accounts/ca.yml+++ b/config/locales/views/accounts/ca.yml@@ -95,6 +95,17 @@ ca:set_default:depository_only: Només els comptes d'efectiu i de targeta de crèdit es podenestablir com a predeterminats.+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): per sota de zero des del %{date}, mínim %{qty}"+ hint: "Probablement falta una compra o un traspàs. Afegeix-la o corregeix les operacions que han deixat la posició per sota de zero."+ link: "Revisa les posicions"+ message: "Algunes posicions han quedat per sota de zero"+ sync_failed:+ message: "L'última sincronització ha fallat"+ sync_hint: "Les xifres poden estar desactualitzades. Torna a sincronitzar per posar-les al dia."+ sync_stale:+ message: "L'última sincronització no ha acabat"show:activity:amount: Importdiff --git a/config/locales/views/accounts/de.yml b/config/locales/views/accounts/de.ymlindex e637d2b900..93d3272f4a 100644--- a/config/locales/views/accounts/de.yml+++ b/config/locales/views/accounts/de.yml@@ -73,6 +73,17 @@ de:next: Weiterprevious: Zurückselect: Auswählen+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): ab %{date} unter null, niedrigster Stand %{qty}"+ hint: Vermutlich fehlt ein Kauf oder ein Übertrag. Lege ihn an oder korrigiere die Trades, die den Bestand unter null gebracht haben.+ link: "Positionen prüfen"+ message: Bestände unter null+ sync_failed:+ message: "Die letzte Synchronisierung ist fehlgeschlagen"+ sync_hint: "Die Zahlen hier sind möglicherweise veraltet. Synchronisiere erneut, um sie zu aktualisieren."+ sync_stale:+ message: "Die letzte Synchronisierung wurde nicht abgeschlossen"show:activity:amount: Betragdiff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.ymlindex 3fad1f2e08..00f96fb023 100644--- a/config/locales/views/accounts/en.yml+++ b/config/locales/views/accounts/en.yml@@ -135,6 +135,17 @@ en:manual_entry: Enter account balancetitle: How would you like to add it?title: What would you like to add?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): below zero from %{date}, lowest %{qty}"+ hint: A purchase or transfer is probably missing. Add it, or correct the trades that took the position below zero.+ link: Review holdings+ message: Some positions went below zero+ sync_failed:+ message: The last sync failed+ sync_hint: The figures here may be out of date. Sync again to bring them up to date.+ sync_stale:+ message: The last sync did not finishshow:limited_fx_history_warning: "Exchange rate history is only available from %{date} onwards. Transactions before this date use approximate currency conversions — this can happen when the FX provider only offers a limited historical window."tabs:diff --git a/config/locales/views/accounts/es.yml b/config/locales/views/accounts/es.ymlindex 96eaa02897..71d7ce3dba 100644--- a/config/locales/views/accounts/es.yml+++ b/config/locales/views/accounts/es.yml@@ -124,6 +124,17 @@ es:manual_entry: Introducir saldo de la cuentatitle: ¿Cómo te gustaría añadirla?title: ¿Qué te gustaría añadir?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): por debajo de cero desde el %{date}, mínimo %{qty}"+ hint: "Probablemente falta una compra o un traspaso. Añádela o corrige las operaciones que dejaron la posición por debajo de cero."+ link: Revisar posiciones+ message: "Algunas posiciones quedaron por debajo de cero"+ sync_failed:+ message: La última sincronización falló+ sync_hint: Las cifras pueden estar desactualizadas. Vuelve a sincronizar para ponerlas al día.+ sync_stale:+ message: La última sincronización no terminóshow:limited_fx_history_warning: El historial de tipos de cambio solo está disponible desde %{date}. Las transacciones anteriores a esa fecha usan conversiones de divisa aproximadas; esto puede ocurrir cuando el proveedor de tipos de cambio solo ofrece una ventana histórica limitada.tabs:diff --git a/config/locales/views/accounts/fr.yml b/config/locales/views/accounts/fr.ymlindex 2d10e3732f..d60ff6e6b8 100644--- a/config/locales/views/accounts/fr.yml+++ b/config/locales/views/accounts/fr.yml@@ -99,6 +99,17 @@ fr:title: Sélectionner un fournisseur à lierset_default:depository_only: Seuls les comptes de liquidités et de carte de crédit peuvent être définis par défaut.+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}) : sous zéro depuis le %{date}, au plus bas %{qty}"+ 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."+ link: "Vérifier les holdings"+ message: "Certaines positions sont passées sous zéro"+ sync_failed:+ message: "La dernière synchronisation a échoué"+ sync_hint: "Les chiffres affichés peuvent être obsolètes. Relancez la synchronisation pour les mettre à jour."+ sync_stale:+ message: "La dernière synchronisation ne s'est pas terminée"show:activity:amount: Montantdiff --git a/config/locales/views/accounts/hu.yml b/config/locales/views/accounts/hu.ymlindex 6041d3d910..9f04e67615 100644--- a/config/locales/views/accounts/hu.yml+++ b/config/locales/views/accounts/hu.yml@@ -69,6 +69,17 @@ hu:manual_entry: Egyenleg manuális megadásatitle: Hogyan szeretnéd hozzáadni?title: Mit szeretnél hozzáadni?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): %{date} óta nulla alatt, legalacsonyabb %{qty}"+ 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."+ link: "Pozíciók ellenőrzése"+ message: "Néhány pozíció nulla alá került"+ sync_failed:+ message: "Az utolsó szinkronizálás sikertelen volt"+ sync_hint: "Az itt látható adatok elavultak lehetnek. Szinkronizálj újra a frissítésükhöz."+ sync_stale:+ message: "Az utolsó szinkronizálás nem fejeződött be"show:limited_fx_history_warning: "Az árfolyam-előzmények csak %{date} dátumtól érhetők el. Az ezt megelőző tranzakciókhoz közelítő árfolyamok kerülnek alkalmazásra – ez akkor fordulhat elő, ha a devizaárfolyam-szolgáltató csak korlátozott előzményadatokat kínál."tabs:diff --git a/config/locales/views/accounts/id.yml b/config/locales/views/accounts/id.ymlindex 6cee79219c..5cf3551e46 100644--- a/config/locales/views/accounts/id.yml+++ b/config/locales/views/accounts/id.yml@@ -81,6 +81,17 @@ id:manual_entry: Masukkan saldo rekeningtitle: Bagaimana Anda ingin menambahkannya?title: Apa yang ingin Anda tambahkan?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): di bawah nol sejak %{date}, terendah %{qty}"+ hint: Kemungkinan ada pembelian atau transfer yang belum dicatat. Tambahkan, atau perbaiki transaksi yang membuat posisi di bawah nol.+ link: "Tinjau kepemilikan"+ message: Beberapa posisi berada di bawah nol+ sync_failed:+ message: "Sinkronisasi terakhir gagal"+ sync_hint: "Angka di sini mungkin sudah usang. Sinkronkan lagi untuk memperbaruinya."+ sync_stale:+ message: "Sinkronisasi terakhir tidak selesai"show:limited_fx_history_warning: "Riwayat kurs valas hanya tersedia mulai %{date} dan seterusnya. Transaksi sebelum tanggal ini menggunakan konversi mata uang perkiraan — hal ini dapat terjadi ketika penyedia valas hanya menyediakan rentang data historis yang terbatas."tabs:diff --git a/config/locales/views/accounts/it.yml b/config/locales/views/accounts/it.ymlindex c847aaf180..6bb220fdd2 100644--- a/config/locales/views/accounts/it.yml+++ b/config/locales/views/accounts/it.yml@@ -73,6 +73,17 @@ it:manual_entry: Inserisci saldo contotitle: Come vuoi aggiungerlo?title: Cosa vuoi aggiungere?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): sotto zero dal %{date}, minimo %{qty}"+ hint: "Probabilmente manca un acquisto o un trasferimento. Aggiungilo o correggi le operazioni che hanno portato la posizione sotto zero."+ link: "Controlla il portafoglio"+ message: "Alcune posizioni sono scese sotto zero"+ sync_failed:+ message: "L'ultima sincronizzazione non è riuscita"+ sync_hint: "I dati qui potrebbero non essere aggiornati. Sincronizza di nuovo per aggiornarli."+ sync_stale:+ message: "L'ultima sincronizzazione non è stata completata"show:limited_fx_history_warning: "La cronologia dei tassi di cambio è disponibile solo dal %{date} in poi. Le transazioni precedenti a questa data usano conversioni valutarie approssimate — questo può accadere quando il provider FX offre solo una finestra storica limitata."tabs:diff --git a/config/locales/views/accounts/nb.yml b/config/locales/views/accounts/nb.ymlindex 7cc45f459f..d7f8e8db20 100644--- a/config/locales/views/accounts/nb.yml+++ b/config/locales/views/accounts/nb.yml@@ -32,6 +32,17 @@ nb:manual_entry: Angi kontobalansetitle: Hvordan vil du legge den til?title: Hva vil du legge til?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): under null fra %{date}, lavest %{qty}"+ hint: "Sannsynligvis mangler et kjøp eller en overføring. Legg det til, eller rett transaksjonene som tok beholdningen under null."+ link: "Se gjennom beholdningene"+ message: "Noen beholdninger gikk under null"+ sync_failed:+ message: "Den siste synkroniseringen mislyktes"+ sync_hint: "Tallene her kan være utdaterte. Synkroniser på nytt for å oppdatere dem."+ sync_stale:+ message: "Den siste synkroniseringen ble ikke fullført"show:activity:amount: Beløpdiff --git a/config/locales/views/accounts/nl.yml b/config/locales/views/accounts/nl.ymlindex 9d32c67d7f..7c7c0bfaca 100644--- a/config/locales/views/accounts/nl.yml+++ b/config/locales/views/accounts/nl.yml@@ -116,6 +116,17 @@ nl:manual_entry: "Accountsaldo invoeren"title: "Hoe wilt u het toevoegen?"title: "Wat wilt u toevoegen?"+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): onder nul sinds %{date}, laagste %{qty}"+ hint: "Waarschijnlijk ontbreekt een aankoop of overboeking. Voeg die toe of corrigeer de transacties die de positie onder nul brachten."+ link: "Posities bekijken"+ message: "Sommige posities zijn onder nul gekomen"+ sync_failed:+ message: "De laatste synchronisatie is mislukt"+ sync_hint: "De cijfers hier zijn mogelijk verouderd. Synchroniseer opnieuw om ze bij te werken."+ sync_stale:+ message: "De laatste synchronisatie is niet voltooid"show:limited_fx_history_warning: "Wisselkoersgeschiedenis is pas beschikbaar vanaf %{date}. Transacties vóór deze datum gebruiken benaderde valutaomrekeningen — dit kan gebeuren als de wisselkoersprovider maar een beperkte historische periode aanbiedt."tabs:diff --git a/config/locales/views/accounts/pl.yml b/config/locales/views/accounts/pl.ymlindex 42dbd0ebd5..a601dba6ce 100644--- a/config/locales/views/accounts/pl.yml+++ b/config/locales/views/accounts/pl.yml@@ -97,6 +97,17 @@ pl:set_default:depository_only: Tylko konta gotówkowe i karty kredytowe mogą być ustawionejako domyślne.+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): poniżej zera od %{date}, najniżej %{qty}"+ hint: "Prawdopodobnie brakuje zakupu lub przeniesienia. Dodaj je albo popraw transakcje, które sprowadziły pozycję poniżej zera."+ link: "Sprawdź pozycje"+ message: "Niektóre pozycje spadły poniżej zera"+ sync_failed:+ message: "Ostatnia synchronizacja nie powiodła się"+ sync_hint: "Dane mogą być nieaktualne. Zsynchronizuj ponownie, aby je zaktualizować."+ sync_stale:+ message: "Ostatnia synchronizacja nie została ukończona"show:activity:amount: Kwotadiff --git a/config/locales/views/accounts/pt-BR.yml b/config/locales/views/accounts/pt-BR.ymlindex 244b91ba58..e37b399ccc 100644--- a/config/locales/views/accounts/pt-BR.yml+++ b/config/locales/views/accounts/pt-BR.yml@@ -39,6 +39,17 @@ pt-BR:manual_entry: Inserir saldo da contatitle: Como você gostaria de adicionar?title: O que você gostaria de adicionar?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): abaixo de zero desde %{date}, mínimo %{qty}"+ hint: "Provavelmente falta uma compra ou transferência. Adicione-a ou corrija as operações que deixaram a posição abaixo de zero."+ link: "Revisar posições"+ message: "Algumas posições ficaram abaixo de zero"+ sync_failed:+ message: "A última sincronização falhou"+ sync_hint: "Os valores aqui podem estar desatualizados. Sincronize novamente para atualizá-los."+ sync_stale:+ message: "A última sincronização não terminou"show:activity:amount: Valordiff --git a/config/locales/views/accounts/pt-PT.yml b/config/locales/views/accounts/pt-PT.ymlindex f9e0d177c0..2bfc7c1839 100644--- a/config/locales/views/accounts/pt-PT.yml+++ b/config/locales/views/accounts/pt-PT.yml@@ -76,6 +76,17 @@ pt-PT:manual_entry: Introduzir saldo da contatitle: Como gostaria de adicionar?title: O que gostaria de adicionar?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): abaixo de zero desde %{date}, mínimo %{qty}"+ hint: "Provavelmente falta uma compra ou transferência. Adicione-a ou corrija as operações que deixaram a posição abaixo de zero."+ link: "Rever posições"+ message: "Algumas posições ficaram abaixo de zero"+ sync_failed:+ message: "A última sincronização falhou"+ sync_hint: "Os valores aqui podem estar desatualizados. Sincronize novamente para os atualizar."+ sync_stale:+ message: "A última sincronização não terminou"show:limited_fx_history_warning: "O histórico de taxas de câmbio só está disponível a partir de %{date}. As transações anteriores a esta data utilizam conversões de moeda aproximadas — tal acontece quando o serviço externo de câmbio apenas oferece uma janela histórica limitada."tabs:diff --git a/config/locales/views/accounts/ro.yml b/config/locales/views/accounts/ro.ymlindex e87bb523c6..24a5c75d82 100644--- a/config/locales/views/accounts/ro.yml+++ b/config/locales/views/accounts/ro.yml@@ -34,6 +34,17 @@ ro:manual_entry: Introdu soldul contuluititle: Cum dorești să adaugi?title: Ce dorești să adaugi?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): sub zero din %{date}, minim %{qty}"+ hint: "Probabil lipsește o cumpărare sau un transfer. Adaug-o sau corectează tranzacțiile care au adus poziția sub zero."+ link: "Verifică dețineri"+ message: "Unele poziții au scăzut sub zero"+ sync_failed:+ message: "Ultima sincronizare a eșuat"+ sync_hint: "Cifrele de aici pot fi neactualizate. Sincronizează din nou pentru a le actualiza."+ sync_stale:+ message: "Ultima sincronizare nu s-a încheiat"show:activity:amount: Sumădiff --git a/config/locales/views/accounts/ru.yml b/config/locales/views/accounts/ru.ymlindex 2c5cf8d43e..be098ff2ad 100644--- a/config/locales/views/accounts/ru.yml+++ b/config/locales/views/accounts/ru.yml@@ -131,6 +131,17 @@ ru:set_default:depository_only: По умолчанию можно установить только денежные счета и счетакредитных карт.+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): ниже нуля с %{date}, минимум %{qty}"+ hint: "Вероятно, не хватает покупки или перевода. Добавьте её или исправьте сделки, из-за которых позиция ушла ниже нуля."+ link: "Проверить активы"+ message: "Некоторые позиции ушли ниже нуля"+ sync_failed:+ message: "Последняя синхронизация не удалась"+ sync_hint: "Данные здесь могут быть устаревшими. Синхронизируйте снова, чтобы обновить их."+ sync_stale:+ message: "Последняя синхронизация не завершилась"show:activity:amount: Суммаdiff --git a/config/locales/views/accounts/tr.yml b/config/locales/views/accounts/tr.ymlindex 1910080e99..05d46ec82f 100644--- a/config/locales/views/accounts/tr.yml+++ b/config/locales/views/accounts/tr.yml@@ -96,6 +96,17 @@ tr:title: Bağlamak için bir sağlayıcı seçinset_default:depository_only: Yalnızca nakit ve kredi kartı hesapları varsayılan olarak ayarlanabilir.+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): %{date} tarihinden beri sıfırın altında, en düşük %{qty}"+ hint: "Muhtemelen bir alım veya transfer eksik. Ekleyin ya da pozisyonu sıfırın altına düşüren işlemleri düzeltin."+ link: "Varlıkları incele"+ message: "Bazı pozisyonlar sıfırın altına düştü"+ sync_failed:+ message: "Son senkronizasyon başarısız oldu"+ sync_hint: "Buradaki rakamlar güncel olmayabilir. Güncellemek için yeniden senkronize edin."+ sync_stale:+ message: "Son senkronizasyon tamamlanmadı"show:activity:amount: Tutardiff --git a/config/locales/views/accounts/uk.yml b/config/locales/views/accounts/uk.ymlindex af93f56bc5..ab053b7f3d 100644--- a/config/locales/views/accounts/uk.yml+++ b/config/locales/views/accounts/uk.yml@@ -78,6 +78,17 @@ uk:manual_entry: "Ввести баланс рахунку"title: "Як би ви хотіли його додати?"title: "Що б ви хотіли додати?"+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): нижче нуля з %{date}, мінімум %{qty}"+ hint: "Імовірно, бракує купівлі або переказу. Додайте її або виправте операції, через які позиція стала від'ємною."+ link: "Переглянути активи"+ message: "Деякі позиції стали від'ємними"+ sync_failed:+ message: "Остання синхронізація не вдалася"+ sync_hint: "Дані тут можуть бути застарілими. Синхронізуйте знову, щоб оновити їх."+ sync_stale:+ message: "Остання синхронізація не завершилася"show:limited_fx_history_warning: "Історія обмінних курсів доступна лише з %{date}. Транзакції до цієї дати використовують приблизні конвертації валют — це може статися, коли постачальник FX пропонує лише обмежене історичне вікно."tabs:diff --git a/config/locales/views/accounts/vi.yml b/config/locales/views/accounts/vi.ymlindex a8257c5024..4f83e0387f 100644--- a/config/locales/views/accounts/vi.yml+++ b/config/locales/views/accounts/vi.yml@@ -69,6 +69,17 @@ vi:manual_entry: Nhập số dư tài khoảntitle: Bạn muốn thêm bằng cách nào?title: Bạn muốn thêm gì?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}): dưới 0 từ %{date}, thấp nhất %{qty}"+ 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."+ link: "Xem lại danh mục nắm giữ"+ message: "Một số vị thế đã xuống dưới 0"+ sync_failed:+ message: "Lần đồng bộ gần nhất đã thất bại"+ sync_hint: "Số liệu ở đây có thể đã cũ. Hãy đồng bộ lại để cập nhật."+ sync_stale:+ message: "Lần đồng bộ gần nhất chưa hoàn tất"show:limited_fx_history_warning: "Lịch sử tỷ giá hối đoái chỉ khả dụng từ %{date} trở đi. Các giao dịch trước ngày này sử dụng chuyển đổi tiền tệ xấp xỉ."tabs:diff --git a/config/locales/views/accounts/zh-CN.yml b/config/locales/views/accounts/zh-CN.ymlindex ced4ab578a..f91672ce0d 100644--- a/config/locales/views/accounts/zh-CN.yml+++ b/config/locales/views/accounts/zh-CN.yml@@ -116,6 +116,17 @@ zh-CN:manual_entry: 手动输入账户余额title: 您希望如何添加?title: 您想添加什么?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}):自 %{date} 起低于零,最低 %{qty}"+ hint: "可能缺少一笔买入或转入。请补上,或更正使持仓低于零的交易。"+ link: "查看持仓"+ message: "部分持仓低于零"+ sync_failed:+ message: "上次同步失败"+ sync_hint: "此处的数据可能已过时。请重新同步以更新数据。"+ sync_stale:+ message: "上次同步未完成"show:limited_fx_history_warning: 汇率历史仅从 %{date} 起可用。该日期之前的交易将使用近似货币换算——当外汇提供商仅提供有限历史窗口时会出现这种情况。tabs:diff --git a/config/locales/views/accounts/zh-TW.yml b/config/locales/views/accounts/zh-TW.ymlindex 4115571599..4788639820 100644--- a/config/locales/views/accounts/zh-TW.yml+++ b/config/locales/views/accounts/zh-TW.yml@@ -76,6 +76,17 @@ zh-TW:manual_entry: 輸入帳戶餘額title: 您想如何新增?title: 您想新增什麼內容?+ health_status:+ negative_positions:+ detail: "%{name} (%{ticker}):自 %{date} 起低於零,最低 %{qty}"+ hint: "可能缺少一筆買入或轉入。請補上,或更正使持倉低於零的交易。"+ link: "檢視持股"+ message: "部分持倉低於零"+ sync_failed:+ message: "上次同步失敗"+ sync_hint: "此處的資料可能已過時。請重新同步以更新資料。"+ sync_stale:+ message: "上次同步未完成"show:limited_fx_history_warning: 匯率歷史只有 %{date}之後的資料。當匯率供應商只提供有限的歷史區間時,這個日期之前的交易會改用近似的匯率換算。tabs:diff --git a/config/locales/views/holdings/ca.yml b/config/locales/views/holdings/ca.ymlindex 8bcc372aed..b7bbb0ba80 100644--- a/config/locales/views/holdings/ca.yml+++ b/config/locales/views/holdings/ca.yml@@ -36,9 +36,6 @@ ca:holdings: Posicionsname: Nomnew_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 totalweight: Pesdiff --git a/config/locales/views/holdings/de.yml b/config/locales/views/holdings/de.ymlindex 23f7c816eb..bef1ee2f79 100644--- a/config/locales/views/holdings/de.yml+++ b/config/locales/views/holdings/de.yml@@ -42,9 +42,6 @@ de:holdings: Positionenname: Namenew_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 nullno_holdings: Keine Positionen vorhandenpositions:one: "%{count} Position"diff --git a/config/locales/views/holdings/en.yml b/config/locales/views/holdings/en.ymlindex 3ef2a9cecd..c6c9f862de 100644--- a/config/locales/views/holdings/en.yml+++ b/config/locales/views/holdings/en.yml@@ -46,9 +46,6 @@ en:holdings: Holdingsname: Namenew_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 zerono_holdings: No holdings to show.positions:one: "%{count} position"diff --git a/config/locales/views/holdings/es.yml b/config/locales/views/holdings/es.ymlindex 79a58547ea..3380bdd35f 100644--- a/config/locales/views/holdings/es.yml+++ b/config/locales/views/holdings/es.yml@@ -49,9 +49,6 @@ es:holdings: Posicionesname: Nombrenew_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 totalweight: Pesodiff --git a/config/locales/views/holdings/fr.yml b/config/locales/views/holdings/fr.ymlindex 19ce9aa670..439f864591 100644--- a/config/locales/views/holdings/fr.yml+++ b/config/locales/views/holdings/fr.yml@@ -36,9 +36,6 @@ fr:holdings: Holdingsname: Nomnew_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 totalweight: Poidsdiff --git a/config/locales/views/holdings/hu.yml b/config/locales/views/holdings/hu.ymlindex e1bef01f86..025ebcf4eb 100644--- a/config/locales/views/holdings/hu.yml+++ b/config/locales/views/holdings/hu.yml@@ -49,9 +49,6 @@ hu:holdings: Pozíciókname: Névnew_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 hozamweight: Súlydiff --git a/config/locales/views/holdings/id.yml b/config/locales/views/holdings/id.ymlindex a176a01846..fa9d1178e5 100644--- a/config/locales/views/holdings/id.yml+++ b/config/locales/views/holdings/id.yml@@ -46,9 +46,6 @@ id:holdings: Kepemilikanname: Namanew_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 nolno_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.ymlindex ea71a195d8..a800b80c01 100644--- a/config/locales/views/holdings/it.yml+++ b/config/locales/views/holdings/it.yml@@ -49,9 +49,6 @@ it:holdings: Portafoglioname: Nomenew_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 totaleweight: Pesodiff --git a/config/locales/views/holdings/nb.yml b/config/locales/views/holdings/nb.ymlindex ae1d496dac..66339a4d9b 100644--- a/config/locales/views/holdings/nb.yml+++ b/config/locales/views/holdings/nb.yml@@ -16,9 +16,6 @@ nb:holdings: Beholdningername: Navnnew_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 avkastningweight: Vektdiff --git a/config/locales/views/holdings/nl.yml b/config/locales/views/holdings/nl.ymlindex bd1f5fcf51..4b8f550036 100644--- a/config/locales/views/holdings/nl.yml+++ b/config/locales/views/holdings/nl.yml@@ -52,9 +52,6 @@ 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.ymlindex f8174412cd..2a8a2b723c 100644--- a/config/locales/views/holdings/pl.yml+++ b/config/locales/views/holdings/pl.yml@@ -34,9 +34,6 @@ pl:holdings: Pozycjename: Nazwanew_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.ymlindex 0018aac68a..86f79f47aa 100644--- a/config/locales/views/holdings/pt-BR.yml+++ b/config/locales/views/holdings/pt-BR.yml@@ -16,9 +16,6 @@ pt-BR:holdings: Posiçõesname: Nomenew_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 totalweight: Pesodiff --git a/config/locales/views/holdings/pt-PT.yml b/config/locales/views/holdings/pt-PT.ymlindex 8dda343980..73bdffe5cb 100644--- a/config/locales/views/holdings/pt-PT.yml+++ b/config/locales/views/holdings/pt-PT.yml@@ -46,9 +46,6 @@ pt-PT:holdings: Posiçõesname: Designaçãonew_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 totalweight: Pesodiff --git a/config/locales/views/holdings/ro.yml b/config/locales/views/holdings/ro.ymlindex 4c88428a50..f4fc26ec7b 100644--- a/config/locales/views/holdings/ro.yml+++ b/config/locales/views/holdings/ro.yml@@ -16,9 +16,6 @@ ro:holdings: Dețineriname: Numenew_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 totalweight: Ponderediff --git a/config/locales/views/holdings/ru.yml b/config/locales/views/holdings/ru.ymlindex 1ae59d8b92..b541a50268 100644--- a/config/locales/views/holdings/ru.yml+++ b/config/locales/views/holdings/ru.yml@@ -38,9 +38,6 @@ 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.ymlindex 5495913ba4..f00327145d 100644--- a/config/locales/views/holdings/tr.yml+++ b/config/locales/views/holdings/tr.yml@@ -36,9 +36,6 @@ tr:holdings: Varlıklarname: İsimnew_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 getiriweight: Ağırlıkdiff --git a/config/locales/views/holdings/uk.yml b/config/locales/views/holdings/uk.ymlindex 6e212c5ab1..ce78e0c032 100644--- a/config/locales/views/holdings/uk.yml+++ b/config/locales/views/holdings/uk.yml@@ -51,9 +51,6 @@ 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.ymlindex fa21cd2a3d..28891d70cf 100644--- a/config/locales/views/holdings/vi.yml+++ b/config/locales/views/holdings/vi.yml@@ -49,9 +49,6 @@ vi:holdings: Danh mục nắm giữname: Tênnew_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ậnweight: Tỷ trọngdiff --git a/config/locales/views/holdings/zh-CN.yml b/config/locales/views/holdings/zh-CN.ymlindex 2798eae8ce..d1ead336ea 100644--- a/config/locales/views/holdings/zh-CN.yml+++ b/config/locales/views/holdings/zh-CN.yml@@ -49,9 +49,6 @@ 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.ymlindex 0fbb5854ee..4e0aac9fa8 100644--- a/config/locales/views/holdings/zh-TW.yml+++ b/config/locales/views/holdings/zh-TW.yml@@ -49,9 +49,6 @@ 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/components/UI/account/health_status_test.rb b/test/components/UI/account/health_status_test.rbnew file mode 100644index 0000000000..9688bbaf36--- /dev/null+++ b/test/components/UI/account/health_status_test.rb@@ -0,0 +1,45 @@+require "test_helper"++class UI::Account::HealthStatusTest < ViewComponent::TestCase+ setup do+ @account = accounts(:investment)+ Current.session = sessions(:one)+ end++ teardown { Current.session = nil }++ test "renders nothing for a healthy account" do+ render_inline(UI::Account::HealthStatus.new(account: @account))++ assert_no_selector "[data-testid='account-health-status']"+ end++ test "renders each issue with its details and link" do+ @account.syncs.create!(status: :failed, failed_at: 1.hour.ago)+ @account.stubs(:negative_positions).returns([+ Account::NegativePosition.new(securities(:msft), 3.days.ago.to_date, -3)+ ])++ render_inline(UI::Account::HealthStatus.new(account: @account))++ assert_selector "[data-testid='account-health-status']"+ assert_text I18n.t("accounts.health_status.sync_failed.message")+ assert_text I18n.t("accounts.health_status.negative_positions.message")+ assert_selector ".privacy-sensitive", text: /Microsoft \(MSFT\)/+ assert_text I18n.t("accounts.health_status.negative_positions.hint")+ assert_link I18n.t("accounts.health_status.negative_positions.link"),+ href: Rails.application.routes.url_helpers.account_path(@account, tab: "holdings")+ assert_no_selector ".translation_missing"+ end++ test "formats each position's date and quantity the way the family sees them" do+ @account.family.update!(date_format: "%d.%m.%Y")+ @account.stubs(:negative_positions).returns([+ Account::NegativePosition.new(securities(:msft), Date.new(2026, 4, 10), BigDecimal("-1.5"))+ ])++ render_inline(UI::Account::HealthStatus.new(account: @account))++ assert_selector ".privacy-sensitive", exact_text: "Microsoft (MSFT): below zero from 10.04.2026, lowest -1.5"+ end+enddiff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex ae5bfe88a1..16d4ad1ce1 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -556,6 +556,49 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_response :successend+ test "show lists positions that went below zero in the account status" do+ account = accounts(:investment)+ # 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 account_url(account)++ assert_response :success+ assert_select "[data-testid='account-health-status']", text: /Microsoft \(MSFT\): below zero from/+ end++ test "show has no account status for a healthy account" do+ get account_url(@account)++ assert_response :success+ assert_select "[data-testid='account-health-status']", count: 0+ end++ test "a member who cannot open the account does not see its status" do+ account = accounts(:investment)+ account.syncs.create!(status: :failed, failed_at: 1.hour.ago)+ sign_in users(:family_member)++ get account_url(account)++ assert_response :not_found+ assert_not_includes response.body, I18n.t("accounts.health_status.sync_failed.message")+ end++ test "a member sees the status of an account shared with them" do+ @account.syncs.create!(status: :failed, failed_at: 1.hour.ago)+ sign_in users(:family_member)++ get account_url(@account)++ assert_response :success+ assert_select "[data-testid='account-health-status']", text: /#{I18n.t("accounts.health_status.sync_failed.message")}/+ end+test "show renders the scheduled balance tooltip when a scheduled transaction exists" docreate_transaction(account: @account, amount: 200, date: 3.days.from_now.to_date)diff --git a/test/controllers/holdings_controller_test.rb b/test/controllers/holdings_controller_test.rbindex 2453d00db4..39d23632ae 100644--- a/test/controllers/holdings_controller_test.rb+++ b/test/controllers/holdings_controller_test.rb@@ -38,28 +38,6 @@ class HoldingsControllerTest < ActionDispatch::IntegrationTestassert_equal trade_queries.first, trade_queries.lastend- 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" doget holding_path(@holding)diff --git a/test/i18n_test.rb b/test/i18n_test.rbindex 76a6706e48..5f3856b166 100644--- a/test/i18n_test.rb+++ b/test/i18n_test.rb@@ -145,11 +145,17 @@ class I18nTest < ActiveSupport::TestCaseassert_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+ # The account status speaks wherever the holdings tab is translated.+ def test_account_health_status_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+ accounts.health_status.negative_positions.detail+ accounts.health_status.negative_positions.hint+ accounts.health_status.negative_positions.link+ accounts.health_status.negative_positions.message+ accounts.health_status.sync_failed.message+ accounts.health_status.sync_hint+ accounts.health_status.sync_stale.message]}.each do |sibling, keys|locales = I18n.available_locales.select { |locale| I18n.t(sibling, locale: locale, fallback: false, default: nil) }diff --git a/test/models/account/health_status_test.rb b/test/models/account/health_status_test.rbnew file mode 100644index 0000000000..957d9e0a85--- /dev/null+++ b/test/models/account/health_status_test.rb@@ -0,0 +1,74 @@+require "test_helper"++class Account::HealthStatusTest < ActiveSupport::TestCase+ setup do+ @account = accounts(:investment)+ end++ test "a healthy account has no issues" do+ @account.syncs.create!(status: :completed, completed_at: 1.hour.ago)++ assert_empty Account::HealthStatus.new(@account).issues+ end++ test "a failed last sync is an error" do+ @account.syncs.create!(status: :failed, failed_at: 1.hour.ago, error: "Provider timeout")++ issue = Account::HealthStatus.new(@account).issues.sole++ assert_equal :error, issue.severity+ assert_equal I18n.t("accounts.health_status.sync_failed.message"), issue.message+ assert_nil issue.link+ end++ test "a stale last sync is a warning" do+ @account.syncs.create!(status: :stale, created_at: 2.days.ago)++ issue = Account::HealthStatus.new(@account).issues.sole++ assert_equal I18n.t("accounts.health_status.sync_stale.message"), issue.message+ assert_equal :warning, issue.severity+ end++ # Sync.clean marks it stale only after a day; the header stops showing it as+ # syncing after Sync::VISIBLE_FOR.+ test "a retry whose job was lost after a failure is a stale warning" do+ @account.syncs.create!(status: :failed, failed_at: 2.hours.ago, created_at: 2.hours.ago)+ @account.syncs.create!(status: :pending, created_at: Sync::VISIBLE_FOR.ago - 1.minute)++ issue = Account::HealthStatus.new(@account).issues.sole++ assert_equal I18n.t("accounts.health_status.sync_stale.message"), issue.message+ assert_equal :warning, issue.severity+ end++ test "a sync still running shows no issue" do+ @account.syncs.create!(status: :failed, failed_at: 2.hours.ago, created_at: 2.hours.ago)+ @account.syncs.create!(status: :syncing, created_at: 1.minute.ago)++ assert_empty Account::HealthStatus.new(@account).issues+ end++ test "a sync that went through after a failed one clears the issue" do+ @account.syncs.create!(status: :failed, failed_at: 2.hours.ago, created_at: 2.hours.ago)+ @account.syncs.create!(status: :completed, completed_at: 1.hour.ago, created_at: 1.hour.ago)++ assert_empty Account::HealthStatus.new(@account).issues+ end++ test "positions below zero list each security and link to the holdings tab" do+ @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++ issue = Account::HealthStatus.new(@account).issues.sole++ assert_equal :warning, issue.severity+ assert_equal I18n.t("accounts.health_status.negative_positions.message"), issue.message+ assert_equal [ Account::NegativePosition.new(securities(:msft), 3.days.ago.to_date, -3) ], issue.details+ assert_equal I18n.t("accounts.health_status.negative_positions.hint"), issue.hint+ assert_equal Rails.application.routes.url_helpers.account_path(@account, tab: "holdings"), issue.link[:href]+ end+enddiff --git a/test/models/account_test.rb b/test/models/account_test.rbindex 2069b06533..18acf83cce 100644--- a/test/models/account_test.rb+++ b/test/models/account_test.rb@@ -39,6 +39,13 @@ class AccountTest < ActiveSupport::TestCaseassert_empty account.negative_positionsend+ test "negative_positions skips the holdings query for an account without holdings" do+ account = accounts(:depository)+ account.expects(:holdings).never++ assert_empty account.negative_positions+ end+test "linked cash and investment accounts hide balance updates by default" doassert accounts(:connected).hides_balance_updates_by_default?