Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Refresh market data per family when clearing the data cache (#4474)

GFR055e1aa7c0d9
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb
index 53555d95f2..b176af2692 100644
--- a/app/controllers/settings/hostings_controller.rb
+++ b/app/controllers/settings/hostings_controller.rb
@@ -60,6 +60,7 @@ class Settings::HostingsController < ApplicationController
@rentcast_usage = Provider::Registry.get_provider(:rentcast)&.usage
@realie_usage = Provider::Registry.get_provider(:realie)&.usage
@chimnie_usage = Provider::Registry.get_provider(:chimnie)&.usage
+ @market_data_refreshable = market_data_provider_configured?
@terrascoutx_usage = Provider::Registry.get_provider(:terrascoutx)&.usage
load_external_assistant_models
@@ -571,4 +572,9 @@ class Settings::HostingsController < ApplicationController
def current_user_timezone
Current.family&.timezone.presence || "UTC"
end
+
+ # A cache clear can only reload rates and prices when a provider is configured
+ def market_data_provider_configured?
+ ExchangeRate.configured_provider.present? || Security.provider.present?
+ end
end
diff --git a/app/jobs/data_cache_clear_job.rb b/app/jobs/data_cache_clear_job.rb
index 045e1e1089..52752e393a 100644
--- a/app/jobs/data_cache_clear_job.rb
+++ b/app/jobs/data_cache_clear_job.rb
@@ -1,16 +1,43 @@
class DataCacheClearJob < ApplicationJob
queue_as :low_priority
+ SYNC_RETRY_WAIT = 1.minute
+
+ # Market data is refreshed before anything is deleted: the holdings decide
+ # which security prices are needed, and the account syncs must start with
+ # the refreshed exchange rates.
+ #
+ # A sync that is already running would have its freshly written balances
+ # deleted, and sync_later would only join it, so the job waits for it.
def perform(family)
- ActiveRecord::Base.transaction do
- ExchangeRate.delete_all
- Security::Price.delete_all
- family.accounts.each do |account|
- account.balances.delete_all
- account.holdings.delete_all
- end
+ return retry_later(family) if sync_running?(family)
+
+ Family::MarketDataRefresher.new(family).refresh
+
+ # The family and account locks keep sync_later from starting a sync
+ # between the check and the delete
+ family.with_lock do
+ family.accounts.order(:id).lock.pluck(:id)
+
+ if sync_running?(family)
+ retry_later(family)
+ else
+ Balance.where(account_id: family.accounts.select(:id)).delete_all
+ Holding.where(account_id: family.accounts.select(:id)).delete_all
- family.sync_later
+ family.sync_later
+ end
end
end
+
+ private
+ def sync_running?(family)
+ Sync.visible.where(syncable: family)
+ .or(Sync.visible.where(syncable_type: "Account", syncable_id: family.accounts.select(:id)))
+ .exists?
+ end
+
+ def retry_later(family)
+ self.class.set(wait: SYNC_RETRY_WAIT).perform_later(family)
+ end
end
diff --git a/app/models/account/market_data_importer.rb b/app/models/account/market_data_importer.rb
index 8dd606af02..a151e9281d 100644
--- a/app/models/account/market_data_importer.rb
+++ b/app/models/account/market_data_importer.rb
@@ -16,6 +16,19 @@ class Account::MarketDataImporter
return unless needs_exchange_rates?
return unless ExchangeRate.provider
+ exchange_rate_pair_dates.each do |(source, target), start_date|
+ ExchangeRate.import_provider_rates(
+ from: source,
+ to: target,
+ start_date: start_date,
+ end_date: Date.current
+ )
+ end
+ end
+
+ # The currency pairs this account converts through, each with the earliest
+ # date a rate is needed. Empty when the account needs no rates.
+ def exchange_rate_pair_dates
pair_dates = {}
family_currency = account.family.primary_currency_code
@@ -49,14 +62,7 @@ class Account::MarketDataImporter
pair_dates[key] = [ pair_dates[key], date ].compact.min
end
- pair_dates.each do |(source, target), start_date|
- ExchangeRate.import_provider_rates(
- from: source,
- to: target,
- start_date: start_date,
- end_date: Date.current
- )
- end
+ pair_dates
end
def import_security_prices
@@ -75,11 +81,11 @@ class Account::MarketDataImporter
end
end
- private
- def price_windows
- @price_windows ||= Security::Price::ImportWindows.new(account).to_h
- end
+ def price_windows
+ @price_windows ||= Security::Price::ImportWindows.new(account).to_h
+ end
+ private
def security_ids
price_windows.keys
end
diff --git a/app/models/exchange_rate/importer.rb b/app/models/exchange_rate/importer.rb
index 2a7667a23c..ef507477d4 100644
--- a/app/models/exchange_rate/importer.rb
+++ b/app/models/exchange_rate/importer.rb
@@ -59,9 +59,14 @@ class ExchangeRate::Importer
db_rate_value = db_rates[date]&.rate
provider_rate_value = provider_rates[date]&.rate
+ # A cache clear replaces the stored rates the provider covers, so the
+ # dates it skips carry its last rate forward rather than keep the old
+ # value. Stored history before the provider's first rate is kept.
+ replace_db_rate = clear_cache && earliest_valid_provider_date.present? && date >= earliest_valid_provider_date
+
chosen_rate = if provider_rate_value.present? && provider_rate_value.to_f > 0
provider_rate_value
- elsif db_rate_value.present? && db_rate_value.to_f > 0
+ elsif !replace_db_rate && db_rate_value.present? && db_rate_value.to_f > 0
db_rate_value
else
prev_rate_value
diff --git a/app/models/exchange_rate/provided.rb b/app/models/exchange_rate/provided.rb
index 4ce9f5b83a..a89db20407 100644
--- a/app/models/exchange_rate/provided.rb
+++ b/app/models/exchange_rate/provided.rb
@@ -6,6 +6,15 @@ module ExchangeRate::Provided
Provider::Registry.for_concept(:exchange_rates).get_provider(name.to_sym)
end
+ # Like provider, but nil instead of an error when no provider or an unknown one is set
+ def configured_provider
+ return if configured_provider_name.blank?
+
+ provider
+ rescue Provider::Registry::Error
+ nil
+ end
+
# Name of the backend `provider` uses. The default, Twelve Data, needs an API key;
# without one, use keyless Frankfurter rather than no provider, which would import
# no rates at all. Pair metadata and sync diagnostics key on this name, so
diff --git a/app/models/family/market_data_refresher.rb b/app/models/family/market_data_refresher.rb
new file mode 100644
index 0000000000..4c5e82cbd6
--- /dev/null
+++ b/app/models/family/market_data_refresher.rb
@@ -0,0 +1,76 @@
+# Downloads again the security prices and exchange rates a family's accounts
+# use, overwriting the stored values. Both are shared by every family on the
+# instance, so they are refreshed in place rather than deleted. Each security
+# and currency pair is fetched once, over the widest window any account needs.
+class Family::MarketDataRefresher
+ def initialize(family)
+ @family = family
+ end
+
+ # Prices come first: their currencies decide which exchange rates are needed.
+ def refresh
+ refresh_security_prices
+ refresh_exchange_rates
+ end
+
+ private
+ attr_reader :family
+
+ def importers
+ @importers ||= family.accounts.map { |account| Account::MarketDataImporter.new(account) }
+ end
+
+ def refresh_security_prices
+ return unless Security.provider
+
+ windows = importers.each_with_object({}) do |importer, merged|
+ importer.price_windows.each do |security_id, window|
+ merged[security_id] = window.merge(merged[security_id])
+ end
+ end
+ return if windows.empty?
+
+ Security.online.where(id: windows.keys).find_each do |security|
+ window = windows[security.id]
+ _, provider_error = security.import_provider_prices(start_date: window.start_date, end_date: window.end_date, clear_cache: true)
+ report_provider_error(provider_error, provider: security.price_data_provider, security_id: security.id) if provider_error.present?
+ security.import_provider_details
+ rescue => e
+ report_failure(e, provider: security.price_data_provider, security_id: security.id)
+ end
+ end
+
+ def refresh_exchange_rates
+ provider = ExchangeRate.configured_provider
+ return unless provider
+
+ pair_dates = importers.each_with_object({}) do |importer, merged|
+ importer.exchange_rate_pair_dates.each do |pair, start_date|
+ merged[pair] = [ merged[pair], start_date ].compact.min
+ end
+ end
+
+ pair_dates.each do |(from, to), start_date|
+ ExchangeRate.import_provider_rates(from: from, to: to, start_date: start_date, end_date: Date.current, clear_cache: true)
+ rescue => e
+ report_failure(e, provider: provider, from_currency: from, to_currency: to)
+ end
+ end
+
+ def report_failure(error, provider:, **metadata)
+ Sentry.capture_exception(error)
+ report_provider_error("#{error.class}: #{error.message}", provider: provider, **metadata)
+ end
+
+ def report_provider_error(error_message, provider:, **metadata)
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Could not refresh market data: #{error_message}",
+ source: self.class.name,
+ family: family,
+ provider: provider,
+ metadata: metadata
+ )
+ end
+end
diff --git a/app/models/market_data_importer.rb b/app/models/market_data_importer.rb
index 03cf7ee777..b507d80c03 100644
--- a/app/models/market_data_importer.rb
+++ b/app/models/market_data_importer.rb
@@ -75,15 +75,7 @@ class MarketDataImporter
accounts_with_securities.find_each do |account|
Security::Price::ImportWindows.new(account, today: end_date).to_h.each do |security_id, window|
- previous = windows[security_id]
- windows[security_id] = if previous
- Security::Price::ImportWindows::Window.new(
- start_date: [ previous.start_date, window.start_date ].min,
- end_date: [ previous.end_date, window.end_date ].max
- )
- else
- window
- end
+ windows[security_id] = window.merge(windows[security_id])
end
end
diff --git a/app/models/security/price/import_windows.rb b/app/models/security/price/import_windows.rb
index 49ff0de409..1cf9a70b0e 100644
--- a/app/models/security/price/import_windows.rb
+++ b/app/models/security/price/import_windows.rb
@@ -1,5 +1,11 @@
class Security::Price::ImportWindows
- Window = Data.define(:start_date, :end_date)
+ Window = Data.define(:start_date, :end_date) do
+ def merge(other)
+ return self if other.nil?
+
+ with(start_date: [ start_date, other.start_date ].min, end_date: [ end_date, other.end_date ].max)
+ end
+ end
def initialize(account, today: Date.current)
@account = account
diff --git a/app/models/security/price/importer.rb b/app/models/security/price/importer.rb
index 082ef0262c..ebe93ee6b6 100644
--- a/app/models/security/price/importer.rb
+++ b/app/models/security/price/importer.rb
@@ -40,15 +40,15 @@ class Security::Price::Importer
# than backfilled from a future price.
advanced_first_price_on = nil
- if prev_price_value.blank?
- # Filter for valid rows BEFORE picking the earliest — otherwise a
- # single listing-day / halt-day row with a nil or zero price would
- # cause us to fall through to the MissingStartPriceError bail even
- # when plenty of valid prices exist later in the window.
- earliest_provider_price = provider_prices.values
- .select { |p| p.price.present? && p.price.to_f > 0 }
- .min_by(&:date)
+ # Filter for valid rows BEFORE picking the earliest — otherwise a
+ # single listing-day / halt-day row with a nil or zero price would
+ # cause us to fall through to the MissingStartPriceError bail even
+ # when plenty of valid prices exist later in the window.
+ earliest_provider_price = provider_prices.values
+ .select { |p| p.price.present? && p.price.to_f > 0 }
+ .min_by(&:date)
+ if prev_price_value.blank?
if earliest_provider_price
Rails.logger.info(
"#{security.ticker}: no provider price on or before #{start_date}; " \
@@ -87,7 +87,11 @@ class Security::Price::Importer
is_provisional = db_price&.provisional
# Choose price and currency from the same source to avoid mismatches
- chosen_price, chosen_currency = if clear_cache || is_provisional
+ # A cache clear replaces only the stored prices the provider covers;
+ # stored history before its first price is kept.
+ replace_db_price = clear_cache && earliest_provider_price.present? && date >= earliest_provider_price.date
+
+ chosen_price, chosen_currency = if replace_db_price || is_provisional
# For provisional/cache clear: only use provider price, let gap-fill handle missing
# This ensures stale DB values don't persist when provider has no weekend data
[ provider_price_value, provider_currency ]
diff --git a/app/views/settings/hostings/_danger_zone_settings.html.erb b/app/views/settings/hostings/_danger_zone_settings.html.erb
index d3b3a2212f..a0f289d779 100644
--- a/app/views/settings/hostings/_danger_zone_settings.html.erb
+++ b/app/views/settings/hostings/_danger_zone_settings.html.erb
@@ -1,16 +1,23 @@
<% if Current.user.admin? %>
+ <% if @market_data_refreshable %>
+ <% warning = t("settings.hostings.show.clear_cache_warning") %>
+ <% confirm_body = t("settings.hostings.show.confirm_clear_cache.body") %>
+ <% else %>
+ <% warning = t("settings.hostings.show.clear_cache_warning_without_provider") %>
+ <% confirm_body = t("settings.hostings.show.confirm_clear_cache.body_without_provider") %>
+ <% end %>
<div class="space-y-4">
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div class="w-full md:w-2/3">
<h3 class="font-medium text-primary"><%= t("settings.hostings.show.clear_cache") %></h3>
- <p class="text-secondary text-sm"><%= t("settings.hostings.show.clear_cache_warning") %></p>
+ <p class="text-secondary text-sm"><%= warning %></p>
</div>
<%=
button_to t("settings.hostings.show.clear_cache"), clear_cache_settings_hosting_path, method: :delete,
class: "w-full md:w-auto bg-yellow-600 text-inverse text-sm font-medium rounded-lg px-4 py-2",
data: { turbo_confirm: {
title: t("settings.hostings.show.confirm_clear_cache.title"),
- body: t("settings.hostings.show.confirm_clear_cache.body"),
+ body: confirm_body,
accept: t("settings.hostings.show.clear_cache"),
acceptClass: "w-full bg-yellow-600 text-inverse rounded-xl text-center p-[10px] border mb-2"
}}
diff --git a/config/locales/views/settings/hostings/ca.yml b/config/locales/views/settings/hostings/ca.yml
index 612d022be2..e6bdcf6a9f 100644
--- a/config/locales/views/settings/hostings/ca.yml
+++ b/config/locales/views/settings/hostings/ca.yml
@@ -148,10 +148,11 @@ ca:
show:
ai_assistant: Assistent d'IA
clear_cache: Neteja la memòria cau de dades
- clear_cache_warning: Netejar la memòria cau de dades eliminarà tots els tipus de canvi, preus de valors, saldos de comptes i altres dades. Això no eliminarà comptes, transaccions, categories ni altres dades de l'usuari.
+ clear_cache_warning: "Netejar la memòria cau de dades recalcula els saldos i les posicions dels comptes de la teva família i torna a carregar els tipus de canvi i els preus dels valors que utilitzen. Només s'eliminen els saldos i les posicions de la teva família; els tipus de canvi i els preus dels valors es comparteixen amb les altres famílies d'aquesta instància i també s'actualitzen per a elles. Això no eliminarà comptes, transaccions, categories ni altres dades dels usuaris."
confirm_clear_cache:
- body: Segur que vols netejar la memòria cau de dades? Això eliminarà tots els tipus de canvi, preus de valors, saldos de comptes i altres dades. Aquesta acció no es pot desfer.
+ body: "Segur que vols netejar la memòria cau de dades? Es recalcularan els saldos i les posicions dels comptes de la teva família i es tornaran a carregar els tipus de canvi i els preus dels valors que utilitzen. Només s'eliminen els saldos i les posicions de la teva família; els tipus de canvi i els preus dels valors es comparteixen amb les altres famílies d'aquesta instància i també s'actualitzen per a elles. Aquesta acció no es pot desfer."
title: Vols netejar la memòria cau de dades?
+ body_without_provider: "Segur que vols netejar la memòria cau de dades? Es recalcularan els saldos i les posicions dels comptes de la teva família. No hi ha cap proveïdor de tipus de canvi ni de preus de valors configurat, de manera que es conserven els tipus de canvi i els preus desats. Aquesta acció no es pot desfer."
danger_zone: Zona perillosa
financial_data_providers: Proveïdors de dades financeres
general: Configuració general
@@ -159,6 +160,7 @@ ca:
sync_settings: Configuració de sincronització
title: Self hosting
property_valuation_providers: Proveïdors de valoració d'immobles
+ clear_cache_warning_without_provider: "Netejar la memòria cau de dades recalcula els saldos i les posicions dels comptes de la teva família. No hi ha cap proveïdor de tipus de canvi ni de preus de valors configurat, de manera que es conserven els tipus de canvi i els preus desats. Això no eliminarà comptes, transaccions, categories ni altres dades dels usuaris."
sync_auto_sync_scheduler!:
scheduler_sync_failed: La configuració s'ha desat, però no s'ha pogut actualitzar la planificació de sincronització. Torna-ho a provar o revisa els registres del servidor.
sync_settings:
diff --git a/config/locales/views/settings/hostings/de.yml b/config/locales/views/settings/hostings/de.yml
index 281d1a7234..5ffef42abd 100644
--- a/config/locales/views/settings/hostings/de.yml
+++ b/config/locales/views/settings/hostings/de.yml
@@ -32,10 +32,12 @@ de:
danger_zone: Gefahrenbereich
instance_settings_restricted: Anbieter-Zugangsdaten, die gemeinsame KI-Verbindung und Synchronisierungseinstellungen gelten für alle Familien dieser Instanz und können daher nur von einem Super-Admin geändert werden. Welchen Assistenten deine Familie nutzt, wird weiterhin pro Familie festgelegt. Wer Zugriff auf den Server hat, kann einen Benutzer zum Super-Admin machen; den Befehl nennt die Docker-Self-Hosting-Anleitung in ihren Upgrade-Hinweisen.
clear_cache: Daten-Cache leeren
- clear_cache_warning: Das Leeren des Daten-Caches entfernt alle Wechselkurse, Wertpapierpreise, Kontostände und andere zwischengespeicherte Daten. Dies löscht keine Konten, Transaktionen, Kategorien oder andere benutzereigenen Daten.
+ clear_cache_warning: "Das Leeren des Daten-Caches berechnet die Kontostände und Bestände deiner Familie neu und lädt die dafür verwendeten Wechselkurse und Wertpapierpreise neu. Gelöscht werden nur die Kontostände und Bestände deiner Familie; Wechselkurse und Wertpapierpreise teilen sich alle Familien dieser Instanz und werden auch für sie aktualisiert. Dies löscht keine Konten, Transaktionen, Kategorien oder andere benutzereigenen Daten."
+ clear_cache_warning_without_provider: "Das Leeren des Daten-Caches berechnet die Kontostände und Bestände deiner Familie neu. Es ist kein Anbieter für Wechselkurse oder Wertpapierpreise eingerichtet, daher bleiben die gespeicherten Wechselkurse und Wertpapierpreise erhalten. Dies löscht keine Konten, Transaktionen, Kategorien oder andere benutzereigenen Daten."
confirm_clear_cache:
title: Daten-Cache leeren?
- body: Bist du sicher, dass du den Daten-Cache leeren möchtest? Dadurch werden alle Wechselkurse, Wertpapierpreise, Kontostände und andere Daten entfernt. Diese Aktion kann nicht rückgängig gemacht werden.
+ body: "Bist du sicher, dass du den Daten-Cache leeren möchtest? Die Kontostände und Bestände deiner Familie werden neu berechnet und die dafür verwendeten Wechselkurse und Wertpapierpreise neu geladen. Gelöscht werden nur die Kontostände und Bestände deiner Familie; Wechselkurse und Wertpapierpreise teilen sich alle Familien dieser Instanz und werden auch für sie aktualisiert. Diese Aktion kann nicht rückgängig gemacht werden."
+ body_without_provider: "Bist du sicher, dass du den Daten-Cache leeren möchtest? Die Kontostände und Bestände deiner Familie werden neu berechnet. Es ist kein Anbieter für Wechselkurse oder Wertpapierpreise eingerichtet, daher bleiben die gespeicherten Wechselkurse und Wertpapierpreise erhalten. Diese Aktion kann nicht rückgängig gemacht werden."
reset_market_data: Marktdaten für alle Familien zurücksetzen
reset_market_data_warning: Löscht die Wechselkurse und Wertpapierpreise, die deine Anbieter neu laden können, lädt sie neu und synchronisiert danach jedes Konto. Bis der Import fertig ist, werden Fremdwährungsbeträge eventuell unumgerechnet angezeigt.
confirm_reset_market_data:
diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml
index f00fe3933e..7574d0d262 100644
--- a/config/locales/views/settings/hostings/en.yml
+++ b/config/locales/views/settings/hostings/en.yml
@@ -35,10 +35,12 @@ en:
danger_zone: Danger Zone
instance_settings_restricted: Provider credentials, the shared AI connection and sync settings apply to every family on this instance, so only a super admin can change them. Which assistant your family uses is still set per family. Someone with access to the server can promote a user to super admin; the Docker self-hosting guide shows the command in its upgrade notes.
clear_cache: Clear data cache
- clear_cache_warning: Clearing the data cache will remove all exchange rates, security prices, account balances, and other data. This will not delete accounts, transactions, categories, or other user-owned data.
+ clear_cache_warning: "Clearing the data cache recalculates your family's account balances and holdings and reloads the exchange rates and security prices they use. Only your family's balances and holdings are deleted; exchange rates and security prices are shared with the other families on this instance and are updated for them too. This will not delete accounts, transactions, categories, or other user-owned data."
+ clear_cache_warning_without_provider: "Clearing the data cache recalculates your family's account balances and holdings. No exchange rate or security price provider is configured, so the stored exchange rates and security prices are kept. This will not delete accounts, transactions, categories, or other user-owned data."
confirm_clear_cache:
title: Clear data cache?
- body: Are you sure you want to clear the data cache? This will remove all exchange rates, security prices, account balances, and other data. This action cannot be undone.
+ body: "Are you sure you want to clear the data cache? Your family's account balances and holdings will be recalculated, and the exchange rates and security prices they use will be reloaded. Only your family's balances and holdings are deleted; exchange rates and security prices are shared with the other families on this instance and are updated for them too. This action cannot be undone."
+ body_without_provider: "Are you sure you want to clear the data cache? Your family's account balances and holdings will be recalculated. No exchange rate or security price provider is configured, so the stored exchange rates and security prices are kept. This action cannot be undone."
reset_market_data: Reset market data for all families
reset_market_data_warning: Deletes the exchange rates and security prices your providers can load again, re-imports them, and then syncs every account. Foreign-currency totals may show unconverted until the import finishes.
confirm_reset_market_data:
diff --git a/config/locales/views/settings/hostings/es.yml b/config/locales/views/settings/hostings/es.yml
index 0d06811958..1a4ad2be34 100644
--- a/config/locales/views/settings/hostings/es.yml
+++ b/config/locales/views/settings/hostings/es.yml
@@ -34,10 +34,12 @@ es:
danger_zone: Zona de Peligro
instance_settings_restricted: Las credenciales de proveedores, la conexión de IA compartida y la configuración de sincronización se aplican a todas las familias de esta instancia, así que solo un superadministrador puede cambiarlas. El asistente que usa tu familia se sigue eligiendo por familia. Alguien con acceso al servidor puede convertir a un usuario en superadministrador; la guía de autoalojamiento con Docker muestra el comando en sus notas de actualización.
clear_cache: Limpiar caché de datos
- clear_cache_warning: Limpiar la caché de datos eliminará todos los tipos de cambio, precios de valores, saldos de cuentas y otros datos temporales. Esto no eliminará cuentas, transacciones, categorías ni otros datos del usuario.
+ clear_cache_warning: "Limpiar la caché de datos recalcula los saldos y las posiciones de las cuentas de tu familia y vuelve a cargar los tipos de cambio y los precios de valores que utilizan. Solo se eliminan los saldos y las posiciones de tu familia; los tipos de cambio y los precios de valores se comparten con las demás familias de esta instancia y también se actualizan para ellas. Esto no eliminará cuentas, transacciones, categorías ni otros datos del usuario."
+ clear_cache_warning_without_provider: "Limpiar la caché de datos recalcula los saldos y las posiciones de las cuentas de tu familia. No hay ningún proveedor de tipos de cambio ni de precios de valores configurado, por lo que se conservan los tipos de cambio y los precios guardados. Esto no eliminará cuentas, transacciones, categorías ni otros datos del usuario."
confirm_clear_cache:
title: ¿Limpiar caché de datos?
- body: ¿Estás seguro de que deseas limpiar la caché de datos? Se eliminarán tipos de cambio, precios y saldos históricos. Esta acción no se puede deshacer.
+ body: "¿Estás seguro de que deseas limpiar la caché de datos? Se recalcularán los saldos y las posiciones de las cuentas de tu familia y se volverán a cargar los tipos de cambio y los precios de valores que utilizan. Solo se eliminan los saldos y las posiciones de tu familia; los tipos de cambio y los precios de valores se comparten con las demás familias de esta instancia y también se actualizan para ellas. Esta acción no se puede deshacer."
+ body_without_provider: "¿Estás seguro de que deseas limpiar la caché de datos? Se recalcularán los saldos y las posiciones de las cuentas de tu familia. No hay ningún proveedor de tipos de cambio ni de precios de valores configurado, por lo que se conservan los tipos de cambio y los precios guardados. Esta acción no se puede deshacer."
reset_market_data: Restablecer los datos de mercado de todas las familias
reset_market_data_warning: Elimina los tipos de cambio y los precios de valores que tus proveedores pueden volver a cargar, los vuelve a importar y después sincroniza todas las cuentas. Los totales en moneda extranjera pueden aparecer sin convertir hasta que termine la importación.
confirm_reset_market_data:
diff --git a/config/locales/views/settings/hostings/fr.yml b/config/locales/views/settings/hostings/fr.yml
index 40e0f0c25f..590dedfb2a 100644
--- a/config/locales/views/settings/hostings/fr.yml
+++ b/config/locales/views/settings/hostings/fr.yml
@@ -264,9 +264,11 @@ fr:
show:
ai_assistant: Assistant IA
clear_cache: Effacer le cache de données
- clear_cache_warning: L'effacement du cache de données supprimera tous les taux de change, les cours des titres, les soldes des comptes et d'autres données. Cela ne supprimera pas les comptes, les transactions, les catégories ou d'autres données possédées par les utilisateurs.
+ clear_cache_warning: "L'effacement du cache de données recalcule les soldes et les positions des comptes de votre famille et recharge les taux de change et les cours des titres qu'ils utilisent. Seuls les soldes et les positions de votre famille sont supprimés ; les taux de change et les cours des titres sont partagés avec les autres familles de cette instance et sont aussi mis à jour pour elles. Cela ne supprimera pas les comptes, les transactions, les catégories ou d'autres données possédées par les utilisateurs."
+ clear_cache_warning_without_provider: "L'effacement du cache de données recalcule les soldes et les positions des comptes de votre famille. Aucun fournisseur de taux de change ou de cours des titres n'est configuré, les taux de change et les cours enregistrés sont donc conservés. Cela ne supprimera pas les comptes, les transactions, les catégories ou d'autres données possédées par les utilisateurs."
confirm_clear_cache:
- body: Êtes-vous sûr(e) de vouloir effacer le cache de données ? Cela supprimera tous les taux de change, les cours des titres, les soldes des comptes et d'autres données. Cette action ne peut pas être annulée.
+ body: "Êtes-vous sûr(e) de vouloir effacer le cache de données ? Les soldes et les positions des comptes de votre famille seront recalculés, et les taux de change et les cours des titres qu'ils utilisent seront rechargés. Seuls les soldes et les positions de votre famille sont supprimés ; les taux de change et les cours des titres sont partagés avec les autres familles de cette instance et sont aussi mis à jour pour elles. Cette action ne peut pas être annulée."
+ body_without_provider: "Êtes-vous sûr(e) de vouloir effacer le cache de données ? Les soldes et les positions des comptes de votre famille seront recalculés. Aucun fournisseur de taux de change ou de cours des titres n'est configuré, les taux de change et les cours enregistrés sont donc conservés. Cette action ne peut pas être annulée."
title: Effacer le cache de données ?
danger_zone: Zone dangereuse
demo_refresh: Actualisation des données de démo
diff --git a/config/locales/views/settings/hostings/hu.yml b/config/locales/views/settings/hostings/hu.yml
index 9d7f87fa38..a88393ba53 100644
--- a/config/locales/views/settings/hostings/hu.yml
+++ b/config/locales/views/settings/hostings/hu.yml
@@ -26,10 +26,12 @@ hu:
title: Lokális futtatás
danger_zone: Veszélyzóna
clear_cache: Adatcache törlése
- clear_cache_warning: Az adatcache törlésével eltávolítod az összes árfolyamot, értékpapír-árat, fiókegyenleget és egyéb adatot. Ez nem törli a fiókokat, tranzakciókat, kategóriákat és egyéb felhasználói adatokat.
+ clear_cache_warning: "Az adatcache törlése újraszámolja a családod fiókjainak egyenlegeit és pozícióit, és újratölti az általuk használt árfolyamokat és értékpapír-árakat. Csak a családod egyenlegei és pozíciói törlődnek; az árfolyamokon és értékpapír-árakon a példány összes családja osztozik, így náluk is frissülnek. Ez nem törli a fiókokat, tranzakciókat, kategóriákat és egyéb felhasználói adatokat."
+ clear_cache_warning_without_provider: "Az adatcache törlése újraszámolja a családod fiókjainak egyenlegeit és pozícióit. Nincs beállítva árfolyam- vagy értékpapírár-szolgáltató, ezért a tárolt árfolyamok és értékpapír-árak megmaradnak. Ez nem törli a fiókokat, tranzakciókat, kategóriákat és egyéb felhasználói adatokat."
confirm_clear_cache:
title: Törli az adatcache-t?
- body: Biztosan törölni szeretnéd az adatcache-t? Ez eltávolítja az összes árfolyamot, értékpapír-árat, fiókegyenleget és egyéb adatot. Ez a művelet nem vonható vissza.
+ body: "Biztosan törölni szeretnéd az adatcache-t? A családod fiókjainak egyenlegei és pozíciói újraszámolódnak, az általuk használt árfolyamok és értékpapír-árak pedig újratöltődnek. Csak a családod egyenlegei és pozíciói törlődnek; az árfolyamokon és értékpapír-árakon a példány összes családja osztozik, így náluk is frissülnek. Ez a művelet nem vonható vissza."
+ body_without_provider: "Biztosan törölni szeretnéd az adatcache-t? A családod fiókjainak egyenlegei és pozíciói újraszámolódnak. Nincs beállítva árfolyam- vagy értékpapírár-szolgáltató, ezért a tárolt árfolyamok és értékpapír-árak megmaradnak. Ez a művelet nem vonható vissza."
provider_selection:
exchange_rate_title: Árfolyam-szolgáltató
exchange_rate_description: Válassz egyetlen szolgáltatót az árfolyamok lekéréséhez.
diff --git a/config/locales/views/settings/hostings/it.yml b/config/locales/views/settings/hostings/it.yml
index dbf7338af5..511ad9f95f 100644
--- a/config/locales/views/settings/hostings/it.yml
+++ b/config/locales/views/settings/hostings/it.yml
@@ -25,10 +25,12 @@ it:
title: Self-Hosting
danger_zone: Zona pericolosa
clear_cache: Svuota cache dati
- clear_cache_warning: Svuotare la cache dei dati rimuoverà tutti i tassi di cambio, i prezzi dei titoli, i saldi dei conti e altri dati. Questo non eliminerà conti, transazioni, categorie o altri dati degli utenti.
+ clear_cache_warning: "Svuotare la cache dei dati ricalcola i saldi e le posizioni dei conti della tua famiglia e ricarica i tassi di cambio e i prezzi dei titoli che utilizzano. Vengono eliminati solo i saldi e le posizioni della tua famiglia; i tassi di cambio e i prezzi dei titoli sono condivisi con le altre famiglie di questa istanza e vengono aggiornati anche per loro. Questo non eliminerà conti, transazioni, categorie o altri dati degli utenti."
+ clear_cache_warning_without_provider: "Svuotare la cache dei dati ricalcola i saldi e le posizioni dei conti della tua famiglia. Non è configurato alcun fornitore di tassi di cambio o di prezzi dei titoli, quindi i tassi di cambio e i prezzi salvati vengono mantenuti. Questo non eliminerà conti, transazioni, categorie o altri dati degli utenti."
confirm_clear_cache:
title: Svuotare la cache dei dati?
- body: Sei sicuro di voler svuotare la cache dei dati? Questo rimuoverà tutti i tassi di cambio, i prezzi dei titoli, i saldi dei conti e altri dati. Questa azione non può essere annullata.
+ body: "Sei sicuro di voler svuotare la cache dei dati? I saldi e le posizioni dei conti della tua famiglia verranno ricalcolati e i tassi di cambio e i prezzi dei titoli che utilizzano verranno ricaricati. Vengono eliminati solo i saldi e le posizioni della tua famiglia; i tassi di cambio e i prezzi dei titoli sono condivisi con le altre famiglie di questa istanza e vengono aggiornati anche per loro. Questa azione non può essere annullata."
+ body_without_provider: "Sei sicuro di voler svuotare la cache dei dati? I saldi e le posizioni dei conti della tua famiglia verranno ricalcolati. Non è configurato alcun fornitore di tassi di cambio o di prezzi dei titoli, quindi i tassi di cambio e i prezzi salvati vengono mantenuti. Questa azione non può essere annullata."
provider_selection:
exchange_rate_title: Provider tasso di cambio
exchange_rate_description: Seleziona un singolo provider per recuperare i tassi di cambio.
diff --git a/config/locales/views/settings/hostings/nb.yml b/config/locales/views/settings/hostings/nb.yml
index 800dc5eab3..51f6d5ffa6 100644
--- a/config/locales/views/settings/hostings/nb.yml
+++ b/config/locales/views/settings/hostings/nb.yml
@@ -21,10 +21,12 @@ nb:
title: Selvhosting
danger_zone: Fareområde
clear_cache: Tøm cache
- clear_cache_warning: Tømming av cache vil fjerne alle valutakurser, verdipapirpriser, kontobalanser og andre data. Dette vil ikke slette kontoer, transaksjoner, kategorier eller andre bruker-eide data.
+ clear_cache_warning: "Tømming av cache beregner kontobalansene og beholdningene til familien din på nytt og laster inn valutakursene og verdipapirprisene de bruker på nytt. Bare familiens balanser og beholdninger slettes; valutakurser og verdipapirpriser deles med de andre familiene på denne instansen og oppdateres også for dem. Dette vil ikke slette kontoer, transaksjoner, kategorier eller andre bruker-eide data."
+ clear_cache_warning_without_provider: "Tømming av cache beregner kontobalansene og beholdningene til familien din på nytt. Ingen leverandør av valutakurser eller verdipapirpriser er konfigurert, så de lagrede valutakursene og verdipapirprisene beholdes. Dette vil ikke slette kontoer, transaksjoner, kategorier eller andre bruker-eide data."
confirm_clear_cache:
title: Tøm cache?
- body: Er du sikker på at du vil tømme cache? Dette vil fjerne alle valutakurser, verdipapirpriser, kontobalanser og andre data. Denne handlingen kan ikke angres.
+ body: "Er du sikker på at du vil tømme cache? Kontobalansene og beholdningene til familien din beregnes på nytt, og valutakursene og verdipapirprisene de bruker lastes inn på nytt. Bare familiens balanser og beholdninger slettes; valutakurser og verdipapirpriser deles med de andre familiene på denne instansen og oppdateres også for dem. Denne handlingen kan ikke angres."
+ body_without_provider: "Er du sikker på at du vil tømme cache? Kontobalansene og beholdningene til familien din beregnes på nytt. Ingen leverandør av valutakurser eller verdipapirpriser er konfigurert, så de lagrede valutakursene og verdipapirprisene beholdes. Denne handlingen kan ikke angres."
update:
failure: Ugyldig innstillingsverdi
success: Innstillinger oppdatert
diff --git a/config/locales/views/settings/hostings/nl.yml b/config/locales/views/settings/hostings/nl.yml
index bc71a094bb..11b1daa6c2 100644
--- a/config/locales/views/settings/hostings/nl.yml
+++ b/config/locales/views/settings/hostings/nl.yml
@@ -34,10 +34,12 @@ nl:
danger_zone: "Gevarenzone"
instance_settings_restricted: "Inloggegevens van providers, de gedeelde AI-koppeling en synchronisatie-instellingen gelden voor elk huishouden op deze instantie, dus alleen een superbeheerder kan ze wijzigen. Welke assistent uw huishouden gebruikt, wordt nog steeds per huishouden ingesteld. Iemand met toegang tot de server kan een gebruiker tot superbeheerder maken; de handleiding voor zelfhosting met Docker toont de opdracht in de upgrade-opmerkingen."
clear_cache: "Datacache wissen"
- clear_cache_warning: "Het wissen van de datacache verwijdert alle wisselkoersen, effectenprijzen, accountsaldo's en andere gegevens. Dit verwijdert geen accounts, transacties, categorieën of andere gegevens van gebruikers."
+ clear_cache_warning: "Het wissen van de datacache berekent de saldo's en posities van de accounts van je familie opnieuw en laadt de wisselkoersen en effectenprijzen die ze gebruiken opnieuw. Alleen de saldo's en posities van je familie worden verwijderd; wisselkoersen en effectenprijzen worden gedeeld met de andere families op deze instantie en worden ook voor hen bijgewerkt. Dit verwijdert geen accounts, transacties, categorieën of andere gegevens van gebruikers."
confirm_clear_cache:
title: "Datacache wissen?"
- body: "Weet u zeker dat u de datacache wilt wissen? Dit verwijdert alle wisselkoersen, effectenprijzen, accountsaldo's en andere gegevens. Deze actie kan niet ongedaan worden gemaakt."
+ body: "Weet u zeker dat u de datacache wilt wissen? De saldo's en posities van de accounts van uw familie worden opnieuw berekend en de wisselkoersen en effectenprijzen die ze gebruiken worden opnieuw geladen. Alleen de saldo's en posities van uw familie worden verwijderd; wisselkoersen en effectenprijzen worden gedeeld met de andere families op deze instantie en worden ook voor hen bijgewerkt. Deze actie kan niet ongedaan worden gemaakt."
+ body_without_provider: "Weet u zeker dat u de datacache wilt wissen? De saldo's en posities van de accounts van uw familie worden opnieuw berekend. Er is geen aanbieder van wisselkoersen of effectenprijzen ingesteld, dus de opgeslagen wisselkoersen en effectenprijzen blijven behouden. Deze actie kan niet ongedaan worden gemaakt."
+ clear_cache_warning_without_provider: "Het wissen van de datacache berekent de saldo's en posities van de accounts van je familie opnieuw. Er is geen aanbieder van wisselkoersen of effectenprijzen ingesteld, dus de opgeslagen wisselkoersen en effectenprijzen blijven behouden. Dit verwijdert geen accounts, transacties, categorieën of andere gegevens van gebruikers."
provider_selection:
exchange_rate_title: "Wisselkoersprovider"
exchange_rate_description: "Selecteer één provider voor het ophalen van wisselkoersen."
diff --git a/config/locales/views/settings/hostings/pl.yml b/config/locales/views/settings/hostings/pl.yml
index 98dbb3a799..f6b8231bf3 100644
--- a/config/locales/views/settings/hostings/pl.yml
+++ b/config/locales/views/settings/hostings/pl.yml
@@ -300,13 +300,11 @@ pl:
show:
ai_assistant: Asystent AI
clear_cache: Wyczyść pamięć podręczną danych
- clear_cache_warning: Wyczyszczenie pamięci podręcznej danych usunie wszystkie
- kursy walut, ceny papierów wartościowych, salda kont i inne dane. Nie usunie
- to kont, transakcji, kategorii ani innych danych należących do użytkownika.
+ clear_cache_warning: "Wyczyszczenie pamięci podręcznej danych przelicza ponownie salda i pozycje kont Twojej rodziny oraz ponownie pobiera używane przez nie kursy walut i ceny papierów wartościowych. Usuwane są tylko salda i pozycje Twojej rodziny; kursy walut i ceny papierów wartościowych są wspólne dla wszystkich rodzin w tej instancji i zostaną zaktualizowane także dla nich. Nie usunie to kont, transakcji, kategorii ani innych danych użytkowników."
+ clear_cache_warning_without_provider: "Wyczyszczenie pamięci podręcznej danych przelicza ponownie salda i pozycje kont Twojej rodziny. Nie skonfigurowano dostawcy kursów walut ani cen papierów wartościowych, więc zapisane kursy walut i ceny pozostają bez zmian. Nie usunie to kont, transakcji, kategorii ani innych danych użytkowników."
confirm_clear_cache:
- body: Czy na pewno chcesz wyczyścić pamięć podręczną danych? Spowoduje to
- usunięcie wszystkich kursów walut, cen papierów wartościowych, sald kont
- i innych danych. Tej akcji nie można cofnąć.
+ body: "Czy na pewno chcesz wyczyścić pamięć podręczną danych? Salda i pozycje kont Twojej rodziny zostaną przeliczone ponownie, a używane przez nie kursy walut i ceny papierów wartościowych zostaną ponownie pobrane. Usuwane są tylko salda i pozycje Twojej rodziny; kursy walut i ceny papierów wartościowych są wspólne dla wszystkich rodzin w tej instancji i zostaną zaktualizowane także dla nich. Tej operacji nie można cofnąć."
+ body_without_provider: "Czy na pewno chcesz wyczyścić pamięć podręczną danych? Salda i pozycje kont Twojej rodziny zostaną przeliczone ponownie. Nie skonfigurowano dostawcy kursów walut ani cen papierów wartościowych, więc zapisane kursy walut i ceny pozostają bez zmian. Tej operacji nie można cofnąć."
title: Wyczyścić pamięć podręczną danych?
danger_zone: Strefa ryzyka
financial_data_providers: Dostawcy danych finansowych
diff --git a/config/locales/views/settings/hostings/pt-BR.yml b/config/locales/views/settings/hostings/pt-BR.yml
index 4c6cb59328..7b37ac8d2b 100644
--- a/config/locales/views/settings/hostings/pt-BR.yml
+++ b/config/locales/views/settings/hostings/pt-BR.yml
@@ -21,10 +21,12 @@ pt-BR:
title: Self-Hosting
danger_zone: Zona de Perigo
clear_cache: Limpar cache de dados
- clear_cache_warning: Limpar o cache de dados removerá todas as taxas de câmbio, preços de ativos, saldos de contas e outros dados. Isso não excluirá contas, transações, categorias ou outros dados do usuário.
+ clear_cache_warning: "Limpar o cache de dados recalcula os saldos e as posições das contas da sua família e recarrega as taxas de câmbio e os preços de ativos que elas usam. Apenas os saldos e as posições da sua família são excluídos; as taxas de câmbio e os preços de ativos são compartilhados com as outras famílias desta instância e também são atualizados para elas. Isso não excluirá contas, transações, categorias ou outros dados do usuário."
+ clear_cache_warning_without_provider: "Limpar o cache de dados recalcula os saldos e as posições das contas da sua família. Nenhum provedor de taxas de câmbio ou de preços de ativos está configurado, então as taxas de câmbio e os preços salvos são mantidos. Isso não excluirá contas, transações, categorias ou outros dados do usuário."
confirm_clear_cache:
title: Limpar cache de dados?
- body: Tem certeza de que deseja limpar o cache de dados? Isso removerá todas as taxas de câmbio, preços de ativos, saldos de contas e outros dados. Esta ação não pode ser desfeita.
+ body: "Tem certeza de que deseja limpar o cache de dados? Os saldos e as posições das contas da sua família serão recalculados, e as taxas de câmbio e os preços de ativos que elas usam serão recarregados. Apenas os saldos e as posições da sua família são excluídos; as taxas de câmbio e os preços de ativos são compartilhados com as outras famílias desta instância e também são atualizados para elas. Esta ação não pode ser desfeita."
+ body_without_provider: "Tem certeza de que deseja limpar o cache de dados? Os saldos e as posições das contas da sua família serão recalculados. Nenhum provedor de taxas de câmbio ou de preços de ativos está configurado, então as taxas de câmbio e os preços salvos são mantidos. Esta ação não pode ser desfeita."
provider_selection:
title: Seleção de Provedor
description: Escolha qual serviço usar para buscar taxas de câmbio e preços de ativos. O Yahoo Finance é gratuito e não requer uma chave de API. O Twelve Data requer uma chave de API gratuita, mas pode oferecer maior cobertura de dados.
diff --git a/config/locales/views/settings/hostings/pt-PT.yml b/config/locales/views/settings/hostings/pt-PT.yml
index 14921ccd28..e385774b35 100644
--- a/config/locales/views/settings/hostings/pt-PT.yml
+++ b/config/locales/views/settings/hostings/pt-PT.yml
@@ -27,10 +27,12 @@ pt-PT:
title: Self-Hosting
danger_zone: Zona de Perigo
clear_cache: Limpar cache de dados
- clear_cache_warning: Limpar a cache de dados removerá todas as taxas de câmbio, preços de títulos, saldos de contas e outros dados. Isto não eliminará contas, transações, categorias ou outros dados pertencentes ao utilizador.
+ clear_cache_warning: "Limpar a cache de dados recalcula os saldos e as posições das contas da sua família e volta a carregar as taxas de câmbio e os preços de títulos que utilizam. Apenas os saldos e as posições da sua família são eliminados; as taxas de câmbio e os preços de títulos são partilhados com as outras famílias desta instância e também são atualizados para elas. Isto não eliminará contas, transações, categorias ou outros dados pertencentes ao utilizador."
+ clear_cache_warning_without_provider: "Limpar a cache de dados recalcula os saldos e as posições das contas da sua família. Não está configurado nenhum fornecedor de taxas de câmbio ou de preços de títulos, por isso as taxas de câmbio e os preços guardados são mantidos. Isto não eliminará contas, transações, categorias ou outros dados pertencentes ao utilizador."
confirm_clear_cache:
title: Limpar a cache de dados?
- body: Tem a certeza de que pretende limpar a cache de dados? Isto removerá todas as taxas de câmbio, preços de títulos, saldos de contas e outros dados. Esta ação é irreversível.
+ body: "Tem a certeza de que pretende limpar a cache de dados? Os saldos e as posições das contas da sua família serão recalculados, e as taxas de câmbio e os preços de títulos que utilizam serão carregados novamente. Apenas os saldos e as posições da sua família são eliminados; as taxas de câmbio e os preços de títulos são partilhados com as outras famílias desta instância e também são atualizados para elas. Esta ação é irreversível."
+ body_without_provider: "Tem a certeza de que pretende limpar a cache de dados? Os saldos e as posições das contas da sua família serão recalculados. Não está configurado nenhum fornecedor de taxas de câmbio ou de preços de títulos, por isso as taxas de câmbio e os preços guardados são mantidos. Esta ação é irreversível."
provider_selection:
exchange_rate_title: Serviço de Taxas de Câmbio
exchange_rate_description: Selecione um único serviço para obter taxas de câmbio de moedas.
diff --git a/config/locales/views/settings/hostings/ro.yml b/config/locales/views/settings/hostings/ro.yml
index f50b3cc16a..60cf98957e 100644
--- a/config/locales/views/settings/hostings/ro.yml
+++ b/config/locales/views/settings/hostings/ro.yml
@@ -20,10 +20,12 @@ ro:
title: Găzduire Proprie
danger_zone: Zonă de Pericol
clear_cache: Șterge cache-ul de date
- clear_cache_warning: Ștergerea cache-ului de date va elimina toate ratele de schimb, prețurile titlurilor de valoare, soldurile conturilor și alte date. Aceasta nu va șterge conturile, tranzacțiile, categoriile sau alte date deținute de utilizator.
+ clear_cache_warning: "Ștergerea cache-ului de date recalculează soldurile și pozițiile conturilor familiei tale și reîncarcă ratele de schimb și prețurile titlurilor de valoare pe care le folosesc. Se șterg doar soldurile și pozițiile familiei tale; ratele de schimb și prețurile titlurilor de valoare sunt comune tuturor familiilor de pe această instanță și se actualizează și pentru ele. Aceasta nu va șterge conturile, tranzacțiile, categoriile sau alte date deținute de utilizator."
+ clear_cache_warning_without_provider: "Ștergerea cache-ului de date recalculează soldurile și pozițiile conturilor familiei tale. Nu este configurat niciun furnizor de rate de schimb sau de prețuri ale titlurilor de valoare, așa că ratele de schimb și prețurile salvate se păstrează. Aceasta nu va șterge conturile, tranzacțiile, categoriile sau alte date deținute de utilizator."
confirm_clear_cache:
title: Ștergi cache-ul de date?
- body: Ești sigur că vrei să ștergi cache-ul de date? Aceasta va elimina toate ratele de schimb, prețurile titlurilor de valoare, soldurile conturilor și alte date. Această acțiune nu poate fi anulată.
+ body: "Ești sigur că vrei să ștergi cache-ul de date? Soldurile și pozițiile conturilor familiei tale vor fi recalculate, iar ratele de schimb și prețurile titlurilor de valoare pe care le folosesc vor fi reîncărcate. Se șterg doar soldurile și pozițiile familiei tale; ratele de schimb și prețurile titlurilor de valoare sunt comune tuturor familiilor de pe această instanță și se actualizează și pentru ele. Această acțiune nu poate fi anulată."
+ body_without_provider: "Ești sigur că vrei să ștergi cache-ul de date? Soldurile și pozițiile conturilor familiei tale vor fi recalculate. Nu este configurat niciun furnizor de rate de schimb sau de prețuri ale titlurilor de valoare, așa că ratele de schimb și prețurile salvate se păstrează. Această acțiune nu poate fi anulată."
brand_fetch_settings:
description: Introdu ID-ul Clientului furnizat de Brandfetch
label: ID Client
diff --git a/config/locales/views/settings/hostings/ru.yml b/config/locales/views/settings/hostings/ru.yml
index 6180c8f709..5b98a43cca 100644
--- a/config/locales/views/settings/hostings/ru.yml
+++ b/config/locales/views/settings/hostings/ru.yml
@@ -171,10 +171,11 @@ ru:
show:
ai_assistant: AI Ассистент
clear_cache: Очистить кэш данных
- clear_cache_warning: Очистка кэша данных удалит все курсы валют, цены на ценные бумаги, балансы счетов и другие данные. Это не удалит счета, операции, категории или другие данные, принадлежащие пользователю.
+ clear_cache_warning: "Очистка кэша данных пересчитывает балансы и позиции счетов вашей семьи и заново загружает используемые ими курсы валют и цены на ценные бумаги. Удаляются только балансы и позиции вашей семьи; курсы валют и цены на ценные бумаги общие для всех семей на этом экземпляре и обновятся и для них. Это не удалит счета, транзакции, категории и другие данные пользователей."
confirm_clear_cache:
- body: Вы уверены, что хотите очистить кэш данных? Это удалит все курсы валют, цены на ценные бумаги, балансы счетов и другие данные. Это действие нельзя отменить.
+ body: "Вы уверены, что хотите очистить кэш данных? Балансы и позиции счетов вашей семьи будут пересчитаны, а используемые ими курсы валют и цены на ценные бумаги будут загружены заново. Удаляются только балансы и позиции вашей семьи; курсы валют и цены на ценные бумаги общие для всех семей на этом экземпляре и обновятся и для них. Это действие нельзя отменить."
title: Очистить кэш данных?
+ body_without_provider: "Вы уверены, что хотите очистить кэш данных? Балансы и позиции счетов вашей семьи будут пересчитаны. Поставщик курсов валют или цен на ценные бумаги не настроен, поэтому сохранённые курсы валют и цены остаются без изменений. Это действие нельзя отменить."
danger_zone: Опасная зона
financial_data_providers: Поставщики финансовых данных
general: Общие настройки
@@ -182,6 +183,7 @@ ru:
sync_settings: Настройки синхронизации
title: Самостоятельный хостинг
property_valuation_providers: Поставщики оценки недвижимости
+ clear_cache_warning_without_provider: "Очистка кэша данных пересчитывает балансы и позиции счетов вашей семьи. Поставщик курсов валют или цен на ценные бумаги не настроен, поэтому сохранённые курсы валют и цены остаются без изменений. Это не удалит счета, транзакции, категории и другие данные пользователей."
sync_auto_sync_scheduler!:
scheduler_sync_failed: Настройки сохранены, но не удалось обновить расписание синхронизации. Пожалуйста, попробуйте снова или проверьте журналы сервера.
sync_settings:
diff --git a/config/locales/views/settings/hostings/tr.yml b/config/locales/views/settings/hostings/tr.yml
index 47e6f068bb..46bcde4cf8 100644
--- a/config/locales/views/settings/hostings/tr.yml
+++ b/config/locales/views/settings/hostings/tr.yml
@@ -235,13 +235,11 @@ tr:
show:
ai_assistant: Yapay Zeka Asistanı
clear_cache: Veri önbelleğini temizle
- clear_cache_warning: Veri önbelleğini temizlemek tüm döviz kurları, menkul
- kıymet fiyatları, hesap bakiyeleri ve diğer verileri kaldıracaktır. Bu işlem
- hesapları, işlemleri, kategorileri veya diğer kullanıcıya ait verileri silmez.
+ clear_cache_warning: "Veri önbelleğini temizlemek, ailenizin hesaplarındaki bakiyeleri ve pozisyonları yeniden hesaplar ve bunların kullandığı döviz kurlarını ve menkul kıymet fiyatlarını yeniden yükler. Yalnızca ailenizin bakiyeleri ve pozisyonları silinir; döviz kurları ve menkul kıymet fiyatları bu sunucudaki diğer ailelerle ortaktır ve onlar için de güncellenir. Bu işlem hesapları, işlemleri, kategorileri veya kullanıcıya ait diğer verileri silmez."
+ clear_cache_warning_without_provider: "Veri önbelleğini temizlemek, ailenizin hesaplarındaki bakiyeleri ve pozisyonları yeniden hesaplar. Döviz kuru veya menkul kıymet fiyatı sağlayıcısı yapılandırılmadığı için kayıtlı döviz kurları ve fiyatlar korunur. Bu işlem hesapları, işlemleri, kategorileri veya kullanıcıya ait diğer verileri silmez."
confirm_clear_cache:
- body: Veri önbelleğini temizlemek istediğinizden emin misiniz? Bu işlem
- tüm döviz kurları, menkul kıymet fiyatları, hesap bakiyeleri ve diğer
- verileri kaldıracaktır. Bu işlem geri alınamaz.
+ body: "Veri önbelleğini temizlemek istediğinizden emin misiniz? Ailenizin hesaplarındaki bakiyeler ve pozisyonlar yeniden hesaplanacak, bunların kullandığı döviz kurları ve menkul kıymet fiyatları yeniden yüklenecek. Yalnızca ailenizin bakiyeleri ve pozisyonları silinir; döviz kurları ve menkul kıymet fiyatları bu sunucudaki diğer ailelerle ortaktır ve onlar için de güncellenir. Bu işlem geri alınamaz."
+ body_without_provider: "Veri önbelleğini temizlemek istediğinizden emin misiniz? Ailenizin hesaplarındaki bakiyeler ve pozisyonlar yeniden hesaplanacak. Döviz kuru veya menkul kıymet fiyatı sağlayıcısı yapılandırılmadığı için kayıtlı döviz kurları ve fiyatlar korunur. Bu işlem geri alınamaz."
title: Veri önbelleği temizlensin mi?
danger_zone: Tehlikeli Bölge
financial_data_providers: Finansal Veri Sağlayıcıları
diff --git a/config/locales/views/settings/hostings/uk.yml b/config/locales/views/settings/hostings/uk.yml
index 21da34c2e7..bc8eb402ee 100644
--- a/config/locales/views/settings/hostings/uk.yml
+++ b/config/locales/views/settings/hostings/uk.yml
@@ -24,10 +24,12 @@ uk:
title: Самостійний хостинг
danger_zone: Небезпечна зона
clear_cache: Очистити кеш даних
- clear_cache_warning: Очищення кешу даних видалить усі курси обміну, ціни на цінні папери, баланси рахунків та інші дані. Це не видалить рахунки, транзакції, категорії та інші дані, що належать користувачеві.
+ clear_cache_warning: "Очищення кешу даних перераховує баланси та позиції рахунків вашої родини і заново завантажує курси обміну та ціни на цінні папери, які вони використовують. Видаляються лише баланси та позиції вашої родини; курси обміну та ціни на цінні папери спільні для всіх родин на цьому екземплярі й оновляться і для них. Це не видалить рахунки, транзакції, категорії та інші дані, що належать користувачеві."
+ clear_cache_warning_without_provider: "Очищення кешу даних перераховує баланси та позиції рахунків вашої родини. Постачальника курсів обміну чи цін на цінні папери не налаштовано, тому збережені курси обміну та ціни залишаються без змін. Це не видалить рахунки, транзакції, категорії та інші дані, що належать користувачеві."
confirm_clear_cache:
title: Очистити кеш даних?
- body: Ви впевнені, що хочете очистити кеш даних? Це видалить усі курси обміну, ціни на цінні папери, баланси рахунків та інші дані. Цю дію неможливо скасувати.
+ body: "Ви впевнені, що хочете очистити кеш даних? Баланси та позиції рахунків вашої родини буде перераховано, а курси обміну та ціни на цінні папери, які вони використовують, буде завантажено заново. Видаляються лише баланси та позиції вашої родини; курси обміну та ціни на цінні папери спільні для всіх родин на цьому екземплярі й оновляться і для них. Цю дію неможливо скасувати."
+ body_without_provider: "Ви впевнені, що хочете очистити кеш даних? Баланси та позиції рахунків вашої родини буде перераховано. Постачальника курсів обміну чи цін на цінні папери не налаштовано, тому збережені курси обміну та ціни залишаються без змін. Цю дію неможливо скасувати."
property_valuation_providers: Постачальники оцінки нерухомості
provider_selection:
exchange_rate_title: Постачальник курсів обміну
diff --git a/config/locales/views/settings/hostings/vi.yml b/config/locales/views/settings/hostings/vi.yml
index 25535315aa..bc134b6a96 100644
--- a/config/locales/views/settings/hostings/vi.yml
+++ b/config/locales/views/settings/hostings/vi.yml
@@ -25,10 +25,12 @@ vi:
title: Tự lưu trữ
danger_zone: Vùng nguy hiểm
clear_cache: Xóa bộ nhớ đệm dữ liệu
- clear_cache_warning: Xóa bộ nhớ đệm dữ liệu sẽ xóa tất cả tỷ giá hối đoái, giá chứng khoán, số dư tài khoản và dữ liệu khác. Thao tác này sẽ không xóa tài khoản, giao dịch, danh mục hoặc dữ liệu người dùng khác.
+ clear_cache_warning: "Xóa bộ nhớ đệm dữ liệu sẽ tính lại số dư và vị thế của các tài khoản trong gia đình bạn, đồng thời tải lại tỷ giá hối đoái và giá chứng khoán mà chúng sử dụng. Chỉ số dư và vị thế của gia đình bạn bị xóa; tỷ giá hối đoái và giá chứng khoán được dùng chung với các gia đình khác trên phiên bản này và cũng được cập nhật cho họ. Thao tác này sẽ không xóa tài khoản, giao dịch, danh mục hoặc dữ liệu người dùng khác."
+ clear_cache_warning_without_provider: "Xóa bộ nhớ đệm dữ liệu sẽ tính lại số dư và vị thế của các tài khoản trong gia đình bạn. Chưa cấu hình nhà cung cấp tỷ giá hối đoái hoặc giá chứng khoán, nên tỷ giá và giá đã lưu được giữ nguyên. Thao tác này sẽ không xóa tài khoản, giao dịch, danh mục hoặc dữ liệu người dùng khác."
confirm_clear_cache:
title: Xóa bộ nhớ đệm dữ liệu?
- body: Bạn có chắc chắn muốn xóa bộ nhớ đệm dữ liệu? Thao tác này sẽ xóa tất cả tỷ giá hối đoái, giá chứng khoán, số dư tài khoản và dữ liệu khác. Hành động này không thể hoàn tác.
+ body: "Bạn có chắc chắn muốn xóa bộ nhớ đệm dữ liệu? Số dư và vị thế của các tài khoản trong gia đình bạn sẽ được tính lại, đồng thời tỷ giá hối đoái và giá chứng khoán mà chúng sử dụng sẽ được tải lại. Chỉ số dư và vị thế của gia đình bạn bị xóa; tỷ giá hối đoái và giá chứng khoán được dùng chung với các gia đình khác trên phiên bản này và cũng được cập nhật cho họ. Hành động này không thể hoàn tác."
+ body_without_provider: "Bạn có chắc chắn muốn xóa bộ nhớ đệm dữ liệu? Số dư và vị thế của các tài khoản trong gia đình bạn sẽ được tính lại. Chưa cấu hình nhà cung cấp tỷ giá hối đoái hoặc giá chứng khoán, nên tỷ giá và giá đã lưu được giữ nguyên. Hành động này không thể hoàn tác."
provider_selection:
exchange_rate_title: Nhà cung cấp tỷ giá hối đoái
exchange_rate_description: Chọn một nhà cung cấp để lấy tỷ giá hối đoái tiền tệ.
diff --git a/config/locales/views/settings/hostings/zh-CN.yml b/config/locales/views/settings/hostings/zh-CN.yml
index e26b0d84c1..e4ef6ef03c 100644
--- a/config/locales/views/settings/hostings/zh-CN.yml
+++ b/config/locales/views/settings/hostings/zh-CN.yml
@@ -107,9 +107,11 @@ zh-CN:
show:
demo_refresh: 演示数据刷新
clear_cache: 清除数据缓存
- clear_cache_warning: 清除数据缓存将移除所有汇率、证券价格、账户余额及其他数据。这不会删除账户、交易记录、分类或其他用户自有数据。
+ clear_cache_warning: "清除数据缓存会重新计算您家庭账户的余额和持仓,并重新加载它们使用的汇率和证券价格。只会删除您家庭的余额和持仓;汇率和证券价格由此实例上的所有家庭共享,也会为他们更新。这不会删除账户、交易记录、分类或其他用户自有数据。"
+ clear_cache_warning_without_provider: "清除数据缓存会重新计算您家庭账户的余额和持仓。由于未配置汇率或证券价格提供商,已保存的汇率和证券价格将保持不变。这不会删除账户、交易记录、分类或其他用户自有数据。"
confirm_clear_cache:
- body: 确定要清除数据缓存吗?这将移除所有汇率、证券价格、账户余额及其他数据,且不可撤销。
+ body: "确定要清除数据缓存吗?您家庭账户的余额和持仓将被重新计算,它们使用的汇率和证券价格将被重新加载。只会删除您家庭的余额和持仓;汇率和证券价格由此实例上的所有家庭共享,也会为他们更新。此操作不可撤销。"
+ body_without_provider: "确定要清除数据缓存吗?您家庭账户的余额和持仓将被重新计算。由于未配置汇率或证券价格提供商,已保存的汇率和证券价格将保持不变。此操作不可撤销。"
title: 确认清除数据缓存?
reset_market_data: 重置所有家庭的市场数据
reset_market_data_warning: 删除您的提供商可重新加载的汇率和证券价格,重新导入它们,然后同步每个账户。在导入完成前,外币总额可能会显示为未换算状态。
diff --git a/config/locales/views/settings/hostings/zh-TW.yml b/config/locales/views/settings/hostings/zh-TW.yml
index 50a3fd6b51..baa6b810c0 100644
--- a/config/locales/views/settings/hostings/zh-TW.yml
+++ b/config/locales/views/settings/hostings/zh-TW.yml
@@ -26,10 +26,12 @@ zh-TW:
title: 自行代管 (Self-Hosting)
danger_zone: 危險區域
clear_cache: 清除資料快取
- clear_cache_warning: 清除資料快取會移除所有匯率、證券價格、帳戶餘額等快取資料。您自己的帳戶、交易紀錄、分類等資料都不會被刪除。
+ clear_cache_warning: "清除資料快取會重新計算您家庭帳戶的餘額與持倉,並重新載入它們使用的匯率與證券價格。只會刪除您家庭的餘額與持倉;匯率與證券價格由此執行個體上的所有家庭共用,也會為他們更新。您自己的帳戶、交易紀錄、分類等資料都不會被刪除。"
+ clear_cache_warning_without_provider: "清除資料快取會重新計算您家庭帳戶的餘額與持倉。由於未設定匯率或證券價格提供者,已儲存的匯率與證券價格將保持不變。您自己的帳戶、交易紀錄、分類等資料都不會被刪除。"
confirm_clear_cache:
title: 清除資料快取?
- body: 您確定要清除資料快取嗎?這將移除所有匯率、證券價格、帳戶餘額及其他暫存資料。此操作無法復原。
+ body: "您確定要清除資料快取嗎?您家庭帳戶的餘額與持倉將重新計算,並重新載入它們使用的匯率與證券價格。只會刪除您家庭的餘額與持倉;匯率與證券價格由此執行個體上的所有家庭共用,也會為他們更新。此操作無法復原。"
+ body_without_provider: "您確定要清除資料快取嗎?您家庭帳戶的餘額與持倉將重新計算。由於未設定匯率或證券價格提供者,已儲存的匯率與證券價格將保持不變。此操作無法復原。"
provider_selection:
exchange_rate_title: 匯率資料供應商
exchange_rate_description: 選擇單一供應商來取得貨幣匯率。
diff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rb
index af1a93f672..6fda4a77c1 100644
--- a/test/controllers/settings/hostings_controller_test.rb
+++ b/test/controllers/settings/hostings_controller_test.rb
@@ -327,6 +327,47 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "clear cache texts promise reloaded market data only when a provider is configured" do
+ with_self_hosting do
+ ExchangeRate.stubs(:provider).returns(@provider)
+ get settings_hosting_url
+ assert_includes response.body, ERB::Util.html_escape(I18n.t("settings.hostings.show.clear_cache_warning"))
+
+ ExchangeRate.stubs(:provider).returns(nil)
+ Security.stubs(:provider).returns(nil)
+ get settings_hosting_url
+ assert_includes response.body, ERB::Util.html_escape(I18n.t("settings.hostings.show.clear_cache_warning_without_provider"))
+ assert_includes response.body, ERB::Util.html_escape(I18n.t("settings.hostings.show.confirm_clear_cache.body_without_provider"))
+ assert_not_includes response.body, ERB::Util.html_escape(I18n.t("settings.hostings.show.clear_cache_warning"))
+ end
+ end
+
+ test "shows the clear cache text without provider when no exchange rate provider is set" do
+ Setting.stubs(:exchange_rate_provider).returns(nil)
+ Security.stubs(:provider).returns(nil)
+
+ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil) do
+ with_self_hosting do
+ get settings_hosting_url
+
+ assert_response :success
+ assert_includes response.body, ERB::Util.html_escape(I18n.t("settings.hostings.show.clear_cache_warning_without_provider"))
+ end
+ end
+ end
+
+ test "an unknown exchange rate provider does not hide a configured security provider" do
+ ExchangeRate.stubs(:provider).raises(Provider::Registry::Error, "Provider 'nope' not found")
+ Security.stubs(:provider).returns(@provider)
+
+ with_self_hosting do
+ get settings_hosting_url
+
+ assert_response :success
+ assert_includes response.body, ERB::Util.html_escape(I18n.t("settings.hostings.show.clear_cache_warning"))
+ end
+ end
+
test "can update terrascoutx api key when self hosting is enabled" do
with_self_hosting do
patch settings_hosting_url, params: { setting: { terrascoutx_api_key: "terrascoutx-token" } }
@@ -887,6 +928,7 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
exchange_rate = exchange_rates(:one)
security_price = holding.security.prices.first
account_balance = account.balances.create!(date: Date.current, balance: 1000, currency: "USD")
+ Family::MarketDataRefresher.any_instance.expects(:refresh)
with_self_hosting do
perform_enqueued_jobs(only: DataCacheClearJob) do
@@ -897,8 +939,9 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to settings_hosting_url
assert_equal I18n.t("settings.hostings.clear_cache.cache_cleared"), flash[:notice]
- assert_not ExchangeRate.exists?(exchange_rate.id)
- assert_not Security::Price.exists?(security_price.id)
+ # Market data is shared with other families, so it is refreshed rather than deleted
+ assert ExchangeRate.exists?(exchange_rate.id)
+ assert Security::Price.exists?(security_price.id)
assert_not Holding.exists?(holding.id)
assert_not Balance.exists?(account_balance.id)
end
diff --git a/test/jobs/data_cache_clear_job_test.rb b/test/jobs/data_cache_clear_job_test.rb
new file mode 100644
index 0000000000..55111cafc2
--- /dev/null
+++ b/test/jobs/data_cache_clear_job_test.rb
@@ -0,0 +1,150 @@
+require "test_helper"
+require "ostruct"
+
+class DataCacheClearJobTest < ActiveJob::TestCase
+ include ProviderTestHelper
+
+ setup do
+ @provider = mock("provider")
+ Provider::Registry.any_instance.stubs(:get_provider).returns(@provider)
+
+ @family = Family.create!(name: "Cache clear", currency: "USD")
+ @account = @family.accounts.create!(
+ name: "Foreign savings",
+ currency: "CAD",
+ balance: 1000,
+ accountable: Depository.new
+ )
+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: Date.current, rate: 0.7)
+ end
+
+ test "reloads the exchange rates the family needs before its accounts sync" do
+ @provider.stubs(:fetch_exchange_rates).returns(provider_success_response([
+ OpenStruct.new(from: "CAD", to: "USD", date: Date.current, rate: 0.73)
+ ]))
+
+ DataCacheClearJob.perform_now(@family)
+
+ assert_enqueued_jobs 1, only: SyncJob
+ assert_equal 0.73, ExchangeRate.find_by(from_currency: "CAD", to_currency: "USD", date: Date.current)&.rate&.to_f,
+ "account syncs must start with the refreshed CAD/USD rate"
+ end
+
+ test "keeps the market data and cached balances of other families" do
+ @provider.stubs(:fetch_exchange_rates).returns(provider_success_response([]))
+ other_rate = ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: Date.current, rate: 0.0067)
+ other_price = Security::Price.create!(security: securities(:aapl), date: 3.days.ago.to_date, price: 200, currency: "USD")
+ other_balance_ids = accounts(:depository).balances.pluck(:id)
+ other_holding_ids = accounts(:investment).holdings.pluck(:id)
+ assert other_balance_ids.any?
+ assert other_holding_ids.any?
+
+ DataCacheClearJob.perform_now(@family)
+
+ assert ExchangeRate.exists?(other_rate.id)
+ assert Security::Price.exists?(other_price.id)
+ assert_equal other_balance_ids.sort, Balance.where(id: other_balance_ids).pluck(:id).sort
+ assert_equal other_holding_ids.sort, Holding.where(id: other_holding_ids).pluck(:id).sort
+ end
+
+ test "refreshes the prices of held securities before it deletes the holdings" do
+ @provider.stubs(:fetch_exchange_rates).returns(provider_success_response([]))
+ brokerage = @family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)
+ security = Security.create!(ticker: "CLRC", exchange_operating_mic: "XNAS")
+ brokerage.holdings.create!(security: security, date: 1.day.ago.to_date, qty: 1, price: 200, amount: 200, currency: "USD")
+
+ Security.any_instance.expects(:import_provider_prices).with(has_entry(clear_cache: true)).once
+ Security.any_instance.stubs(:import_provider_details)
+
+ DataCacheClearJob.perform_now(@family)
+
+ assert_empty brokerage.holdings.reload
+ end
+
+ test "deletes the family's cached balances and holdings" do
+ Family::MarketDataRefresher.any_instance.stubs(:refresh)
+ @account.balances.create!(date: 1.day.ago.to_date, balance: 1000, currency: "CAD")
+ @account.holdings.create!(security: securities(:aapl), date: 1.day.ago.to_date, qty: 1, price: 200, amount: 200, currency: "CAD")
+
+ DataCacheClearJob.perform_now(@family)
+
+ assert_empty @account.balances.reload
+ assert_empty @account.holdings.reload
+ end
+
+ test "rolls the delete back when the sync cannot be scheduled" do
+ Family::MarketDataRefresher.any_instance.stubs(:refresh)
+ balance = @account.balances.create!(date: 1.day.ago.to_date, balance: 1000, currency: "CAD")
+ @family.stubs(:sync_later).raises(ActiveRecord::StatementInvalid, "connection lost")
+
+ assert_raises(ActiveRecord::StatementInvalid) { DataCacheClearJob.perform_now(@family) }
+
+ assert Balance.exists?(balance.id)
+ end
+
+ test "waits for a running sync instead of deleting the balances it writes" do
+ Family::MarketDataRefresher.any_instance.expects(:refresh).never
+ balance = @account.balances.create!(date: 1.day.ago.to_date, balance: 1000, currency: "CAD")
+ @account.syncs.create!(status: "syncing")
+
+ assert_enqueued_with(job: DataCacheClearJob, args: [ @family ]) do
+ DataCacheClearJob.perform_now(@family)
+ end
+
+ assert Balance.exists?(balance.id)
+ assert_no_enqueued_jobs only: SyncJob
+ end
+
+ test "waits when a sync starts while the market data is refreshed" do
+ Family::MarketDataRefresher.any_instance.stubs(:refresh).with { @family.syncs.create!(status: "pending") }
+ balance = @account.balances.create!(date: 1.day.ago.to_date, balance: 1000, currency: "CAD")
+
+ assert_enqueued_with(job: DataCacheClearJob, args: [ @family ]) do
+ DataCacheClearJob.perform_now(@family)
+ end
+
+ assert Balance.exists?(balance.id)
+ end
+
+ test "locks the family's accounts before it checks for running syncs" do
+ Family::MarketDataRefresher.any_instance.stubs(:refresh)
+ queries = []
+ callback = ->(*, payload) { queries << payload[:sql] }
+
+ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
+ DataCacheClearJob.perform_now(@family)
+ end
+
+ lock_index = queries.index { |sql| sql.match?(/FROM "accounts".*FOR UPDATE/m) }
+ sync_check_index = queries.rindex { |sql| sql.match?(/FROM "syncs"/) && sql.include?("EXISTS") || sql.match?(/SELECT 1 AS one FROM "syncs"/) }
+ assert lock_index, "accounts are not locked"
+ assert lock_index < sync_check_index, "accounts are locked only after the running-sync check"
+ end
+
+ test "clears the balances and syncs when no exchange rate provider is set" do
+ Setting.stubs(:exchange_rate_provider).returns(nil)
+ Security.stubs(:provider).returns(nil)
+ balance = @account.balances.create!(date: 1.day.ago.to_date, balance: 1000, currency: "CAD")
+
+ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil) do
+ DataCacheClearJob.perform_now(@family)
+ end
+
+ assert_not Balance.exists?(balance.id)
+ assert_enqueued_jobs 1, only: SyncJob
+ end
+
+ test "clears the balances and syncs when the exchange rate provider is unknown" do
+ Provider::Registry.any_instance.stubs(:get_provider).raises(Provider::Registry::Error)
+ Setting.stubs(:exchange_rate_provider).returns("nope")
+ Security.stubs(:provider).returns(nil)
+ balance = @account.balances.create!(date: 1.day.ago.to_date, balance: 1000, currency: "CAD")
+
+ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil) do
+ DataCacheClearJob.perform_now(@family)
+ end
+
+ assert_not Balance.exists?(balance.id)
+ assert_enqueued_jobs 1, only: SyncJob
+ end
+end
diff --git a/test/models/exchange_rate/importer_test.rb b/test/models/exchange_rate/importer_test.rb
index b9614f9242..8db771395e 100644
--- a/test/models/exchange_rate/importer_test.rb
+++ b/test/models/exchange_rate/importer_test.rb
@@ -116,6 +116,70 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCase
assert_equal [ 1.3, 1.4, 1.5 ], db_rates.map(&:rate)
end
+ test "clear_cache carries the provider rate over the dates it skips instead of keeping stale rates" do
+ ExchangeRate.delete_all
+
+ (2.days.ago.to_date..Date.current).each do |date|
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date:, rate: 1.0)
+ end
+
+ # The provider skips yesterday (a weekend or holiday)
+ provider_response = provider_success_response([
+ OpenStruct.new(from: "USD", to: "EUR", date: 2.days.ago.to_date, rate: 1.3),
+ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.5)
+ ])
+
+ @provider.expects(:fetch_exchange_rates)
+ .with(from: "USD", to: "EUR", start_date: get_provider_fetch_start_date(2.days.ago.to_date), end_date: Date.current)
+ .returns(provider_response)
+
+ ExchangeRate::Importer.new(
+ exchange_rate_provider: @provider,
+ from: "USD",
+ to: "EUR",
+ start_date: 2.days.ago.to_date,
+ end_date: Date.current,
+ clear_cache: true
+ ).import_provider_rates
+
+ db_rates = ExchangeRate.where(from_currency: "USD", to_currency: "EUR").order(:date)
+ assert_equal [ 1.3, 1.3, 1.5 ], db_rates.map(&:rate)
+ end
+
+ test "clear_cache keeps stored rates from before the provider's first rate" do
+ ExchangeRate.delete_all
+
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: 10.days.ago.to_date, rate: 0.9)
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: 9.days.ago.to_date, rate: 0.95)
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: 1.day.ago.to_date, rate: 1.0)
+
+ # The provider's history starts later than the stored history
+ provider_response = provider_success_response([
+ OpenStruct.new(from: "USD", to: "EUR", date: 1.day.ago.to_date, rate: 1.3),
+ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.5)
+ ])
+
+ @provider.expects(:fetch_exchange_rates)
+ .with(from: "USD", to: "EUR", start_date: get_provider_fetch_start_date(10.days.ago.to_date), end_date: Date.current)
+ .returns(provider_response)
+
+ ExchangeRate::Importer.new(
+ exchange_rate_provider: @provider,
+ from: "USD",
+ to: "EUR",
+ start_date: 10.days.ago.to_date,
+ end_date: Date.current,
+ clear_cache: true
+ ).import_provider_rates
+
+ rates = ExchangeRate.where(from_currency: "USD", to_currency: "EUR").order(:date).pluck(:date, :rate).to_h
+ assert_equal 0.9, rates[10.days.ago.to_date]
+ assert_equal 0.95, rates[9.days.ago.to_date]
+ assert_equal 0.95, rates[8.days.ago.to_date]
+ assert_equal 1.3, rates[1.day.ago.to_date]
+ assert_equal 1.5, rates[Date.current]
+ end
+
test "clamps end_date to today when future date is provided" do
ExchangeRate.delete_all
diff --git a/test/models/family/market_data_refresher_test.rb b/test/models/family/market_data_refresher_test.rb
new file mode 100644
index 0000000000..07f016b002
--- /dev/null
+++ b/test/models/family/market_data_refresher_test.rb
@@ -0,0 +1,73 @@
+require "test_helper"
+require "ostruct"
+
+class Family::MarketDataRefresherTest < ActiveSupport::TestCase
+ include ProviderTestHelper
+
+ setup do
+ @provider = mock("provider")
+ Provider::Registry.any_instance.stubs(:get_provider).returns(@provider)
+
+ @family = Family.create!(name: "Refresh", currency: "USD")
+ end
+
+ test "fetches a currency pair shared by several accounts once and overwrites the stored rates" do
+ accounts = 3.times.map do |i|
+ @family.accounts.create!(name: "Savings #{i}", currency: "CAD", balance: 100, accountable: Depository.new)
+ end
+ start_date = accounts.map(&:start_date).min
+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: Date.current, rate: 1.0)
+
+ @provider.expects(:fetch_exchange_rates)
+ .with(from: "CAD", to: "USD", start_date: anything, end_date: anything)
+ .once
+ .returns(provider_success_response([
+ OpenStruct.new(from: "CAD", to: "USD", date: start_date, rate: 0.73)
+ ]))
+
+ Family::MarketDataRefresher.new(@family).refresh
+
+ assert_equal 0.73, ExchangeRate.find_by(from_currency: "CAD", to_currency: "USD", date: Date.current).rate.to_f
+ end
+
+ test "downloads the prices of a security held in several accounts once, overwriting stored prices" do
+ security = Security.create!(ticker: "RFSH", exchange_operating_mic: "XNAS")
+ 2.times do |i|
+ account = @family.accounts.create!(name: "Brokerage #{i}", currency: "USD", balance: 0, accountable: Investment.new)
+ account.holdings.create!(security: security, date: Date.current, qty: 1, price: 100, amount: 100, currency: "USD")
+ end
+
+ Security.any_instance.expects(:import_provider_prices)
+ .with(has_entry(clear_cache: true))
+ .once
+ Security.any_instance.stubs(:import_provider_details)
+
+ Family::MarketDataRefresher.new(@family).refresh
+ end
+
+ test "logs a price refresh the provider reports as failed" do
+ security = Security.create!(ticker: "RFSH", exchange_operating_mic: "XNAS")
+ account = @family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)
+ account.holdings.create!(security: security, date: Date.current, qty: 1, price: 100, amount: 100, currency: "USD")
+
+ Security.any_instance.expects(:import_provider_prices).returns([ 0, "Rate limit exceeded" ])
+ Security.any_instance.stubs(:import_provider_details)
+
+ assert_difference -> { DebugLogEntry.where(family: @family, level: "error").count }, 1 do
+ Family::MarketDataRefresher.new(@family).refresh
+ end
+ assert_match "Rate limit exceeded", DebugLogEntry.where(family: @family).order(:created_at).last.message
+ end
+
+ test "logs a pair that fails and goes on with the others" do
+ @family.accounts.create!(name: "Savings", currency: "CAD", balance: 100, accountable: Depository.new)
+ @family.accounts.create!(name: "Card", currency: "GBP", balance: 100, accountable: CreditCard.new)
+
+ ExchangeRate.expects(:import_provider_rates).with(has_entry(from: "CAD")).raises(StandardError, "provider down")
+ ExchangeRate.expects(:import_provider_rates).with(has_entries(from: "GBP", clear_cache: true))
+
+ assert_difference -> { DebugLogEntry.where(family: @family, level: "error").count }, 1 do
+ Family::MarketDataRefresher.new(@family).refresh
+ end
+ end
+end
diff --git a/test/models/security/price/importer_test.rb b/test/models/security/price/importer_test.rb
index 705f289cf4..a1f00272bf 100644
--- a/test/models/security/price/importer_test.rb
+++ b/test/models/security/price/importer_test.rb
@@ -377,6 +377,40 @@ class Security::Price::ImporterTest < ActiveSupport::TestCase
assert_equal [ 150, 155, 160 ], db_prices.map(&:price)
end
+ test "clear_cache keeps stored prices from before the provider's first price" do
+ Security::Price.delete_all
+
+ Security::Price.create!(security: @security, date: 10.days.ago.to_date, price: 90, currency: "USD")
+ Security::Price.create!(security: @security, date: 9.days.ago.to_date, price: 95, currency: "USD")
+ Security::Price.create!(security: @security, date: 1.day.ago.to_date, price: 100, currency: "USD")
+
+ # The provider's history starts later than the stored history
+ provider_response = provider_success_response([
+ OpenStruct.new(security: @security, date: 1.day.ago.to_date, price: 155, currency: "USD"),
+ OpenStruct.new(security: @security, date: Date.current, price: 160, currency: "USD")
+ ])
+
+ @provider.expects(:fetch_security_prices)
+ .with(symbol: @security.ticker, exchange_operating_mic: @security.exchange_operating_mic,
+ start_date: get_provider_fetch_start_date(10.days.ago.to_date), end_date: Date.current)
+ .returns(provider_response)
+
+ Security::Price::Importer.new(
+ security: @security,
+ security_provider: @provider,
+ start_date: 10.days.ago.to_date,
+ end_date: Date.current,
+ clear_cache: true
+ ).import_provider_prices
+
+ prices = Security::Price.where(security: @security).order(:date).pluck(:date, :price).to_h
+ assert_equal 90, prices[10.days.ago.to_date]
+ assert_equal 95, prices[9.days.ago.to_date]
+ assert_equal 95, prices[8.days.ago.to_date]
+ assert_equal 155, prices[1.day.ago.to_date]
+ assert_equal 160, prices[Date.current]
+ end
+
test "clamps end_date to today when future date is provided" do
Security::Price.delete_all