diff --git a/app/models/lunchflow_item/syncer.rb b/app/models/lunchflow_item/syncer.rb index 2bfc94a29a..f3ce081ebe 100644 --- a/app/models/lunchflow_item/syncer.rb +++ b/app/models/lunchflow_item/syncer.rb @@ -1,6 +1,12 @@ +# Syncs one Lunch Flow connection: import, count linked and unlinked accounts, +# process the linked ones and schedule their balance syncs. Status text and +# errors come from `lunchflow_items.syncer.*`, in the same shape as the +# provider kit's shared syncer. class LunchflowItem::Syncer include SyncStats::Collector + SafeSyncError = Class.new(StandardError) + attr_reader :lunchflow_item def initialize(lunchflow_item) @@ -8,59 +14,88 @@ class LunchflowItem::Syncer end def perform_sync(sync) - # Phase 1: Import data from Lunchflow API - sync.update!(status_text: "Importing accounts from Lunchflow...") if sync.respond_to?(:status_text) + sync_errors = [] + + # Phase 1: Import data from the Lunch Flow API + update_status(sync, :importing_accounts) import_result = lunchflow_item.import_latest_lunchflow_data + sync_errors.concat(import_result_errors(import_result)) - # Phase 2: Collect setup statistics using shared concern - sync.update!(status_text: "Checking account configuration...") if sync.respond_to?(:status_text) - collect_setup_stats(sync, provider_accounts: lunchflow_item.lunchflow_accounts) + # Phase 2: Collect setup statistics + update_status(sync, :checking_account_configuration) - # Check for unlinked accounts - linked_accounts = lunchflow_item.lunchflow_accounts.joins(:account_provider) - unlinked_accounts = lunchflow_item.lunchflow_accounts.left_joins(:account_provider).where(account_providers: { id: nil }) + linked_count = lunchflow_item.lunchflow_accounts.joins(:account_provider).count + unlinked_count = lunchflow_item.lunchflow_accounts + .left_joins(:account_provider) + .where(account_providers: { id: nil }) + .count + total_count = linked_count + unlinked_count + collect_provider_setup_stats( + sync, + total_count: total_count, + linked_count: linked_count, + unlinked_count: unlinked_count + ) # Set pending_account_setup if there are unlinked accounts - if unlinked_accounts.any? + if unlinked_count.positive? lunchflow_item.update!(pending_account_setup: true) - sync.update!(status_text: "#{unlinked_accounts.count} accounts need setup...") if sync.respond_to?(:status_text) + update_status(sync, :accounts_need_setup, count: unlinked_count) else lunchflow_item.update!(pending_account_setup: false) end # Phase 3: Process transactions and holdings for linked accounts only - if linked_accounts.any? - sync.update!(status_text: "Processing transactions and holdings...") if sync.respond_to?(:status_text) + if linked_count.positive? + linked_accounts = lunchflow_item.lunchflow_accounts.joins(:account_provider) + update_status(sync, :processing_transactions) mark_import_started(sync) - Rails.logger.info "LunchflowItem::Syncer - Processing #{linked_accounts.count} linked accounts" - lunchflow_item.process_accounts - Rails.logger.info "LunchflowItem::Syncer - Finished processing accounts" + Rails.logger.info "#{self.class.name} - Processing #{linked_count} linked accounts" + process_results = lunchflow_item.process_accounts + sync_errors.concat(result_failure_errors(process_results, category: :account_processing_error, message_key: :account_processing_failed)) + Rails.logger.info "#{self.class.name} - Finished processing accounts" # Warn about limited investment data for investment/crypto accounts collect_investment_data_quality_warning(sync, linked_accounts) # Phase 4: Schedule balance calculations for linked accounts - sync.update!(status_text: "Calculating balances...") if sync.respond_to?(:status_text) - lunchflow_item.schedule_account_syncs( + update_status(sync, :calculating_balances) + schedule_results = lunchflow_item.schedule_account_syncs( parent_sync: sync, window_start_date: sync.window_start_date, window_end_date: sync.window_end_date ) + sync_errors.concat(result_failure_errors(schedule_results, category: :account_sync_error, message_key: :account_sync_failed)) # Phase 5: Collect transaction statistics - account_ids = linked_accounts.includes(:account_provider).filter_map { |la| la.current_account&.id } + account_ids = linked_accounts + .includes(account_provider: :account) + .filter_map { |provider_account| provider_account.current_account&.id } collect_transaction_stats(sync, account_ids: account_ids, source: "lunchflow") else - Rails.logger.info "LunchflowItem::Syncer - No linked accounts to process" + Rails.logger.info "#{self.class.name} - No linked accounts to process" end - # Mark sync health — surface importer failures so the sync isn't reported - # as completed when the upstream Lunchflow API rejected fetches (e.g. - # 429 rate-limit responses wrapped as 500s, transient network errors). - collect_health_stats(sync, errors: import_failures_as_errors(import_result).presence) + # Mark sync health + collect_health_stats(sync, errors: sync_errors.presence) rescue => e - collect_health_stats(sync, errors: [ { message: e.message, category: "sync_error" } ]) - raise + safe_message = user_safe_error_message(e) + Rails.logger.error "#{self.class.name} - sync failed for #{lunchflow_item.class.name} #{lunchflow_item.id}: #{e.class} - #{e.message}" + Rails.logger.error Array(e.backtrace).first(10).join("\n") + DebugLogEntry.capture( + category: "provider_sync_error", + level: "error", + message: "Sync failed", + source: self.class.name, + provider_key: "lunchflow", + family: lunchflow_item.family, + metadata: { lunchflow_item_id: lunchflow_item.id, error_class: e.class.name, error_message: e.message } + ) + Sentry.capture_exception(e) do |scope| + scope.set_tags(lunchflow_item_id: lunchflow_item.id) + end + collect_health_stats(sync, errors: [ { message: safe_message, category: "sync_error" } ]) + raise SafeSyncError, safe_message end def perform_post_sync @@ -69,37 +104,67 @@ class LunchflowItem::Syncer private - # Translate the LunchflowItem::Importer result hash into the error-shape - # collect_health_stats expects. Returns [] for a successful import. - def import_failures_as_errors(import_result) - return [] unless import_result.is_a?(Hash) - return [] if import_result[:success] + def update_status(sync, key, **options) + return unless sync.respond_to?(:status_text) + + sync.update!(status_text: I18n.t("lunchflow_items.syncer.#{key}", **options)) + end + + def collect_provider_setup_stats(sync, total_count:, linked_count:, unlinked_count:) + return {} unless sync.respond_to?(:sync_stats) + + setup_stats = { + "total_accounts" => total_count, + "linked_accounts" => linked_count, + "unlinked_accounts" => unlinked_count + } + + merge_sync_stats(sync, setup_stats) + setup_stats + end + + def import_result_errors(result) + return [] if result.is_a?(Hash) && result[:success] + + unless result.is_a?(Hash) + return [ sync_error(:import_error, :import_failed) ] + end errors = [] - accounts_failed = import_result[:accounts_failed].to_i - transactions_failed = import_result[:transactions_failed].to_i + accounts_failed = result[:accounts_failed].to_i + transactions_failed = result[:transactions_failed].to_i - if accounts_failed.positive? - errors << { - message: I18n.t("provider_warnings.lunchflow_accounts_failed", count: accounts_failed), - category: "lunchflow_import" - } - end - if transactions_failed.positive? - errors << { - message: I18n.t("provider_warnings.lunchflow_transactions_failed", count: transactions_failed), - category: "lunchflow_import" - } - end - if errors.empty? && import_result[:error].present? - errors << { - message: I18n.t("provider_warnings.lunchflow_import_error", error: import_result[:error]), - category: "lunchflow_import" - } + errors << sync_error(:account_import_error, :accounts_failed, count: accounts_failed) if accounts_failed.positive? + errors << sync_error(:transaction_import_error, :transactions_failed, count: transactions_failed) if transactions_failed.positive? + if errors.empty? + errors << (result[:error].present? ? sync_error(:import_error, :import_failed_with_error, error: result[:error]) : sync_error(:import_error, :import_failed)) end errors end + def result_failure_errors(results, category:, message_key:) + failed_count = Array(results).count { |result| result.is_a?(Hash) && result[:success] == false } + return [] unless failed_count.positive? + + [ sync_error(category, message_key, count: failed_count) ] + end + + def sync_error(category, message_key, **options) + { + message: I18n.t("lunchflow_items.syncer.#{message_key}", **options), + category: category.to_s + } + end + + def user_safe_error_message(error) + key = credentials_error?(error) ? :credentials_invalid : :failed + I18n.t("lunchflow_items.syncer.#{key}") + end + + def credentials_error?(error) + error.is_a?(Provider::Lunchflow::LunchflowError) && error.error_type.in?([ :unauthorized, :access_forbidden ]) + end + # Collects a data quality warning if any linked accounts are investment or crypto accounts. # Lunchflow cannot provide activity labels (Buy, Sell, Dividend, etc.) for investment transactions, # which may affect budget accuracy. diff --git a/config/locales/models/provider_warnings/ca.yml b/config/locales/models/provider_warnings/ca.yml index 53d3b45498..d972ab1716 100644 --- a/config/locales/models/provider_warnings/ca.yml +++ b/config/locales/models/provider_warnings/ca.yml @@ -5,10 +5,3 @@ ca: Les etiquetes d'activitat (Compra, Venda, Dividend) no estan disponibles, cosa que pot afectar la precisió del pressupost. Considera crear regles per excloure o categoritzar les transaccions d'inversió. - lunchflow_accounts_failed: - one: 'Importació de Lunchflow: no s''ha pogut actualitzar %{count} compte' - other: 'Importació de Lunchflow: no s''han pogut actualitzar %{count} comptes' - lunchflow_transactions_failed: - one: 'Importació de Lunchflow: no s''han pogut obtenir les transaccions de %{count} compte' - other: 'Importació de Lunchflow: no s''han pogut obtenir les transaccions de %{count} comptes' - lunchflow_import_error: 'Importació de Lunchflow: %{error}' diff --git a/config/locales/models/provider_warnings/en.yml b/config/locales/models/provider_warnings/en.yml index 6d4fe6041d..af191c4144 100644 --- a/config/locales/models/provider_warnings/en.yml +++ b/config/locales/models/provider_warnings/en.yml @@ -5,13 +5,6 @@ en: enable_banking_history_truncated: one: "Enable Banking: the full transaction history of %{count} account could not be fetched, so older transactions may be missing" other: "Enable Banking: the full transaction history of %{count} accounts could not be fetched, so older transactions may be missing" - lunchflow_accounts_failed: - one: "Lunchflow import: %{count} account failed to update" - other: "Lunchflow import: %{count} accounts failed to update" - lunchflow_transactions_failed: - one: "Lunchflow import: transaction fetch failed for %{count} account" - other: "Lunchflow import: transaction fetch failed for %{count} accounts" - lunchflow_import_error: "Lunchflow import: %{error}" truelayer_accounts_failed: one: "TrueLayer import: %{count} account failed to update" other: "TrueLayer import: %{count} accounts failed to update" diff --git a/config/locales/models/provider_warnings/es.yml b/config/locales/models/provider_warnings/es.yml index b1d0af34da..04f6c2e20d 100644 --- a/config/locales/models/provider_warnings/es.yml +++ b/config/locales/models/provider_warnings/es.yml @@ -5,13 +5,6 @@ es: enable_banking_history_truncated: one: 'Enable Banking: no se ha podido obtener el historial completo de transacciones de %{count} cuenta, así que pueden faltar transacciones antiguas' other: 'Enable Banking: no se ha podido obtener el historial completo de transacciones de %{count} cuentas, así que pueden faltar transacciones antiguas' - lunchflow_accounts_failed: - one: 'Importación de Lunchflow: no se ha podido actualizar %{count} cuenta' - other: 'Importación de Lunchflow: no se han podido actualizar %{count} cuentas' - lunchflow_transactions_failed: - one: 'Importación de Lunchflow: no se han podido obtener las transacciones de %{count} cuenta' - other: 'Importación de Lunchflow: no se han podido obtener las transacciones de %{count} cuentas' - lunchflow_import_error: 'Importación de Lunchflow: %{error}' truelayer_accounts_failed: one: 'Importación de TrueLayer: no se ha podido actualizar %{count} cuenta' other: 'Importación de TrueLayer: no se han podido actualizar %{count} cuentas' diff --git a/config/locales/models/provider_warnings/fr.yml b/config/locales/models/provider_warnings/fr.yml index 3f855d5ed3..56e17c29fa 100644 --- a/config/locales/models/provider_warnings/fr.yml +++ b/config/locales/models/provider_warnings/fr.yml @@ -8,13 +8,6 @@ fr: Les étiquettes d'activité (Achat, Vente, Dividende) ne sont pas disponibles, ce qui peut affecter la précision du budget. Pensez à créer des règles pour exclure ou catégoriser les transactions d'investissement. - lunchflow_accounts_failed: - one: 'Import Lunchflow : la mise à jour de %{count} compte a échoué' - other: 'Import Lunchflow : la mise à jour de %{count} comptes a échoué' - lunchflow_import_error: 'Import Lunchflow : %{error}' - lunchflow_transactions_failed: - one: 'Import Lunchflow : la récupération des transactions a échoué pour %{count} compte' - other: 'Import Lunchflow : la récupération des transactions a échoué pour %{count} comptes' truelayer_accounts_failed: one: 'Import TrueLayer : échec de la mise à jour de %{count} compte' other: 'Import TrueLayer : échec de la mise à jour de %{count} comptes' diff --git a/config/locales/models/provider_warnings/nb.yml b/config/locales/models/provider_warnings/nb.yml index d4130a353b..446f39db75 100644 --- a/config/locales/models/provider_warnings/nb.yml +++ b/config/locales/models/provider_warnings/nb.yml @@ -2,13 +2,6 @@ nb: provider_warnings: limited_investment_data: "Investeringsdata fra denne leverandøren er begrenset. Aktivitetsetiketter (Kjøp, Salg, Utbytte) er ikke tilgjengelige, noe som kan påvirke budsjettnøyaktigheten. Vurder å opprette regler for å ekskludere eller kategorisere investeringstransaksjoner." - lunchflow_accounts_failed: - one: 'Lunchflow-import: %{count} konto kunne ikke oppdateres' - other: 'Lunchflow-import: %{count} kontoer kunne ikke oppdateres' - lunchflow_transactions_failed: - one: 'Lunchflow-import: kunne ikke hente transaksjoner for %{count} konto' - other: 'Lunchflow-import: kunne ikke hente transaksjoner for %{count} kontoer' - lunchflow_import_error: 'Lunchflow-import: %{error}' enable_banking_history_truncated: one: "Enable Banking: Hele transaksjonshistorikken for %{count} konto kunne ikke hentes, så eldre transaksjoner kan mangle" other: "Enable Banking: Hele transaksjonshistorikken for %{count} kontoer kunne ikke hentes, så eldre transaksjoner kan mangle" diff --git a/config/locales/models/provider_warnings/nl.yml b/config/locales/models/provider_warnings/nl.yml index 5d6ecc6d20..8698b82dcf 100644 --- a/config/locales/models/provider_warnings/nl.yml +++ b/config/locales/models/provider_warnings/nl.yml @@ -2,13 +2,6 @@ nl: provider_warnings: limited_investment_data: "Beleggingsgegevens van deze provider zijn beperkt. Activiteitslabels (Koop, Verkoop, Dividend) zijn niet beschikbaar, wat de nauwkeurigheid van het budget kan beïnvloeden. Overweeg regels te maken om beleggingstransacties uit te sluiten of te categoriseren." - lunchflow_accounts_failed: - one: "Lunchflow-import: %{count} account kon niet worden bijgewerkt" - other: "Lunchflow-import: %{count} accounts konden niet worden bijgewerkt" - lunchflow_transactions_failed: - one: "Lunchflow-import: ophalen van transacties mislukt voor %{count} account" - other: "Lunchflow-import: ophalen van transacties mislukt voor %{count} accounts" - lunchflow_import_error: "Lunchflow-import: %{error}" truelayer_accounts_failed: one: "TrueLayer-import: %{count} account kon niet worden bijgewerkt" other: "TrueLayer-import: %{count} accounts konden niet worden bijgewerkt" diff --git a/config/locales/models/provider_warnings/pl.yml b/config/locales/models/provider_warnings/pl.yml index 01689371ce..2be55b25d0 100644 --- a/config/locales/models/provider_warnings/pl.yml +++ b/config/locales/models/provider_warnings/pl.yml @@ -4,16 +4,3 @@ pl: limited_investment_data: Dane inwestycyjne od tego dostawcy są ograniczone. Etykiety transakcji (Kupno, Sprzedaż, Dywidenda) są niedostępne, co może wpłynąć na dokładność budżetu. Rozważ tworzenie reguł wykluczenia lub kategoryzacji transakcji inwestycyjnych. - lunchflow_accounts_failed: - few: 'Import Lunch Flow: nie udało się zaktualizować %{count} konta' - many: 'Import Lunch Flow: nie udało się zaktualizować %{count} kont' - one: 'Import Lunch Flow: nie udało się zaktualizować %{count} konto' - other: 'Import Lunch Flow: nie udało się zaktualizować %{count} kont' - lunchflow_import_error: 'Import Lunch Flow: %{error}' - lunchflow_transactions_failed: - few: 'Import Lunch Flow: pobranie transakcji nie powiodło się dla %{count} kont' - many: 'Import Lunch Flow: pobranie transakcji nie powiodło się dla %{count} - kont' - one: 'Import Lunch Flow: pobranie transakcji nie powiodło się dla %{count} konta' - other: 'Import Lunch Flow: pobranie transakcji nie powiodło się dla %{count} - kont' diff --git a/config/locales/models/provider_warnings/pt-BR.yml b/config/locales/models/provider_warnings/pt-BR.yml index 7caee06390..f4309d7cfb 100644 --- a/config/locales/models/provider_warnings/pt-BR.yml +++ b/config/locales/models/provider_warnings/pt-BR.yml @@ -5,13 +5,6 @@ pt-BR: enable_banking_history_truncated: one: "Enable Banking: não foi possível buscar o histórico completo de transações de %{count} conta, então transações mais antigas podem estar faltando" other: "Enable Banking: não foi possível buscar o histórico completo de transações de %{count} contas, então transações mais antigas podem estar faltando" - lunchflow_accounts_failed: - one: "Importação do Lunchflow: %{count} conta não foi atualizada" - other: "Importação do Lunchflow: %{count} contas não foram atualizadas" - lunchflow_transactions_failed: - one: "Importação do Lunchflow: falha ao buscar transações de %{count} conta" - other: "Importação do Lunchflow: falha ao buscar transações de %{count} contas" - lunchflow_import_error: "Importação do Lunchflow: %{error}" truelayer_accounts_failed: one: "Importação do TrueLayer: %{count} conta não foi atualizada" other: "Importação do TrueLayer: %{count} contas não foram atualizadas" diff --git a/config/locales/models/provider_warnings/pt-PT.yml b/config/locales/models/provider_warnings/pt-PT.yml index 952e80f4de..8a1ecfc311 100644 --- a/config/locales/models/provider_warnings/pt-PT.yml +++ b/config/locales/models/provider_warnings/pt-PT.yml @@ -2,10 +2,3 @@ pt-PT: provider_warnings: limited_investment_data: "Os dados de investimento deste serviço são limitados. Os rótulos de atividade (Compra, Venda, Dividendo) não estão disponíveis, o que pode afetar a precisão do orçamento. Considere criar regras para excluir ou categorizar transações de investimento." - lunchflow_accounts_failed: - one: "Importação Lunchflow: a atualização de %{count} conta falhou" - other: "Importação Lunchflow: a atualização de %{count} contas falhou" - lunchflow_transactions_failed: - one: "Importação Lunchflow: a obtenção de transações falhou para %{count} conta" - other: "Importação Lunchflow: a obtenção de transações falhou para %{count} contas" - lunchflow_import_error: "Importação Lunchflow: %{error}" diff --git a/config/locales/models/provider_warnings/ru.yml b/config/locales/models/provider_warnings/ru.yml index df7a41b0ac..ace3353f8f 100644 --- a/config/locales/models/provider_warnings/ru.yml +++ b/config/locales/models/provider_warnings/ru.yml @@ -5,14 +5,3 @@ ru: Метки активности (Покупка, Продажа, Дивиденд) недоступны, что может повлиять на точность бюджета. Рассмотрите возможность создания правил для исключения или категоризации инвестиционных операций. - lunchflow_accounts_failed: - one: 'Импорт Lunchflow: не удалось обновить %{count} счёт' - few: 'Импорт Lunchflow: не удалось обновить %{count} счёта' - many: 'Импорт Lunchflow: не удалось обновить %{count} счетов' - other: 'Импорт Lunchflow: не удалось обновить %{count} счёта' - lunchflow_transactions_failed: - one: 'Импорт Lunchflow: не удалось получить операции по %{count} счёту' - few: 'Импорт Lunchflow: не удалось получить операции по %{count} счетам' - many: 'Импорт Lunchflow: не удалось получить операции по %{count} счетам' - other: 'Импорт Lunchflow: не удалось получить операции по %{count} счёта' - lunchflow_import_error: 'Импорт Lunchflow: %{error}' diff --git a/config/locales/models/provider_warnings/tr.yml b/config/locales/models/provider_warnings/tr.yml index 3f31d09b49..c8b4ea4c4d 100644 --- a/config/locales/models/provider_warnings/tr.yml +++ b/config/locales/models/provider_warnings/tr.yml @@ -5,10 +5,3 @@ tr: etiketleri (Al, Sat, Temettü) mevcut olmadığından bütçe doğruluğu etkilenebilir. Yatırım işlemlerini hariç tutmak veya kategorize etmek için kurallar oluşturmayı düşünün. - lunchflow_accounts_failed: - one: 'Lunchflow içe aktarma: %{count} hesap güncellenemedi' - other: 'Lunchflow içe aktarma: %{count} hesap güncellenemedi' - lunchflow_transactions_failed: - one: 'Lunchflow içe aktarma: %{count} hesabın işlemleri alınamadı' - other: 'Lunchflow içe aktarma: %{count} hesabın işlemleri alınamadı' - lunchflow_import_error: 'Lunchflow içe aktarma: %{error}' diff --git a/config/locales/models/provider_warnings/uk.yml b/config/locales/models/provider_warnings/uk.yml index 36091ab3e8..bc01b2b7b7 100644 --- a/config/locales/models/provider_warnings/uk.yml +++ b/config/locales/models/provider_warnings/uk.yml @@ -2,14 +2,3 @@ uk: provider_warnings: limited_investment_data: "Інвестиційні дані від цього постачальника обмежені. Мітки активності (Купівля, Продаж, Дивіденди) недоступні, що може вплинути на точність бюджету. Розгляньте можливість створення правил для виключення або категоризації інвестиційних транзакцій." - lunchflow_accounts_failed: - one: 'Імпорт Lunchflow: не вдалося оновити %{count} рахунок' - few: 'Імпорт Lunchflow: не вдалося оновити %{count} рахунки' - many: 'Імпорт Lunchflow: не вдалося оновити %{count} рахунків' - other: 'Імпорт Lunchflow: не вдалося оновити %{count} рахунку' - lunchflow_transactions_failed: - one: 'Імпорт Lunchflow: не вдалося отримати транзакції для %{count} рахунку' - few: 'Імпорт Lunchflow: не вдалося отримати транзакції для %{count} рахунків' - many: 'Імпорт Lunchflow: не вдалося отримати транзакції для %{count} рахунків' - other: 'Імпорт Lunchflow: не вдалося отримати транзакції для %{count} рахунку' - lunchflow_import_error: 'Імпорт Lunchflow: %{error}' diff --git a/config/locales/models/provider_warnings/zh-CN.yml b/config/locales/models/provider_warnings/zh-CN.yml index c74af5baea..c60d531e27 100644 --- a/config/locales/models/provider_warnings/zh-CN.yml +++ b/config/locales/models/provider_warnings/zh-CN.yml @@ -2,13 +2,6 @@ zh-CN: provider_warnings: limited_investment_data: "此提供商的投资数据有限。活动标签(买入、卖出、股息)不可用,这可能会影响预算准确性。请考虑创建规则以排除或分类投资交易。" - lunchflow_accounts_failed: - one: Lunchflow 导入:%{count} 个账户更新失败 - other: Lunchflow 导入:%{count} 个账户更新失败 - lunchflow_transactions_failed: - one: Lunchflow 导入:%{count} 个账户的交易获取失败 - other: Lunchflow 导入:%{count} 个账户的交易获取失败 - lunchflow_import_error: Lunchflow 导入:%{error} truelayer_accounts_failed: one: "TrueLayer 导入:%{count} 个账户更新失败" other: "TrueLayer 导入:%{count} 个账户更新失败" diff --git a/config/locales/views/lunchflow_items/ca.yml b/config/locales/views/lunchflow_items/ca.yml index 49f6ffb3ae..52ce73b520 100644 --- a/config/locales/views/lunchflow_items/ca.yml +++ b/config/locales/views/lunchflow_items/ca.yml @@ -1,6 +1,14 @@ --- ca: lunchflow_items: + syncer: + accounts_failed: + one: 'Importació de Lunchflow: no s''ha pogut actualitzar %{count} compte' + other: 'Importació de Lunchflow: no s''han pogut actualitzar %{count} comptes' + import_failed_with_error: 'Importació de Lunchflow: %{error}' + transactions_failed: + one: 'Importació de Lunchflow: no s''han pogut obtenir les transaccions de %{count} compte' + other: 'Importació de Lunchflow: no s''han pogut obtenir les transaccions de %{count} comptes' api_error: check_provider_settings: Revisa la configuració del proveïdor common_issues: 'Problemes habituals:' diff --git a/config/locales/views/lunchflow_items/en.yml b/config/locales/views/lunchflow_items/en.yml index 7a1740c4e4..5f061c764f 100644 --- a/config/locales/views/lunchflow_items/en.yml +++ b/config/locales/views/lunchflow_items/en.yml @@ -1,6 +1,30 @@ --- en: lunchflow_items: + syncer: + account_processing_failed: + one: "%{count} Lunch Flow account failed while processing." + other: "%{count} Lunch Flow accounts failed while processing." + account_sync_failed: + one: "%{count} Lunch Flow account sync could not be scheduled." + other: "%{count} Lunch Flow account syncs could not be scheduled." + accounts_need_setup: + one: "%{count} account needs setup..." + other: "%{count} accounts need setup..." + calculating_balances: Calculating balances... + checking_account_configuration: Checking account configuration... + credentials_invalid: Invalid Lunch Flow API key or account permissions + failed: Sync failed. Please try again or contact support. + import_failed: Lunch Flow import failed. + importing_accounts: Importing accounts from Lunchflow... + processing_transactions: Processing transactions and holdings... + accounts_failed: + one: "Lunchflow import: %{count} account failed to update" + other: "Lunchflow import: %{count} accounts failed to update" + import_failed_with_error: "Lunchflow import: %{error}" + transactions_failed: + one: "Lunchflow import: transaction fetch failed for %{count} account" + other: "Lunchflow import: transaction fetch failed for %{count} accounts" api_error: title: Lunch Flow Connection Error unable_to_connect: Unable to connect to Lunch Flow diff --git a/config/locales/views/lunchflow_items/es.yml b/config/locales/views/lunchflow_items/es.yml index 15f3a3ba09..5198e2a048 100644 --- a/config/locales/views/lunchflow_items/es.yml +++ b/config/locales/views/lunchflow_items/es.yml @@ -1,6 +1,14 @@ --- es: lunchflow_items: + syncer: + accounts_failed: + one: 'Importación de Lunchflow: no se ha podido actualizar %{count} cuenta' + other: 'Importación de Lunchflow: no se han podido actualizar %{count} cuentas' + import_failed_with_error: 'Importación de Lunchflow: %{error}' + transactions_failed: + one: 'Importación de Lunchflow: no se han podido obtener las transacciones de %{count} cuenta' + other: 'Importación de Lunchflow: no se han podido obtener las transacciones de %{count} cuentas' api_error: title: Error de conexión con Lunch Flow unable_to_connect: No se puede conectar con Lunch Flow diff --git a/config/locales/views/lunchflow_items/fr.yml b/config/locales/views/lunchflow_items/fr.yml index 912a2b69b4..4b26bad4f4 100644 --- a/config/locales/views/lunchflow_items/fr.yml +++ b/config/locales/views/lunchflow_items/fr.yml @@ -1,6 +1,14 @@ --- fr: lunchflow_items: + syncer: + accounts_failed: + one: 'Import Lunchflow : la mise à jour de %{count} compte a échoué' + other: 'Import Lunchflow : la mise à jour de %{count} comptes a échoué' + import_failed_with_error: 'Import Lunchflow : %{error}' + transactions_failed: + one: 'Import Lunchflow : la récupération des transactions a échoué pour %{count} compte' + other: 'Import Lunchflow : la récupération des transactions a échoué pour %{count} comptes' api_error: check_provider_settings: Vérifier les paramètres du fournisseur common_issues: 'Problèmes courants :' diff --git a/config/locales/views/lunchflow_items/nb.yml b/config/locales/views/lunchflow_items/nb.yml index e7e5e62d26..19c531f46d 100644 --- a/config/locales/views/lunchflow_items/nb.yml +++ b/config/locales/views/lunchflow_items/nb.yml @@ -1,6 +1,14 @@ --- nb: lunchflow_items: + syncer: + accounts_failed: + one: 'Lunchflow-import: %{count} konto kunne ikke oppdateres' + other: 'Lunchflow-import: %{count} kontoer kunne ikke oppdateres' + import_failed_with_error: 'Lunchflow-import: %{error}' + transactions_failed: + one: 'Lunchflow-import: kunne ikke hente transaksjoner for %{count} konto' + other: 'Lunchflow-import: kunne ikke hente transaksjoner for %{count} kontoer' api_error: title: Tilkoblingsfeil for Lunch Flow unable_to_connect: Kan ikke koble til Lunch Flow diff --git a/config/locales/views/lunchflow_items/nl.yml b/config/locales/views/lunchflow_items/nl.yml index 5a49608994..128a7dfa5e 100644 --- a/config/locales/views/lunchflow_items/nl.yml +++ b/config/locales/views/lunchflow_items/nl.yml @@ -1,6 +1,14 @@ --- nl: lunchflow_items: + syncer: + accounts_failed: + one: "Lunchflow-import: %{count} account kon niet worden bijgewerkt" + other: "Lunchflow-import: %{count} accounts konden niet worden bijgewerkt" + import_failed_with_error: "Lunchflow-import: %{error}" + transactions_failed: + one: "Lunchflow-import: ophalen van transacties mislukt voor %{count} account" + other: "Lunchflow-import: ophalen van transacties mislukt voor %{count} accounts" api_error: title: "Lunch Flow-verbindingsfout" unable_to_connect: "Kan geen verbinding maken met Lunch Flow" diff --git a/config/locales/views/lunchflow_items/pl.yml b/config/locales/views/lunchflow_items/pl.yml index 00bc66e52c..6de7c0456a 100644 --- a/config/locales/views/lunchflow_items/pl.yml +++ b/config/locales/views/lunchflow_items/pl.yml @@ -1,6 +1,20 @@ --- pl: lunchflow_items: + syncer: + accounts_failed: + few: 'Import Lunch Flow: nie udało się zaktualizować %{count} konta' + many: 'Import Lunch Flow: nie udało się zaktualizować %{count} kont' + one: 'Import Lunch Flow: nie udało się zaktualizować %{count} konto' + other: 'Import Lunch Flow: nie udało się zaktualizować %{count} kont' + import_failed_with_error: 'Import Lunch Flow: %{error}' + transactions_failed: + few: 'Import Lunch Flow: pobranie transakcji nie powiodło się dla %{count} kont' + many: 'Import Lunch Flow: pobranie transakcji nie powiodło się dla %{count} + kont' + one: 'Import Lunch Flow: pobranie transakcji nie powiodło się dla %{count} konta' + other: 'Import Lunch Flow: pobranie transakcji nie powiodło się dla %{count} + kont' api_error: check_provider_settings: Sprawdź ustawienia dostawcy common_issues: 'Typowe problemy:' diff --git a/config/locales/views/lunchflow_items/pt-BR.yml b/config/locales/views/lunchflow_items/pt-BR.yml index 6ffe548989..cfad8308cd 100644 --- a/config/locales/views/lunchflow_items/pt-BR.yml +++ b/config/locales/views/lunchflow_items/pt-BR.yml @@ -1,6 +1,14 @@ --- pt-BR: lunchflow_items: + syncer: + accounts_failed: + one: "Importação do Lunchflow: %{count} conta não foi atualizada" + other: "Importação do Lunchflow: %{count} contas não foram atualizadas" + import_failed_with_error: "Importação do Lunchflow: %{error}" + transactions_failed: + one: "Importação do Lunchflow: falha ao buscar transações de %{count} conta" + other: "Importação do Lunchflow: falha ao buscar transações de %{count} contas" api_error: title: Erro de conexão com o Lunch Flow unable_to_connect: Não é possível conectar ao Lunch Flow diff --git a/config/locales/views/lunchflow_items/pt-PT.yml b/config/locales/views/lunchflow_items/pt-PT.yml index 6718d8b1b9..b7124ee246 100644 --- a/config/locales/views/lunchflow_items/pt-PT.yml +++ b/config/locales/views/lunchflow_items/pt-PT.yml @@ -1,6 +1,14 @@ --- pt-PT: lunchflow_items: + syncer: + accounts_failed: + one: "Importação Lunchflow: a atualização de %{count} conta falhou" + other: "Importação Lunchflow: a atualização de %{count} contas falhou" + import_failed_with_error: "Importação Lunchflow: %{error}" + transactions_failed: + one: "Importação Lunchflow: a obtenção de transações falhou para %{count} conta" + other: "Importação Lunchflow: a obtenção de transações falhou para %{count} contas" api_error: title: Erro de ligação Lunch Flow unable_to_connect: Não foi possível ligar ao Lunch Flow diff --git a/config/locales/views/lunchflow_items/ru.yml b/config/locales/views/lunchflow_items/ru.yml index d191ef37f3..7dfe222668 100644 --- a/config/locales/views/lunchflow_items/ru.yml +++ b/config/locales/views/lunchflow_items/ru.yml @@ -1,6 +1,18 @@ --- ru: lunchflow_items: + syncer: + accounts_failed: + one: 'Импорт Lunchflow: не удалось обновить %{count} счёт' + few: 'Импорт Lunchflow: не удалось обновить %{count} счёта' + many: 'Импорт Lunchflow: не удалось обновить %{count} счетов' + other: 'Импорт Lunchflow: не удалось обновить %{count} счёта' + import_failed_with_error: 'Импорт Lunchflow: %{error}' + transactions_failed: + one: 'Импорт Lunchflow: не удалось получить операции по %{count} счёту' + few: 'Импорт Lunchflow: не удалось получить операции по %{count} счетам' + many: 'Импорт Lunchflow: не удалось получить операции по %{count} счетам' + other: 'Импорт Lunchflow: не удалось получить операции по %{count} счёта' api_error: check_provider_settings: Проверьте настройки провайдера common_issues: 'Возможные проблемы:' diff --git a/config/locales/views/lunchflow_items/tr.yml b/config/locales/views/lunchflow_items/tr.yml index 18845f5da2..abe17f3195 100644 --- a/config/locales/views/lunchflow_items/tr.yml +++ b/config/locales/views/lunchflow_items/tr.yml @@ -1,6 +1,14 @@ --- tr: lunchflow_items: + syncer: + accounts_failed: + one: 'Lunchflow içe aktarma: %{count} hesap güncellenemedi' + other: 'Lunchflow içe aktarma: %{count} hesap güncellenemedi' + import_failed_with_error: 'Lunchflow içe aktarma: %{error}' + transactions_failed: + one: 'Lunchflow içe aktarma: %{count} hesabın işlemleri alınamadı' + other: 'Lunchflow içe aktarma: %{count} hesabın işlemleri alınamadı' api_error: check_provider_settings: Sağlayıcı Ayarlarını Kontrol Et common_issues: 'Yaygın Sorunlar:' diff --git a/config/locales/views/lunchflow_items/uk.yml b/config/locales/views/lunchflow_items/uk.yml index f15f9eb19c..d9172b59e7 100644 --- a/config/locales/views/lunchflow_items/uk.yml +++ b/config/locales/views/lunchflow_items/uk.yml @@ -1,5 +1,17 @@ uk: lunchflow_items: + syncer: + accounts_failed: + one: 'Імпорт Lunchflow: не вдалося оновити %{count} рахунок' + few: 'Імпорт Lunchflow: не вдалося оновити %{count} рахунки' + many: 'Імпорт Lunchflow: не вдалося оновити %{count} рахунків' + other: 'Імпорт Lunchflow: не вдалося оновити %{count} рахунку' + import_failed_with_error: 'Імпорт Lunchflow: %{error}' + transactions_failed: + one: 'Імпорт Lunchflow: не вдалося отримати транзакції для %{count} рахунку' + few: 'Імпорт Lunchflow: не вдалося отримати транзакції для %{count} рахунків' + many: 'Імпорт Lunchflow: не вдалося отримати транзакції для %{count} рахунків' + other: 'Імпорт Lunchflow: не вдалося отримати транзакції для %{count} рахунку' api_error: title: Помилка з'єднання Lunch Flow unable_to_connect: Неможливо підключитися до Lunch Flow diff --git a/config/locales/views/lunchflow_items/zh-CN.yml b/config/locales/views/lunchflow_items/zh-CN.yml index cc6c128cc6..dfa33590ad 100644 --- a/config/locales/views/lunchflow_items/zh-CN.yml +++ b/config/locales/views/lunchflow_items/zh-CN.yml @@ -1,6 +1,14 @@ --- zh-CN: lunchflow_items: + syncer: + accounts_failed: + one: Lunchflow 导入:%{count} 个账户更新失败 + other: Lunchflow 导入:%{count} 个账户更新失败 + import_failed_with_error: Lunchflow 导入:%{error} + transactions_failed: + one: Lunchflow 导入:%{count} 个账户的交易获取失败 + other: Lunchflow 导入:%{count} 个账户的交易获取失败 api_error: title: Lunch Flow 连接错误 unable_to_connect: 无法连接到 Lunch Flow diff --git a/test/models/lunchflow_item/syncer_test.rb b/test/models/lunchflow_item/syncer_test.rb index e3f9b5a8f4..fcffafadaa 100644 --- a/test/models/lunchflow_item/syncer_test.rb +++ b/test/models/lunchflow_item/syncer_test.rb @@ -34,10 +34,10 @@ class LunchflowItem::SyncerTest < ActiveSupport::TestCase assert_equal 1, sync.sync_stats["total_errors"] assert_equal( - [ I18n.t("provider_warnings.lunchflow_accounts_failed", count: 2) ], + [ I18n.t("lunchflow_items.syncer.accounts_failed", count: 2) ], sync.sync_stats["errors"].map { |e| e["message"] } ) - assert_equal "lunchflow_import", sync.sync_stats["errors"].first["category"] + assert_equal "account_import_error", sync.sync_stats["errors"].first["category"] end test "marks sync unhealthy when importer reports transactions_failed" do @@ -52,9 +52,10 @@ class LunchflowItem::SyncerTest < ActiveSupport::TestCase assert_equal 1, sync.sync_stats["total_errors"] assert_equal( - [ I18n.t("provider_warnings.lunchflow_transactions_failed", count: 3) ], + [ I18n.t("lunchflow_items.syncer.transactions_failed", count: 3) ], sync.sync_stats["errors"].map { |e| e["message"] } ) + assert_equal "transaction_import_error", sync.sync_stats["errors"].first["category"] end test "records both failure categories when accounts and transactions both fail" do @@ -70,25 +71,92 @@ class LunchflowItem::SyncerTest < ActiveSupport::TestCase assert_equal 2, sync.sync_stats["total_errors"] assert_equal( [ - I18n.t("provider_warnings.lunchflow_accounts_failed", count: 1), - I18n.t("provider_warnings.lunchflow_transactions_failed", count: 4) + I18n.t("lunchflow_items.syncer.accounts_failed", count: 1), + I18n.t("lunchflow_items.syncer.transactions_failed", count: 4) ], sync.sync_stats["errors"].map { |e| e["message"] } ) end - test "captures sync_error category and reraises when import raises" do + test "an import that raises stores a safe message and reraises it as SafeSyncError" do sync = recording_sync @lunchflow_item.expects(:import_latest_lunchflow_data).raises(StandardError, "boom") + Sentry.expects(:capture_exception).once - assert_raises(StandardError) do + error = assert_raises(LunchflowItem::Syncer::SafeSyncError) do @syncer.perform_sync(sync) end + assert_equal I18n.t("lunchflow_items.syncer.failed"), error.message assert_equal 1, sync.sync_stats["total_errors"] - error = sync.sync_stats["errors"].first - assert_equal "boom", error["message"] - assert_equal "sync_error", error["category"] + stored = sync.sync_stats["errors"].first + assert_equal [ I18n.t("lunchflow_items.syncer.failed"), "sync_error" ], stored.values_at("message", "category") + end + + test "an import that fails with the provider's own error reports that error" do + sync = recording_sync + @lunchflow_item.expects(:import_latest_lunchflow_data).returns(success: false, error: "Rate limited") + + @syncer.perform_sync(sync) + + assert_equal [ [ I18n.t("lunchflow_items.syncer.import_failed_with_error", error: "Rate limited"), "import_error" ] ], + sync.sync_stats["errors"].map { |e| e.values_at("message", "category") } + end + + test "a failed sync records a debug log entry for support" do + @lunchflow_item.expects(:import_latest_lunchflow_data).raises(RuntimeError, "connection reset") + Sentry.stubs(:capture_exception) + + assert_difference -> { DebugLogEntry.where(provider_key: "lunchflow").count }, 1 do + assert_raises(LunchflowItem::Syncer::SafeSyncError) { @syncer.perform_sync(recording_sync) } + end + + entry = DebugLogEntry.where(provider_key: "lunchflow").recent.first + assert_equal [ "provider_sync_error", "error", "LunchflowItem::Syncer" ], [ entry.category, entry.level, entry.source ] + assert_equal @lunchflow_item.family, entry.family + assert_equal({ "lunchflow_item_id" => @lunchflow_item.id, "error_class" => "RuntimeError", "error_message" => "connection reset" }, entry.metadata) + end + + test "a failed import with no counts and no error text reports the generic failure" do + sync = recording_sync + @lunchflow_item.expects(:import_latest_lunchflow_data).returns(success: false) + + @syncer.perform_sync(sync) + + assert_equal [ [ I18n.t("lunchflow_items.syncer.import_failed"), "import_error" ] ], + sync.sync_stats["errors"].map { |e| e.values_at("message", "category") } + end + + test "linked accounts that fail to process or schedule are reported" do + lunchflow_account = @lunchflow_item.lunchflow_accounts.first + account = @lunchflow_item.family.accounts.create!(name: "Linked", balance: 0, currency: "USD", accountable: Depository.new) + AccountProvider.create!(account: account, provider: lunchflow_account) + sync = Sync.create!(syncable: @lunchflow_item) + @lunchflow_item.stubs(:import_latest_lunchflow_data).returns(success: true) + @lunchflow_item.stubs(:process_accounts).returns([ { success: false, error: "bad row" } ]) + @lunchflow_item.stubs(:schedule_account_syncs).returns([ { success: true }, { success: false, error: "queue down" } ]) + + @syncer.perform_sync(sync) + + assert_equal( + [ + [ I18n.t("lunchflow_items.syncer.account_processing_failed", count: 1), "account_processing_error" ], + [ I18n.t("lunchflow_items.syncer.account_sync_failed", count: 1), "account_sync_error" ] + ], + sync.reload.sync_stats["errors"].map { |e| e.values_at("message", "category") } + ) + end + + test "status text comes from the Lunch Flow syncer translations" do + I18n.backend.store_translations(:en, lunchflow_items: { syncer: { importing_accounts: "Fetching from Lunch Flow" } }) + sync = recording_sync + @lunchflow_item.stubs(:import_latest_lunchflow_data).returns(success: true) + + @syncer.perform_sync(sync) + + assert_includes sync.updates.filter_map { |update| update[:status_text] }, "Fetching from Lunch Flow" + ensure + I18n.reload! end test "a rejected API key fails the sync and flags the connection" do @@ -99,7 +167,7 @@ class LunchflowItem::SyncerTest < ActiveSupport::TestCase sync.perform assert sync.reload.failed?, "expected the sync to fail, was #{sync.status}" - assert_equal "Invalid API key", sync.error + assert_equal I18n.t("lunchflow_items.syncer.credentials_invalid"), sync.error assert @lunchflow_item.reload.requires_update? end