The personal finance app for everyone (by everyone)
Ruby
Enable Banking: fetch the full available history on the first transaction fetch (#5045)
arnaurodondev1e7b605e0cf1
diff --git a/app/controllers/enable_banking_items_controller.rb b/app/controllers/enable_banking_items_controller.rbindex a8903da28a..639a667470 100644--- a/app/controllers/enable_banking_items_controller.rb+++ b/app/controllers/enable_banking_items_controller.rb@@ -354,9 +354,10 @@ class EnableBankingItemsController < ApplicationControlleraccount_types = params[:account_types] || {}account_subtypes = params[:account_subtypes] || {}- # Update sync start date from form if provided- if params[:sync_start_date].present?- @enable_banking_item.update!(sync_start_date: params[:sync_start_date])+ # The modal's date field is optional: a blank one means no lower bound, so+ # the first fetch imports as much history as the bank provides.+ if params.key?(:sync_start_date)+ @enable_banking_item.update!(sync_start_date: params[:sync_start_date].presence)endcreated_count = 0diff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rbindex 6c52a861ae..8814b70945 100644--- a/app/models/enable_banking_item/importer.rb+++ b/app/models/enable_banking_item/importer.rb@@ -5,6 +5,19 @@ class EnableBankingItem::Importer# Enable Banking typically returns ~100 transactions per page, so 100 pages = ~10,000 transactionsMAX_PAGINATION_PAGES = 100+ # A first fetch with strategy=longest can span many years, and Enable Banking+ # says it may return empty pages with a continuation key, so it gets a larger+ # budget. Hitting the cap keeps the partial result and reports the fetch as+ # truncated (see fetch_and_store_transactions).+ MAX_LONGEST_PAGINATION_PAGES = 1000++ # Under PSD2, access without a fresh SCA covers the last 90 days, and some+ # ASPSPs reject a date_from at exactly 90 days. The newest stored row only+ # pulls an incremental fetch back this far, the same 89 days the provider's+ # WRONG_TRANSACTIONS_PERIOD fallback starts with (see+ # incremental_sync_start_date).+ STORED_ROW_LOOKBACK_LIMIT = Provider::EnableBanking::FALLBACK_TRANSACTIONS_DATE_FROM_DAYS.first.days+# Prefer booked ledger balances for net worth/current_balance. Available balances# can include an arranged overdraft facility for some ASPSPs (for example CGD PT),# so they are only a last-resort fallback.@@ -142,6 +155,7 @@ class EnableBankingItem::Importer# must not prevent transaction sync for the same account.transactions_imported = 0transactions_failed = 0+ transactions_truncated = 0balances_failed = 0linked_accounts_query = enable_banking_item.enable_banking_accounts.joins(:account_provider).joins(:account).merge(Account.visible)@@ -151,6 +165,7 @@ class EnableBankingItem::Importerresult = fetch_and_store_transactions(enable_banking_account)if result[:success]transactions_imported += result[:transactions_count]+ transactions_truncated += 1 if result[:truncated]elsetransactions_failed += 1@sync_error = promote_session_invalid(@sync_error, result[:error])@@ -179,7 +194,8 @@ class EnableBankingItem::Importeraccounts_failed: accounts_failed,transactions_imported: transactions_imported,transactions_failed: transactions_failed,- balances_failed: balances_failed+ balances_failed: balances_failed,+ transactions_truncated: transactions_truncated}result[:error] = @sync_error || I18n.t("enable_banking_items.errors.unexpected") if !result[:success]@@ -739,6 +755,28 @@ class EnableBankingItem::Importer)end+ # A strategy=longest fetch that stops at the page cap or on a repeated+ # continuation key keeps its rows and is not retried, so the missing+ # history is surfaced here.+ def capture_longest_truncation_debug_log(enable_banking_account, transactions_kept:, reason:)+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "Enable Banking strategy=longest transaction fetch stopped early; kept partial history",+ source: self.class.name,+ provider_key: "enable_banking",+ family: enable_banking_item.family,+ account_provider: enable_banking_account.account_provider,+ metadata: {+ enable_banking_item_id: enable_banking_item.id,+ enable_banking_account_id: enable_banking_account.id,+ uid: enable_banking_account.uid,+ transactions_kept: transactions_kept,+ reason: reason+ }+ )+ end+# Surfaces "ASPSP doesn't support PDNG" as a support-visible diagnostic, same# rationale as capture_pagination_truncation_debug_log: this is a partial# degradation (booked transactions still sync, pending transactions are@@ -805,15 +843,21 @@ class EnableBankingItem::Importerenddef fetch_and_store_transactions(enable_banking_account)+ first_fetch = first_transactions_fetch?(enable_banking_account)start_date = determine_sync_start_date(enable_banking_account)include_pending = include_pending?- all_transactions = fetch_paginated_transactions(+ all_transactions, book_truncated = fetch_paginated_transactions(enable_banking_account,start_date: start_date,transaction_status: "BOOK",- psu_headers: enable_banking_item.build_psu_headers+ psu_headers: enable_banking_item.build_psu_headers,+ strategy: first_fetch ? "longest" : nil)+ truncated = first_fetch && book_truncated+ if truncated+ Rails.logger.warn "EnableBankingItem::Importer - strategy=longest fetch for account #{enable_banking_account.uid} was cut short; the stored history may be incomplete"+ endif include_pending# Tag any transaction in all_transactions (fetched as BOOK but actually PDNG or an unidentified hold) with _pending: true@@ -842,9 +886,11 @@ class EnableBankingItem::Importer# Trade Republic rejects the same request with a 400 (:bad_request) instead of a# 422 (:validation_error), so both error types are treated as "PDNG unsupported". (Issue #392)begin- pending_transactions = fetch_paginated_transactions(+ # Pending rows are only a few days old, so a first fetch without a+ # start date still sends a short, explicit window here.+ pending_transactions, _pending_truncated = fetch_paginated_transactions(enable_banking_account,- start_date: start_date,+ start_date: start_date || 30.days.ago.to_date,transaction_status: "PDNG",psu_headers: enable_banking_item.build_psu_headers)@@ -950,7 +996,13 @@ class EnableBankingItem::Importer)end- { success: true, transactions_count: transactions_count }+ # A completed first fetch always leaves a payload, even an empty one, so+ # the next fetch is incremental (nil means "never fetched").+ if enable_banking_account.raw_transactions_payload.nil?+ enable_banking_account.upsert_enable_banking_transactions_snapshot!([])+ end++ { success: true, transactions_count: transactions_count, truncated: truncated }rescue Provider::EnableBanking::EnableBankingError => eRails.logger.error "EnableBankingItem::Importer - Error fetching transactions for account #{enable_banking_account.uid}: #{e.message}"{ success: false, transactions_count: 0, error: handle_sync_error(e) }@@ -1027,17 +1079,21 @@ class EnableBankingItem::Importerclass PaginationTruncatedError < StandardError; end- def fetch_paginated_transactions(enable_banking_account, start_date:, transaction_status:, psu_headers: {})+ # Returns the rows fetched and whether the fetch stopped before the last+ # page (page cap, repeated continuation key, or a 400/422 on a later page).+ def fetch_paginated_transactions(enable_banking_account, start_date:, transaction_status:, psu_headers: {}, strategy: nil)all_transactions = []+ truncated = falsecontinuation_key = nilprevious_continuation_key = nilpage_count = 0+ max_pages = strategy.present? ? MAX_LONGEST_PAGINATION_PAGES : MAX_PAGINATION_PAGESloop dopage_count += 1- if page_count > MAX_PAGINATION_PAGES- msg = "EnableBankingItem::Importer - Pagination limit exceeded for account #{enable_banking_account.uid} (status=#{transaction_status}). Stopped after #{MAX_PAGINATION_PAGES} pages."+ if page_count > max_pages+ msg = "EnableBankingItem::Importer - Pagination limit exceeded for account #{enable_banking_account.uid} (status=#{transaction_status}). Stopped after #{max_pages} pages."raise PaginationTruncatedError, msgend@@ -1047,7 +1103,8 @@ class EnableBankingItem::Importerdate_from: start_date,continuation_key: continuation_key,transaction_status: transaction_status,- psu_headers: psu_headers+ psu_headers: psu_headers,+ strategy: strategy)rescue Provider::EnableBanking::EnableBankingError => e# Some ASPSPs (e.g. Trade Republic via Enable Banking) issue a continuation_key@@ -1079,6 +1136,7 @@ class EnableBankingItem::Importertransactions_kept: all_transactions.count,error: e)+ truncated = truebreakend@@ -1096,12 +1154,15 @@ class EnableBankingItem::Importerbreak if continuation_key.blank?end- all_transactions+ [ all_transactions, truncated ]rescue PaginationTruncatedError => e# Log as warning and return collected partial data instead of failing entirely.# This ensures accounts with huge history don't lose all synced data.Rails.logger.warn(e.message)- all_transactions+ if strategy.present?+ capture_longest_truncation_debug_log(enable_banking_account, transactions_kept: all_transactions.count, reason: e.message)+ end+ [ all_transactions, true ]enddef filter_transactions_by_date(transactions, start_date)@@ -1154,22 +1215,52 @@ class EnableBankingItem::Importerendend- def determine_sync_start_date(enable_banking_account)- has_stored_transactions = enable_banking_account.raw_transactions_payload.to_a.any?-- # Use user-configured sync_start_date if set, otherwise default- user_start_date = enable_banking_item.sync_start_date+ # nil means this account's transactions were never fetched. A completed+ # fetch always stores an array, even an empty one.+ def first_transactions_fetch?(enable_banking_account)+ enable_banking_account.raw_transactions_payload.nil?+ end- if has_stored_transactions- # For incremental syncs, get transactions from 7 days before last sync- if enable_banking_item.last_synced_at- enable_banking_item.last_synced_at.to_date - 7.days- else- 30.days.ago.to_date- end+ def determine_sync_start_date(enable_banking_account)+ if first_transactions_fetch?(enable_banking_account)+ # The first fetch asks for strategy=longest. The user's start date, when+ # set, is the lower bound (never after today); without one the ASPSP+ # returns all it allows.+ [ enable_banking_item.sync_start_date, Date.current ].min if enable_banking_item.sync_start_dateelse- # Initial sync: use user's configured date or default to 3 months- user_start_date || 3.months.ago.to_date+ incremental_sync_start_date(enable_banking_account)endend++ # 7 days before the older of the last completed sync and the newest stored+ # row. The stored rows cover an account that was not fetched while the item+ # kept syncing (for example linked again after being unlinked, or linked to+ # an existing account), so its incremental fetch doesn't leave a gap. The+ # stored-row term never goes past STORED_ROW_LOOKBACK_LIMIT, overlap+ # included, so a dormant account doesn't ask for more than the ASPSP serves+ # without SCA on every sync. An account with no stored rows has no anchor,+ # so it uses that limit. The last-sync term is not clamped, so a long+ # outage is handled as before. Nothing before the user's start date is+ # requested, and nothing after today.+ def incremental_sync_start_date(enable_banking_account)+ newest_stored = newest_stored_transaction_date(enable_banking_account)+ stored_row_start = [ newest_stored && newest_stored - 7.days, STORED_ROW_LOOKBACK_LIMIT.ago.to_date ].compact.max++ start = [+ enable_banking_item.last_synced_at && (enable_banking_item.last_synced_at.to_date - 7.days),+ stored_row_start+ ].compact.min++ [ [ start, enable_banking_item.sync_start_date ].compact.max, Date.current ].min+ end++ def newest_stored_transaction_date(enable_banking_account)+ newest = enable_banking_account.raw_transactions_payload.to_a.filter_map do |tx|+ tx = tx.with_indifferent_access+ date_str = tx[:booking_date] || tx[:value_date] || tx[:transaction_date]+ Date.parse(date_str.to_s) if date_str.present?+ rescue ArgumentError+ nil+ end.max+ endenddiff --git a/app/models/enable_banking_item/syncer.rb b/app/models/enable_banking_item/syncer.rbindex 3049a05eb2..cc1448d610 100644--- a/app/models/enable_banking_item/syncer.rb+++ b/app/models/enable_banking_item/syncer.rb@@ -21,6 +21,9 @@ class EnableBankingItem::Syncer# Phase 1: Import data from Enable Banking APIsync.update!(status_text: "Importing accounts from Enable Banking...") if sync.respond_to?(:status_text)import_result = enable_banking_item.import_latest_enable_banking_data+ # Before the failure check: a cut-short fetch is not retried, so it is+ # reported even when another account fails in the same sync.+ collect_truncated_history_warning(sync, import_result[:transactions_truncated].to_i)unless import_result[:success]# A session-level auth failure detected mid-import flips the item to@@ -88,4 +91,20 @@ class EnableBankingItem::Syncerdef perform_post_sync# no-opend++ private++ # A full-history fetch that stopped early keeps its rows and the sync+ # completes, so the sync summary shows that older history may be missing.+ def collect_truncated_history_warning(sync, count)+ return unless count.positive?++ collect_data_quality_stats(sync,+ warnings: count,+ details: [ {+ message: I18n.t("provider_warnings.enable_banking_history_truncated", count: count),+ severity: "warning"+ } ]+ )+ endenddiff --git a/app/models/provider/enable_banking.rb b/app/models/provider/enable_banking.rbindex 3fd1e5808c..03cd6b1be1 100644--- a/app/models/provider/enable_banking.rb+++ b/app/models/provider/enable_banking.rb@@ -171,15 +171,18 @@ class Provider::EnableBanking# @param continuation_key [String, nil] For pagination# @param transaction_status [String, nil] Filter: "BOOK", "PDNG", or nil for all# @param psu_headers [Hash] Optional PSU context headers required by some ASPSPs+ # @param strategy [String, nil] "longest" asks Enable Banking for the longest period+ # the ASPSP allows (date_from is still applied as a lower bound, date_to is ignored)# @return [Hash] Transactions and continuation_key for paginationdef get_account_transactions(account_id:, date_from: nil, date_to: nil,- continuation_key: nil, transaction_status: nil, psu_headers: {}, retry_attempt: 0)+ continuation_key: nil, transaction_status: nil, psu_headers: {}, strategy: nil, retry_attempt: 0)encoded_id = CGI.escape(account_id.to_s)query_params = {}query_params[:transaction_status] = transaction_status if transaction_status.present?query_params[:date_from] = date_from.to_date.iso8601 if date_fromquery_params[:date_to] = date_to.to_date.iso8601 if date_toquery_params[:continuation_key] = continuation_key if continuation_key+ query_params[:strategy] = strategy if strategy.present?response = self.class.get("#{BASE_URL}/accounts/#{encoded_id}/transactions",@@ -199,6 +202,7 @@ class Provider::EnableBankingcontinuation_key: continuation_key,transaction_status: transaction_status,psu_headers: psu_headers,+ strategy: strategy,retry_attempt: retry_attempt + 1)elsediff --git a/app/views/enable_banking_items/setup_accounts.html.erb b/app/views/enable_banking_items/setup_accounts.html.erbindex 97060d2c21..aea994a7f1 100644--- a/app/views/enable_banking_items/setup_accounts.html.erb+++ b/app/views/enable_banking_items/setup_accounts.html.erb@@ -55,13 +55,13 @@<p class="text-sm text-primary mb-3"><strong><%= t(".historical_data_range") %></strong></p>+ <%= form.label :sync_start_date, t(".sync_start_date_label"), class: "block text-sm text-secondary mb-1" %><%= form.date_field :sync_start_date,- label: t(".sync_start_date_label"),- value: @enable_banking_item.sync_start_date || 3.months.ago.to_date,- min: 2.years.ago.to_date,+ value: @enable_banking_item.sync_start_date,max: Date.current,- class: "w-full max-w-xs rounded-md border border-primary px-3 py-2 text-sm bg-container-inset text-primary",- help_text: t(".sync_start_date_help") %>+ aria: { describedby: "sync_start_date_help" },+ class: "w-full max-w-xs rounded-md border border-primary px-3 py-2 text-sm bg-container-inset text-primary" %>+ <p id="sync_start_date_help" class="text-xs text-secondary mt-1"><%= t(".sync_start_date_help") %></p></div></div></div>diff --git a/config/locales/models/provider_warnings/en.yml b/config/locales/models/provider_warnings/en.ymlindex 8a1a2b1dcf..6d4fe6041d 100644--- a/config/locales/models/provider_warnings/en.yml+++ b/config/locales/models/provider_warnings/en.yml@@ -2,6 +2,9 @@en:provider_warnings:limited_investment_data: "Investment data from this provider is limited. Activity labels (Buy, Sell, Dividend) are not available, which may affect budget accuracy. Consider creating rules to exclude or categorize investment transactions."+ 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"diff --git a/config/locales/views/enable_banking_items/en.yml b/config/locales/views/enable_banking_items/en.ymlindex 8913c7319c..1a86db39f8 100644--- a/config/locales/views/enable_banking_items/en.yml+++ b/config/locales/views/enable_banking_items/en.yml@@ -68,7 +68,7 @@ en:choose_account_type: "Choose the correct account type for each Enable Banking account:"historical_data_range: "Historical Data Range:"sync_start_date_label: "Start syncing transactions from:"- sync_start_date_help: Select how far back you want to sync transaction history. Maximum 2 years of history available.+ sync_start_date_help: Optional. Leave it blank to import as much history as your bank provides; how far back that goes depends on the bank. If you pick a date, transactions before it are not imported.account_type_label: "Account Type:"balance: Balancecreate_accounts: Create Accountsdiff --git a/test/controllers/enable_banking_items_controller_test.rb b/test/controllers/enable_banking_items_controller_test.rbindex 929d100842..04909a596c 100644--- a/test/controllers/enable_banking_items_controller_test.rb+++ b/test/controllers/enable_banking_items_controller_test.rb@@ -344,6 +344,61 @@ class EnableBankingItemsControllerTest < ActionDispatch::IntegrationTestassert_equal "active", orphan.reload.statusend+ # The modal's form is a plain form_with, so the date field's label and help+ # must be rendered as elements rather than passed as builder options (which+ # end up as unknown attributes on the input).+ test "setup modal shows the start date label and help and leaves the date blank by default" do+ @item.enable_banking_accounts.create!(name: "Checking", uid: "eb_setup_1", currency: "EUR", current_balance: 0)++ get setup_accounts_enable_banking_item_url(@item)++ assert_response :success+ assert_select "label[for=sync_start_date]", text: I18n.t("enable_banking_items.setup_accounts.sync_start_date_label")+ assert_select "p#sync_start_date_help", text: I18n.t("enable_banking_items.setup_accounts.sync_start_date_help")+ assert_select "input[type=date][name=sync_start_date][aria-describedby=sync_start_date_help]" do |inputs|+ assert inputs.first["value"].blank?, "A first setup must not prefill a date, or it would cap the first fetch"+ assert_nil inputs.first["label"]+ assert_nil inputs.first["help_text"]+ end+ end++ test "setup modal shows a start date that is already set" do+ @item.update!(sync_start_date: Date.new(2024, 1, 15))+ @item.enable_banking_accounts.create!(name: "Checking", uid: "eb_setup_1", currency: "EUR", current_balance: 0)++ get setup_accounts_enable_banking_item_url(@item)++ assert_select "input[type=date][name=sync_start_date][value='2024-01-15']"+ end++ test "complete_account_setup stores a chosen start date" do+ post complete_account_setup_enable_banking_item_url(@item), params: { sync_start_date: "2024-01-15" }++ assert_equal Date.new(2024, 1, 15), @item.reload.sync_start_date+ end++ test "complete_account_setup with a blank start date leaves it unset" do+ post complete_account_setup_enable_banking_item_url(@item), params: { sync_start_date: "" }++ assert_nil @item.reload.sync_start_date+ end++ test "complete_account_setup with a cleared start date removes the stored one" do+ @item.update!(sync_start_date: Date.new(2024, 1, 15))++ post complete_account_setup_enable_banking_item_url(@item), params: { sync_start_date: "" }++ assert_nil @item.reload.sync_start_date+ end++ test "complete_account_setup without the date field keeps the stored start date" do+ @item.update!(sync_start_date: Date.new(2024, 1, 15))++ post complete_account_setup_enable_banking_item_url(@item), params: { account_types: {} }++ assert_equal Date.new(2024, 1, 15), @item.reload.sync_start_date+ end+privatedef stub_authorization_startdiff --git a/test/models/enable_banking_item/importer_error_handling_test.rb b/test/models/enable_banking_item/importer_error_handling_test.rbindex 9e51db2f71..6b3de4cdb2 100644--- a/test/models/enable_banking_item/importer_error_handling_test.rb+++ b/test/models/enable_banking_item/importer_error_handling_test.rb@@ -96,6 +96,7 @@ class EnableBankingItem::ImporterErrorHandlingTest < ActiveSupport::TestCasetest "fetch_and_store_transactions succeeds and skips pending when ASPSP rejects PDNG transaction_status" doenable_banking_account = EnableBankingAccount.new(uid: "test_uid")+ enable_banking_account.stubs(:upsert_enable_banking_transactions_snapshot!)@importer.stubs(:determine_sync_start_date).returns(Date.today)@importer.stubs(:include_pending?).returns(true)@@ -104,7 +105,7 @@ class EnableBankingItem::ImporterErrorHandlingTest < ActiveSupport::TestCase:validation_error)- @importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "BOOK")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [], false ])@importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "PDNG")).raises(pdng_error)result = @importer.send(:fetch_and_store_transactions, enable_banking_account)@@ -116,6 +117,7 @@ class EnableBankingItem::ImporterErrorHandlingTest < ActiveSupport::TestCase# with a plain 400 (:bad_request) instead of the 422 (:validation_error) other ASPSPs use.test "fetch_and_store_transactions succeeds and skips pending when ASPSP rejects PDNG with a bad_request error" doenable_banking_account = EnableBankingAccount.new(uid: "test_uid")+ enable_banking_account.stubs(:upsert_enable_banking_transactions_snapshot!)@importer.stubs(:determine_sync_start_date).returns(Date.today)@importer.stubs(:include_pending?).returns(true)@@ -125,7 +127,7 @@ class EnableBankingItem::ImporterErrorHandlingTest < ActiveSupport::TestCaseresponse_data: { error: "WRONG_REQUEST_PARAMETERS" })- @importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "BOOK")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [], false ])@importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "PDNG")).raises(trade_republic_pdng_error)result = nil@@ -144,6 +146,7 @@ class EnableBankingItem::ImporterErrorHandlingTest < ActiveSupport::TestCase# The sync must still succeed and import booked transactions.test "fetch_and_store_transactions succeeds when ASPSP rejects PDNG with WRONG_REQUEST_PARAMETERS" doenable_banking_account = EnableBankingAccount.new(uid: "test_uid")+ enable_banking_account.stubs(:upsert_enable_banking_transactions_snapshot!)@importer.stubs(:determine_sync_start_date).returns(Date.today)@importer.stubs(:include_pending?).returns(true)@@ -153,7 +156,7 @@ class EnableBankingItem::ImporterErrorHandlingTest < ActiveSupport::TestCaseresponse_data: { error: "WRONG_REQUEST_PARAMETERS" })- @importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "BOOK")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [], false ])@importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "PDNG")).raises(imagin_error)result = @importer.send(:fetch_and_store_transactions, enable_banking_account)@@ -171,7 +174,7 @@ class EnableBankingItem::ImporterErrorHandlingTest < ActiveSupport::TestCase:rate_limited)- @importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "BOOK")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [], false ])@importer.stubs(:fetch_paginated_transactions).with(enable_banking_account, has_entries(transaction_status: "PDNG")).raises(rate_limit_error)result = @importer.send(:fetch_and_store_transactions, enable_banking_account)@@ -197,14 +200,15 @@ class EnableBankingItem::ImporterErrorHandlingTest < ActiveSupport::TestCase@mock_provider.expects(:get_account_transactions).twice.returns(page1_response).then.raises(error)assert_difference "DebugLogEntry.count", 1 do- result = @importer.send(+ transactions, truncated = @importer.send(:fetch_paginated_transactions,enable_banking_account,start_date: Date.today,transaction_status: "BOOK")- assert_equal [ page1_tx ], result+ assert_equal [ page1_tx ], transactions+ assert truncatedenddebug_log = DebugLogEntry.last@@ -235,14 +239,15 @@ class EnableBankingItem::ImporterErrorHandlingTest < ActiveSupport::TestCase@mock_provider.expects(:get_account_transactions).twice.returns(page1_response).then.raises(error)- result = @importer.send(+ transactions, truncated = @importer.send(:fetch_paginated_transactions,enable_banking_account,start_date: Date.today,transaction_status: "PDNG")- assert_equal [ page1_tx ], result+ assert_equal [ page1_tx ], transactions+ assert truncatedend# A validation error on the very first page has no prior page to fall back on, so itdiff --git a/test/models/enable_banking_item/importer_full_history_test.rb b/test/models/enable_banking_item/importer_full_history_test.rbnew file mode 100644index 0000000000..4ca5322d79--- /dev/null+++ b/test/models/enable_banking_item/importer_full_history_test.rb@@ -0,0 +1,351 @@+require "test_helper"++class EnableBankingItem::ImporterFullHistoryTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)++ @enable_banking_item = EnableBankingItem.create!(+ family: @family,+ name: "Test EB",+ country_code: "FR",+ application_id: "test_app_id",+ client_certificate: "test_cert",+ session_id: "test_session",+ session_expires_at: 1.day.from_now+ )+ @enable_banking_account = EnableBankingAccount.create!(+ enable_banking_item: @enable_banking_item,+ name: "Compte courant",+ uid: "hash_full_history",+ account_id: "uuid-full-history",+ currency: "EUR"+ )++ @requests = []+ Setting.stubs(:syncs_include_pending).returns(false)+ @enable_banking_item.stubs(:upsert_enable_banking_snapshot!)+ end++ test "first fetch uses strategy=longest with sync_start_date as date_from" do+ @enable_banking_item.update!(sync_start_date: Date.new(2020, 1, 1))+ link!++ build_importer(transactions: [ booked_tx("tx_new", 5.days.ago.to_date.iso8601) ]).import++ assert_equal 1, @requests.size+ assert_equal "longest", @requests.first[:strategy]+ assert_equal Date.new(2020, 1, 1), @requests.first[:date_from]+ end++ test "a future sync_start_date does not push the first fetch past today" do+ @enable_banking_item.update_columns(sync_start_date: 1.day.from_now.to_date)+ link!++ build_importer.import++ assert_equal "longest", @requests.first[:strategy]+ assert_equal Date.current, @requests.first[:date_from]+ end++ test "first fetch without sync_start_date sends no date_from and keeps all rows" do+ link!++ build_importer(transactions: [ booked_tx("tx_old", "2019-04-02"), booked_tx("tx_new", 5.days.ago.to_date.iso8601) ]).import++ assert_equal "longest", @requests.first[:strategy]+ assert_nil @requests.first[:date_from]+ assert_equal 2, @enable_banking_account.reload.raw_transactions_payload.size+ end++ test "later fetches are incremental and do not use strategy=longest" do+ link!+ @enable_banking_account.update!(raw_transactions_payload: [ booked_tx("tx_stored", Date.current.iso8601) ])+ @enable_banking_item.stubs(:last_synced_at).returns(1.day.ago)++ build_importer.import++ assert_equal 1, @requests.size+ assert_nil @requests.first[:strategy]+ assert_equal 8.days.ago.to_date, @requests.first[:date_from]+ end++ test "an empty first fetch is stored so the next fetch is incremental" do+ link!++ build_importer.import+ assert_equal [], @enable_banking_account.reload.raw_transactions_payload++ @enable_banking_item.stubs(:last_synced_at).returns(1.hour.ago)+ build_importer.import+ assert_nil @requests.last[:strategy], "an account without transactions gets strategy=longest on every sync"+ end++ test "an account with an empty stored payload is fetched over the 89-day window" do+ # Fetched empty, then unlinked while the item kept syncing, then relinked.+ @enable_banking_account.update!(raw_transactions_payload: [])+ link!+ @enable_banking_item.stubs(:last_synced_at).returns(1.hour.ago)++ build_importer.import++ assert_nil @requests.first[:strategy]+ assert_equal 89.days.ago.to_date, @requests.first[:date_from], "rows from the gap before the last sync are skipped"+ end++ test "an incremental fetch does not start before sync_start_date" do+ @enable_banking_item.update!(sync_start_date: 3.days.ago.to_date)+ link!+ @enable_banking_account.update!(raw_transactions_payload: [ booked_tx("tx_stored", 2.days.ago.to_date.iso8601) ])+ @enable_banking_item.stubs(:last_synced_at).returns(1.day.ago)++ build_importer(transactions: [ booked_tx("tx_before_start", 5.days.ago.to_date.iso8601) ]).import++ assert_equal 3.days.ago.to_date, @requests.first[:date_from]+ assert_equal %w[tx_stored], @enable_banking_account.reload.raw_transactions_payload.map { |row| row["transaction_id"] }+ end++ test "a future sync_start_date does not push an incremental fetch past today" do+ @enable_banking_item.update_columns(sync_start_date: 5.days.from_now.to_date)+ link!+ @enable_banking_account.update!(raw_transactions_payload: [ booked_tx("tx_stored", 2.days.ago.to_date.iso8601) ])+ @enable_banking_item.stubs(:last_synced_at).returns(1.day.ago)++ build_importer.import++ assert_equal Date.current, @requests.first[:date_from]+ end++ test "a failed first fetch stays a first fetch" do+ link!+ provider = mock()+ provider.stubs(:get_account_balances).returns(balances: [])+ provider.stubs(:get_account_transactions).raises(Provider::EnableBanking::EnableBankingError.new("boom", :request_failed))+ importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: provider)+ importer.stubs(:fetch_session_data).returns(accounts: [])++ importer.import++ assert_nil @enable_banking_account.reload.raw_transactions_payload+ end++ test "failed syncs after linking do not repeat strategy=longest" do+ Sync.create!(syncable: @enable_banking_item, status: "completed", completed_at: 2.days.ago, created_at: 2.days.ago)+ link!+ @enable_banking_account.update!(raw_transactions_payload: [ booked_tx("a", 5.days.ago.to_date.iso8601) ])+ Sync.create!(syncable: @enable_banking_item, status: "failed", failed_at: 12.hours.ago, created_at: 12.hours.ago)++ build_importer.import++ assert_nil @requests.last[:strategy]+ end++ test "an incremental fetch starts before the newest stored row when the account was not fetched since" do+ # e.g. linked again, or linked to an existing account, after the item kept syncing+ link!+ @enable_banking_account.update!(raw_transactions_payload: [ booked_tx("tx_stored", 20.days.ago.to_date.iso8601) ])+ @enable_banking_item.stubs(:last_synced_at).returns(1.day.ago)++ build_importer.import++ assert_nil @requests.first[:strategy]+ assert_equal 27.days.ago.to_date, @requests.first[:date_from]+ end++ test "a dormant account's newest stored row pulls the incremental fetch back at most 89 days" do+ link!+ @enable_banking_account.update!(raw_transactions_payload: [ booked_tx("tx_stored", 2.years.ago.to_date.iso8601) ])+ @enable_banking_item.stubs(:last_synced_at).returns(1.day.ago)++ build_importer.import++ assert_nil @requests.first[:strategy]+ assert_equal 89.days.ago.to_date, @requests.first[:date_from]+ end++ test "a newest stored row 85 days old still keeps the incremental fetch within 89 days" do+ link!+ @enable_banking_account.update!(raw_transactions_payload: [ booked_tx("tx_stored", 85.days.ago.to_date.iso8601) ])+ @enable_banking_item.stubs(:last_synced_at).returns(1.day.ago)++ build_importer.import++ assert_equal 89.days.ago.to_date, @requests.first[:date_from]+ end++ test "a long outage still starts the incremental fetch 7 days before the last sync" do+ link!+ @enable_banking_account.update!(raw_transactions_payload: [ booked_tx("tx_stored", 200.days.ago.to_date.iso8601) ])+ @enable_banking_item.stubs(:last_synced_at).returns(200.days.ago)++ build_importer.import++ assert_equal 207.days.ago.to_date, @requests.first[:date_from]+ end++ test "a longest first fetch is not cut at the incremental page cap" do+ link!+ pages = EnableBankingItem::Importer::MAX_PAGINATION_PAGES + 20+ importer = build_paging_importer(pages: pages)++ importer.import++ assert_equal pages, @requests.size+ assert @requests.all? { |params| params[:strategy] == "longest" }+ assert_equal pages, @enable_banking_account.reload.raw_transactions_payload.size+ end++ test "a longest first fetch still stops at its own page cap" do+ link!+ importer = build_paging_importer(pages: nil)++ importer.import++ assert_equal EnableBankingItem::Importer::MAX_LONGEST_PAGINATION_PAGES, @requests.size+ end++ test "a longest fetch cut at the page cap is reported as truncated, with a warning" do+ link!+ warnings = []+ Rails.logger.stubs(:warn).with { |msg| warnings << msg.to_s; true }++ result = build_paging_importer(pages: nil).import++ assert result[:success], "the partial history is kept and the sync does not fail"+ assert_equal 1, result[:transactions_truncated]+ assert_equal EnableBankingItem::Importer::MAX_LONGEST_PAGINATION_PAGES, @enable_banking_account.reload.raw_transactions_payload.size+ assert warnings.any? { |msg| msg.include?("may be incomplete") }, "no truncation warning logged"+ end++ test "a longest fetch cut at the page cap is captured as a debug log entry" do+ link!++ assert_difference -> { DebugLogEntry.where(provider_key: "enable_banking", category: "provider_sync_error").count }, 1 do+ build_paging_importer(pages: nil).import+ end++ entry = DebugLogEntry.last+ assert_equal @family, entry.family+ assert_equal @enable_banking_account.account_provider, entry.account_provider+ assert_equal EnableBankingItem::Importer::MAX_LONGEST_PAGINATION_PAGES, entry.metadata["transactions_kept"]+ end++ test "a longest fetch cut short by a mid-pagination validation error is reported as truncated" do+ link!+ provider = Object.new+ provider.define_singleton_method(:get_account_balances) { |**| { balances: [] } }+ provider.define_singleton_method(:get_account_transactions) do |**params|+ raise Provider::EnableBanking::EnableBankingError.new("Bad request", :bad_request) if params[:continuation_key]++ { transactions: [ { transaction_id: "a", booking_date: 300.days.ago.to_date.iso8601, status: "BOOK",+ transaction_amount: { amount: "1.00", currency: "EUR" }, credit_debit_indicator: "DBIT" } ],+ continuation_key: "k1" }+ end+ importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: provider)+ importer.stubs(:fetch_session_data).returns(accounts: [])++ result = importer.import++ assert result[:success], "the rows from the first page are kept and the sync does not fail"+ assert_equal 1, result[:transactions_truncated]+ assert_equal 1, @enable_banking_account.reload.raw_transactions_payload.size+ end++ test "a pending fetch cut short is not reported as a truncated history" do+ Setting.stubs(:syncs_include_pending).returns(true)+ link!+ provider = Object.new+ provider.define_singleton_method(:get_account_balances) { |**| { balances: [] } }+ provider.define_singleton_method(:get_account_transactions) do |**params|+ if params[:transaction_status] == "PDNG"+ raise Provider::EnableBanking::EnableBankingError.new("Bad request", :bad_request) if params[:continuation_key]++ next { transactions: [], continuation_key: "p1" }+ end++ { transactions: [ { transaction_id: "a", booking_date: 300.days.ago.to_date.iso8601, status: "BOOK",+ transaction_amount: { amount: "1.00", currency: "EUR" }, credit_debit_indicator: "DBIT" } ] }+ end+ importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: provider)+ importer.stubs(:fetch_session_data).returns(accounts: [])++ result = importer.import++ assert result[:success]+ assert_equal 0, result[:transactions_truncated], "the booked history was fetched in full"+ end++ test "a complete fetch is not reported as truncated" do+ link!++ result = build_importer(transactions: [ booked_tx("a", 5.days.ago.to_date.iso8601) ]).import++ assert_equal 0, result[:transactions_truncated]+ end++ test "the pending fetch on a first fetch without sync_start_date sends a short window" do+ Setting.stubs(:syncs_include_pending).returns(true)+ link!++ build_importer.import++ book, pending = @requests+ assert_equal "BOOK", book[:transaction_status]+ assert_equal "longest", book[:strategy]+ assert_equal "PDNG", pending[:transaction_status]+ assert_nil pending[:strategy]+ assert_equal 30.days.ago.to_date, pending[:date_from]+ end++ private++ def build_importer(transactions: [])+ requests = @requests+ provider = mock()+ provider.stubs(:get_account_balances).returns(balances: [])+ provider.stubs(:get_account_transactions).with { |params| requests << params; true }.returns(transactions: transactions)+ importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: provider)+ importer.stubs(:fetch_session_data).returns(accounts: [])+ importer+ end++ # Each page returns one row and a continuation key, up to `pages` pages+ # (forever when nil).+ def build_paging_importer(pages:)+ requests = @requests+ test_case = self+ provider = Object.new+ provider.define_singleton_method(:get_account_balances) { |**| { balances: [] } }+ provider.define_singleton_method(:get_account_transactions) do |**params|+ requests << params+ page = requests.size+ more = pages.nil? || page < pages+ { transactions: [ test_case.send(:booked_tx, "p#{page}", (page % 300).days.ago.to_date.iso8601) ], continuation_key: (more ? "k#{page}" : nil) }+ end+ importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: provider)+ importer.stubs(:fetch_session_data).returns(accounts: [])+ importer+ end++ def link!+ account = Account.create!(+ family: @family,+ name: "EB linked",+ balance: 0,+ currency: "EUR",+ accountable: Depository.create!+ )+ AccountProvider.create!(account: account, provider: @enable_banking_account)+ @enable_banking_account.reload+ end++ def booked_tx(id, date)+ {+ transaction_id: id,+ entry_reference: "ref_#{id}",+ booking_date: date,+ transaction_amount: { amount: "10.00", currency: "EUR" },+ credit_debit_indicator: "DBIT",+ status: "BOOK"+ }+ end+enddiff --git a/test/models/enable_banking_item/importer_id_less_test.rb b/test/models/enable_banking_item/importer_id_less_test.rbindex 2ca068fccb..29f2d0701e 100644--- a/test/models/enable_banking_item/importer_id_less_test.rb+++ b/test/models/enable_banking_item/importer_id_less_test.rb@@ -40,8 +40,8 @@ class EnableBankingItem::ImporterIdLessTest < ActiveSupport::TestCasetest "stores id-less transactions in raw_transactions_payload on first sync" dotx = id_less_tx- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ tx ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ [ tx ], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([ [], false ])@importer.stubs(:include_pending?).returns(false)@importer.stubs(:determine_sync_start_date).returns(1.month.ago.to_date)@@ -55,8 +55,8 @@ class EnableBankingItem::ImporterIdLessTest < ActiveSupport::TestCasetx = id_less_tx# First sync- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ tx ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ [ tx ], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([ [], false ])@importer.stubs(:include_pending?).returns(false)@importer.stubs(:determine_sync_start_date).returns(1.month.ago.to_date)@@ -74,8 +74,8 @@ class EnableBankingItem::ImporterIdLessTest < ActiveSupport::TestCasetx1 = id_less_tx(amount: "50.00", creditor: "Kaufland")tx2 = id_less_tx(amount: "12.50", creditor: "Starbucks")- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ tx1, tx2 ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ [ tx1, tx2 ], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([ [], false ])@importer.stubs(:include_pending?).returns(false)@importer.stubs(:determine_sync_start_date).returns(1.month.ago.to_date)@@ -91,8 +91,8 @@ class EnableBankingItem::ImporterIdLessTest < ActiveSupport::TestCase@enable_banking_account.update!(raw_transactions_payload: [ pending_tx ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ tx ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ [ tx ], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([ [], false ])@importer.stubs(:include_pending?).returns(true)@importer.stubs(:determine_sync_start_date).returns(1.month.ago.to_date)@@ -130,8 +130,8 @@ class EnableBankingItem::ImporterIdLessTest < ActiveSupport::TestCase@enable_banking_account.update!(raw_transactions_payload: [ pending_tx ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ booked_tx ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ [ booked_tx ], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([ [], false ])@importer.stubs(:include_pending?).returns(true)@importer.stubs(:determine_sync_start_date).returns(1.month.ago.to_date)diff --git a/test/models/enable_banking_item/importer_pdng_test.rb b/test/models/enable_banking_item/importer_pdng_test.rbindex c70f444d3a..aa54e557d4 100644--- a/test/models/enable_banking_item/importer_pdng_test.rb+++ b/test/models/enable_banking_item/importer_pdng_test.rb@@ -158,8 +158,8 @@ class EnableBankingItem::ImporterPdngTest < ActiveSupport::TestCasestatus: "PDNG"}- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ tx ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG")).returns([ tx ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [ tx ], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG")).returns([ [ tx ], false ])result = @importer.send(:fetch_and_store_transactions, @enable_banking_account)@@ -181,12 +181,12 @@ class EnableBankingItem::ImporterPdngTest < ActiveSupport::TestCasestatus: "PDNG"}- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ tx ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [ tx ], false ])result = @importer.send(:fetch_and_store_transactions, @enable_banking_account)assert result[:success]- assert_nil @enable_banking_account.raw_transactions_payload+ assert_equal [], @enable_banking_account.raw_transactions_payloadendtest "fetch_and_store_transactions tags unidentified hold with BOOK status as pending when include_pending is true" do@@ -203,8 +203,8 @@ class EnableBankingItem::ImporterPdngTest < ActiveSupport::TestCasestatus: "BOOK"}- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ hold_tx ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [ hold_tx ], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG")).returns([ [], false ])result = @importer.send(:fetch_and_store_transactions, @enable_banking_account)@@ -228,12 +228,12 @@ class EnableBankingItem::ImporterPdngTest < ActiveSupport::TestCasestatus: "BOOK"}- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ hold_tx ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [ hold_tx ], false ])result = @importer.send(:fetch_and_store_transactions, @enable_banking_account)assert result[:success]- assert_nil @enable_banking_account.raw_transactions_payload+ assert_equal [], @enable_banking_account.raw_transactions_payloadendtest "fetch_and_store_transactions prunes cached unidentified holds from existing transactions when include_pending is false" do@@ -260,7 +260,7 @@ class EnableBankingItem::ImporterPdngTest < ActiveSupport::TestCase@enable_banking_account.upsert_enable_banking_transactions_snapshot!([ cached_hold, cached_settled ])- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [], false ])result = @importer.send(:fetch_and_store_transactions, @enable_banking_account)diff --git a/test/models/enable_banking_item/syncer_test.rb b/test/models/enable_banking_item/syncer_test.rbindex 861db6e6ca..f9cfa03ea5 100644--- a/test/models/enable_banking_item/syncer_test.rb+++ b/test/models/enable_banking_item/syncer_test.rb@@ -28,4 +28,27 @@ class EnableBankingItem::SyncerTest < ActiveSupport::TestCaseassert_equal 0, (stats["total_errors"] || 0),"Expired session should be a graceful reconnect state, not a red sync error"end++ test "a truncated full-history fetch is recorded as a data warning on the sync" do+ @item.update!(session_expires_at: 1.day.from_now)+ @item.stubs(:import_latest_enable_banking_data).returns(success: true, transactions_truncated: 1)+ sync = Sync.create!(syncable: @item)++ @syncer.perform_sync(sync)++ stats = sync.reload.sync_stats+ assert_equal 1, stats["data_warnings"]+ assert_match(/older transactions may be missing/, stats["data_quality_details"].first["message"])+ assert_equal 0, stats["total_errors"]+ end++ test "a truncated full-history fetch is recorded even when another account fails" do+ @item.update!(session_expires_at: 1.day.from_now)+ @item.stubs(:import_latest_enable_banking_data).returns(success: false, transactions_failed: 1, transactions_truncated: 1)+ sync = Sync.create!(syncable: @item)++ assert_raises(StandardError) { @syncer.perform_sync(sync) }++ assert_equal 1, sync.reload.sync_stats["data_warnings"]+ endenddiff --git a/test/models/provider/enable_banking_test.rb b/test/models/provider/enable_banking_test.rbindex 3b7fbc91cd..f508df7a2e 100644--- a/test/models/provider/enable_banking_test.rb+++ b/test/models/provider/enable_banking_test.rb@@ -440,4 +440,19 @@ class Provider::EnableBankingTest < ActiveSupport::TestCaseassert_equal "BALANCES_UNAVAILABLE", error.response_data[:error]assert_equal "redacted", error.response_data.dig(:detail, :account_id)end++ test "get_account_transactions sends strategy only when given" do+ requested_queries = []+ Provider::EnableBanking.expects(:get).twice.with do |_url, options|+ requested_queries << options[:query].dup+ true+ end.returns(OpenStruct.new(code: 200, body: { transactions: [] }.to_json))++ @provider.get_account_transactions(account_id: "acct_123", transaction_status: "BOOK", strategy: "longest")+ @provider.get_account_transactions(account_id: "acct_123", transaction_status: "BOOK", date_from: Date.new(2026, 1, 1))++ assert_equal "longest", requested_queries.first[:strategy]+ assert_not requested_queries.first.key?(:date_from)+ assert_not requested_queries.second.key?(:strategy)+ endend