The personal finance app for everyone (by everyone)
Ruby
Fix Wise multi-currency sync: routing, missing activities, fees, paging (#4166)
Yong Cong Sin529d7de76f07
diff --git a/app/controllers/transfers_controller.rb b/app/controllers/transfers_controller.rbindex a34c47b0cd..9d4e4f5b46 100644--- a/app/controllers/transfers_controller.rb+++ b/app/controllers/transfers_controller.rb@@ -136,7 +136,9 @@ class TransfersController < ApplicationControllerdef destroyreturn unless require_account_permission!(unlink_permission_account, redirect_path: transactions_url)- @transfer.destroy!+ # A link the Wise sync makes again on its own is rejected instead, so it+ # stays removed.+ WiseItem::InterbalanceLinker.relinks?(@transfer) ? @transfer.reject! : @transfer.destroy!redirect_back_or_to transactions_url, notice: t(".success")enddiff --git a/app/controllers/wise_items_controller.rb b/app/controllers/wise_items_controller.rbindex d970a3fc80..cb2e2143d4 100644--- a/app/controllers/wise_items_controller.rb+++ b/app/controllers/wise_items_controller.rb@@ -164,7 +164,7 @@ class WiseItemsController < ApplicationControllerprovider: wise_account)- @wise_item.sync_later unless @wise_item.syncing?+ @wise_item.sync_linked_account_later(wise_account)redirect_to accounts_path, notice: t(".success")rescue => e@@ -197,7 +197,7 @@ class WiseItemsController < ApplicationControlleraccount = Account.create_from_wise_account(wise_account)AccountProvider.create!(account: account, provider: wise_account)- wise_account.wise_item.sync_later unless wise_account.wise_item.syncing?+ wise_account.wise_item.sync_linked_account_later(wise_account)redirect_to safe_return_to_path || accounts_path, notice: t("wise_items.link_accounts.success")rescue => e@@ -214,7 +214,9 @@ class WiseItemsController < ApplicationControllerredirect_to accounts_path, alert: t("wise_items.select_existing_account.not_found") and returnend- @available_accounts = @wise_item.wise_accounts.unlinked+ # Only a balance in the account's currency can be linked to it+ # (#existing_account_link_refusal).+ @available_accounts = @wise_item.wise_accounts.unlinked.where(currency: @account.currency)render layout: falseend@@ -227,8 +229,12 @@ class WiseItemsController < ApplicationControllerredirect_to accounts_path, alert: t("wise_items.link_existing_account.not_found") and returnend+ if (refusal = existing_account_link_refusal(account, wise_account))+ redirect_to safe_return_to_path || accounts_path, alert: refusal and return+ end+AccountProvider.create!(account: account, provider: wise_account)- wise_account.wise_item.sync_later unless wise_account.wise_item.syncing?+ wise_account.wise_item.sync_linked_account_later(wise_account)redirect_to safe_return_to_path || accounts_path, notice: t("wise_items.link_existing_account.success", account_name: account.name)rescue => e@@ -271,6 +277,20 @@ class WiseItemsController < ApplicationController.find_by(id: wise_account_id)end+ # A Wise balance is cash in one currency, and every sync writes its balance+ # and currency onto the linked account, so only an unlinked cash account in+ # that currency can take it.+ def existing_account_link_refusal(account, wise_account)+ if account.linked?+ t("wise_items.link_existing_account.account_already_linked")+ elsif Provider::WiseAdapter.supported_account_types.exclude?(account.accountable_type)+ t("wise_items.link_existing_account.unsupported_account_type")+ elsif account.currency != wise_account.currency+ t("wise_items.link_existing_account.currency_mismatch",+ account_currency: account.currency, balance_currency: wise_account.currency)+ end+ end+def profile_display_name(profile)type_key = profile["type"] == "business" ? :business : :personaltype_label = I18n.t("wise_items.profile_types.#{type_key}")diff --git a/app/jobs/wise_item/process_linked_account_job.rb b/app/jobs/wise_item/process_linked_account_job.rbnew file mode 100644index 0000000000..bbabcb00f3--- /dev/null+++ b/app/jobs/wise_item/process_linked_account_job.rb@@ -0,0 +1,53 @@+# frozen_string_literal: true++# Processes a Wise balance that was linked to a Sure account while its+# connection was already syncing. That sync picked the accounts it processes+# before the link existed, and WiseItem#sync_later only reuses a sync in+# flight, so without this the new account stayed empty until the next sync.+class WiseItem::ProcessLinkedAccountJob < ApplicationJob+ queue_as :high_priority++ def perform(wise_account)+ account = wise_account.current_account+ return unless processable?(wise_account, account)++ # Processing holds the balance's processing lock (WiseAccount+ # #with_processing_lock), so it does not interleave with the connection's+ # sync processing the same balance, and its rows commit one by one: no+ # transaction spans the payload, which would keep the next link click+ # and every other account save of the owner waiting until it ends. The+ # stored payload is booked as a sync books it, but nothing is deleted:+ # only the sync that imported the payload knows whether it is complete.+ WiseAccount::Processor.new(wise_account, import_complete: false).process+ # Once the new legs are committed, and before the account sync's+ # transfer matching sees them.+ wise_account.wise_item.link_jar_transfers!++ account.sync_later+ rescue ActiveRecord::Deadlocked+ raise # retried (ApplicationJob)+ rescue => e+ # The next sync processes the balance anyway, so this is logged rather+ # than retried.+ Rails.logger.error("#{self.class.name} - Failed to process wise_account #{wise_account.id}: #{e.class} - #{e.message}")+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "#{self.class.name} - Failed to process a newly linked Wise balance",+ source: self.class.name,+ provider_key: "wise",+ family: wise_account.wise_item&.family,+ account_provider: wise_account.account_provider,+ metadata: { wise_item_id: wise_account.wise_item_id, wise_account_id: wise_account.id, error_class: e.class.name }+ )+ end++ private++ # The balances WiseItem#process_accounts would process.+ def processable?(wise_account, account)+ account.present? &&+ Account::VISIBLE_STATUSES.include?(account.status) &&+ !wise_account.wise_item.scheduled_for_deletion?+ end+enddiff --git a/app/models/account.rb b/app/models/account.rbindex b3f2f8e938..827a33d98b 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -395,7 +395,7 @@ class Account < ApplicationRecorddef create_from_wise_account(wise_account)family = wise_account.wise_item.family- create_and_sync(+ account = create_and_sync({family: family,name: wise_account.name || "Wise #{wise_account.currency}",@@ -407,6 +407,21 @@ class Account < ApplicationRecord},skip_initial_sync: true)++ # When Sure imports a balance's whole history, it opens at 0 the day+ # before Wise opened it, not at today's balance two years back.+ if (opening_date = wise_account.opening_date)+ manager = Account::OpeningBalanceManager.new(account)+ date = [ opening_date, manager.oldest_entry_date&.prev_day ].compact.min+ result = manager.set_opening_balance(balance: 0, date: date)+ Rails.logger.warn "Account.create_from_wise_account - Opening balance kept for account #{account.id}: #{result.error}" if result.error+ # So later syncs may move it again (WiseAccount::Processor).+ if result.changes_made?+ wise_account.remember_opening_anchor!(account.valuations.opening_anchor.includes(:entry).first.entry)+ end+ end++ accountenddef create_from_coinbase_account(coinbase_account)diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex 6aec221c3d..30647aa706 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -794,10 +794,13 @@ class Account::ProviderImportAdapter# 5. Entry type is Transaction (not Trade or Valuation)# 6. Optionally same name (if name parameter is provided)# 7. Not in the excluded IDs list (if provided)+ # 8. Not a part of a split entry: a person's share of another movement,+ # never a copy of the incoming onequery = account.entries.where(entryable_type: "Transaction").where(amount: amount).where(currency: currency)+ .where(parent_entry_id: nil)query = if date_window.to_i.zero?query.where(date: date)diff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rbindex beeecd6488..7137576cca 100644--- a/app/models/data_enrichment.rb+++ b/app/models/data_enrichment.rb@@ -25,6 +25,7 @@ class DataEnrichment < ApplicationRecordsynth: "synth",trade_republic: "trade_republic",truelayer: "truelayer",- up: "up"+ up: "up",+ wise: "wise"}enddiff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rbindex fd99753c9a..1d88ab5e70 100644--- a/app/models/family/auto_transfer_matchable.rb+++ b/app/models/family/auto_transfer_matchable.rb@@ -45,7 +45,8 @@ module Family::AutoTransferMatchabletransaction_ids: nil,include_rejected: true,restrict_cross_currency_to_linked_accounts: false,- require_common_writer: false+ require_common_writer: false,+ exclude_same_wise_item: false)date_window = coerce_transfer_match_date_window!(date_window)exchange_rate_tolerance = coerce_transfer_match_exchange_rate_tolerance!(exchange_rate_tolerance)@@ -65,6 +66,7 @@ module Family::AutoTransferMatchableinclude_rejected:,restrict_cross_currency_to_linked_accounts:,require_common_writer:,+ exclude_same_wise_item:,lower_exchange_rate_bound: 1 - exchange_rate_tolerance,upper_exchange_rate_bound: 1 + exchange_rate_tolerance}@@ -115,7 +117,13 @@ module Family::AutoTransferMatchablerestrict_cross_currency_to_linked_accounts: true,# Only pair accounts that at least one member can write to on both sides, so# someone can always confirm or reject the match.- require_common_writer: true+ require_common_writer: true,+ # Two balances of one Wise connection move money between each other only+ # through conversions and Jar moves, which WiseItem#link_jar_transfers!+ # links from Wise's own activity feed. Any other pair across them is a+ # coincidence (a GBP top-up "matching" a USD payout), so it is never+ # suggested here; the manual dialog still offers it.+ exclude_same_wise_item: true)# Track which transactions we've already matched to avoid duplicates@@ -249,6 +257,30 @@ module Family::AutoTransferMatchableSQLend+ # With :exclude_same_wise_item, drops pairs whose two accounts are linked to+ # balances (WiseAccounts) of the same WiseItem. Applied in both UNION branches,+ # since two balances of one item may share a currency (a balance and its Jar)+ # or not. Only auto_match_transfers! sets it (see the comment there); the+ # manual "match as transfer" dialog leaves it off.+ def same_wise_item_condition_sql+ <<~SQL.squish+ (:exclude_same_wise_item = FALSE OR NOT EXISTS (+ SELECT 1+ FROM account_providers inflow_wise_links+ JOIN wise_accounts inflow_wise_accounts ON inflow_wise_accounts.id = inflow_wise_links.provider_id+ JOIN account_providers outflow_wise_links ON (+ outflow_wise_links.account_id = outflow_accounts.id AND+ outflow_wise_links.provider_type = 'WiseAccount'+ )+ JOIN wise_accounts outflow_wise_accounts ON outflow_wise_accounts.id = outflow_wise_links.provider_id+ WHERE+ inflow_wise_links.account_id = inflow_accounts.id AND+ inflow_wise_links.provider_type = 'WiseAccount' AND+ outflow_wise_accounts.wise_item_id = inflow_wise_accounts.wise_item_id+ ))+ SQL+ end+# Mirrors Account.writable_by for the `writers` row: owner or full_control share.def writer_can_write_sql(accounts_alias)<<~SQL.squish@@ -344,6 +376,7 @@ module Family::AutoTransferMatchable(:outflow_transaction_id IS NULL OR outflow_candidates.entryable_id = :outflow_transaction_id) AND(:filter_transaction_ids = FALSE OR inflow_candidates.entryable_id IN (:transaction_ids) OR outflow_candidates.entryable_id IN (:transaction_ids)) AND(:include_rejected = TRUE OR rejected_transfers.id IS NULL) AND+ #{same_wise_item_condition_sql} AND#{common_writer_condition_sql}UNION ALLSELECT@@ -433,6 +466,7 @@ module Family::AutoTransferMatchable(#{linked_account_sql("inflow_accounts")} AND #{linked_account_sql("outflow_accounts")}) ORconfirmed_routes.outflow_account_id IS NOT NULL) AND+ #{same_wise_item_condition_sql} AND#{common_writer_condition_sql}) transfer_match_candidatesORDER BY transfer_match_candidates.match_rank ASC, transfer_match_candidates.date_diff ASCdiff --git a/app/models/provider/wise.rb b/app/models/provider/wise.rbindex c2660ccb57..45100eba76 100644--- a/app/models/provider/wise.rb+++ b/app/models/provider/wise.rb@@ -9,6 +9,11 @@ class Provider::Wise# Wise caps a single balance-statement request at 469 days; chunk at 468 to# stay safely within the limit while covering the full requested range.MAX_STATEMENT_DAYS = 468+ # A request that may succeed later (WiseError#retryable?) is retried this+ # many times, never waiting longer than RETRY_MAX_WAIT seconds between+ # attempts.+ RETRIES = 3+ RETRY_MAX_WAIT = 60headers "User-Agent" => "Sure Finance Wise Client"default_options.merge!({ timeout: 120 }.merge(httparty_ssl_options))@@ -21,6 +26,25 @@ class Provider::Wiseattr_reader :token, :base_url, :sca_private_key+ # Runs the block, retrying a request Wise rate-limited (429), answered with+ # a server error (5xx), or that failed on the way (a timeout, a refused+ # connection). Each wait follows Wise's Retry-After when it is longer than+ # the exponential backoff (2, 4, 8 s) and adds up to a second of jitter. A+ # Retry-After beyond RETRY_MAX_WAIT is not waited out: an earlier attempt+ # would be refused too, so the error is raised and the next sync tries again.+ def self.with_retries(max_retries: RETRIES)+ retries = 0+ begin+ yield+ rescue WiseError => e+ raise unless e.retryable? && retries < max_retries && e.retry_after.to_f <= RETRY_MAX_WAIT++ retries += 1+ sleep([ [ e.retry_after.to_f, 2**retries ].max + rand, RETRY_MAX_WAIT ].min)+ retry+ end+ end+def initialize(token, base_url: LIVE_BASE_URL, sca_private_key: nil)@token = token@base_url = base_url@@ -54,46 +78,62 @@ class Provider::Wise)end- def get_balance_statements(profile_id, balance_id, currency:, start_date:, end_date: Date.current)+ # The statement rows between two instants, which Wise reads as UTC (so a+ # window starts at the moment given, not at midnight in whatever zone the+ # job runs in). Longer intervals are asked for in windows of+ # MAX_STATEMENT_DAYS, each retried on its own (.with_retries) so earlier+ # windows are not fetched again.+ def get_balance_statements(profile_id, balance_id, currency:, interval_start:, interval_end: Time.current)transactions = []- window_start = start_date.to_date- end_date = end_date.to_date-- while window_start <= end_date- window_end = [ window_start + MAX_STATEMENT_DAYS - 1, end_date ].min- response = with_rate_limit_retry do- get_balance_statement(- profile_id,- balance_id,- currency: currency,- interval_start: window_start.beginning_of_day,- interval_end: window_end.end_of_day- )+ window_start = interval_start.to_time.utc+ finish = interval_end.to_time.utc+ return transactions if window_start > finish++ loop do+ window_end = [ window_start + MAX_STATEMENT_DAYS.days, finish ].min+ response = self.class.with_retries do+ get_balance_statement(profile_id, balance_id, currency: currency, interval_start: window_start, interval_end: window_end)endtransactions.concat(Array(response["transactions"] || response[:transactions]))- window_start = window_end + 1.day+ break if window_end >= finish++ window_start = window_endendtransactionsend- def get_transfers(profile_id, limit: 100, offset: 0)- get(- "/v1/transfers",- query: { profile: profile_id, limit: limit, offset: offset }- )+ # Wise lists transfers oldest first. createdDateStart/createdDateEnd are+ # inclusive dates, sent as the UTC date of the given time. The offset+ # must be a multiple of the limit (HTTP 422 inconsistent.pagination).+ def get_transfers(profile_id, limit: 100, offset: 0, created_date_start: nil, created_date_end: nil)+ query = { profile: profile_id, limit: limit, offset: offset }+ query[:createdDateStart] = utc_date(created_date_start) if created_date_start+ query[:createdDateEnd] = utc_date(created_date_end) if created_date_end+ get("/v1/transfers", query: query)enddef get_transfer(transfer_id)get("/v1/transfers/#{transfer_id}")end- def get_activities(profile_id, cursor: nil, size: 100)+ # Wise lists activities newest first. The next page is requested with the+ # previous response's `cursor` as `nextCursor` (a `cursor` parameter is+ # ignored and returns the first page again); since/until are UTC instants.+ def get_activities(profile_id, cursor: nil, size: 100, since: nil, until_time: nil)query = { size: size }- query[:cursor] = cursor if cursor+ query[:nextCursor] = cursor if cursor+ query[:since] = since.to_time.utc.iso8601 if since+ query[:until] = until_time.to_time.utc.iso8601 if until_timeget("/v1/profiles/#{profile_id}/activities", query: query)end+ # The account recipient (`recipientId`, the target of transfers into the+ # account) and the account's `creationTime`.+ def get_multi_currency_account(profile_id)+ get("/v4/profiles/#{profile_id}/multi-currency-account")+ end+def get_borderless_accounts(profile_id)get("/v1/borderless-accounts", query: { profileId: profile_id })end@@ -111,7 +151,7 @@ class Provider::Wisereturn get(path, query: query, sca_headers: sca_approval_headers(response))end- handle_response(response)+ handle_response(response, sca_challenged: sca_headers.present? || sca_challenge_token(response).present?)rescue WiseErrorraiserescue SocketError, Net::OpenTimeout, Net::ReadTimeout => e@@ -155,45 +195,57 @@ class Provider::Wise}end- def handle_response(response)+ def handle_response(response, sca_challenged: false)case response.codewhen 200JSON.parse(response.body)when 401raise WiseError.new("Invalid API token", :unauthorized)when 403- raise WiseError.new("Access forbidden — check token permissions", :access_forbidden)+ raise WiseError.new("Access forbidden — check token permissions", :access_forbidden, sca_challenged: sca_challenged)when 404raise WiseError.new("Resource not found", :not_found)when 429- raise WiseError.new("Rate limit exceeded. Please try again later.", :rate_limited)+ raise WiseError.new("Rate limit exceeded. Please try again later.", :rate_limited, retry_after: retry_after_seconds(response))else- raise WiseError.new("Unexpected response #{response.code}: #{response.body}", :fetch_failed)+ error_type = response.code.to_i.between?(500, 599) ? :server_error : :fetch_failed+ raise WiseError.new("Unexpected response #{response.code}: #{response.body}", error_type)endend- private+ # Wise sends Retry-After as a number of seconds.+ def retry_after_seconds(response)+ seconds = Integer(response.headers&.[]("Retry-After").to_s, exception: false)+ seconds if seconds&.positive?+ end- # Retries only the failed window so a rate-limited request does not- # restart earlier windows in a multi-window statement fetch.- def with_rate_limit_retry(max_retries: 3)- retries = 0- begin- yield- rescue WiseError => e- raise unless e.error_type == :rate_limited && retries < max_retries- retries += 1- sleep(2 ** retries)- retry- end- end+ def utc_date(value)+ date = value.is_a?(Date) && !value.is_a?(DateTime) ? value : value.to_time.utc.to_date+ date.iso8601+ end++ privateclass WiseError < StandardError- attr_reader :error_type+ attr_reader :error_type, :retry_after- def initialize(message, error_type = :unknown)+ def initialize(message, error_type = :unknown, retry_after: nil, sca_challenged: false)super(message)@error_type = error_type+ @retry_after = retry_after+ @sca_challenged = sca_challenged+ end++ # A 403 that carried Wise's one-time-token challenge (or answered a+ # signed retry) needs a registered SCA key. A 403 without one means+ # the token may not use the endpoint at all.+ def sca_challenged?+ @sca_challenged+ end++ # Asking again later may succeed (Provider::Wise.with_retries).+ def retryable?+ %i[rate_limited server_error request_failed].include?(error_type)endendenddiff --git a/app/models/wise_account.rb b/app/models/wise_account.rbindex 7869b867a8..24546c1465 100644--- a/app/models/wise_account.rb+++ b/app/models/wise_account.rb@@ -3,6 +3,22 @@class WiseAccount < ApplicationRecordinclude Encryptable+ # Kept from the stored snapshot when a new one lacks them: the recipient+ # ids that decide transfer direction (a failed lookup must not flip it)+ # and Sure's own markers on the balance.+ PRESERVED_KEYS = %w[+ recipient_id borderless_account_id recipientId closed_at absent_count statements_coverage name_history prune_cap_bypass+ opening_anchor+ ].freeze++ # First key of the advisory lock that serializes the processing of one+ # balance (#with_processing_lock); the second is a hash of its id.+ PROCESSING_LOCK_NAMESPACE = 4014++ # Processing was asked to run inside a caller's transaction (see+ # #with_processing_lock).+ ProcessingInTransaction = Class.new(StandardError)+if encryption_ready?encrypts :raw_payloadencrypts :raw_transactions_payload@@ -26,6 +42,136 @@ class WiseAccount < ApplicationRecordraw_payload&.dig("type") == "SAVINGS"end+ # Every name Wise gave the balance that Sure saw: the current one, the+ # ones it had before a rename (raw_payload "name_history", one of+ # PRESERVED_KEYS) and the one Sure stored when it first saw it. Activity+ # titles name a jar as it was called at the time.+ def known_names+ payload = raw_payload.is_a?(Hash) ? raw_payload : {}+ [ payload["name"], *Array(payload["name_history"]), name ].filter_map { |known| known.to_s.strip.presence }.uniq+ end++ # The name Wise gives the balance now (raw_payload "name"), or nil.+ def current_name+ raw_payload["name"].to_s.strip.presence if raw_payload.is_a?(Hash)+ end++ # Wise no longer lists the balance (raw_payload "closed_at", one of+ # PRESERVED_KEYS).+ def closed?+ raw_payload.is_a?(Hash) && raw_payload["closed_at"].present?+ end++ # When Sure found the balance closed, as a UTC time, or nil.+ def closed_at+ parse_utc(raw_payload["closed_at"]) if closed?+ end++ # When Wise opened the balance (its creationTime), as a UTC time, or nil.+ def creation_time+ parse_utc(raw_payload["creationTime"]) if raw_payload.is_a?(Hash)+ end++ # The window successful statement fetches for this balance have covered+ # without a gap, as { from:, through: } UTC times (raw_payload+ # "statements_coverage", one of PRESERVED_KEYS), or nil before the first.+ def statements_coverage+ coverage = raw_payload["statements_coverage"] if raw_payload.is_a?(Hash)+ return nil unless coverage.is_a?(Hash)++ from, through = coverage.values_at("from", "through").map { |time| parse_utc(time) }+ { from: from, through: through } if from && through+ end++ # The external ids of the entries whose rows a sync that re-fetched the+ # whole history moved out of this balance's payload, or left booking+ # nothing on it (raw_payload "prune_cap_bypass", one of PRESERVED_KEYS):+ # the stale-entry clean-up may delete these beyond its cap until it has+ # run after a complete import (WiseAccount::Transactions::Processor).+ def prune_cap_bypass_ids+ ids = raw_payload["prune_cap_bypass"] if raw_payload.is_a?(Hash)+ Array(ids).map(&:to_s)+ end++ # Once the clean-up has run after a complete import; taken out of the+ # snapshot as stored now (#locked_raw_payload), so what a sync stored+ # meanwhile stays.+ def spend_prune_cap_bypass!+ return unless raw_payload.is_a?(Hash) && raw_payload.key?("prune_cap_bypass")++ self.class.transaction { update!(raw_payload: locked_raw_payload.except("prune_cap_bypass")) }+ end++ # The opening anchor Sure last set on the balance's account (raw_payload+ # "opening_anchor", one of PRESERVED_KEYS), as { entry_id:, date:,+ # amount: }, or nil before Sure set one.+ def written_opening_anchor+ written = raw_payload["opening_anchor"] if raw_payload.is_a?(Hash)+ return nil unless written.is_a?(Hash)++ { entry_id: written["entry_id"], date: Date.iso8601(written["date"].to_s), amount: written["amount"].to_d }+ rescue ArgumentError+ nil+ end++ # Records an opening anchor entry as Sure just set it, so a later change+ # by a person can be told apart (WiseAccount::Processor). Merged into the+ # snapshot as stored now, under a row lock, so the marks a sync writes+ # meanwhile stay.+ def remember_opening_anchor!(entry)+ written = { "entry_id" => entry.id, "date" => entry.date.iso8601, "amount" => entry.amount.to_d.to_s }+ merge_raw_payload!({ "opening_anchor" => written })+ end++ # The day a balance whose whole history Sure imports starts at 0: the day+ # before Wise opened it, in the family's zone. nil unless the item imports+ # the full history and Wise said when it opened the balance.+ def opening_date+ created = creation_time+ return nil unless created && wise_item.import_all_history?++ created.in_time_zone(wise_item.time_zone).to_date.prev_day+ end++ # Serializes everything that books or deletes this balance's entries, such+ # as an item sync's processing and a balance processed on its own. It is a+ # session-level advisory lock, not a row lock or a transaction: saving an+ # Account locks its owner's users row, so a transaction held across a whole+ # payload would stall every other account save of that user meanwhile.+ # Rows still commit one by one. Re-entrant on the same connection.+ #+ # Never inside a caller's transaction: its rows would not commit one by+ # one, and an error aborting it would make the unlock fail, leaving the+ # lock with the pooled connection, where every later processing of the+ # balance would wait for it for good.+ def with_processing_lock+ if self.class.current_transaction.open?+ raise ProcessingInTransaction, "WiseAccount #{id} must not be processed inside a transaction"+ end++ connection = self.class.lease_connection+ key = [ PROCESSING_LOCK_NAMESPACE, id.to_s ]++ connection.execute(self.class.sanitize_sql_array([ "SELECT pg_advisory_lock(?, hashtext(?))", *key ]))+ outermost = @processing_lock_session.nil?+ @processing_lock_session ||= backend_pid(connection)+ begin+ yield+ ensure+ release_processing_lock(connection, key)+ @processing_lock_session = nil if outermost+ end+ end++ # The session that took the processing lock ended while the block ran: a+ # broken connection that Rails opened again on the next query, on a new+ # session that holds no lock, so another processor may hold it now. What+ # deletes entries (WiseAccount::Transactions::Processor) waits for the+ # next sync then. false outside the lock.+ def processing_lock_lost?+ @processing_lock_session.present? && backend_pid(self.class.lease_connection) != @processing_lock_session+ end+def account_subtypejar? ? "savings" : Depository::DEFAULT_SUBTYPEend@@ -35,23 +181,87 @@ class WiseAccount < ApplicationRecordpayload = balance_data.is_a?(Hash) ? balance_data.dup : balance_datapayload = payload.merge("borderless_account_id" => borderless_account_id) if borderless_account_idpayload = payload.merge("recipient_id" => recipient_id) if recipient_id+ # Read under the row lock, so a mark another sync or link stored after+ # this record was loaded is kept (see #merge_raw_payload!). A balance+ # seen for the first time has nothing stored yet.+ self.class.transaction do+ previous = persisted? ? locked_raw_payload : {}+ # Renamed in Wise: the old name joins the history (#known_names).+ if previous["name"].present? && previous["name"] != payload["name"]+ payload = payload.merge("name_history" => (Array(previous["name_history"]) + [ previous["name"] ]).uniq)+ end+ PRESERVED_KEYS.each do |key|+ payload = payload.merge(key => previous[key]) if previous.key?(key) && !payload.key?(key)+ end- currency_code = data.dig(:amount, :currency).presence || data[:currency].presence || currency- savings = data[:type] == "SAVINGS"- balance_value = savings ? data.dig(:totalWorth, :value).to_d : data.dig(:amount, :value).to_d- api_name = data[:name].presence- default_name = savings ? "Wise JAR #{currency_code}" : "Wise #{currency_code}"+ currency_code = data.dig(:amount, :currency).presence || data[:currency].presence || currency+ savings = data[:type] == "SAVINGS"+ # A STANDARD balance's amount leaves out what card holds keep back+ # (reservedAmount), while Sure books a card payment only once Wise+ # completes it, so the holds are counted back in. A jar's is totalWorth.+ balance_value = savings ? data.dig(:totalWorth, :value).to_d : data.dig(:amount, :value).to_d + data.dig(:reservedAmount, :value).to_d+ api_name = data[:name].presence+ default_name = savings ? "Wise JAR #{currency_code}" : "Wise #{currency_code}"- update!(- current_balance: balance_value,- reserved_balance: data.dig(:reservedAmount, :value).to_d,- currency: currency_code,- name: name.presence || api_name || default_name,- raw_payload: payload- )+ update!(+ current_balance: balance_value,+ reserved_balance: data.dig(:reservedAmount, :value).to_d,+ currency: currency_code,+ name: name.presence || api_name || default_name,+ raw_payload: payload+ )+ endend- def upsert_wise_transactions_snapshot!(transactions)- update!(raw_transactions_payload: transactions)+ # statements_coverage: the coverage this sync's statement fetch extended+ # ({ "from", "through" } ISO-8601 strings), saved with the rows it brought.+ # prune_cap_bypass: what #prune_cap_bypass_ids lists from now on. Marks are+ # merged into the snapshot as stored now (#merge_raw_payload!), so an+ # opening anchor a link recorded meanwhile stays.+ def upsert_wise_transactions_snapshot!(transactions, statements_coverage: nil, prune_cap_bypass: nil)+ markers = { "statements_coverage" => statements_coverage, "prune_cap_bypass" => prune_cap_bypass }.compact+ return update!(raw_transactions_payload: transactions) if markers.empty?++ merge_raw_payload!(markers, raw_transactions_payload: transactions)end++ private++ # Merges the given keys into the snapshot as stored now, so a writer+ # holding an older copy of the balance loses nothing to it.+ def merge_raw_payload!(attributes, **others)+ self.class.transaction { update!(raw_payload: locked_raw_payload.merge(attributes), **others) }+ end++ # The stored snapshot, its row locked until the caller's transaction ends.+ def locked_raw_payload+ stored = self.class.lock.select(:id, :raw_payload).find(id).raw_payload+ stored.is_a?(Hash) ? stored : {}+ end++ # An unlock that does not run (the connection broke, the thread was+ # interrupted) would leave the lock with the connection; throwing the+ # connection away ends its session, which releases the lock. A session+ # that ended took the lock with it, and the new one has none to release.+ def release_processing_lock(connection, key)+ released = false+ if processing_lock_lost?+ Rails.logger.warn "WiseAccount #{id} - The processing lock ended with its database session while the balance was processed"+ else+ connection.execute(self.class.sanitize_sql_array([ "SELECT pg_advisory_unlock(?, hashtext(?))", *key ]))+ end+ released = true+ ensure+ connection.throw_away! unless released+ end++ def backend_pid(connection)+ connection.select_value("SELECT pg_backend_pid()")+ end++ def parse_utc(raw)+ ActiveSupport::TimeZone["UTC"].parse(raw.to_s) if raw.present?+ rescue ArgumentError+ nil+ endenddiff --git a/app/models/wise_account/processor.rb b/app/models/wise_account/processor.rbindex 82105a0de6..c0eb3721b9 100644--- a/app/models/wise_account/processor.rb+++ b/app/models/wise_account/processor.rb@@ -1,20 +1,35 @@# frozen_string_literal: trueclass WiseAccount::Processor- attr_reader :wise_account+ attr_reader :wise_account, :import_complete- def initialize(wise_account)+ # import_complete: see WiseItem#process_accounts. Processing an account on+ # its own leaves it false, so nothing is deleted or rewritten.+ def initialize(wise_account, import_complete: false)@wise_account = wise_account+ @import_complete = import_completeenddef process- unless wise_account.current_account.present?- Rails.logger.info "WiseAccount::Processor - No linked account for wise_account #{wise_account.id}, skipping"- return- end+ wise_account.with_processing_lock do+ # The payload a sync stored while this run waited for the lock.+ wise_account.reload++ unless wise_account.current_account.present?+ Rails.logger.info "WiseAccount::Processor - No linked account for wise_account #{wise_account.id}, skipping"+ next+ end- process_account!- process_transactions+ account = wise_account.current_account+ follow_current_anchor(account)+ result = process_transactions+ repair_opening_anchor+ # The account's own save last, once the rows behind its balance are+ # booked; it locks the owner's users row for that save's transaction+ # only (Account#owner_belongs_to_family), never for the rows'.+ update_balance!(account)+ result+ endrescue StandardError => eRails.logger.error "WiseAccount::Processor - Failed to process account #{wise_account.id}: #{e.message}"Sentry.capture_exception(e) { |s| s.set_tags(wise_account_id: wise_account.id) }@@ -23,22 +38,160 @@ class WiseAccount::Processorprivate- def process_account!- account = wise_account.current_account- balance = wise_account.current_balance || 0+ def update_balance!(account)+ balance = live_balance+ account.update!(balance: balance, cash_balance: balance, currency: wise_account.currency)+ end++ def live_balance+ wise_account.current_balance || 0+ end++ # The balance is set as is, with no current anchor: set_current_balance+ # would turn each day's anchor into a reconciliation, and a card payment+ # Wise completes after a sync, dated on or before that day, would then+ # shift every earlier day for good. An account linked from another+ # provider can still hold that provider's current anchor, which the+ # balance history would start from (frozen at its date and amount), so it+ # follows the live balance in place, never rotated. It moves before the+ # opening balance repair, which reads the oldest entry. Never raises.+ def follow_current_anchor(account)+ anchor = account.valuations.current_anchor.includes(:entry).first&.entry+ return unless anchor- account.update!(- balance: balance,- cash_balance: balance,- currency: wise_account.currency+ anchor.update!(amount: live_balance, currency: wise_account.currency,+ date: Time.current.in_time_zone(wise_account.wise_item.time_zone).to_date)+ rescue StandardError => e+ capture_debug_log(+ category: "provider_sync_error",+ level: "warn",+ message: "WiseAccount::Processor - Could not move the current balance anchor to the Wise balance (#{e.class})",+ operation: "current_anchor",+ error_class: e.class.name)enddef process_transactions- WiseAccount::Transactions::Processor.new(wise_account).process+ WiseAccount::Transactions::Processor.new(wise_account, import_complete: import_complete).processrescue StandardError => eRails.logger.error "WiseAccount::Processor - Failed to process transactions for wise_account #{wise_account.id}: #{e.message}"Rails.logger.error Array(e.backtrace).first(10).join("\n")Sentry.capture_exception(e) { |s| s.set_tags(wise_account_id: wise_account.id) }end++ # A balance whose whole history Sure has imported was 0 the day before+ # Wise opened it (WiseAccount#opening_date), so its opening anchor (made+ # at the live balance, two years back, when the account was created) is+ # moved there, or to the day before an entry booked even earlier. Only+ # after a complete import whose coverage reaches the balance's creation,+ # for an anchor Sure set (#set_by_sure?), on an account holding nothing+ # but Wise transactions. Never raises.+ def repair_opening_anchor+ return unless import_complete++ account = wise_account.current_account+ opening_date = wise_account.opening_date+ return unless opening_date && covered_since?(wise_account.creation_time)++ anchor = account.valuations.opening_anchor.includes(:entry).first&.entry+ return if anchor.nil?+ return if account.entries.where(entryable_type: "Transaction").where("entries.source IS DISTINCT FROM ?", "wise").exists?++ manager = Account::OpeningBalanceManager.new(account)+ date = [ opening_date, manager.oldest_entry_date&.prev_day ].compact.min+ return if anchor.date == date && anchor.amount.zero?++ unless set_by_sure?(anchor)+ capture_debug_log(+ category: "provider_sync",+ level: "info",+ message: "WiseAccount::Processor - Kept an opening balance Sure does not recognise as its own, although the Wise history starts at 0 on another day",+ operation: "opening_anchor",+ opening_date: date.iso8601,+ kept_opening_date: anchor.date.iso8601+ )+ return+ end++ previous_date = anchor.date+ result = manager.set_opening_balance(balance: 0, date: date)+ wise_account.remember_opening_anchor!(anchor.reload) if result.changes_made?+ if result.error+ capture_debug_log(+ category: "provider_sync_error",+ level: "warn",+ message: "WiseAccount::Processor - Could not move the opening balance to 0 on the day before Wise opened the balance: #{result.error}",+ operation: "opening_anchor",+ opening_date: date.iso8601+ )+ elsif result.changes_made?+ capture_debug_log(+ category: "provider_sync",+ level: "info",+ message: "WiseAccount::Processor - Moved the opening balance to 0 on the day before Wise opened the balance",+ operation: "opening_anchor",+ previous_opening_date: previous_date.iso8601,+ opening_date: date.iso8601+ )+ end+ rescue StandardError => e+ capture_debug_log(+ category: "provider_sync_error",+ level: "error",+ message: "WiseAccount::Processor - Opening balance repair failed (#{e.class})",+ operation: "opening_anchor",+ error_class: e.class.name+ )+ end++ # An opening anchor is Sure's to move when it is as Sure last set it+ # (WiseAccount#written_opening_anchor) or, on an account Sure never set+ # one for, still the default made with the account (#default_anchor?).+ # One a person changed is theirs: the valuation drawer saves an edit+ # without marking it user_modified.+ def set_by_sure?(anchor)+ return false if anchor.user_modified?++ written = wise_account.written_opening_anchor+ return written[:date] == anchor.date && written[:amount] == anchor.amount if written && written[:entry_id] == anchor.id++ default_anchor?(anchor)+ end++ # The default opening anchor: the balance two years back, never changed+ # since. It was dated in the zone of the request that created the+ # account, which neither the zone this sync runs in nor the family's+ # zone now need be, so its date is within a day of the UTC date two+ # years before its creation (zones run from UTC-12 to UTC+14).+ def default_anchor?(anchor)+ (anchor.updated_at - anchor.created_at).abs < 1.second &&+ ((anchor.created_at.utc - 2.years).to_date - anchor.date).abs <= 1+ end++ # Activities, and transfers or the balance's statements (which carry what+ # its transfers did), were fetched back to `time`. A connection whose+ # balances all have statements fetches no transfer list.+ def covered_since?(time)+ return false unless time++ reaches = ->(coverage) { coverage.present? && coverage[:from] <= time }+ wise_item = wise_account.wise_item+ reaches.call(wise_item.fetch_coverage(:activities)) &&+ (reaches.call(wise_item.fetch_coverage(:transfers)) || reaches.call(wise_account.statements_coverage))+ end++ def capture_debug_log(category:, level:, message:, **metadata)+ DebugLogEntry.capture(+ category: category,+ level: level,+ message: message,+ source: self.class.name,+ provider_key: "wise",+ family: wise_account.wise_item.family,+ account_provider: wise_account.account_provider,+ metadata: { wise_item_id: wise_account.wise_item_id, wise_account_id: wise_account.id, currency: wise_account.currency }.merge(metadata)+ )+ rescue StandardError => e+ Rails.logger.warn "WiseAccount::Processor - Failed to capture Wise debug log: #{e.message}"+ endenddiff --git a/app/models/wise_account/transactions/processor.rb b/app/models/wise_account/transactions/processor.rbindex fa31a0f56f..ea587f80e8 100644--- a/app/models/wise_account/transactions/processor.rb+++ b/app/models/wise_account/transactions/processor.rb@@ -1,35 +1,60 @@# frozen_string_literal: trueclass WiseAccount::Transactions::Processor- attr_reader :wise_account+ # A sync that would delete more stale entries than this (at least+ # PRUNE_CAP_MINIMUM, or PRUNE_CAP_SHARE of the account's Wise entries)+ # deletes none: that many at once looks like a fault, not a correction.+ PRUNE_CAP_MINIMUM = 5+ PRUNE_CAP_SHARE = BigDecimal("0.1")- def initialize(wise_account)+ # The entries of the rows routing moves between balances (transfers and+ # activities; statement rows never move). With no row to date an empty+ # payload by, only these can be stale on it.+ ROUTED_EXTERNAL_ID_PREFIXES = %w[wise_transfer_ wise_fee_ wise_refund_ wise_interbalance_ wise_activity_].freeze+ # The fetches each kind of entry's rows come from: a transfer's entries+ # from the transfer list and its activities (its fee and refund), an+ # activity's (conversion legs included) from the activities, a statement+ # row's from the balance's statements.+ COVERAGE_SOURCES = {+ "wise_transfer_" => %i[transfers activities], "wise_fee_" => %i[transfers activities],+ "wise_refund_" => %i[transfers activities], "wise_interbalance_" => %i[activities],+ "wise_activity_" => %i[activities], "wise_statement_" => %i[statements]+ }.freeze+ MAX_LOGGED_EXTERNAL_IDS = 20++ attr_reader :wise_account, :import_complete++ # import_complete: see WiseItem#process_accounts.+ def initialize(wise_account, import_complete: false)@wise_account = wise_account+ @import_complete = import_completeenddef process- unless wise_account.raw_transactions_payload.present?+ payload = wise_account.raw_transactions_payload+ rows = Array(payload)+ total = rows.count+ if rows.empty?Rails.logger.info "WiseAccount::Transactions::Processor - No transactions for wise_account #{wise_account.id}"- return { success: true, total: 0, imported: 0, skipped: 0, failed: 0, errors: [] }+ else+ Rails.logger.info "WiseAccount::Transactions::Processor - Processing #{total} transactions for wise_account #{wise_account.id}"end- total = wise_account.raw_transactions_payload.count- Rails.logger.info "WiseAccount::Transactions::Processor - Processing #{total} transactions for wise_account #{wise_account.id}"-imported = 0failed = 0skipped = 0errors = []+ expected_ids = Set.new+ row_dates = []+ # { kind of rename => { outcome => external ids } } (#take_over_entries).+ @rekeys = Hash.new { |kinds, kind| kinds[kind] = Hash.new { |outcomes, outcome| outcomes[outcome] = [] } }- wise_account.raw_transactions_payload.each_with_index do |tx_data, index|- processor_class = if WiseActivity::Processor::JAR_ACTIVITY_TYPES.include?(tx_data["type"])- WiseActivity::Processor- elsif tx_data["wise_statement"].present?- WiseStatement::Processor- else- WiseEntry::Processor- end- result = processor_class.new(tx_data, wise_account: wise_account).process+ rows.each_with_index do |tx_data, index|+ processor = processor_for(tx_data)+ take_over_entries(processor)+ result = processor.process+ expected_ids.merge(processor.expected_external_ids)+ row_dates << processor.booking_datecase resultwhen :skipped@@ -51,8 +76,352 @@ class WiseAccount::Transactions::Processorerrors << { index: index, error: "#{e.class}: #{e.message}" }end- Rails.logger.info "WiseAccount::Transactions::Processor - Done: #{imported} imported, #{skipped} skipped, #{failed} failed"+ log_rekeys+ prune = prune?(payload, failed) ? prune_stale_entries(rows, expected_ids, row_dates) : { destroyed: 0, kept: 0 }+ Rails.logger.info "WiseAccount::Transactions::Processor - Done: #{imported} imported, #{skipped} skipped, #{failed} failed, #{prune[:destroyed]} stale deleted"- { success: failed == 0, total: total, imported: imported, skipped: skipped, failed: failed, errors: errors }+ { success: failed == 0, total: total, imported: imported, skipped: skipped, failed: failed, errors: errors,+ pruned: prune[:destroyed], prune_kept: prune[:kept] }end++ private++ # The row's kind, not its type, picks the processor: a statement row,+ # an activity row (any activity type the importer stored, see+ # WiseActivity::Processor.activity_row?), else a /v1/transfers row.+ def processor_for(tx_data)+ if tx_data["wise_statement"].present?+ WiseStatement::Processor.new(tx_data, wise_account: wise_account)+ elsif WiseActivity::Processor.activity_row?(tx_data)+ WiseActivity::Processor.new(tx_data, wise_account: wise_account)+ else+ WiseEntry::Processor.new(tx_data, wise_account: wise_account, own_recipient_ids: own_recipient_ids,+ recipient_owners: recipient_owners)+ end+ end++ # A statement row that carries the movement of a row the balance booked+ # before it had statements (WiseItem::StatementMigration) first takes+ # that row's entries over, main entry and fee together, so they keep+ # what a person did to them: renamed to the statement row's ids when+ # those are free. When both exist (an older migration booked both), the+ # one a person acted on or linked stays under the statement id and the+ # other is deleted; if a person acted on both, both stay (logged).+ # Deleting waits for a complete import. A jar move's leg takes over its+ # entry booked on the other side the same way (WiseActivity::Processor+ # #superseded_external_ids).+ def take_over_entries(processor)+ return unless account.present? && processor.respond_to?(:superseded_external_ids)++ mapping = processor.superseded_external_ids+ # Every jar move names its other side, and most have no entry under it,+ # so the account's ids are read once per run (#entry_external_ids).+ return if mapping.empty? || mapping.keys.none? { |external_id| entry_external_ids.include?(external_id) }++ rekeys = @rekeys[processor.is_a?(WiseStatement::Processor) ? :statement : :leg_side]+ outcomes = Entry.transaction(requires_new: true) { mapping.map { |from, to| rekey_entry(from, to) } }+ outcomes.each { |outcome, external_id| rekeys[outcome] << external_id unless outcome == :none }+ mapping.each_key.zip(outcomes) do |from, (outcome, _external_id)|+ entry_external_ids.delete(from) if %i[renamed replaced dropped].include?(outcome)+ end+ rescue StandardError+ # The row fails rather than book a second entry next to the old one;+ # the next sync tries again.+ rekeys[:failed].concat(Array(mapping&.keys)) if rekeys+ raise+ end++ # [outcome, the external id it concerns]; destroyed entries are named by+ # the id they had.+ def rekey_entry(from, to)+ scope = account.entries.where(source: "wise", entryable_type: "Transaction")+ old = scope.lock.find_by(external_id: from)+ return [ :none, from ] unless old++ current = scope.lock.find_by(external_id: to)+ if current.nil?+ old.update!(external_id: to)+ [ :renamed, to ]+ elsif !import_complete || wise_account.processing_lock_lost?+ [ :deferred, from ]+ elsif keep_rank(old) > keep_rank(current) && !protected_entry?(current)+ current.destroy!+ old.update!(external_id: to)+ [ :replaced, to ]+ elsif !protected_entry?(old)+ old.destroy!+ [ :dropped, from ]+ else+ [ :kept_both, from ]+ end+ end++ # Which of two entries for one movement to keep: one a person acted on+ # (#protected_entry?), then one in a transfer (a suggestion included),+ # then one not excluded (a person may have hidden the other copy).+ def keep_rank(entry)+ return 3 if protected_entry?(entry)++ transaction = entry.entryable+ return 2 if transaction.transfer_as_inflow.present? || transaction.transfer_as_outflow.present?++ entry.excluded? ? 0 : 1+ end++ # One DebugLogEntry per kind of rename that did anything this run.+ def log_rekeys+ @rekeys.each do |kind, rekeys|+ next if rekeys.values.all?(&:empty?)++ taken = rekeys[:renamed].size + rekeys[:replaced].size+ if kind == :statement+ log_rekey(rekeys, operation: "statement_rekey",+ message: "Statement rows took over #{taken} Wise entries booked before the balance had statements")+ else+ log_rekey(rekeys, operation: "leg_side_rekey",+ message: "Renamed #{taken} Wise jar move entries to the side of the move they are booked on")+ end+ end+ end++ def log_rekey(rekeys, operation:, message:)+ warn = rekeys[:kept_both].any? || rekeys[:failed].any?+ DebugLogEntry.capture(+ category: "provider_sync",+ level: warn ? "warn" : "info",+ message: "WiseAccount::Transactions::Processor - #{message}",+ source: self.class.name,+ provider_key: "wise",+ family: account.family,+ account_provider: wise_account.account_provider,+ metadata: {+ wise_item_id: wise_account.wise_item_id,+ wise_account_id: wise_account.id,+ currency: wise_account.currency,+ operation: operation,+ renamed_count: rekeys[:renamed].size,+ replaced_count: rekeys[:replaced].size.nonzero?,+ replaced_external_ids: rekeys[:replaced].first(MAX_LOGGED_EXTERNAL_IDS).presence,+ dropped_count: rekeys[:dropped].size.nonzero?,+ dropped_external_ids: rekeys[:dropped].first(MAX_LOGGED_EXTERNAL_IDS).presence,+ deferred_count: rekeys[:deferred].size.nonzero?,+ kept_both_count: rekeys[:kept_both].size.nonzero?,+ kept_both_external_ids: rekeys[:kept_both].first(MAX_LOGGED_EXTERNAL_IDS).presence,+ failed_count: rekeys[:failed].size.nonzero?+ }.compact+ )+ rescue StandardError => e+ Rails.logger.warn "WiseAccount::Transactions::Processor - Failed to capture Wise debug log: #{e.message}"+ end++ # The external ids of the account's Wise entries, as renames leave them.+ def entry_external_ids+ @entry_external_ids ||= account.entries.where(source: "wise").pluck(:external_id).to_set+ end++ # Looked up once per run rather than once per transfer.+ def own_recipient_ids+ @own_recipient_ids ||= wise_account.wise_item.own_recipient_ids+ end++ def recipient_owners+ @recipient_owners ||= wise_account.wise_item.balance_recipient_owners+ end++ def account+ @account ||= wise_account.current_account+ end++ # The payload speaks for the balance only after an import that fetched+ # everything (nil: nothing was ever stored for it), only if every row was+ # processed, and only where Sure knows what it fetched (#first_covered_days).+ # A closed balance's payload is frozen as it was, and nothing is deleted+ # once the balance's processing lock was lost (WiseAccount#processing_lock_lost?).+ def prune?(payload, failed)+ import_complete && payload.is_a?(Array) && failed.zero? && !wise_account.closed? && account.present? &&+ first_covered_days.any? && !wise_account.processing_lock_lost?+ end++ # Deletes the Wise entries no stored row books any more: a leg routed to+ # this balance by an older rule, a payout Wise cancelled or the balance+ # replay found paid by card, a split part now 0, a statement row of a+ # conversion whose own row books it, an activity a statement row books+ # under a reference Sure could not match. Entries a person acted+ # on stay (#protected_entry?). When there are too many (#prune_cap),+ # only those whose rows a sync that re-fetched the whole history moved+ # out of the payload go (WiseAccount#prune_cap_bypass_ids, spent once+ # this has run); the rest wait. Logged with the external ids.+ def prune_stale_entries(rows, expected_ids, row_dates)+ destroyed = []+ stale = stale_entries(rows, expected_ids, row_dates)+ kept, doomed = stale.partition { |entry| protected_entry?(entry) }+ cap = doomed.empty? ? 0 : prune_cap+ capped = []+ bypassed = false+ if doomed.size > cap+ moved = wise_account.prune_cap_bypass_ids.to_set+ capped = doomed.reject { |entry| moved.include?(entry.external_id) }+ doomed -= capped+ bypassed = doomed.any?+ end+ doomed.each do |entry|+ destroy_stale_entry(entry) ? destroyed << entry : kept << entry+ end++ log_prune(destroyed: destroyed, kept: kept, capped: capped, cap: cap, cap_bypassed: bypassed) if stale.any?+ wise_account.spend_prune_cap_bypass!+ { destroyed: destroyed.size, kept: kept.size }+ rescue StandardError => e+ # The rows are booked by now; a failed clean-up only waits for the next sync.+ Rails.logger.error "WiseAccount::Transactions::Processor - Stale entry clean-up failed for wise_account #{wise_account.id}: #{e.class} - #{e.message}"+ Sentry.capture_exception(e) { |scope| scope.set_tags(wise_account_id: wise_account.id) }+ { destroyed: destroyed.size, kept: 0 }+ end++ # Wise transaction entries on this balance that no row of the payload+ # expects (each processor's #expected_external_ids, none for a row that+ # books nothing here), booked since the balance was linked to the account+ # (an older one is an earlier connection's history), dated where Sure+ # fetched every row of their kind (#first_covered_days) and from the+ # payload's earliest row on: before that an entry can stand for a movement+ # Sure never fetched (a shorter history), unless a row the item holds+ # booked it (WiseAccount#prune_cap_bypass_ids). An empty payload has no+ # row to date by, and only the entries of routed rows count there.+ def stale_entries(rows, expected_ids, row_dates)+ first_days = first_covered_days+ first_days = first_days.slice(*ROUTED_EXTERNAL_ID_PREFIXES) if rows.empty?+ return [] if first_days.empty?++ scope = account.entries.where(source: "wise", entryable_type: "Transaction")+ .where.not(external_id: expected_ids.to_a)+ .where(created_at: wise_account.account_provider.created_at..)+ unless rows.empty?+ earliest = row_dates.compact.min+ dated = earliest ? scope.where(date: earliest..) : scope.none+ explained = wise_account.prune_cap_bypass_ids+ scope = explained.any? ? dated.or(scope.where(external_id: explained)) : dated+ end++ covered = first_days.map do |prefix, day|+ Entry.sanitize_sql_array([ "(entries.external_id LIKE ? AND entries.date >= ?)", "#{Entry.sanitize_sql_like(prefix)}%", day ])+ end+ scope.where(covered.join(" OR ")).includes(:entryable).order(:date, :external_id).to_a+ end++ # { external id prefix => the first day, in the family's zone, from which+ # every fetch its rows come from (COVERAGE_SOURCES) covered the whole+ # day }, for the kinds of entries all of whose fetches have coverage.+ def first_covered_days+ return @first_covered_days if defined?(@first_covered_days)++ wise_item = wise_account.wise_item+ starts = { transfers: wise_item.fetch_coverage(:transfers)&.dig(:from),+ activities: wise_item.fetch_coverage(:activities)&.dig(:from),+ statements: wise_account.statements_coverage&.dig(:from) }++ @first_covered_days = COVERAGE_SOURCES.each_with_object({}) do |(prefix, sources), days|+ froms = starts.values_at(*sources)+ next unless froms.all?++ start = froms.max.in_time_zone(wise_item.time_zone)+ days[prefix] = start == start.beginning_of_day ? start.to_date : start.to_date.next_day+ end+ end++ # What a person decided about an entry, which a re-routed row must not+ # take away: an edit or lock, notes, tags, receipts, a reconciliation, a+ # split, or a transfer they confirmed. Exclusion alone does not count,+ # since an excluded entry still moves the balance. Wise's own transfer+ # links do not count either (#wise_link?): they go with the entry, and+ # the next link run restores what still applies.+ def protected_entry?(entry)+ transaction = entry.entryable+ entry.user_modified? || entry.import_locked? || entry.reconciled_at.present? ||+ entry.locked_attributes.present? || transaction.locked_attributes.present? ||+ entry.notes.present? || transaction.taggings.exists? || transaction.attachments.attached? ||+ entry.split_parent? || person_transfer?(transaction)+ end++ def person_transfer?(transaction)+ # A fee another transfer carries.+ return true if transaction.transfer_id.present?++ [ transaction.transfer_as_inflow, transaction.transfer_as_outflow ].compact.any? { |transfer| !wise_link?(transfer) }+ end++ # A pending suggestion, or a link the linker confirmed: the two legs of+ # one conversion or jar move on this item, with nothing a person added+ # (WiseItem::InterbalanceLinker.system_link?; a fee entry a person added+ # would go with the transfer). A transfer a person matched between two+ # Wise entries, or noted, is theirs.+ def wise_link?(transfer)+ transfer.pending? || WiseItem::InterbalanceLinker.system_link?(transfer, item_account_ids)+ end++ def item_account_ids+ @item_account_ids ||= wise_account.wise_item.accounts.pluck(:id).to_set+ end++ def prune_cap+ [ PRUNE_CAP_MINIMUM, account.entries.where(source: "wise").count * PRUNE_CAP_SHARE ].max+ end++ # One entry at a time, each in a savepoint, so a failed delete cannot+ # abort a transaction the caller holds. The row lock and a second look+ # keep an entry a person changed meanwhile.+ def destroy_stale_entry(entry)+ Entry.transaction(requires_new: true) do+ entry.lock!+ next false if protected_entry?(entry)++ entry.destroy!+ true+ end+ rescue ActiveRecord::RecordNotFound+ false+ rescue StandardError => e+ Rails.logger.error "WiseAccount::Transactions::Processor - Could not delete stale entry #{entry.id}: #{e.class} - #{e.message}"+ false+ end++ def log_prune(destroyed:, kept:, capped:, cap:, cap_bypassed:)+ message =+ if capped.any? && destroyed.any?+ "Deleted #{destroyed.size} Wise entries whose rows a full re-fetch moved out of the payload; #{capped.size} more " \+ "no stored row books are more than one sync may delete (#{cap.to_f.round(1)}) and stay"+ elsif capped.any?+ "#{capped.size} Wise entries no stored row books are more than one sync may delete (#{cap.to_f.round(1)}); none was deleted"+ else+ "Deleted #{destroyed.size} Wise entries no stored row books any more; kept #{kept.size} a person acted on"+ end++ DebugLogEntry.capture(+ category: "provider_sync",+ level: capped.any? || cap_bypassed ? "warn" : "info",+ message: "WiseAccount::Transactions::Processor - #{message}",+ source: self.class.name,+ provider_key: "wise",+ family: account.family,+ account_provider: wise_account.account_provider,+ metadata: {+ wise_item_id: wise_account.wise_item_id,+ wise_account_id: wise_account.id,+ currency: wise_account.currency,+ operation: "prune",+ destroyed_count: destroyed.size,+ destroyed_external_ids: logged_ids(destroyed),+ kept_count: kept.size,+ kept_external_ids: logged_ids(kept),+ capped_count: capped.size.nonzero?,+ capped_external_ids: logged_ids(capped),+ cap_bypassed: (true if cap_bypassed)+ }.compact+ )+ rescue StandardError => e+ Rails.logger.warn "WiseAccount::Transactions::Processor - Failed to capture Wise debug log: #{e.message}"+ end++ def logged_ids(entries)+ entries.first(MAX_LOGGED_EXTERNAL_IDS).map(&:external_id).presence+ endenddiff --git a/app/models/wise_activity/processor.rb b/app/models/wise_activity/processor.rbindex e58d5c9df8..feea5849bb 100644--- a/app/models/wise_activity/processor.rb+++ b/app/models/wise_activity/processor.rb@@ -1,7 +1,191 @@# frozen_string_literal: trueclass WiseActivity::Processor- JAR_ACTIVITY_TYPES = %w[INTERBALANCE BALANCE_CASHBACK BALANCE_ASSET_FEE].freeze+ # Conversions between two of the profile's own balances. Wise credits the+ # primary amount to one balance and debits the secondary from another, with+ # no markup, so they have no single direction.+ TWO_LEG_TYPES = %w[INTERBALANCE AUTO_CONVERSION].freeze++ # Money one balance paid or received that, without balance statements,+ # only the activity feed reports: card payments and their refunds, cash+ # withdrawals, direct debits, cashback and rewards, adjustments, card+ # acquiring, and the card and account-details order fees.+ SINGLE_LEG_TYPES = %w[+ CARD_PAYMENT CASH_WITHDRAWAL DIRECT_DEBIT_TRANSACTION CARD_CASHBACK REWARD+ BALANCE_ADJUSTMENT ACQUIRING_PAYMENT CARD_ORDER BANK_DETAILS_ORDER+ ].freeze++ # The activity of a transfer. For a /v1/transfers transfer it only enriches+ # that transfer; a credit for a transfer Sure does not have (a bank payment+ # into the account details, money from another Wise profile) is booked like+ # a single-leg activity (see WiseItem::Importer#activity_route).+ TRANSFER_TYPES = %w[TRANSFER BALANCE_DEPOSIT].freeze++ # Interest, cashback and fees on what a balance holds, which belong to a+ # jar or an invested balance in their currency.+ HOLDING_TYPES = %w[BALANCE_INTEREST BALANCE_CASHBACK BALANCE_ASSET_FEE BALANCE_HOLD_FEE].freeze++ # Types that only ever pay money in: an unmarked amount is still a credit.+ CREDIT_ONLY_TYPES = %w[REWARD CARD_CASHBACK BALANCE_INTEREST BALANCE_CASHBACK].freeze++ # Only a completed activity moved money. Wise also lists IN_PROGRESS (a card+ # hold), UPCOMING, REQUIRES_ATTENTION and CANCELLED (a declined payment)+ # ones; they are stored so a later status is seen, but book nothing.+ BOOKED_STATUS = "COMPLETED"++ # At least one digit, so the comma in a split-funding list such as+ # "GBP, EUR" is not read as an amount of 0.+ AMOUNT_PATTERN = /\d[\d,]*(?:\.\d+)?/+ CURRENCY_PATTERN = /\b[A-Z]{3}\b/++ # Splits a Wise amount string like "<positive>+ 1,000.50 EUR</positive>"+ # into [BigDecimal value, currency code]. Either part is nil when absent.+ def self.parse_money(str)+ parse_amount(str).values_at(:value, :currency)+ end++ # INTERBALANCE covers both Jar moves and currency conversions between the+ # profile's own balances; AUTO_CONVERSION is a conversion Wise made on its+ # own. For a conversion Wise reports the target amount as primaryAmount and+ # the source amount as secondaryAmount, so the two currencies differ.+ def self.conversion_currencies(activity)+ return nil unless TWO_LEG_TYPES.include?(activity["type"].to_s)++ target = parse_money(activity["primaryAmount"]).last+ source = parse_money(activity["secondaryAmount"]).last+ return nil if source.blank? || target.blank? || source == target++ { source: source, target: target }+ end++ # Reads a Wise amount string. The value is unsigned; Wise marks direction+ # with markup instead: a top-up is "<positive>+ 2,465 GBP</positive>" and a+ # card refund "<positive>+ 0.64 EUR</positive>", while debits are usually+ # unmarked ("1,618.42 USD"). A card payment split across balances lists+ # only their currencies ("GBP, EUR"), with no amount.+ #+ # parse_amount("<positive>+ 2,465 GBP</positive>")+ # # => { value: 2465, currency: "GBP", currencies: ["GBP"], marked: :positive, sign: 1 }+ # parse_amount("GBP, EUR")+ # # => { value: nil, currency: "GBP", currencies: ["GBP", "EUR"], marked: nil, sign: nil }+ def self.parse_amount(str)+ raw = str.to_s+ text = ActionController::Base.helpers.strip_tags(raw).strip+ currencies = text.scan(CURRENCY_PATTERN).uniq+ marked =+ if raw.match?(/<positive>/i) then :positive+ elsif raw.match?(/<negative>/i) then :negative+ elsif text.start_with?("+") then :positive+ elsif text.start_with?("-") then :negative+ end++ {+ value: text[AMOUNT_PATTERN]&.delete(",")&.to_d,+ currency: currencies.first,+ currencies: currencies,+ marked: marked,+ sign: { positive: 1, negative: -1 }[marked]+ }+ end++ # :credit or :debit for a single-leg activity, nil for a conversion (see+ # TWO_LEG_TYPES). The type alone cannot tell: a CARD_PAYMENT can be a+ # refund and a TRANSFER a top-up, so a positive mark on either amount makes+ # a credit, and only the credit-only types are credits without one.+ def self.direction(activity)+ type = activity["type"].to_s+ return nil if TWO_LEG_TYPES.include?(type)++ marks = [ activity["primaryAmount"], activity["secondaryAmount"] ].map { |str| parse_amount(str)[:marked] }+ return :credit if marks.include?(:positive)+ return :debit if marks.include?(:negative)++ CREDIT_ONLY_TYPES.include?(type) ? :credit : :debit+ end++ # A debit Wise drew from several balances without saying how much from+ # each: its secondary lists the currencies but has no amount.+ def self.split?(activity)+ direction(activity) == :debit && split_funding?(parse_amount(activity["secondaryAmount"]))+ end++ # What a single-leg activity moved on the balance it touched, unsigned,+ # with its direction. Wise puts the amount it credited in primaryAmount.+ # For a debit the primary is what the merchant or recipient received and+ # the secondary, when it has an amount, is what left the balance: the gross+ # including fees, or the paying balance's side of an auto-conversion.+ # A split debit (see .split?) returns the primary, in the merchant's+ # currency, with the funding currencies it lists. nil for conversions.+ #+ # balance_amount("type" => "CARD_PAYMENT", "primaryAmount" => "7.40 EUR", "secondaryAmount" => "6.42 GBP")+ # # => { value: 6.42, currency: "GBP", direction: :debit, split: false, currencies: ["GBP"] }+ def self.balance_amount(activity)+ direction = direction(activity)+ return nil unless direction++ primary = parse_amount(activity["primaryAmount"])+ secondary = parse_amount(activity["secondaryAmount"])+ split = direction == :debit && split_funding?(secondary)+ booked = (direction == :debit && secondary[:value]) ? secondary : primary++ {+ value: booked[:value],+ currency: booked[:currency],+ direction: direction,+ split: split,+ currencies: split ? secondary[:currencies] : [ booked[:currency] ].compact+ }+ end++ # A stored activity row, as opposed to a /v1/transfers or a statement row.+ def self.activity_row?(row)+ row["wise_statement"].blank? && row["createdOn"].present? && row["resource"].present?+ end++ # createdOn is a UTC ISO-8601 timestamp ("2026-09-16T22:41:38.553Z").+ # Order activities by this instant; book them on its family-zone date.+ def self.created_at(activity)+ raw = activity["createdOn"]+ ActiveSupport::TimeZone["UTC"].parse(raw.to_s) if raw.present?+ end++ # A Wise title such as "<strong>Tom & Jerry</strong>" as plain text+ # ("Tom & Jerry"): strip_tags alone leaves the entities escaped.+ def self.plain_text(html)+ CGI.unescapeHTML(ActionController::Base.helpers.strip_tags(html.to_s)).strip+ end++ # The balance a title names, as plain text: its last <strong>, e.g.+ # "Holiday" in "To <strong>Holiday</strong>"; nil without one.+ def self.named_balance(activity)+ named = activity["title"].to_s.scan(%r{<strong>([^<]*)</strong>}i).flatten.last+ plain_text(named).presence if named+ end++ # Whether a move between a balance and a jar in one currency went into+ # the jar, which only its title tells. Wise names where the money went+ # ("To <strong>Holiday</strong>", as "To <strong>EUR</strong>" on every+ # conversion), so a title naming the currency, that is the balance, or+ # the jar the money came from ("From <strong>Holiday</strong>") is a+ # withdrawal. A title naming no balance leaves only its wording.+ def self.jar_deposit?(activity)+ title = activity["title"].to_s+ named = named_balance(activity)+ unless named+ text = plain_text(title).downcase+ return text.start_with?("to") || text.include?("received") || text.include?("added")+ end++ currency = parse_amount(activity["primaryAmount"])[:currency]+ return false if currency.present? && named.casecmp?(currency)++ !plain_text(title[0...title.rindex(/<strong>/i)]).match?(/\bfrom\b/i)+ end++ def self.split_funding?(parsed)+ parsed[:value].nil? && parsed[:currencies].size >= 2+ end+ private_class_method :split_funding?def initialize(activity, wise_account:)@activity = activity.with_indifferent_access@@ -14,14 +198,21 @@ class WiseActivity::Processorreturn :skippedend- import_adapter.import_transaction(+ if skip_reason+ Rails.logger.debug "WiseActivity::Processor - Skipping activity #{safe_id} on wise_account #{wise_account.id}: #{skip_reason}"+ return :skipped+ end++ import_entry(external_id: external_id,amount: amount,currency: currency,date: date,name: name,source: "wise",- extra: extra+ extra: extra,+ # extra[:wise] is the full snapshot, so a flag Wise stops reporting clears.+ replace_extra_namespaces: [ "wise" ])rescue ArgumentError => eRails.logger.error "WiseActivity::Processor - Validation error for activity #{safe_id}: #{e.message}"@@ -31,6 +222,42 @@ class WiseActivity::Processorraiseend+ # The external ids of the entries processing this activity keeps on its+ # balance: none when it books nothing there (not completed, another+ # balance's share of a split payment, or carried by a statement row now),+ # so an entry it booked earlier is stale.+ def expected_external_ids+ skip_reason ? [] : [ external_id ]+ end++ # What the activity books on this balance, { external_id:, amount:,+ # currency: } with Sure's sign (positive = money out), or nil when it+ # books nothing here. Needs no linked account.+ def booking+ { external_id: external_id, amount: amount, currency: currency } unless skip_reason+ end++ # Sure used to name a jar's leg of a move "_inflow" and a balance's+ # "_outflow" whichever way the money went, the leg of a conversion on its+ # target balance included. Its side now follows the money, so the entry+ # booked the old way is renamed in place (WiseAccount::Transactions+ # ::Processor#take_over_entries), keeping what a person did to it:+ # { old external id => external id }.+ def superseded_external_ids+ return {} unless two_leg? && skip_reason.nil? && (wise_account.jar? || conversion.nil? || conversion_target?)++ other_side = leg_direction == :credit ? "outflow" : "inflow"+ { "wise_interbalance_#{resource_id}_#{other_side}" => external_id }+ end++ # The day the activity books on, whether it books here or not; nil when+ # it has no readable date.+ def booking_date+ date if account.present?+ rescue ArgumentError+ nil+ end+privateattr_reader :activity, :wise_account@@ -39,21 +266,96 @@ class WiseActivity::Processor@import_adapter ||= Account::ProviderImportAdapter.new(account)end+ # Imports through the adapter; Wise's amount also reaches an entry a+ # person acted on (WiseItem::AmountCorrection).+ def import_entry(**attributes)+ entry = import_adapter.import_transaction(**attributes)+ WiseItem::AmountCorrection.apply(entry, amount: attributes[:amount], currency: attributes[:currency])+ end+def account@account ||= wise_account.current_accountend- # INTERBALANCE uses resource_id so both sides can be matched for Transfer linking.- # Other activity types use the opaque activity id.+ # Why the activity books nothing on this balance, or nil when it books.+ # A statement row that carries its movement books it instead+ # ("wise_superseded_by", see WiseItem::StatementMigration).+ def skip_reason+ return @skip_reason if defined?(@skip_reason)++ @skip_reason =+ if activity[:wise_superseded_by].present?+ :superseded+ elsif !routed_here?+ :other_balance+ elsif activity[:status].to_s != BOOKED_STATUS+ :status+ elsif split? && split_amount.nil?+ :split_paid_elsewhere+ end+ end++ # Whether the row is this balance's at all. Processing books what a+ # payload holds, also one an older build stored, which put every+ # conversion and jar move on every balance and interest on every jar:+ # after an import that fails before it stores the payloads again, or for+ # a balance linked while a sync still fetches. So a move between+ # currencies the balance is not in books nothing here, nor a jar move or+ # interest the importer routed to another balance (its routing decision,+ # WiseItem::Importer::ROUTING_DECISION_KEY), nor a payment none of whose+ # currencies is the balance's.+ def routed_here?+ decided = activity[WiseItem::Importer::ROUTING_DECISION_KEY].presence&.to_s+ balance_id = wise_account.balance_id.to_s+ if two_leg? && conversion+ conversion.values.include?(wise_account.currency) &&+ (decided.nil? || (wise_account.jar? ? decided == balance_id : wise_account.currency != jar_side))+ elsif two_leg?+ currency = self.class.parse_amount(activity[:primaryAmount])[:currency]+ (currency.blank? || currency == wise_account.currency) && (!wise_account.jar? || decided.nil? || decided == balance_id)+ elsif HOLDING_TYPES.include?(activity_type) && decided+ decided == balance_id+ else+ single_leg[:currencies].include?(wise_account.currency)+ end+ end++ # The currency of a jar move's jar side: a deposit credits the jar in the+ # target currency, a withdrawal debits it in the source one.+ def jar_side+ self.class.jar_deposit?(activity) ? conversion[:target] : conversion[:source]+ end++ # Conversions use resource_id so both sides can be matched for Transfer+ # linking; the leg the money went to is the inflow. Other activity types+ # use the opaque activity id.def external_id- if activity_type == "INTERBALANCE"- side = wise_account.jar? ? "inflow" : "outflow"+ if two_leg?+ side = leg_direction == :credit ? "inflow" : "outflow""wise_interbalance_#{resource_id}_#{side}"else"wise_activity_#{activity[:id]}"endend+ # This balance's leg of a move between two of the profile's balances:+ # :credit when the money came in, else :debit. A conversion debits the+ # balance in its source currency and credits the one in its target+ # currency, a jar's included; a move between a balance and a jar in one+ # currency goes the way its title says (.jar_deposit?).+ def leg_direction+ @leg_direction ||=+ if conversion_source? then :debit+ elsif conversion_target? then :credit+ elsif wise_account.jar? == self.class.jar_deposit?(activity) then :credit+ else :debit+ end+ end++ def two_leg?+ TWO_LEG_TYPES.include?(activity_type)+ end+def safe_idactivity[:id].presence || "unknown"end@@ -66,91 +368,170 @@ class WiseActivity::Processoractivity.dig(:resource, :id).to_send+ def conversion+ return @conversion if defined?(@conversion)++ @conversion = self.class.conversion_currencies(activity)+ end++ def conversion_source?+ conversion.present? && conversion[:source] == wise_account.currency+ end++ def conversion_target?+ conversion.present? && conversion[:target] == wise_account.currency+ end+# Expenses (outflow) → positive in Sure.# Incomes (inflow / interest) → negative in Sure.+ # A conversion's source pays its secondary amount, every other leg moves+ # the primary one.def amount- raw = parse_amount- case activity_type- when "BALANCE_ASSET_FEE"- raw.abs # fee = outflow = positive (expense)- when "INTERBALANCE"- if wise_account.jar?- # JAR perspective: "To Jar" = deposit (income, negative)- deposit_direction? ? -raw.abs : raw.abs- else- # STANDARD perspective: "To Jar" = outflow (expense, positive)- deposit_direction? ? raw.abs : -raw.abs+ return single_leg_amount unless two_leg?++ value = amount_value(conversion_source? ? activity[:secondaryAmount] : activity[:primaryAmount])+ leg_direction == :credit ? -value : value+ end++ # The sign comes from Wise's markup (see .direction), not from the type.+ def single_leg_amount+ value = split? ? split_amount : (single_leg[:value] || 0.to_d)+ single_leg[:direction] == :credit ? -value : value+ end++ def single_leg+ @single_leg ||= self.class.balance_amount(activity) ||+ raise(ArgumentError, "Wise activity #{safe_id} (#{activity_type}) moves money between two balances")+ end++ # A debit Wise drew from several balances (see .split?). The importer+ # stores it on each of them.+ def split?+ !two_leg? && single_leg[:split]+ end++ # This balance's share of a split debit: the part the balance replay+ # worked out ("wise_split_parts", { currency => decimal string }), or+ # without one the whole merchant amount on one balance the payment lists+ # (#unresolved_split_currency), a documented limitation for items+ # without a replay. nil when this balance books nothing.+ def split_amount+ return @split_amount if defined?(@split_amount)++ @split_amount =+ if split_parts+ part = split_parts[wise_account.currency].presence&.to_d+ part if part&.positive?+ elsif unresolved_split_currency == wise_account.currency+ single_leg[:value]end- else- -raw.abs # BALANCE_CASHBACK / interest → income (negative)- endend- # True when the activity title indicates money flowing INTO the JAR.- def deposit_direction?- title = strip_html(activity[:title]).downcase- title.start_with?("to") || title.include?("received") || title.include?("added")+ # The balance a split debit without parts books in full on, in the+ # merchant's currency: the merchant-currency one, or the first Wise+ # lists when it drew on no balance in that currency (a payment in a+ # currency the profile does not hold).+ def unresolved_split_currency+ listed = single_leg[:currencies]+ listed.include?(single_leg[:currency]) ? single_leg[:currency] : listed.first+ end++ def split_parts+ parts = activity[:wise_split_parts]+ parts if parts.is_a?(Hash) && parts.present?+ end++ # The balance replay marks a part estimated ("wise_split_estimated", the+ # list of currencies whose parts it estimated, or true for all of them).+ def split_estimated?+ estimated = activity[:wise_split_estimated]+ estimated == true || (estimated.is_a?(Array) && estimated.include?(wise_account.currency))enddef currency- parse_currency || wise_account.currency+ return conversion[:source] if conversion_source?+ return conversion[:target] if conversion_target?+ # A split part is in the currency of the balance that paid it; the+ # whole payment, without parts, in the merchant's.+ return split_parts ? wise_account.currency : single_leg[:currency] if split?+ return single_leg[:currency] || wise_account.currency unless two_leg?++ self.class.parse_amount(activity[:primaryAmount])[:currency] || wise_account.currencyenddef name- jar_name = wise_account.jar? ? (wise_account.raw_payload&.dig("name") || "Jar") : nil-case activity_type- when "INTERBALANCE"+ when *TWO_LEG_TYPESif wise_account.jar?- deposit_direction? ? I18n.t("wise_items.activities.jar_deposit") : I18n.t("wise_items.activities.jar_withdrawal")+ leg_direction == :credit ? I18n.t("wise_items.activities.jar_deposit") : I18n.t("wise_items.activities.jar_withdrawal")+ elsif conversion_source?+ I18n.t("wise_items.activities.transfer_to_jar", jar: conversion[:target])+ elsif conversion_target?+ I18n.t("wise_items.activities.transfer_from_jar", jar: conversion[:source])+ elsif leg_direction == :debit+ I18n.t("wise_items.activities.transfer_to_jar", jar: jar_name_for_standard)+ elsif names_currency?+ # A withdrawal titled with the balance's own currency names no jar.+ I18n.t("wise_items.activities.jar_withdrawal")else- deposit_direction? ? I18n.t("wise_items.activities.transfer_to_jar", jar: jar_name_for_standard) : I18n.t("wise_items.activities.transfer_from_jar", jar: jar_name_for_standard)+ I18n.t("wise_items.activities.transfer_from_jar", jar: jar_name_for_standard)end- when "BALANCE_CASHBACK"+ when "BALANCE_CASHBACK", "BALANCE_INTEREST"I18n.t("wise_items.activities.interest")when "BALANCE_ASSET_FEE"I18n.t("wise_items.activities.asset_fee")else- strip_html(activity[:title]).strip.presence ||+ self.class.plain_text(activity[:title]).presence ||I18n.t("wise_items.activities.default_name")endenddef jar_name_for_standard- activity[:title].to_s.scan(/<strong>([^<]+)<\/strong>/).flatten.last || "Jar"+ self.class.named_balance(activity) || "Jar"end+ def names_currency?+ named = self.class.named_balance(activity)+ named.present? && named.casecmp?(currency.to_s)+ end++ # The date in the family's zone (WiseItem#time_zone), as for transfers+ # and statement rows: 23:52 UTC on 11 August is 12 August in Dublin (IST).def dateraw = activity[:createdOn].presenceraise ArgumentError, "Activity missing createdOn" unless raw- DateTime.parse(raw).to_date++ created_at = self.class.created_at(activity)+ raise ArgumentError, "Unable to parse createdOn #{raw.inspect}" unless created_at++ created_at.in_time_zone(wise_account.wise_item.time_zone).to_dateend+ # The full wise namespace on every import (flags clear when false).def extra+ split = split?+{wise: {activity_id: activity[:id],activity_type: activity_type,resource_type: activity.dig(:resource, :type),- resource_id: resource_id.presence+ resource_id: resource_id.presence,+ description: activity[:description].presence,+ primary_amount: activity[:primaryAmount].presence,+ secondary_amount: activity[:secondaryAmount].presence,+ split_part: (true if split && split_parts),+ split_estimated: (true if split && split_parts && split_estimated?),+ split_unresolved: (true if split && !split_parts)}.compact}end- # Parses the numeric amount from strings like:+ # The unsigned amount in strings like:# "1,000 EUR" → 1000.0# "<positive>+ 1.12 EUR</positive>" → 1.12# "0.83 EUR" → 0.83- def parse_amount- stripped = strip_html(activity[:primaryAmount]).strip- stripped.scan(/[\d,]+\.?\d*/).first.to_s.delete(",").to_d- end-- def parse_currency- activity[:primaryAmount].to_s.scan(/\b[A-Z]{3}\b/).first- end-- def strip_html(str)- ActionController::Base.helpers.strip_tags(str.to_s)+ def amount_value(raw)+ self.class.parse_amount(raw)[:value] || 0.to_dendenddiff --git a/app/models/wise_entry/processor.rb b/app/models/wise_entry/processor.rbindex 8f1bb86d6b..9156c272b4 100644--- a/app/models/wise_entry/processor.rb+++ b/app/models/wise_entry/processor.rb@@ -1,21 +1,185 @@# frozen_string_literal: trueclass WiseEntry::Processor- # Statuses Wise uses for outgoing transfers (money leaves the Wise balance).- OUTGOING_STATUSES = %w[- processing funds_converted outgoing_payment_sent- bounced_back funds_refunded+ # What a transfer's status means for the balance it books on. Once Wise has+ # funded a payout from the balance, the balance stays debited while Wise+ # processes, converts, sends, waits for the recipient or holds a bounced+ # payout. A pay-in reaches the balance only once Wise has sent it. Nothing+ # else books: incoming_payment_* (not funded yet), cancelled (never+ # funded), charged_back (returned to the payer) and unknown. A refunded+ # payout books only together with its refund credit.+ OUTGOING_BOOKED_STATUSES = %w[+ outgoing_payment_sent processing funds_converted bounced_back waiting_recipient_input_to_proceed].freeze+ INCOMING_BOOKED_STATUSES = %w[outgoing_payment_sent].freeze+ REFUNDED_STATUS = "funds_refunded"- # Statuses Wise uses for incoming transfers (money arrives in the Wise balance).- INCOMING_STATUSES = %w[- incoming_payment_waiting incoming_payment_received- funds_credited credited+ # The statuses Wise documents with a meaning Sure acts on. Any other status,+ # Wise's own "unknown" included, books nothing and is reported.+ KNOWN_STATUSES = %w[+ incoming_payment_waiting incoming_payment_initiated processing funds_converted outgoing_payment_sent+ cancelled funds_refunded bounced_back charged_back waiting_recipient_input_to_proceed].freeze- def initialize(wise_transaction, wise_account:)+ # Below half a cent, a gap between the gross debit and sourceValue is+ # rounding, not a fee.+ FEE_THRESHOLD = BigDecimal("0.005")++ # :incoming for a pay-in, a transfer into one of the profile's own+ # recipients (see WiseItem#own_recipient_ids); :outgoing for anything else.+ # Wise ends top-ups in outgoing_payment_sent like payouts, so the status+ # cannot tell them apart. Only when no recipient is known at all does the+ # transfer's activity decide: Wise marks a top-up "<positive>+ 2,465 GBP".+ def self.direction(transfer, own_recipient_ids:)+ ids = Array(own_recipient_ids).compact_blank.map(&:to_s)++ if ids.any?+ ids.include?(transfer["targetAccount"].to_s) ? :incoming : :outgoing+ elsif (activity = activity_of(transfer)) && WiseActivity::Processor.direction(activity) == :credit+ :incoming+ else+ :outgoing+ end+ end++ # How a transfer reaches a balance, or nil when it does not. A pay-in (see+ # .direction) reaches only the balance whose own account details it paid+ # into (:account_details; recipient_owners: WiseItem#balance_recipient_owners)+ # or, paid to the account recipient, the balance in its target currency;+ # any other transfer only the balance it was paid from (:currency).+ # Matching either currency would also book e.g. a GBP-funded payout to PLN+ # on the PLN balance, and Wise does not say whether a balance paid for a+ # pay-in ("send to myself"). A transfer without a currency reaches every+ # balance. The importer routes transfers by this, and a balance books only+ # the ones it reaches.+ def self.balance_route(transfer, wise_account, own_recipient_ids:, recipient_owners:)+ incoming = direction(transfer, own_recipient_ids: own_recipient_ids) == :incoming+ owners = recipient_owners[transfer["targetAccount"].to_s] if incoming+ return (:account_details if owners.include?(wise_account.id)) if owners++ currency = incoming ? transfer["targetCurrency"] : transfer["sourceCurrency"]+ :currency if currency.blank? || currency == wise_account.currency+ end++ # Why a transfer books nothing on its balance, or nil when it books. The+ # balance replay marks a payout Wise took from a card or bank instead of+ # the balance as externally funded ("wise_funding"); a statement row that+ # carries the transfer's movement books it instead ("wise_superseded_by",+ # see WiseItem::StatementMigration).+ def self.skip_reason(transfer, direction:)+ return :superseded if transfer["wise_superseded_by"].present?+ return :external_funding if transfer["wise_funding"] == "external"+ return :activity_cancelled if activity_of(transfer)&.dig("status") == "CANCELLED"++ status = transfer["status"].to_s+ if direction == :incoming+ :status unless INCOMING_BOOKED_STATUSES.include?(status)+ elsif status == REFUNDED_STATUS+ :refunded_without_credit unless refund(transfer)+ else+ :status unless OUTGOING_BOOKED_STATUSES.include?(status)+ end+ end++ def self.unknown_status?(transfer)+ KNOWN_STATUSES.exclude?(transfer["status"].to_s)+ end++ # What Wise took from the balance for an outgoing transfer, in its source+ # currency. sourceValue excludes the fee, but the transfer's activity shows+ # the gross debit: as its secondary amount, or as the primary when there+ # was neither a fee nor a conversion. nil without such an amount.+ def self.gross_debit(transfer)+ activity = activity_of(transfer)+ currency = transfer["sourceCurrency"].presence+ return nil unless activity && currency++ [ activity["secondaryAmount"], activity["primaryAmount"] ].each do |raw|+ amount = WiseActivity::Processor.parse_amount(raw)+ return amount[:value] if amount[:value] && amount[:currency] == currency+ end+ nil+ end++ # The fee Wise charged an outgoing transfer on top of sourceValue: the+ # gross debit minus sourceValue, or, without the transfer's activity, the+ # same-currency gap between sourceValue and targetValue. Pay-ins carry no+ # fee for the balance they land in.+ def self.fee(transfer)+ gross = gross_debit(transfer)+ fee =+ if gross+ gross - transfer["sourceValue"].to_d+ elsif transfer["sourceCurrency"] == transfer["targetCurrency"]+ transfer["sourceValue"].to_d - transfer["targetValue"].to_d+ else+ 0.to_d+ end+ fee = fee.round(4)+ fee > FEE_THRESHOLD ? fee : 0.to_d+ end++ # The money a refunded payout brought back: the credit Wise shows for it+ # (attached as "wise_refund_activity"), as { value:, currency:,+ # created_at: }, or nil when none is known. Wise may refund less than it+ # took, so the refund books on its own next to the debit.+ def self.refund(transfer)+ activity = transfer["wise_refund_activity"]+ return nil unless activity.is_a?(Hash) && activity["status"] != "CANCELLED"++ amount = WiseActivity::Processor.parse_amount(activity["primaryAmount"])+ return nil unless amount[:value]&.positive?++ created_at = begin+ WiseActivity::Processor.created_at(activity)+ rescue ArgumentError+ nil+ end+ { value: amount[:value], currency: amount[:currency], created_at: created_at }+ end++ # The activity Wise shows for a transfer, as the importer attaches it to+ # the transfer row ("wise_activity", or "wise_refund_activity" for a+ # refund credit): amounts keep Wise's markup, the title is plain text.+ def self.activity_snapshot(activity)+ {+ "id" => activity["id"],+ "type" => activity["type"],+ "status" => activity["status"],+ "primaryAmount" => activity["primaryAmount"],+ "secondaryAmount" => activity["secondaryAmount"],+ "title" => WiseActivity::Processor.plain_text(activity["title"]).presence,+ "description" => activity["description"],+ "createdOn" => activity["createdOn"],+ "updatedOn" => activity["updatedOn"]+ }.compact+ end++ def self.activity_of(transfer)+ activity = transfer["wise_activity"]+ activity if activity.is_a?(Hash)+ end+ private_class_method :activity_of++ # Wise reports `created` in UTC without a zone designator+ # ("2025-03-27 18:04:33"), so it is parsed as UTC rather than in the+ # server's zone. Order transfers by this instant; book them on its+ # family-zone date.+ def self.created_at(transfer)+ raw = transfer["created"]+ case raw+ when String then ActiveSupport::TimeZone["UTC"].parse(raw) if raw.present?+ when Time, Date then raw.in_time_zone("UTC")+ end+ end++ # own_recipient_ids, recipient_owners: WiseItem#own_recipient_ids and+ # #balance_recipient_owners, looked up when not given.+ def initialize(wise_transaction, wise_account:, own_recipient_ids: nil, recipient_owners: nil)@wise_transaction = wise_transaction@wise_account = wise_account+ @own_recipient_ids = own_recipient_ids+ @recipient_owners = recipient_ownersenddef process@@ -24,6 +188,11 @@ class WiseEntry::Processorreturn :skippedend+ if skip_reason+ Rails.logger.debug "WiseEntry::Processor - Skipping transfer #{safe_id}: #{skip_reason}"+ return :skipped+ end+result = import_main_transactionif fee > 0@@ -34,6 +203,8 @@ class WiseEntry::Processorendend+ import_refund_transaction if refund+resultrescue ArgumentError => eRails.logger.error "WiseEntry::Processor - Validation error for transfer #{safe_id}: #{e.message}"@@ -43,6 +214,26 @@ class WiseEntry::Processorraiseend+ # The external ids of the entries processing this transfer keeps on its+ # balance: none when it books nothing, so an entry it booked earlier (a+ # payout Wise has since cancelled) is stale.+ def expected_external_ids+ return [] if skip_reason++ ids = [ "wise_transfer_#{transfer_id}" ]+ ids << "wise_fee_#{transfer_id}" if fee.positive?+ ids << "wise_refund_#{transfer_id}" if refund+ ids+ end++ # The day the transfer books on, whether it books or not; nil when it has+ # no readable date.+ def booking_date+ date+ rescue ArgumentError+ nil+ end+privateattr_reader :wise_transaction, :wise_account@@ -55,31 +246,79 @@ class WiseEntry::Processor@import_adapter ||= Account::ProviderImportAdapter.new(account)end+ # Imports through the adapter; Wise's amount also reaches an entry a+ # person acted on (WiseItem::AmountCorrection).+ def import_entry(**attributes)+ entry = import_adapter.import_transaction(**attributes)+ WiseItem::AmountCorrection.apply(entry, amount: attributes[:amount], currency: attributes[:currency])+ end+def account@account ||= wise_account.current_accountend+ def own_recipient_ids+ @own_recipient_ids ||= wise_account.wise_item.own_recipient_ids+ end++ def recipient_owners+ @recipient_owners ||= wise_account.wise_item.balance_recipient_owners+ end++ # A row stored on a balance it does not reach (.balance_route) books+ # nothing there: e.g. the funding side of a pay-in, which an older build+ # stored and which stays in the payload when an import fails before it+ # stores the payloads again.+ def skip_reason+ return @skip_reason if defined?(@skip_reason)++ @skip_reason = (:other_balance unless routed_here?) || self.class.skip_reason(data, direction: direction)+ end++ def routed_here?+ self.class.balance_route(data, wise_account, own_recipient_ids: own_recipient_ids, recipient_owners: recipient_owners).present?+ end+def import_main_transaction- import_adapter.import_transaction(+ import_entry(external_id: "wise_transfer_#{transfer_id}",amount: main_amount,- currency: source_currency,+ currency: outgoing? ? source_currency : target_currency,date: date,name: name,source: "wise",- extra: extra+ extra: extra,+ # extra[:wise] is the full snapshot, so a flag Wise stops reporting+ # clears; the top-level exchange_rate is still merged.+ replace_extra_namespaces: [ "wise" ])enddef import_fee_transaction- import_adapter.import_transaction(+ import_entry(external_id: "wise_fee_#{transfer_id}",amount: fee,currency: source_currency,date: date,name: I18n.t("wise_items.entries.fee_name"),source: "wise",- extra: { wise: { transfer_id: transfer_id, type: "FEE" } }+ extra: { wise: { transfer_id: transfer_id, type: "FEE" } },+ replace_extra_namespaces: [ "wise" ]+ )+ end++ # The debit and its fee stay booked, so a partial refund nets to what+ # Wise kept.+ def import_refund_transaction+ import_entry(+ external_id: "wise_refund_#{transfer_id}",+ amount: -refund[:value],+ currency: refund[:currency] || source_currency,+ date: refund[:created_at]&.in_time_zone(time_zone)&.to_date || date,+ name: I18n.t("wise_items.entries.refund_name"),+ source: "wise",+ extra: { wise: { transfer_id: transfer_id, type: "REFUND", activity_id: data.dig(:wise_refund_activity, :id) }.compact },+ replace_extra_namespaces: [ "wise" ])end@@ -91,9 +330,12 @@ class WiseEntry::Processordata[:id].presence || "unknown"end+ # The payment reference, else the counterparty Wise names in the+ # transfer's activity ("To GBP" for a top-up).def name- ref = data.dig(:details, :reference).presence || data[:reference].presence- ref.present? ? ref : I18n.t("wise_items.entries.default_name")+ data.dig(:details, :reference).presence || data[:reference].presence ||+ data.dig(:wise_activity, :title).to_s.strip.presence ||+ I18n.t("wise_items.entries.default_name")end# Expenses (outgoing) → positive amount in Sure convention.@@ -107,15 +349,15 @@ class WiseEntry::Processorendend- # Fee is the difference between what was debited and what the recipient received,- # only applicable for same-currency transfers.def fee- @fee ||= begin- return 0 unless source_currency == target_currency+ @fee ||= outgoing? ? self.class.fee(data) : 0.to_d+ end- diff = (data[:sourceValue].to_d - data[:targetValue].to_d).round(4)- diff > 0 ? diff : 0- end+ # Only a refunded payout books its refund.+ def refund+ return @refund if defined?(@refund)++ @refund = (self.class.refund(data) if outgoing? && data[:status] == REFUNDED_STATUS)enddef source_currency@@ -126,23 +368,17 @@ class WiseEntry::Processordata[:targetCurrency].presence || wise_account.currencyend- # An expense if targetAccount does NOT match our Wise recipientId- # (i.e. money went TO an external account, not to us).- # An income if targetAccount == recipientId (money arrived at our Wise account).- # Falls back to status-based detection when no recipientId is stored.- def outgoing?- recipient_id = wise_account.raw_payload&.dig("recipient_id")-- if recipient_id.present?- return data[:targetAccount].to_s != recipient_id.to_s- end+ def direction+ @direction ||= self.class.direction(data, own_recipient_ids: own_recipient_ids)+ end- # Status-based fallback- status = data[:status].to_s.downcase- return false if INCOMING_STATUSES.any? { |s| status.include?(s) }- return true if OUTGOING_STATUSES.any? { |s| status.include?(s) }+ def outgoing?+ direction == :outgoing+ end- true+ # The family's zone (WiseItem#time_zone).+ def time_zone+ wise_account.wise_item.time_zoneenddef date@@ -152,12 +388,15 @@ class WiseEntry::Processorcase rawwhen Stringif raw.include?("T") || raw.include?(":")- Time.parse(raw).in_time_zone(account&.family&.timezone).to_date+ created_at = self.class.created_at(data)+ raise ArgumentError, "Unable to parse date #{raw.inspect}" unless created_at++ created_at.in_time_zone(time_zone).to_dateelseDate.parse(raw)endwhen Time, DateTime- raw.in_time_zone(account&.family&.timezone).to_date+ raw.in_time_zone(time_zone).to_datewhen Date then rawelse raise ArgumentError, "Invalid date format: #{raw.inspect}"end@@ -180,7 +419,8 @@ class WiseEntry::Processortarget_value: data[:targetValue],rate: data[:rate],fee: fee > 0 ? fee : nil,- reference: data.dig(:details, :reference).presence || data[:reference]+ reference: data.dig(:details, :reference).presence || data[:reference],+ activity_id: data.dig(:wise_activity, :id)}.compact}.compactenddiff --git a/app/models/wise_item.rb b/app/models/wise_item.rbindex 73c9eab5d0..34ac6105b6 100644--- a/app/models/wise_item.rb+++ b/app/models/wise_item.rb@@ -5,6 +5,16 @@ class WiseItem < ApplicationRecordSCA_PRIVATE_KEY_ATTRIBUTE = "sca_private_key"+ # Raised whenever a build starts storing rows an earlier build dropped or+ # routing stored rows to other balances: coverage an older build recorded+ # claims rows it did not keep, so every install then fetches its whole+ # history once more (WiseItem::Importer#window_start).+ COVERAGE_VERSION = 1++ # How often a family zone tzdata does not know is reported (#time_zone):+ # every balance's processing asks for it on every sync.+ UNKNOWN_TIME_ZONE_LOG_INTERVAL = 1.day+# Raised rather than returned so no caller can mistake "not stored" for# "stored"; the controller turns it into the same panel error as any other# keypair failure.@@ -55,13 +65,16 @@ class WiseItem < ApplicationRecordraiseend- def process_accounts+ # import_complete: whether this sync's import fetched every source in full+ # (see WiseItem::Importer#import). Steps that delete or rewrite entries+ # only run when it is true.+ def process_accounts(import_complete: false)return [] if wise_accounts.empty?results = []wise_accounts.joins(:account).merge(Account.visible).each do |wise_account|begin- result = WiseAccount::Processor.new(wise_account).process+ result = WiseAccount::Processor.new(wise_account, import_complete: import_complete).processresults << { wise_account_id: wise_account.id, success: true, result: result }rescue => eRails.logger.error "WiseItem #{id} - Failed to process account #{wise_account.id}: #{e.message}"@@ -72,35 +85,10 @@ class WiseItem < ApplicationRecordresultsend- # Finds interbalance entry pairs (JAR inflow ↔ STANDARD outflow) and links them as Transfers.+ # Links each conversion and Jar move between this item's balances as a+ # confirmed Transfer with transfer kinds (see WiseItem::InterbalanceLinker).def link_jar_transfers!- account_ids = accounts.pluck(:id)- return if account_ids.empty?-- inflow_entries = Entry.where(source: "wise", account_id: account_ids)- .where("external_id LIKE 'wise_interbalance_%_inflow'")-- inflow_entries.each do |inflow_entry|- resource_id = inflow_entry.external_id.sub("wise_interbalance_", "").sub("_inflow", "")- outflow_entry = Entry.where(source: "wise", account_id: account_ids,- external_id: "wise_interbalance_#{resource_id}_outflow").first-- next unless outflow_entry- next unless inflow_entry.entryable.is_a?(Transaction) && outflow_entry.entryable.is_a?(Transaction)-- inflow_txn = inflow_entry.entryable- outflow_txn = outflow_entry.entryable-- next if Transfer.exists?(inflow_transaction_id: inflow_txn.id)- next if Transfer.exists?(outflow_transaction_id: outflow_txn.id)-- transfer = Transfer.new(inflow_transaction: inflow_txn, outflow_transaction: outflow_txn, status: "confirmed")- unless transfer.save- Rails.logger.warn "WiseItem #{id} - Could not link interbalance #{resource_id}: #{transfer.errors.full_messages.join(", ")}"- end- rescue => e- Rails.logger.error "WiseItem #{id} - Error linking interbalance #{resource_id}: #{e.message}"- end+ WiseItem::InterbalanceLinker.new(self).link!enddef schedule_account_syncs(parent_sync: nil, window_start_date: nil, window_end_date: nil)@@ -124,10 +112,87 @@ class WiseItem < ApplicationRecordresultsend+ # For a balance the user has just linked to a Sure account. A sync in flight+ # picked the accounts it processes before the link existed, and sync_later+ # would only reuse it, so the balance then gets processing of its own.+ def sync_linked_account_later(wise_account)+ if syncing?+ WiseItem::ProcessLinkedAccountJob.perform_later(wise_account)+ else+ sync_later+ end+ end+def has_completed_initial_setup?accounts.any?end+ # Sure's own sync bookkeeping (fetch coverage, the multi-currency account)+ # lives in raw_payload, which Wise never fills.+ def sync_metadata+ raw_payload.is_a?(Hash) ? raw_payload : {}+ end++ def merge_sync_metadata!(attributes)+ update!(raw_payload: sync_metadata.merge(attributes.deep_stringify_keys))+ end++ # The window successful fetches of `source` (:transfers or :activities)+ # have covered without a gap, as { from:, through: } UTC times, or nil+ # before the first one and when an older build recorded it+ # (COVERAGE_VERSION). `through` is when the latest fetch started.+ def fetch_coverage(source)+ coverage = sync_metadata["coverage"]+ window = coverage[source.to_s] if coverage.is_a?(Hash)+ return nil unless window.is_a?(Hash) && window["version"].to_i >= COVERAGE_VERSION++ from, through = window.values_at("from", "through").map do |time|+ ActiveSupport::TimeZone["UTC"].parse(time.to_s) if time.present?+ end+ { from: from, through: through } if from && through+ rescue ArgumentError+ nil+ end++ # The zone Wise movements are dated in: the family's, or UTC when it has+ # none or one tzdata does not know. Family checks its zone only when it+ # changes, so one stored before that check (or one tzdata dropped later)+ # can stay; it is reported (#log_unknown_time_zone) rather than failing+ # every row.+ def time_zone+ @time_zone ||= begin+ requested = family&.timezone.presence+ ActiveSupport::TimeZone[requested || "UTC"] || begin+ log_unknown_time_zone(requested)+ ActiveSupport::TimeZone["UTC"]+ end+ end+ end++ # The profile's own recipients: the account recipient (the multi-currency+ # account's, kept on every balance as recipient_id) and each balance's own+ # account details (recipientId), closed balances included. A transfer into+ # one of them is a pay-in, not a payout (WiseEntry::Processor.direction).+ def own_recipient_ids+ multi_currency_account = sync_metadata["multi_currency_account"]+ ids = [ (multi_currency_account["recipientId"] if multi_currency_account.is_a?(Hash)) ]+ balance_snapshots.each do |wise_account|+ payload = wise_account.raw_payload+ ids.concat(payload.values_at("recipient_id", "recipientId")) if payload.is_a?(Hash)+ end+ ids.compact_blank.map(&:to_s).uniq+ end++ # Each balance's own account details (recipientId) => the ids of the+ # WiseAccounts holding them, closed balances included: a pay-in into them+ # reaches that balance only (WiseEntry::Processor.balance_route).+ def balance_recipient_owners+ balance_snapshots.each_with_object({}) do |wise_account, owners|+ recipient = wise_account.raw_payload["recipientId"] if wise_account.raw_payload.is_a?(Hash)+ (owners[recipient.to_s] ||= []) << wise_account.id if recipient.present?+ end+ end+def credentials_configured?token.to_s.strip.present?end@@ -203,10 +268,36 @@ class WiseItem < ApplicationRecordprivate+ # Every balance's id and snapshot, without its stored rows: those are the+ # whole history, and processing asks for the recipients once per balance.+ def balance_snapshots+ wise_accounts.select(:id, :raw_payload)+ end+def normalize_tokenself.token = token&.stripend+ # Once per interval for a family and value, the way Localize reports a+ # zone it cannot use (an atomic write that only one caller wins).+ def log_unknown_time_zone(requested)+ lease = Rails.cache.write([ "wise_unknown_family_timezone", family_id, requested ], true,+ expires_in: UNKNOWN_TIME_ZONE_LOG_INTERVAL, unless_exist: true)+ return unless lease++ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: "WiseItem - Unknown family time zone #{requested.inspect}; Wise movements are dated in UTC",+ source: self.class.name,+ provider_key: "wise",+ family: family,+ metadata: { wise_item_id: id, operation: "time_zone" }+ )+ rescue StandardError => e+ Rails.logger.warn "WiseItem - Failed to capture Wise debug log: #{e.message}"+ end+# Scoped to writes of the key itself. An install that generated a key# before this validation existed still has that value in the column, so# validating on every save would reject every later write to the record,diff --git a/app/models/wise_item/amount_correction.rb b/app/models/wise_item/amount_correction.rbnew file mode 100644index 0000000000..40a6339572--- /dev/null+++ b/app/models/wise_item/amount_correction.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++# A person's category, note or exclusion marks an entry user-modified, which+# keeps Account::ProviderImportAdapter off it, but it does not make Wise's+# amount theirs. So a later sync's amount (a sign or currency an older build+# got wrong, a split payment's part) still reaches such an entry, unless the+# person changed the amount or currency themselves (they are locked), an+# import owns the entry, they reconciled or split it, or it sits in a+# transfer, whose other leg would no longer match.+module WiseItem::AmountCorrection+ # entry: what the adapter returned for a Wise row that books amount in+ # currency. Returns the entry.+ def self.apply(entry, amount:, currency:)+ return entry unless entry.is_a?(Entry) && entry.persisted? && entry.protected_from_sync?+ return entry if entry.amount == amount.to_d && entry.currency == currency+ return entry unless correctable?(entry)++ entry.update!(amount: amount, currency: currency)+ entry+ end++ def self.correctable?(entry)+ transaction = entry.entryable+ return false unless transaction.is_a?(Transaction)+ return false if entry.import_locked? || entry.locked?(:amount) || entry.locked?(:currency) || entry.reconciled_at.present?++ !entry.split_parent? && transaction.transfer_id.nil? && transaction.transfer_as_inflow.nil? && transaction.transfer_as_outflow.nil?+ end+ private_class_method :correctable?+enddiff --git a/app/models/wise_item/balance_replay.rb b/app/models/wise_item/balance_replay.rbnew file mode 100644index 0000000000..166da0eded--- /dev/null+++ b/app/models/wise_item/balance_replay.rb@@ -0,0 +1,534 @@+# frozen_string_literal: true++# Replays Wise balances from zero through the rows Sure stores for them, to+# work out what neither /v1/transfers nor the activity feed says:+#+# - Whether a balance paid an outgoing transfer at all. Wise also takes a+# transfer's money from a card or a bank, and both payloads look the same.+# A payout the balance could not have paid, when it was created nor when+# its activity last changed, was funded externally ("wise_funding").+# - How much each balance paid of a card payment Wise split across several+# balances; the secondaryAmount lists only their currencies ("GBP, EUR").+# The balance in the merchant's currency pays first, so it is drained to+# zero. The other balances' parts come out of what each has left over at+# the end (its running balance minus the live amount), oldest payment+# first: each part at most the balance's lowest point until its next such+# payment (low-water rule), the last one taking the rest, and none more+# than the rest of the payment at the nearest known exchange rate plus a+# fee allowance ("wise_split_parts", and "wise_split_estimated" for the+# currencies that paid more than one such payment). A payment one of whose+# parts no exchange rate bounds gets none: a debit Sure does not book+# would pass for that part.+#+# A balance reconciles only when the replay with those results never goes+# below zero and ends at the live amount. The importer then replaces the+# marks on that balance's rows; any other balance keeps what it had. So does+# one whose leftover went into a split payment's part that is not written+# (#funding_withheld), as a credit Sure misses could hide there, and it+# reconciles only when its split parts fit the funding marks it keeps+# (#marks_that_fit). The replay itself ignores the marks already on the+# rows: it always starts from what Wise reported.+class WiseItem::BalanceReplay+ ANNOTATION_KEYS = %w[wise_funding wise_split_parts wise_split_estimated].freeze+ EXTERNAL_FUNDING = "external"++ # Rounding the replay tolerates at every step and at the end.+ TOLERANCE = BigDecimal("0.01")+ # A balance short of a payout's gross by more than this did not pay it+ # (WiseEntry::Processor::FEE_THRESHOLD).+ SHORTFALL = BigDecimal("0.005")+ # Fees Wise may charge on top of a split payment: 3 % plus 2 units of the+ # payment's currency.+ FEE_ALLOWANCE_SHARE = BigDecimal("0.03")+ FEE_ALLOWANCE_UNITS = BigDecimal("2")+ # How far a split part's own exchange rate may stray from the nearest one.+ RATE_MARGIN = BigDecimal("1.1")+ # Days around a payment within which a rate Sure stored is used.+ STORED_RATE_DAYS = 5+ ZERO = BigDecimal("0")++ # key: the caller's id for the balance; live: what Wise holds now (amount+ # plus reservedAmount); rows: the balance's stored payload rows.+ Balance = Data.define(:key, :currency, :live, :rows)++ # reason: nil when the balance reconciled. funding_withheld: why it keeps+ # its funding marks although it reconciled (#funding_withheld), or nil.+ # counts: its rows by role, for support. notes: e.g. split parts no+ # exchange rate could bound.+ Outcome = Data.define(:key, :currency, :reason, :funding_withheld, :counts, :notes) do+ def success? = reason.nil?+ end++ # funding: { balance key => ids of its externally funded transfers }, for+ # the balances that reconciled and whose funding is not withheld.+ # split_annotations: { activity id =>+ # { "wise_split_parts" => {...}, "wise_split_estimated" => [...] or nil } },+ # for the split payments whose every balance reconciled.+ Result = Data.define(:outcomes, :funding, :split_annotations)++ # One movement of a balance. amount is unsigned: what a credit, debit or+ # refund moved, a payout's gross debit, or a split payment's full amount+ # in the merchant's currency (currency).+ Flow = Struct.new(:kind, :at, :amount, :id, :currency, :settle_at, :payout_id, :funding_currencies, keyword_init: true) do+ def credit? = kind == :credit || kind == :refund+ def split? = kind == :split_primary || kind == :split_secondary++ # Timestamps in order, except that within one second credits come first:+ # a transfer's creation time has no fractions, so a payout must not sort+ # before the conversion that paid for it.+ def sort_key = [ at.to_i, credit? ? 0 : 1, at, id ]+ end++ # A rate Sure already holds (no provider call): the nearest within+ # STORED_RATE_DAYS, read in either direction, else the cross rate through+ # a currency Sure holds rates for with both (such as the family's, which+ # every account's balance converts to). nil when there is none.+ def self.stored_rate(from, to, date)+ window = (date - STORED_RATE_DAYS)..(date + STORED_RATE_DAYS)+ rates = ExchangeRate.where(date: window).where("from_currency IN (:pair) OR to_currency IN (:pair)", pair: [ from, to ]).to_a+ direct = nearest_rate(rates, from, to, date)+ return direct if direct++ pivots = rates.flat_map { |rate| [ rate.from_currency, rate.to_currency ] }.uniq - [ from, to ]+ pivots.sort.each do |pivot|+ from_pivot = nearest_rate(rates, from, pivot, date)+ to_pivot = nearest_rate(rates, to, pivot, date)+ return from_pivot / to_pivot if from_pivot && to_pivot+ end+ nil+ end++ # Units of `to` per unit of `from` from the nearest of the given rates for+ # the pair, read in either direction.+ def self.nearest_rate(rates, from, to, date)+ [ [ from, to, false ], [ to, from, true ] ].each do |source, target, inverse|+ stored = rates.select { |rate| rate.from_currency == source && rate.to_currency == target }.min_by { |rate| (rate.date - date).abs }+ rate = stored&.rate&.to_d+ return inverse ? 1 / rate : rate if rate&.positive?+ end+ nil+ end+ private_class_method :nearest_rate++ def self.fee_allowance(amount)+ amount * FEE_ALLOWANCE_SHARE + FEE_ALLOWANCE_UNITS+ end++ # balances: the balances to replay, one per currency. own_recipient_ids:+ # see WiseItem#own_recipient_ids. feed: rows to read exchange rates from+ # (by default the balances' own). stored_rate: the fallback rate lookup.+ def initialize(balances, own_recipient_ids:, feed: nil, stored_rate: self.class.method(:stored_rate))+ @balances = balances+ @own_recipient_ids = own_recipient_ids+ @feed = feed || balances.flat_map(&:rows)+ @stored_rate = stored_rate+ end++ def call+ ledgers = @balances.map { |balance| Ledger.new(balance, own_recipient_ids: @own_recipient_ids) }+ ledgers.each(&:forward_pass)+ merchant_parts = ledgers.reject(&:failed?).map(&:drains).reduce({}, :merge)+ ledgers.each { |ledger| ledger.allocate_parts { |flow| part_limit(flow, ledger.currency, merchant_parts) } }+ ledgers.each(&:final_check)+ annotations, withheld = marks_that_fit(ledgers)++ Result.new(+ outcomes: ledgers.map { |ledger| ledger.outcome(funding_withheld: withheld[ledger]) },+ funding: ledgers.reject { |ledger| ledger.failed? || withheld[ledger] }.to_h { |ledger| [ ledger.balance.key, ledger.externals.dup ] },+ split_annotations: annotations+ )+ end++ # One balance's replay.+ class Ledger+ attr_reader :balance, :reason, :flows, :externals, :drains++ def initialize(balance, own_recipient_ids:)+ @balance = balance+ @own_recipient_ids = own_recipient_ids+ @externals = Set.new+ @drains = {}+ @parts = {}+ @unbounded = Set.new+ @secondaries = []+ @notes = {}+ @flows = balance.rows.flat_map { |row| flows_for(row.except(*ANNOTATION_KEYS)) }.sort_by(&:sort_key)+ # The processors would book such a row in another currency.+ fail!(:foreign_currency_row) if @flows.any? { |flow| !flow.split? && flow.currency != currency }+ end++ def currency+ balance.currency+ end++ def failed?+ !reason.nil?+ end++ # The running balance's upper bound: other balances' unknown parts of+ # split payments count as nothing. A payout the balance cannot pay when+ # created waits until its activity last changed (credits arriving in the+ # meantime count); still unpaid then, it was funded externally.+ def forward_pass+ return if failed?++ running = ZERO+ waiting = []+ flows.each_with_index do |flow, index|+ running = settle(waiting, running) { |payout| payout.settle_at < flow.at }+ case flow.kind+ when :credit+ running += flow.amount+ when :refund+ running = settle(waiting, running) { |payout| payout.id == flow.payout_id }+ running += flow.amount unless externals.include?(flow.payout_id)+ when :debit+ running -= flow.amount+ when :payout+ if running >= flow.amount - SHORTFALL+ running -= flow.amount+ else+ waiting << flow+ end+ when :split_primary+ # Wise splits a payment only when this balance cannot pay it all.+ return fail!(:split_payment_affordable) if running > flow.amount + WiseItem::BalanceReplay.fee_allowance(flow.amount)++ drains[flow.id] = [ running, ZERO ].max+ running -= drains[flow.id]+ when :split_secondary+ @secondaries << [ flow, index ]+ end+ end+ @upper_bound = settle(waiting, running) { true }+ end++ # What this balance paid of split payments in other currencies: the+ # leftover, oldest payment first, each part at most the lowest running+ # balance from that payment until the next one (parts already taken+ # included), the last one taking the rest. The block gives a part's+ # plausible maximum, or nil when no rate bounds it (#unbounded?).+ def allocate_parts+ return if failed?++ leftover = @upper_bound - balance.live+ if @secondaries.empty?+ fail!(:leftover_unexplained) if leftover.abs > TOLERANCE+ return+ end+ return fail!(:leftover_negative) if leftover < -TOLERANCE++ running = running_balances+ taken = ZERO+ @secondaries.each_with_index do |(flow, index), position|+ following = @secondaries[position + 1]+ part = following ? [ leftover - taken, running[index...following.last].min - taken ].min : leftover - taken+ part = [ part, ZERO ].max+ limit = yield(flow)+ if limit.nil?+ @unbounded << flow.id if part > TOLERANCE+ @notes[:unbounded_part_count] = @unbounded.size if @unbounded.any?+ elsif part > limit+ return fail!(:implausible_split_part)+ end+ @parts[flow.id] = part+ taken += part+ end+ end++ # The replay with its results applied must never go below zero and must+ # end at the live amount.+ def final_check+ return if failed?++ running = running_balances(@parts)+ return fail!(:negative_running_balance) if running.any? { |value| value < -TOLERANCE }++ fail!(:live_amount_mismatch) if ((running.last || ZERO) - balance.live).abs > TOLERANCE+ end++ # This balance's part of a split payment, or nil when it had none.+ def part(id)+ drains[id] || @parts[id]+ end++ def estimated?(id)+ @secondaries.size > 1 && @parts.key?(id)+ end++ # Its part of the split payment is more than nothing, and no exchange+ # rate bounds it.+ def unbounded?(id)+ @unbounded.include?(id)+ end++ def outcome(funding_withheld: nil)+ Outcome.new(key: balance.key, currency: currency, reason: reason, funding_withheld: funding_withheld, counts: counts,+ notes: @notes)+ end++ # The payouts its rows already mark as externally funded, as they stay+ # when its funding marks are withheld. A mark on a row that books no+ # payout changes nothing, so it does not count.+ def marked_externals+ payouts = flows.filter_map { |flow| flow.id if flow.kind == :payout }+ balance.rows.filter_map { |row| row["id"].to_s if row["wise_funding"] == EXTERNAL_FUNDING }.to_set & payouts+ end++ # Its split parts do not fit the funding marks it keeps+ # (WiseItem::BalanceReplay#marks_that_fit).+ def funding_unconfirmed!+ fail!(:funding_unconfirmed)+ end++ private++ def fail!(reason)+ @reason ||= reason+ nil+ end++ def counts+ {+ flow_count: flows.size,+ payout_count: flows.count { |flow| flow.kind == :payout },+ external_candidate_count: externals.size,+ drained_split_count: drains.size,+ secondary_split_count: @secondaries.size+ }+ end++ def settle(waiting, running)+ waiting.select { |payout| yield(payout) }.each do |payout|+ waiting.delete(payout)+ if running < payout.amount - SHORTFALL+ externals << payout.id+ else+ running -= payout.amount+ end+ end+ running+ end++ # The running balance after each flow, externally funded payouts left+ # out, drained parts and the given other-currency parts applied.+ def running_balances(parts = {})+ running = ZERO+ flows.map do |flow|+ running += case flow.kind+ when :credit then flow.amount+ when :refund then externals.include?(flow.payout_id) ? ZERO : flow.amount+ when :debit then -flow.amount+ when :payout then externals.include?(flow.id) ? ZERO : -flow.amount+ when :split_primary then -drains.fetch(flow.id, ZERO)+ when :split_secondary then -parts.fetch(flow.id, ZERO)+ end+ end+ end++ # The movements a stored row books on this balance, as the processors+ # book them (see WiseAccount::Transactions::Processor#processor_for).+ def flows_for(row)+ return [] if row["wise_statement"].present?+ return activity_flows(row) if WiseActivity::Processor.activity_row?(row)++ row["id"].present? ? transfer_flows(row) : []+ end++ # WiseEntry::Processor: an outgoing transfer debits sourceValue plus its+ # fee (the gross) and a refunded one credits its refund; a pay-in+ # credits targetValue. A row the processor cannot date books nothing.+ def transfer_flows(row)+ direction = WiseEntry::Processor.direction(row, own_recipient_ids: @own_recipient_ids)+ return [] if WiseEntry::Processor.skip_reason(row, direction: direction)++ at = parse_time { WiseEntry::Processor.created_at(row) }+ return [] unless at++ id = row["id"].to_s+ if direction == :incoming+ return [ Flow.new(kind: :credit, at: at, amount: row["targetValue"].to_d.abs, id: id,+ currency: row["targetCurrency"].presence || currency) ]+ end++ source_currency = row["sourceCurrency"].presence || currency+ activity = row["wise_activity"].is_a?(Hash) ? row["wise_activity"] : {}+ updated_at = parse_time { ActiveSupport::TimeZone["UTC"].parse(activity["updatedOn"].to_s) if activity["updatedOn"].present? }+ flows = [ Flow.new(kind: :payout, at: at, amount: row["sourceValue"].to_d.abs + WiseEntry::Processor.fee(row), id: id,+ currency: source_currency, settle_at: [ at, updated_at ].compact.max) ]+ refund = WiseEntry::Processor.refund(row) if row["status"] == WiseEntry::Processor::REFUNDED_STATUS+ if refund+ flows << Flow.new(kind: :refund, at: refund[:created_at] || at, amount: refund[:value], id: "#{id}/refund",+ currency: refund[:currency] || source_currency, payout_id: id)+ end+ flows+ end++ # WiseActivity::Processor books completed activities only.+ def activity_flows(row)+ return [] unless row["status"].to_s == WiseActivity::Processor::BOOKED_STATUS++ at = parse_time { WiseActivity::Processor.created_at(row) }+ return [] unless at++ if WiseActivity::Processor::TWO_LEG_TYPES.include?(row["type"].to_s)+ conversion_flows(row, at)+ else+ single_leg_flows(row, at)+ end+ end++ def conversion_flows(row, at)+ primary = WiseActivity::Processor.parse_amount(row["primaryAmount"])+ secondary = WiseActivity::Processor.parse_amount(row["secondaryAmount"])+ conversion = WiseActivity::Processor.conversion_currencies(row)+ kind, amount, flow_currency =+ if conversion && conversion[:source] == currency+ [ :debit, secondary[:value], currency ]+ elsif conversion && conversion[:target] == currency+ [ :credit, primary[:value], currency ]+ else+ # A move between the balance and a jar, booked by its title.+ [ WiseActivity::Processor.jar_deposit?(row) ? :debit : :credit, primary[:value], primary[:currency] || currency ]+ end+ [ Flow.new(kind: kind, at: at, amount: amount || ZERO, id: row["id"].to_s, currency: flow_currency) ]+ end++ def single_leg_flows(row, at)+ funding = WiseActivity::Processor.balance_amount(row)+ return [] unless funding++ id = row["id"].to_s+ if funding[:split]+ return [] unless funding[:currencies].include?(currency)++ kind = funding[:currency] == currency ? :split_primary : :split_secondary+ return [ Flow.new(kind: kind, at: at, amount: funding[:value] || ZERO, id: id, currency: funding[:currency],+ funding_currencies: funding[:currencies]) ]+ end++ [ Flow.new(kind: funding[:direction] == :credit ? :credit : :debit, at: at, amount: funding[:value] || ZERO, id: id,+ currency: funding[:currency] || currency) ]+ end++ def parse_time+ yield+ rescue ArgumentError+ nil+ end+ end++ private++ # The most a balance can have paid of a split payment in another+ # currency: the rest after the merchant-currency part, with RATE_MARGIN+ # and the fee allowance, at the nearest known rate. nil without a rate.+ # (Without the merchant-currency part, the rest is the whole payment, but+ # then that balance did not reconcile and no part is written.)+ def part_limit(flow, currency, merchant_parts)+ rate = exchange_rate(from: flow.currency, to: currency, at: flow.at)+ return nil unless rate++ rest = [ flow.amount - merchant_parts.fetch(flow.id, ZERO), ZERO ].max+ (rest * RATE_MARGIN + self.class.fee_allowance(flow.amount)) * rate+ end++ # Units of `to` per unit of `from`: from the nearest completed conversion+ # or auto-converted card payment between the two, else a stored rate.+ def exchange_rate(from:, to:, at:)+ nearest = rate_points.fetch([ from, to ], []).min_by { |point| (point[:at] - at).abs }+ nearest ? nearest[:rate] : @stored_rate.call(from, to, at.utc.to_date)+ end++ def rate_points+ @rate_points ||= @feed.uniq { |row| row["id"] }.each_with_object({}) do |row, points|+ next unless rate_row?(row)++ at = parse_time { WiseActivity::Processor.created_at(row) }+ primary = WiseActivity::Processor.parse_amount(row["primaryAmount"])+ secondary = WiseActivity::Processor.parse_amount(row["secondaryAmount"])+ next unless at && primary[:value]&.positive? && secondary[:value]&.positive?+ next if primary[:currency].blank? || secondary[:currency].blank? || primary[:currency] == secondary[:currency]++ (points[[ primary[:currency], secondary[:currency] ]] ||= []) << { at: at, rate: secondary[:value] / primary[:value] }+ (points[[ secondary[:currency], primary[:currency] ]] ||= []) << { at: at, rate: primary[:value] / secondary[:value] }+ end+ end++ def rate_row?(row)+ return false unless WiseActivity::Processor.activity_row?(row) && row["status"] == WiseActivity::Processor::BOOKED_STATUS++ type = row["type"].to_s+ WiseActivity::Processor::TWO_LEG_TYPES.include?(type) ||+ (WiseActivity::Processor::SINGLE_LEG_TYPES.include?(type) && WiseActivity::Processor.direction(row) == :debit)+ end++ # Why a balance that reconciled keeps its funding marks: what it held+ # beyond its live amount went into a share of a split payment (its own+ # drained part, or another currency's rest) that is not written, as not+ # every balance the payment lists reconciled or one of its parts has no+ # rate to bound it (:split_parts_withheld). A credit Sure misses would+ # then pass for a payout the balance could not pay. nil when nothing went+ # into such a share.+ def funding_withheld(ledger, annotations)+ return nil if ledger.failed?++ paid = ledger.flows.select { |flow| flow.split? && (ledger.part(flow.id) || ZERO) > TOLERANCE }+ :split_parts_withheld if paid.any? { |flow| !annotations.key?(flow.id) }+ end++ # The split annotations, and per balance why it keeps its funding marks+ # (#funding_withheld). Such a balance's split parts were worked out with+ # the payouts its replay took as externally funded, so they fit the marks+ # it keeps only when those mark the same payouts. Otherwise they would+ # book a payout's money twice (the payout and a part holding it) or not+ # at all, so it does not reconcile (:funding_unconfirmed) and its split+ # payments keep their parts, which can withhold another balance's+ # funding in turn.+ def marks_that_fit(ledgers)+ loop do+ annotations = split_annotations(ledgers)+ withheld = ledgers.to_h { |ledger| [ ledger, funding_withheld(ledger, annotations) ] }+ unfit = ledgers.select { |ledger| withheld[ledger] && ledger.externals != ledger.marked_externals }+ return [ annotations, withheld ] if unfit.empty?++ unfit.each(&:funding_unconfirmed!)+ end+ end++ # A split payment's parts are written only when every balance it lists+ # reconciled, so its copies on those balances never disagree, and a rate+ # bounded each part.+ def split_annotations(ledgers)+ reconciled = ledgers.reject(&:failed?).index_by(&:currency)+ ledgers.flat_map { |ledger| ledger.flows.select(&:split?) }.group_by(&:id).each_with_object({}) do |(id, flows), annotations|+ currencies = flows.first.funding_currencies+ next unless currencies.all? { |currency| reconciled.key?(currency) }+ next if currencies.any? { |currency| reconciled[currency].unbounded?(id) }++ parts = currencies.to_h { |currency| [ currency, reconciled[currency].part(id) ] }+ next if parts.values.any?(&:nil?)++ annotations[id] = {+ "wise_split_parts" => parts.to_h { |currency, part| [ currency, decimal_string(part, currency) ] },+ "wise_split_estimated" => currencies.select { |currency| reconciled[currency].estimated?(id) }.presence+ }+ end+ end++ def decimal_string(value, currency)+ precision = begin+ Money::Currency.new(currency).default_precision+ rescue Money::Currency::UnknownCurrencyError+ 2+ end+ whole, fraction = value.round(precision).to_s("F").split(".")+ precision.zero? ? whole : "#{whole}.#{fraction.to_s.ljust(precision, "0")}"+ end++ def parse_time+ yield+ rescue ArgumentError+ nil+ end+enddiff --git a/app/models/wise_item/importer.rb b/app/models/wise_item/importer.rbindex db307561d8..94001f859c 100644--- a/app/models/wise_item/importer.rb+++ b/app/models/wise_item/importer.rb@@ -4,6 +4,60 @@ class WiseItem::ImporterDEFAULT_HISTORY_DAYS = 365# Wise has existed since 2011, so this safely predates any account creation.FULL_HISTORY_START_DATE = Date.new(2000, 1, 1)+ PAGE_SIZE = 100++ # An incremental fetch starts before the end of the last successful one+ # (its coverage `through`) so late arrivals and status changes are read+ # again: transfers 14 days before it and never later than 60 days ago (a+ # sent payout can still bounce), activities 30 days before it or a day+ # before the oldest stored activity that can still change, if that is+ # within 180 days (activities cannot be read by id).+ TRANSFER_OVERLAP = 14.days+ TRANSFER_RECHECK_PERIOD = 60.days+ ACTIVITY_OVERLAP = 30.days+ UNFINISHED_ACTIVITY_LOOKBACK = 180.days+ FINAL_ACTIVITY_STATUSES = %w[COMPLETED CANCELLED].freeze+ # A balance's statements are fetched again from a week before the end of+ # its last successful statement fetch.+ STATEMENT_OVERLAP = 7.days++ # A transfer in one of these statuses no longer changes. Stored transfers+ # in any other status but outgoing_payment_sent (which the 60-day window+ # re-lists) are read again by id each sync, newest first, and so is a sent+ # payout once a refund credit for it shows up.+ FINAL_TRANSFER_STATUSES = %w[cancelled funds_refunded charged_back].freeze+ MAX_TRANSFER_REREADS = 50+ # A stored transfer Wise no longer finds by id is read again on this many+ # syncs ("wise_missing_count" on its stored copy), then left as stored.+ MISSING_TRANSFER_REREADS = 3++ # What Sure attaches to a stored transfer row: the activity Wise shows for+ # the transfer and the refund credit of a refunded payout.+ ENRICHMENT_KEYS = %w[wise_activity wise_refund_activity].freeze+ # A re-fetched copy of a row keeps what Sure attached to the stored copy+ # unless it brings its own, so a sync whose activities do not reach that+ # far back (or failed) loses nothing: the enrichment, the balance replay's+ # marks, which only the replay changes (WiseItem::BalanceReplay), and the+ # id a statement row booked under (WiseItem::StatementMigration).+ STICKY_ROW_KEYS = (ENRICHMENT_KEYS + WiseItem::BalanceReplay::ANNOTATION_KEYS + %w[wise_statement_id]).freeze+ MAX_LOGGED_TRANSFER_IDS = 20++ # Where a jar move, or interest or a fee on holdings, was first routed:+ # the Wise balance id of its jar (for interest and fees, of whichever+ # balance took them). Written on every stored copy and honoured from then+ # on, so a jar renamed in Wise, a second jar in the currency or a jar+ # opened later moves nothing already routed (#routing_decision).+ ROUTING_DECISION_KEY = "wise_jar_balance_id"+ # A balance in one of these states holds investments, which earn interest+ # and fees like a jar.+ INVESTED_STATES = %w[INVESTED INVESTING DIVESTING].freeze++ # Wise answered with a page this fetch had already read.+ PaginationError = Class.new(StandardError)++ # How many syncs in a row both balance lists must arrive in full without a+ # stored balance before Sure takes it as closed.+ CLOSURE_ABSENCES = 2attr_reader :wise_item, :wise_provider, :sync_start_date@@ -11,8 +65,27 @@ class WiseItem::Importer@wise_item = wise_item@wise_provider = wise_provider@sync_start_date = sync_start_date+ @fetch_failures = 0+ @fetched_windows = {}+ @coverage_upgrade_sources = Set.new+ @statement_windows = {}+ @statement_coverage_upgrades = Set.new+ @known_transfer_ids = Set.new+ @statement_covered_account_ids = Set.new+ @statement_cutoffs = {}+ @statement_retry_accounts = []+ @statements_refused_accounts = []+ @deferred_activity_times = []+ @live_amounts = {}end+ # `complete:` is true only when every source this sync needed arrived in+ # full: balances, transfers and their re-reads, activities, and statements+ # of balances that already hold statement rows. Steps that delete or+ # rewrite entries must not run after an incomplete import.+ # `coverage_upgraded:` see #coverage_upgraded? (for support and tests: the+ # balances it rebuilt keep what it means for them themselves,+ # WiseAccount#prune_cap_bypass_ids).def importRails.logger.info "WiseItem::Importer - Starting import for item #{wise_item.id} (profile #{wise_item.profile_id})"@@ -22,27 +95,42 @@ class WiseItem::Importersavings_balances = fetch_savings_balancesall_balances = Array(balances) + Array(savings_balances)+ @multi_currency_account = fetch_multi_currency_accountborderless_accounts = fetch_borderless_accounts- account_result = import_balances(all_balances, borderless_accounts: borderless_accounts)+ account_result = import_balances(+ all_balances,+ borderless_accounts: borderless_accounts,+ account_recipient_id: @multi_currency_account&.dig("recipientId")+ )+ track_closed_balances(all_balances)transfers = fetch_transfers if legacy_transfer_import_needed?- activities = fetch_jar_activities+ activities = fetch_activitiesstatements = fetch_statementsstatement_fallbacks = statement_fetches_failed_completely?- transfers ||= fetch_transfers if statement_fallbacks+ transfers = fetch_transfers if (statement_fallbacks || statements_missing?) && !@transfers_attempted+ @live_amounts = fetch_live_amounts(balances) if balance_replay_wanted?(balances)transaction_result = store_transfers_per_account(transfers || [],- activities: activities,+ activities: activities || [],statements: statements,- statement_failures: Array(@statement_fetch_failed_accounts),+ statement_failures: @statement_retry_accounts,fallback_to_transfers: statement_fallbacks)- @interbalance_activities = activities.select { |a| a["type"] == "INTERBALANCE" }+ # Coverage also claims the fetched rows reached every payload, which+ # they cannot while a balance list failed or a balance was not saved.+ if transaction_result[:transactions_failed].zero? && account_result[:accounts_failed].zero? && !@balance_list_failed+ record_coverage!+ end- wise_item.update!(status: :good) if account_result[:accounts_failed].zero? && transaction_result[:transactions_failed].zero?+ success = account_result[:accounts_failed].zero? && transaction_result[:transactions_failed].zero? && @fetch_failures.zero?+ wise_item.update!(status: :good) if success{- success: account_result[:accounts_failed].zero? && transaction_result[:transactions_failed].zero?,+ success: success,+ complete: @fetch_failures.zero?,+ coverage_upgraded: coverage_upgraded?,+ fetch_failures: @fetch_failures,**account_result,**transaction_result}@@ -50,39 +138,139 @@ class WiseItem::Importerprivate+ # nil fails the import. Wise's not_found keeps the "no balances" import+ # going, but like any error it leaves the list incomplete, so nothing may+ # conclude a balance missing from it was closed (#balance_lists_complete?).def fetch_balances- wise_provider.get_balances(wise_item.profile_id)+ balances = Provider::Wise.with_retries { wise_provider.get_balances(wise_item.profile_id) }+ @standard_balances_complete = true+ balancesrescue Provider::Wise::WiseError => eif e.error_type == :not_foundRails.logger.info "WiseItem::Importer - No balances for profile #{wise_item.profile_id}"return []endmark_requires_update_if_credentials_error(e)- Rails.logger.error "WiseItem::Importer - Failed to fetch balances: #{e.message}"+ record_fetch_failure("balances", e, level: "error")# A rejected token fails the sync instead of completing it with nothing importedraise if credentials_error?(e)nilrescue => e- Rails.logger.error "WiseItem::Importer - Unexpected error fetching balances: #{e.class} - #{e.message}"+ record_fetch_failure("balances", e, level: "error")nilend+ # The import goes on without the jars when their list fails, but it is+ # incomplete and its coverage stays: a jar the list left out stores none+ # of this sync's rows, which a later incremental fetch would not reach.def fetch_savings_balances- wise_provider.get_savings_balances(wise_item.profile_id)+ balances = Provider::Wise.with_retries { wise_provider.get_savings_balances(wise_item.profile_id) }+ @savings_balances_complete = true+ balancesrescue Provider::Wise::WiseError => e- Rails.logger.info "WiseItem::Importer - No savings (JAR) balances for profile #{wise_item.profile_id}: #{e.message}"+ if e.error_type == :not_found+ Rails.logger.info "WiseItem::Importer - No savings (JAR) balances for profile #{wise_item.profile_id}: #{e.message}"+ else+ savings_list_failed(e)+ end[]rescue => e- Rails.logger.warn "WiseItem::Importer - Unexpected error fetching savings balances: #{e.message}"+ savings_list_failed(e)[]end+ def savings_list_failed(error)+ @balance_list_failed = true+ record_fetch_failure("savings_balances", error)+ end++ # Both balance lists arrived in full, so a stored balance missing from+ # them is really gone from Wise.+ def balance_lists_complete?+ @standard_balances_complete == true && @savings_balances_complete == true+ end++ # Wise lists only the balances a profile has now, and closes only empty+ # ones. A stored balance missing from both lists, arrived in full, in+ # CLOSURE_ABSENCES syncs in a row is closed: marked closed_at and set to+ # 0 (once; Wise no longer reports it), which freezes its payload (see+ # #store_transfers_per_account) and stops its statements. One the lists+ # show again is open again. A failed or partial list proves nothing, so+ # it counts no absence.+ def track_closed_balances(listed_balances)+ listed_ids = Array(listed_balances).filter_map { |balance| balance["id"].presence&.to_s if balance.is_a?(Hash) }.to_set+ complete = balance_lists_complete?+ changed = false++ WiseAccount.where(wise_item_id: wise_item.id).find_each do |wise_account|+ payload = wise_account.raw_payload.is_a?(Hash) ? wise_account.raw_payload : {}+ changed |=+ if listed_ids.include?(wise_account.balance_id.to_s)+ reopen_balance(wise_account, payload)+ elsif complete && payload["closed_at"].blank?+ count_balance_absence(wise_account, payload)+ else+ false+ end+ rescue => e+ Rails.logger.error "WiseItem::Importer - Failed to track whether balance #{wise_account.id} is closed: #{e.message}"+ end++ # Later reads of the item's balances see the marks.+ wise_item.wise_accounts.reset if changed+ end++ # Clears the absence count and closure of a balance Wise lists.+ def reopen_balance(wise_account, payload)+ return false unless payload.key?("closed_at") || payload.key?("absent_count")++ wise_account.update!(raw_payload: payload.except("closed_at", "absent_count"))+ if payload["closed_at"].present?+ capture_debug_log(category: "provider_sync", level: "info", wise_account: wise_account, operation: "balances",+ message: "WiseItem::Importer - Wise lists a balance Sure had marked closed again; it is open again")+ end+ true+ end++ def count_balance_absence(wise_account, payload)+ absences = payload["absent_count"].to_i + 1+ if absences < CLOSURE_ABSENCES+ wise_account.update!(raw_payload: payload.merge("absent_count" => absences))+ else+ wise_account.update!(current_balance: 0, reserved_balance: 0,+ raw_payload: payload.merge("absent_count" => absences, "closed_at" => Time.current.utc.iso8601))+ capture_debug_log(category: "provider_sync", level: "info", wise_account: wise_account, operation: "balances",+ message: "WiseItem::Importer - Wise no longer lists a balance; Sure marks it closed at 0",+ absent_count: absences)+ end+ true+ end++ # The account recipient (what transfers into the account target) and the+ # account's creationTime, where a full-history import starts. Kept on the+ # item, so a failed lookup falls back to the last known values.+ def fetch_multi_currency_account+ result = Provider::Wise.with_retries { wise_provider.get_multi_currency_account(wise_item.profile_id) }+ account = result.is_a?(Hash) ? result.slice("id", "recipientId", "creationTime") : {}+ wise_item.merge_sync_metadata!("multi_currency_account" => account) if account.present?+ account.presence || stored_multi_currency_account+ rescue => e+ trace_wise_fetch(operation: "multi_currency_account", status: "failed", level: "warn", error: e)+ stored_multi_currency_account+ end++ def stored_multi_currency_account+ account = wise_item.sync_metadata["multi_currency_account"]+ account if account.is_a?(Hash)+ end+# Returns a map of { balance_id => { borderless_account_id:, recipient_id: } }.- # Used in WiseEntry::Processor to distinguish expenses (targetAccount != recipientId)- # from incomes (targetAccount == recipientId).+ # The recipient is the fallback for the multi-currency account's, one of+ # the profile's own recipients that tell a pay-in from a payout+ # (WiseItem#own_recipient_ids).def fetch_borderless_accountstrace_wise_fetch(operation: "borderless_accounts", status: "started", level: "info")- result = wise_provider.get_borderless_accounts(wise_item.profile_id)+ result = Provider::Wise.with_retries { wise_provider.get_borderless_accounts(wise_item.profile_id) }trace_wise_fetch(operation: "borderless_accounts",status: "completed",@@ -101,7 +289,7 @@ class WiseItem::Importer{}end- def import_balances(balances, borderless_accounts: {})+ def import_balances(balances, borderless_accounts: {}, account_recipient_id: nil)accounts_created = 0accounts_updated = 0accounts_failed = 0@@ -126,7 +314,7 @@ class WiseItem::Importerwise_account.upsert_wise_snapshot!(data,borderless_account_id: account_ids[:borderless_account_id],- recipient_id: account_ids[:recipient_id]+ recipient_id: account_recipient_id.presence || account_ids[:recipient_id])if existing_ids.include?(balance_id)@@ -137,77 +325,84 @@ class WiseItem::Importerendrescue => eaccounts_failed += 1+ # A new balance that failed to save must not stay among the item's+ # balances unsaved: every later read of them would trip over it.+ wise_item.wise_accounts.reset if wise_account&.new_record?Rails.logger.error "WiseItem::Importer - Failed to import balance #{balance_id.presence || 'unknown'}: #{e.message}"end{ accounts_created: accounts_created, accounts_updated: accounts_updated, accounts_failed: accounts_failed }end- # Fetches all profile activities and keeps only JAR-relevant types.- def fetch_jar_activities- cutoff = transfer_cutoff+ # Every activity since the window start, of all types: routing decides+ # what each balance stores. nil when the fetch failed; its pages are+ # dropped and the next sync starts from the same point.+ def fetch_activities+ started_at = Time.current+ since = window_start(:activities)activities = []cursor = nilseen_cursors = Set.newloop do- trace_wise_fetch(operation: "activities", status: "started", level: "info", cursor: cursor, page_size: 100)- result = with_rate_limit_retry { wise_provider.get_activities(wise_item.profile_id, cursor: cursor, size: 100) }+ trace_wise_fetch(operation: "activities", status: "started", level: "info", cursor: cursor, page_size: PAGE_SIZE)+ result = Provider::Wise.with_retries do+ wise_provider.get_activities(wise_item.profile_id, cursor: cursor, size: PAGE_SIZE, since: since)+ endbatch = Array(result["activities"])+ next_cursor = result["cursor"].presencetrace_wise_fetch(operation: "activities",status: "completed",level: "info",cursor: cursor,received_record_count: batch.size,- next_cursor_present: result["cursor"].present?+ next_cursor_present: next_cursor.present?)- break if batch.empty?-- old_ones = batch.select { |a| parse_transfer_date(a["createdOn"]) < cutoff }- relevant = (batch - old_ones).select { |a| WiseActivity::Processor::JAR_ACTIVITY_TYPES.include?(a["type"]) }- activities.concat(relevant)-- break if old_ones.any? || batch.size < 100-- next_cursor = result["cursor"].presence- break if next_cursor.nil?-- if seen_cursors.include?(next_cursor)- trace_wise_fetch(- operation: "activities",- status: "failed",- level: "warn",- cursor: cursor,- next_cursor: next_cursor,- error: StandardError.new("Wise activities pagination cursor did not advance")- )- break- end+ activities.concat(batch)+ break if batch.empty? || next_cursor.nil?+ raise PaginationError, "Wise activities pagination cursor did not advance" if seen_cursors.include?(next_cursor)seen_cursors << next_cursorcursor = next_cursorend- activities.uniq { |a| a["id"] }- rescue Provider::Wise::WiseError => e- trace_wise_fetch(operation: "activities", status: "failed", level: "warn", error: e, cursor: cursor)- []+ @fetched_windows[:activities] = { start: since, through: started_at }+ activities.uniq { |activity| activity["id"] || activity.to_json }rescue => e- trace_wise_fetch(operation: "activities", status: "failed", level: "warn", error: e, cursor: cursor)- []+ record_fetch_failure("activities", e, cursor: cursor)+ nilend- # Fetches all transfers for the profile, filtered to the sync window.+ # Transfers created since the window start, plus the stored ones that can+ # still change, read again by id. nil when the list failed; its pages are+ # dropped and the next sync starts from the same point.def fetch_transfers- cutoff = transfer_cutoff+ @transfers_attempted = true+ started_at = Time.current+ start = window_start(:transfers)+ listed = list_transfers(start)+ return nil if listed.nil?++ @fetched_windows[:transfers] = { start: start, through: started_at }+ listed + Array(reread_transfers(except: listed.map { |transfer| transfer["id"].to_s }))+ end++ # Pages until Wise returns an empty page, without assuming an order.+ # Wise takes an offset only as a multiple of the limit (HTTP 422+ # inconsistent.pagination otherwise), so each page starts PAGE_SIZE rows+ # after the previous one, however many rows that held: a page shorter+ # than the limit need not be the last.+ def list_transfers(start)transfers = []+ seen_ids = Set.newoffset = 0- limit = 100loop do- trace_wise_fetch(operation: "transfers", status: "started", level: "info", offset: offset, page_size: limit)- page = with_rate_limit_retry { wise_provider.get_transfers(wise_item.profile_id, limit: limit, offset: offset) }+ trace_wise_fetch(operation: "transfers", status: "started", level: "info", offset: offset, page_size: PAGE_SIZE)+ page = Provider::Wise.with_retries do+ wise_provider.get_transfers(wise_item.profile_id, limit: PAGE_SIZE, offset: offset, created_date_start: start)+ endbatch = Array(page.is_a?(Hash) ? page["content"] : page)trace_wise_fetch(operation: "transfers",@@ -218,59 +413,282 @@ class WiseItem::Importer)break if batch.empty?- # Wise returns transfers newest-first; stop once we're past the cutoff.- old_ones = batch.select { |t| parse_transfer_date(t["created"]) < cutoff }- transfers.concat(batch - old_ones)- break if old_ones.any? || batch.size < limit+ fresh = batch.reject { |transfer| seen_ids.include?(transfer_key(transfer)) }+ raise PaginationError, "Wise transfers page at offset #{offset} repeated earlier transfers" if fresh.empty?- offset += limit+ fresh.each { |transfer| seen_ids << transfer_key(transfer) }+ transfers.concat(fresh)+ offset += PAGE_SIZEend- transfers.uniq! { |t| t["id"] }Rails.logger.info "WiseItem::Importer - Fetched #{transfers.size} transfers for profile #{wise_item.profile_id}"transfers- rescue Provider::Wise::WiseError => e- trace_wise_fetch(operation: "transfers", status: "failed", level: "warn", error: e, offset: offset)- []rescue => e- trace_wise_fetch(operation: "transfers", status: "failed", level: "warn", error: e, offset: offset)- []+ record_fetch_failure("transfers", e, offset: offset)+ nil+ end++ # Wise lists a transfer under its creation date only, so a later change+ # (delivered, bounced, refunded) to an older one is read by id. A transfer+ # Wise no longer finds keeps its stored copy, which counts the syncs it+ # went missing on ("wise_missing_count", gone once Wise finds it again)+ # until MISSING_TRANSFER_REREADS stop its reads; support is told when it+ # first goes missing. nil when a read failed; the stored copies stay as+ # they are.+ def reread_transfers(except:)+ candidates = stored_transfer_rows+ .select { |row| reread_transfer?(row) && row["wise_superseded_by"].blank? && except.exclude?(row["id"].to_s) }+ .reject { |row| row["wise_missing_count"].to_i >= MISSING_TRANSFER_REREADS }+ .sort_by { |row| transfer_created_at(row) || Time.at(0) }+ .last(MAX_TRANSFER_REREADS)+ .reverse+ newly_missing = 0++ transfers = candidates.filter_map do |row|+ Provider::Wise.with_retries { wise_provider.get_transfer(row["id"]) }+ rescue Provider::Wise::WiseError => e+ raise unless e.error_type == :not_found++ newly_missing += 1 if row["wise_missing_count"].to_i.zero?+ row.merge("wise_missing_count" => row["wise_missing_count"].to_i + 1)+ end++ if newly_missing.positive?+ capture_debug_log(+ category: "provider_sync_error",+ level: "warn",+ message: "WiseItem::Importer - Wise no longer finds #{newly_missing} stored transfers; keeping their stored copies",+ operation: "transfer",+ missing_transfer_count: newly_missing+ )+ end+ transfers.select { |transfer| transfer.is_a?(Hash) && transfer["id"].present? }+ rescue => e+ record_fetch_failure("transfer", e)+ nil+ end++ # A payout Wise refunds after the window stopped re-listing it is read+ # again once its refund credit is on its row (from the sync that saw the+ # credit on), so its new status books the refund.+ def reread_transfer?(row)+ status = row["status"].to_s+ return false if FINAL_TRANSFER_STATUSES.include?(status)++ status != "outgoing_payment_sent" || WiseEntry::Processor.refund(row).present?+ end++ # One copy per transfer stored on the STANDARD balances, statement-+ # covered ones included: a transfer their statement rows have not taken+ # over yet still books from its row (WiseItem::StatementMigration), so+ # it is read again like any other (#reread_transfers skips the rest).+ def stored_transfer_rows+ wise_item.wise_accounts.reject(&:jar?).flat_map do |wise_account|+ Array(wise_account.raw_transactions_payload).select { |row| transfer_row?(row) }+ end.uniq { |row| row["id"].to_s }+ end++ def transfer_row?(row)+ row["wise_statement"].blank? && !WiseActivity::Processor.activity_row?(row) && row["id"].present?+ end++ def transfer_key(transfer)+ transfer["id"].presence&.to_s || transfer.to_json+ end++ def transfer_created_at(row)+ WiseEntry::Processor.created_at(row)+ rescue ArgumentError+ nil+ end++ # Where this sync's fetch of `source` (:transfers or :activities) starts:+ # the whole history (#history_start) while nothing is covered, an older+ # build recorded the coverage (WiseItem::COVERAGE_VERSION) or it starts+ # later than the history (import_all_history switched on, the sync start+ # date moved back); otherwise incrementally.+ def window_start(source)+ coverage = wise_item.fetch_coverage(source)+ start = history_start+ if coverage.nil? || coverage[:from] > start+ @coverage_upgrade_sources << source+ return start+ end++ if source == :transfers+ [ coverage[:through] - TRANSFER_OVERLAP, TRANSFER_RECHECK_PERIOD.ago ].min+ else+ [ coverage[:through] - ACTIVITY_OVERLAP, unfinished_activity_start ].compact.min+ end+ end++ # Where the history Sure imports starts: the given full history start,+ # unless a sync start date (the sync's or the item's) says otherwise;+ # an item that imports the whole history starts at the earlier of the+ # two. A start date is where the history starts, not where every sync+ # starts: once covered from it, syncs go on incrementally.+ def history_start(full_start = full_history_start)+ explicit = explicit_window_start+ return full_start unless explicit++ full_history? ? [ explicit, full_start ].min : explicitend- # Fetches statement rows for STANDARD balances. Legacy transfer snapshots- # are retained; outgoing statement rows dated on/after the oldest legacy- # transfer are dropped since transfers already captured that side (see- # #legacy_overlap_outgoing_row?), while incoming rows there are kept so- # money the legacy fallback could never capture (external payments) gets- # backfilled -- at the cost of occasionally re-importing the credit leg of- # a historical internal conversion transfers also already captured (see- # #legacy_overlap_outgoing_row? for why that trade-off is intentional).+ # The start of the explicit sync start date in the family's zone.+ def explicit_window_start+ return @explicit_window_start if defined?(@explicit_window_start)++ date = (sync_start_date.presence || wise_item.sync_start_date.presence)&.to_date+ @explicit_window_start = date&.in_time_zone(wise_item.time_zone)+ end++ # A full-history import starts a day before Wise opened the account,+ # which predates every balance; otherwise DEFAULT_HISTORY_DAYS back.+ def full_history_start+ return DEFAULT_HISTORY_DAYS.days.ago unless full_history?++ created_at = parse_utc((@multi_currency_account || stored_multi_currency_account)&.dig("creationTime"))+ created_at ? created_at - 1.day : FULL_HISTORY_START_DATE.in_time_zone("UTC")+ end++ # A day before the oldest stored activity that can still change, so its+ # final status is fetched; activities older than the lookback are no+ # longer re-read, which is logged.+ def unfinished_activity_start+ created = stored_activity_rows+ .select { |row| row["status"].present? && FINAL_ACTIVITY_STATUSES.exclude?(row["status"]) }+ .filter_map { |row| activity_created_at(row) }+ return nil if created.empty?++ limit = UNFINISHED_ACTIVITY_LOOKBACK.ago+ aged = created.count { |time| time - 1.day < limit }+ if aged.positive? && aged_activities_unreported?(aged)+ capture_debug_log(+ category: "provider_sync",+ level: "info",+ message: "WiseItem::Importer - #{aged} unfinished Wise activities are older than #{UNFINISHED_ACTIVITY_LOOKBACK.inspect} and are no longer re-read",+ operation: "activities",+ aged_activity_count: aged+ )+ end+ [ created.min - 1.day, limit ].max+ end++ # Once a day per connection and count, the way WiseItem#time_zone reports a+ # zone it cannot use, not on every sync.+ def aged_activities_unreported?(count)+ Rails.cache.write([ "wise_aged_unfinished_activities", wise_item.id, count ], true, expires_in: 1.day, unless_exist: true)+ end++ def stored_activity_rows+ wise_item.wise_accounts+ .flat_map { |wise_account| Array(wise_account.raw_transactions_payload) }+ .select { |row| WiseActivity::Processor.activity_row?(row) }+ end++ def activity_created_at(row)+ WiseActivity::Processor.created_at(row)+ rescue ArgumentError+ nil+ end++ def record_coverage!+ wise_item.merge_sync_metadata!("coverage" => coverage_after_fetch) if @fetched_windows.any?+ end++ # Whether a source arrived in full for the first time (an install from+ # before coverage was kept) or from the start of the whole history its+ # coverage did not reach (the full history switched on), transfers and+ # activities or a balance's statements (#statement_coverage_upgrade?):+ # the payloads were rebuilt from a complete fetch, so the stale entry+ # clean-up may exceed its cap for the rows that moved (#prune_cap_bypass_to_store).+ def coverage_upgraded?+ @coverage_upgrade_sources.any? { |source| @fetched_windows.key?(source) } || @statement_coverage_upgrades.any?+ end++ # Transfers and activities feed every balance; a balance's statements+ # only that balance.+ def coverage_upgraded_for?(wise_account)+ @coverage_upgrade_sources.any? { |source| @fetched_windows.key?(source) } ||+ @statement_coverage_upgrades.include?(wise_account.id)+ end++ # The stored coverage extended by each source fetched in full this sync,+ # recorded under this build's WiseItem::COVERAGE_VERSION: `through` is+ # when that fetch started and `from` only moves earlier. A window that+ # starts after the stored `through` restarts the coverage, since the rows+ # in between were never fetched.+ def coverage_after_fetch+ stored = wise_item.sync_metadata["coverage"]+ coverage = stored.is_a?(Hash) ? stored.dup : {}+ @fetched_windows.each do |source, window|+ covered = wise_item.fetch_coverage(source)+ from = covered && window[:start] <= covered[:through] ? [ covered[:from], window[:start] ].min : window[:start]+ through = source == :activities ? [ window[:through], deferred_activity_cutoff ].compact.min : window[:through]+ coverage[source.to_s] = { "from" => from.utc.iso8601, "through" => through.utc.iso8601,+ "version" => WiseItem::COVERAGE_VERSION }+ end+ coverage+ end++ # A credit this sync deferred (#transfer_activity_route) is booked by a+ # later sync, which must read it again: activity coverage ends a day+ # before the oldest one, so the next window reaches back to it. Not when+ # this sync asked for no transfer list at all (statements carry the+ # movements): no later sync is sure to list transfers either, and the+ # window would only grow.+ def deferred_activity_cutoff+ oldest = @deferred_activity_times.compact.min if @transfers_attempted+ oldest - 1.day if oldest+ end++ def parse_utc(raw)+ ActiveSupport::TimeZone["UTC"].parse(raw.to_s) if raw.present?+ rescue ArgumentError+ nil+ end++ # Fetches statement rows for STANDARD balances, each from its own+ # coverage (#statement_window_start) until now, as UTC instants. Every+ # row is kept: rows a balance booked before it had statements (its+ # /v1/transfers and activity rows) hand their movements over to the+ # statement rows that carry them (WiseItem::StatementMigration).+ #+ # A 403 Sure cannot get past (#statements_refused?) means the token+ # cannot read statements this sync: the other balances without statement+ # rows are not asked, and it is logged once, not counted as a failure. A+ # balance that holds statement rows is still asked, and a 403 on it (also+ # Wise refusing a configured SCA key's answer) is no failure either:+ # nothing a later sync retries would get past it. The balance then takes+ # what happened after its statements last reached from transfers and+ # activities (#statement_covered?). Any other failure+ # counts against the import for a balance that holds statement rows,+ # also when the transfer fallback runs, and keeps its payload as it was+ # (#statement_retry_accounts); a balance without statement rows takes+ # its transfers and activities this sync instead (#statements_missing?).def fetch_statements@statement_fetch_attempted_accounts = []@statement_fetch_failed_accounts = []+ unavailable_count = 0+ refusal = nil- wise_item.wise_accounts.each_with_object({}) do |wise_account, result|- next if wise_account.jar?+ statements = wise_item.wise_accounts.each_with_object({}) do |wise_account, result|+ # A closed balance has no statements to fetch any more.+ next if wise_account.jar? || wise_account.closed?- existing = Array(wise_account.raw_transactions_payload)- legacy = existing.select do |transaction|- transaction["wise_statement"].blank? && !jar_activity?(transaction)+ has_statement_rows = Array(wise_account.raw_transactions_payload).any? { |transaction| transaction["wise_statement"].present? }++ if unavailable_count.positive? && !has_statement_rows+ @statement_fetch_attempted_accounts << wise_account.id+ @statement_fetch_failed_accounts << wise_account.id+ unavailable_count += 1+ result[wise_account.id] = []+ nextend- legacy_cutoff = legacy.filter_map { |transaction| parse_transaction_date(transaction) }.min-- start_date =- if existing.any? { |transaction| transaction["wise_statement"].present? } &&- sync_start_date.blank? && wise_item.sync_start_date.blank? && wise_item.last_synced_at.present?- # Incremental: once statements exist, only fetch the short overlap.- (wise_item.last_synced_at - 7.days).to_date- elsif full_history?- full_history_start_date(wise_account)- else- sync_start_date_value- end- end_date = Date.current- next if start_date > end_date+ started_at = Time.current+ interval_start = statement_window_start(wise_account)+ next if interval_start > started_at@statement_fetch_attempted_accounts << wise_account.idtrace_wise_fetch(@@ -278,62 +696,179 @@ class WiseItem::Importerstatus: "started",level: "info",wise_account: wise_account,- start_date: start_date,- end_date: end_date+ interval_start: interval_start,+ interval_end: started_at)rows = wise_provider.get_balance_statements(wise_item.profile_id,wise_account.balance_id,currency: wise_account.currency,- start_date: start_date,- end_date: end_date+ interval_start: interval_start,+ interval_end: started_at)- received_row_count = Array(rows).size- rows = Array(rows).reject { |row| legacy_overlap_outgoing_row?(row, legacy_cutoff) }+ rows = Array(rows).map { |row| row.merge("wise_statement" => true) }.uniq { |row| statement_key(row) }trace_wise_fetch(operation: "balance_statement",status: "completed",level: "info",wise_account: wise_account,- received_row_count: received_row_count,- stored_row_count: rows.size+ received_row_count: rows.size)- result[wise_account.id] = rows.map { |row| row.merge("wise_statement" => true) }- rescue Provider::Wise::WiseError => e- @statement_fetch_failed_accounts << wise_account.id- trace_wise_fetch(operation: "balance_statement", status: "failed", level: "warn", wise_account: wise_account, error: e)- result[wise_account.id] = []+ @statement_windows[wise_account.id] = { start: interval_start, through: started_at }+ @statement_coverage_upgrades << wise_account.id if statement_coverage_upgrade?(wise_account)+ check_running_balances(wise_account, rows)+ result[wise_account.id] = rowsrescue => e@statement_fetch_failed_accounts << wise_account.id- trace_wise_fetch(operation: "balance_statement", status: "failed", level: "warn", wise_account: wise_account, error: e)result[wise_account.id] = []+ @statements_refused_accounts << wise_account.id if has_statement_rows && statements_forbidden?(e)+ if statements_refused?(e)+ unavailable_count += 1+ refusal ||= e+ elsif has_statement_rows && !statements_forbidden?(e)+ @statement_retry_accounts << wise_account.id+ record_fetch_failure("balance_statement", e, wise_account: wise_account)+ else+ trace_wise_fetch(operation: "balance_statement", status: "failed", level: "warn", wise_account: wise_account, error: e)+ endend++ log_statements_unavailable(unavailable_count, refusal) if refusal+ statementsend- # The legacy /v1/transfers fallback captured outgoing money unconditionally,- # plus the incoming leg of any internal cross-currency conversion between- # the profile's own balances (transfers where this balance is the target).- # So an outgoing statement row (Wise reports debits as non-positive) dated- # on/after the oldest legacy transfer already has a legacy counterpart and- # would double-book it.- #- # An incoming row in that same window *could* be the credit leg of one of- # those internal conversions (also already covered) rather than a genuine- # external payment -- but nothing short of an endpoint-proven correlation- # id can tell the two apart without risk of a false match, and silently- # dropping a real external payment is a worse failure than an occasional- # visible, user-correctable duplicate for a historical conversion. So- # incoming rows are always kept here; #legacy_transfer_import_needed?- # instead bounds the exposure by stopping the transfer fallback (and with- # it, any *new* double-booking) as soon as an account's statements prove- # to work.- def legacy_overlap_outgoing_row?(row, legacy_cutoff)- return false unless legacy_cutoff+ # Where this sync's statement fetch for a balance starts, from the+ # balance's own coverage, like #window_start for transfers and+ # activities: the whole history (#statement_history_start) while+ # nothing is covered or the coverage starts later (the full history+ # switched on, the sync start date moved back); otherwise a week before+ # the end of the last successful fetch, so a statement outage leaves no+ # gap. Statement rows are kept whatever the build, so their coverage+ # has no version.+ def statement_window_start(wise_account)+ coverage = wise_account.statements_coverage+ start = statement_history_start(wise_account)+ return start if coverage.nil? || coverage[:from] > start++ coverage[:through] - STATEMENT_OVERLAP+ end++ def statement_history_start(wise_account)+ history_start(statement_full_start(wise_account))+ end++ # A full-history import fetches a balance's statements from the moment+ # Wise opened it, else from where transfers and activities start.+ def statement_full_start(wise_account)+ (full_history? && wise_account.creation_time) || full_history_start+ end++ # Whether this sync's statements rebuild a balance's stored rows from its+ # first coverage or from the whole history its coverage did not reach+ # (see #coverage_upgraded?).+ def statement_coverage_upgrade?(wise_account)+ return false if Array(wise_account.raw_transactions_payload).empty?++ coverage = wise_account.statements_coverage+ coverage.nil? || coverage[:from] > statement_history_start(wise_account)+ end++ # The balance's statement coverage ({ from:, through: } UTC times)+ # extended by this sync's fetch, else as stored: `from` only moves+ # earlier, unless the fetch started after the stored `through` (see+ # #coverage_after_fetch).+ def statement_coverage(wise_account)+ stored = wise_account.statements_coverage+ window = @statement_windows[wise_account.id]+ return stored unless window++ from = stored && window[:start] <= stored[:through] ? [ stored[:from], window[:start] ].min : window[:start]+ { from: from, through: window[:through] }+ end++ # What is saved with the rows a balance's statement fetch brought this+ # sync (raw_payload "statements_coverage"); nil when it fetched none.+ def statements_coverage_to_store(wise_account)+ return nil unless @statement_windows.key?(wise_account.id)++ statement_coverage(wise_account).transform_keys(&:to_s).transform_values { |time| time.utc.iso8601 }+ end++ # Each statement row carries the balance after it (runningBalance), so+ # consecutive rows chain: previous + amount = running. A break suggests+ # Sure reads the amounts wrongly (a credit's amount is taken as already+ # net of its fee), so it is logged for support: counts only, and how+ # many breaks the row's own fee would explain. Rows at the same time may+ # come in any order, so a row chains from any row of its own time or of+ # the time before; the earliest time has its predecessor outside the+ # window and is not checked.+ def check_running_balances(wise_account, rows)+ groups = rows.filter_map do |row|+ posted_at = WiseStatement::Processor.posted_at(row)+ [ posted_at, row ] if posted_at && row.dig("runningBalance", "value").present? && row.dig("amount", "value").present?+ end.group_by(&:first).sort_by(&:first).map { |_time, pairs| pairs.map(&:last) }++ breaks = 0+ fee_explained = 0+ groups.each_cons(2) do |previous, group|+ group.each do |row|+ gaps = (previous + group.reject { |other| other.equal?(row) }).map do |before|+ row.dig("runningBalance", "value").to_d - before.dig("runningBalance", "value").to_d - row.dig("amount", "value").to_d+ end+ next if gaps.any? { |gap| gap.abs <= WiseItem::StatementMigration::TOLERANCE }++ breaks += 1+ fee = row.dig("totalFees", "value").to_d+ fee_explained += 1 if fee.positive? && gaps.any? { |gap| (gap.abs - fee).abs <= WiseItem::StatementMigration::TOLERANCE }+ end+ end+ return if breaks.zero?++ capture_debug_log(+ category: "provider_sync",+ level: "warn",+ message: "WiseItem::Importer - #{breaks} Wise statement rows do not follow on from the running balance before them",+ wise_account: wise_account,+ operation: "running_balance",+ row_count: groups.sum(&:size),+ break_count: breaks,+ fee_explained_count: fee_explained+ )+ end- date = parse_transaction_date(row)- return false unless date && date >= legacy_cutoff+ # A 403 without an SCA challenge (the token may not read statements at+ # all), or with one Sure cannot sign as no SCA key is configured+ # (Provider::Wise answers a challenge with a signed retry whenever one+ # is, so with a key a challenged 403 is Wise refusing that answer).+ def statements_refused?(error)+ return false unless statements_forbidden?(error)- row.dig("amount", "value").to_d <= 0+ !error.sca_challenged? || wise_item.sca_private_key.blank?+ end++ def statements_forbidden?(error)+ error.is_a?(Provider::Wise::WiseError) && error.error_type == :access_forbidden+ end++ # A balance without statement rows whose statements did not arrive takes+ # its transfers and activities this sync like a balance without+ # statements, so the transfer list is fetched for it.+ def statements_missing?+ (Array(@statement_fetch_failed_accounts) - @statement_retry_accounts).any?+ end++ def log_statements_unavailable(balance_count, refusal)+ reason = refusal.sca_challenged? ? "an SCA challenge and no SCA key configured to sign it" : "no SCA challenge"+ capture_debug_log(+ category: "provider_sync",+ level: "info",+ message: "WiseItem::Importer - Wise balance statements are unavailable to this token " \+ "(403 with #{reason}); using transfers and activities instead",+ operation: "balance_statement",+ error_type: "access_forbidden",+ sca_challenged: refusal.sca_challenged?,+ balance_count: balance_count+ )end# Statements are only "unavailable" when every attempted standard balance@@ -347,98 +882,662 @@ class WiseItem::Importerattempted.any? && (attempted - failed).empty?end- # The transfer endpoint remains a compatibility fallback only until an- # account's statements are proven to work: once a statement row has- # landed for an account, statements alone cover both directions of money- # movement going forward, so re-fetching transfers would only re-invite- # double-booking new internal conversions (see #legacy_overlap_outgoing_row?)- # for no benefit.+ # Transfers are fetched ahead of the statements while a balance still+ # books /v1/transfers rows: one without statement rows yet, or one whose+ # statements have not taken over every transfer that books inside their+ # window (WiseItem::StatementMigration keeps those rows, which are read+ # again, until a statement row carries them).def legacy_transfer_import_needed?- wise_item.wise_accounts.any? do |wise_account|- next false if wise_account.jar?+ wise_item.wise_accounts.any? { |wise_account| legacy_transfers_pending?(wise_account) }+ end- payload = Array(wise_account.raw_transactions_payload)- has_legacy = payload.any? { |transaction| transaction["wise_statement"].blank? && !jar_activity?(transaction) }- has_statement = payload.any? { |transaction| transaction["wise_statement"].present? }+ def legacy_transfers_pending?(wise_account)+ return false if wise_account.jar?- has_legacy && !has_statement- end+ payload = Array(wise_account.raw_transactions_payload)+ legacy = payload.select { |transaction| transfer_row?(transaction) }+ return false if legacy.empty?+ return true if payload.none? { |transaction| transaction["wise_statement"].present? }++ window = wise_account.statements_coverage+ window.present? && legacy.any? { |transfer| transfer["wise_superseded_by"].blank? && books_since?(transfer, window[:from]) }end- # Partitions transactions by the currency relevant to each WiseAccount:- # - Expenses (outgoing): matched by sourceCurrency- # - Incomes (incoming): matched by targetCurrency- # Routes transfers to STANDARD accounts and activities to JAR accounts.+ # Whether a transfer row books and was created at `from` or later.+ def books_since?(transfer, from)+ created_at = transfer_created_at(transfer)+ direction = WiseEntry::Processor.direction(transfer, own_recipient_ids: own_recipient_ids)+ created_at.present? && created_at >= from && WiseEntry::Processor.skip_reason(transfer, direction: direction).nil?+ end++ # Partitions transactions by the balance each one moved money on (see+ # #transfer_for_account? and #activity_for_account?): transfers and+ # statement rows go to STANDARD balances, activities to the balances they+ # moved money on, jars included. Transfers, fetched or stored, first get+ # the activity this sync saw for them. The balance replay then marks the+ # merged payloads (#annotate_with_balance_replay) before they are stored.def store_transfers_per_account(transfers, activities: [], statements: {}, statement_failures: [], fallback_to_transfers: false)transactions_imported = 0transactions_failed = 0+ transfer_activities = transfer_activities_by_id(activities)+ stored_transfers = stored_transfer_rows.index_by { |row| row["id"].to_s }+ transfers = transfers.map { |transfer| enrich_transfer(transfer, transfer_activities) }+ report_transfer_notes(transfers, stored_transfers, transfer_activities)+ @known_transfer_ids = known_transfer_ids(transfers)+ @statement_covered_account_ids = statement_covered_account_ids(statements)+ @statement_cutoffs = statement_cutoffs+ @deferred_activity_times = activities.select { |activity| activity_route(activity) == :deferred }.map { |activity| activity_created_at(activity) }+ report_activity_routing(activities)+ payloads = {}wise_item.wise_accounts.find_each do |wise_account|- # A failed statement request for this balance (without a transfer- # fallback) leaves the account incomplete: keep its existing payload- # and surface the failure so the item is not marked good.+ # A failed statement request for a balance that holds statement rows+ # (without a transfer fallback) leaves the account incomplete: keep+ # its existing payload and surface the failure so the item is not+ # marked good.if statement_failures.include?(wise_account.id) && !fallback_to_transferstransactions_failed += 1nextendif wise_account.jar?- jar_activities = activities.select { |a| activity_for_account?(a, wise_account) }- wise_account.upsert_wise_transactions_snapshot!(jar_activities)- transactions_imported += jar_activities.size+ stored_rows = Array(wise_account.raw_transactions_payload)+ # Merged, never replaced: this sync's window (or a failed fetch)+ # holds only part of the jar's history, and a jar is only linked+ # after the sync that first stored it. Its stored rows are routed+ # again like new ones, which keeps every row on the jar it first+ # went to (#routing_decision) and drops rows an older rule copied+ # to every jar; a closed jar's stay as they are.+ unless wise_account.closed?+ stored_rows = stored_rows.select { |row| activity_for_account?(row, wise_account, stored: true) }.map { |row| with_routing_decision(row) }+ end+ jar_activities = activities.select { |a| activity_for_account?(a, wise_account) }.map { |a| with_routing_decision(a) }+ payloads[wise_account] = merge_transaction_payloads(stored_rows + jar_activities)else+ covered = @statement_covered_account_ids.include?(wise_account.id)+ stored_rows = Array(wise_account.raw_transactions_payload)account_statements = statements[wise_account.id] || []- existing_legacy = Array(wise_account.raw_transactions_payload).reject { |transaction| transaction["wise_statement"].present? }- existing_statements = Array(wise_account.raw_transactions_payload).select { |transaction| transaction["wise_statement"].present? }- # `transfers` is fetched profile-wide as soon as ANY account still- # needs the legacy fallback (see #legacy_transfer_import_needed?),- # so it can contain movements for a currency this specific account- # already covers via its own statements. Only apply it here if this- # account hasn't migrated yet -- otherwise the same movement would- # be merged twice under different keys (see #merge_transaction_payloads).- account_transfers =- if existing_statements.any?- []+ # Stored rows are re-routed too, so rows saved under an older+ # routing rule (an INTERBALANCE for another currency, the funding+ # side of a pay-in) drop out. A closed balance's stored rows stay+ # as they are: nothing Wise still lists can show they belong+ # elsewhere, and its entries are no longer pruned. A balance's+ # statements do not drop its stored activities here: they are+ # handed over to the statement rows (#hand_over_to_statements).+ existing_legacy = stored_rows.filter_map do |transaction|+ next if transaction["wise_statement"].present?++ if WiseActivity::Processor.activity_row?(transaction)+ next transaction if wise_account.closed?++ with_routing_decision(transaction) if activity_for_account?(transaction, wise_account, stored: true, ignore_statements: true)else- transfers.select do |t|- t["sourceCurrency"] == wise_account.currency ||- t["targetCurrency"] == wise_account.currency- end+ transfer = enrich_transfer(transaction, transfer_activities)+ transfer if wise_account.closed? || transfer_for_account?(transfer, wise_account)end- # Also include INTERBALANCE activities so the standard account shows outflows to the JAR.- interbalance = activities.select { |a| activity_for_account?(a, wise_account) }+ end+ existing_statements = WiseItem::StatementMigration.with_booked_ids(stored_rows.select { |transaction| transaction["wise_statement"].present? })+ # `transfers` is fetched profile-wide while any balance still books+ # them (#legacy_transfer_import_needed?). A balance with statements+ # takes no new one its statement rows carry (#statement_covered?);+ # it takes fresh copies of the rows it still holds.+ account_transfers = transfers.select { |t| transfer_for_account?(t, wise_account) }+ if covered+ held = existing_legacy.filter_map { |transaction| transaction["id"].to_s if transfer_row?(transaction) }.to_set+ account_transfers = account_transfers.select do |t|+ held.include?(t["id"].to_s) || !statement_covered?(wise_account) { transfer_created_at(t) }+ end+ end+ routed_activities = activities.select { |a| activity_for_account?(a, wise_account) }.map { |a| with_routing_decision(a) }payload = merge_transaction_payloads(- existing_legacy + account_transfers + existing_statements + account_statements + interbalance+ existing_legacy + account_transfers + existing_statements + account_statements + routed_activities)- # A statement request can legitimately return no rows for a token- # lacking statement permission; preserve transfer fallback behavior.- payload = merge_transaction_payloads(account_transfers + interbalance) if payload.empty?- wise_account.upsert_wise_transactions_snapshot!(payload)- transactions_imported += payload.size+ payload = hand_over_to_statements(wise_account, payload) if covered && !wise_account.closed?+ payloads[wise_account] = payloadendrescue => etransactions_failed += 1Rails.logger.error "WiseItem::Importer - Failed to store transactions for wise_account #{wise_account.id}: #{e.message}"end+ # Each balance in its own savepoint, so one that fails to save keeps its+ # old payload without holding back the others, except that the balances+ # whose split marks the replay changed are stored all or none: the+ # copies of a split payment on several balances carry the same parts.+ item_ids = coverage_upgraded? ? payloads.values.flatten.flat_map { |row| booked_external_ids(row) }.to_set : Set.new+ WiseAccount.transaction do+ changed, unchanged = annotate_with_balance_replay(payloads).partition do |wise_account, payload|+ split_marks_changed?(wise_account, payload)+ end+ [ changed, *unchanged.map { |pair| [ pair ] } ].reject(&:empty?).each do |group|+ WiseAccount.transaction(requires_new: true) do+ group.each do |wise_account, payload|+ wise_account.upsert_wise_transactions_snapshot!(payload, statements_coverage: statements_coverage_to_store(wise_account),+ prune_cap_bypass: prune_cap_bypass_to_store(wise_account, item_ids))+ end+ end+ transactions_imported += group.sum { |_wise_account, payload| payload.size }+ rescue => e+ transactions_failed += group.size+ Rails.logger.error "WiseItem::Importer - Failed to store transactions for wise_accounts #{group.map { |wise_account, _payload| wise_account.id }.join(', ')}: #{e.message}"+ end+ end+{ transactions_imported: transactions_imported, transactions_failed: transactions_failed }end- def merge_transaction_payloads(transactions)- transactions.each_with_object({}) do |transaction, merged|- key = if transaction["wise_statement"].present?- [ "statement", transaction["referenceNumber"].presence || transaction["id"] || transaction.to_json ]- elsif transaction["type"].present?- [ "activity", transaction["id"] || transaction.to_json ]+ # A sync that rebuilt the payloads from a whole history (#coverage_upgraded_for?)+ # can leave more stale entries than the clean-up deletes at once: what an+ # older build booked from rows this one routes elsewhere or books another+ # way (a conversion's copy on every balance, interest copied to every+ # jar, a payout Wise cancelled), and the entries of rows handed over to+ # statement rows or that book nothing here now. The balance's entries a+ # row Sure holds can have booked (#booked_external_ids of the balance's+ # stored rows and of every payload this sync stores, item_ids), added to+ # what an earlier such sync left, are kept on the balance until a+ # clean-up after a complete import has used them (WiseAccount+ # #prune_cap_bypass_ids); an entry no row explains stays under the cap.+ # nil when this sync adds nothing.+ def prune_cap_bypass_to_store(wise_account, item_ids)+ return nil unless coverage_upgraded_for?(wise_account)++ account = wise_account.current_account+ return nil unless account++ explained = item_ids | Array(wise_account.raw_transactions_payload).flat_map { |row| booked_external_ids(row) }+ ids = account.entries.where(source: "wise").pluck(:external_id).select { |external_id| explained.include?(external_id) }+ wise_account.prune_cap_bypass_ids | ids if ids.any?+ end++ # The external ids of every entry a stored row can have booked on a+ # balance, whichever side or kind the row processors gave it.+ def booked_external_ids(row)+ if row["wise_statement"].present?+ id = "wise_statement_#{WiseStatement::Processor.transaction_id(row)}"+ [ id, "#{id}_fee" ]+ elsif WiseActivity::Processor.activity_row?(row)+ resource_id = row["resource"]["id"] if row["resource"].is_a?(Hash)+ if WiseActivity::Processor::TWO_LEG_TYPES.include?(row["type"].to_s)+ resource_id.present? ? %w[inflow outflow].map { |side| "wise_interbalance_#{resource_id}_#{side}" } : []else- [ "transfer", transaction["id"] || transaction.to_json ]+ row["id"].present? ? [ "wise_activity_#{row['id']}" ] : []end- merged[key] = transaction+ elsif row["id"].present?+ %w[transfer fee refund].map { |kind| "wise_#{kind}_#{row['id']}" }+ else+ []+ end+ end++ # The rows a balance with statements booked before it had them hand their+ # movements over to the statement rows that carry them, and its statement+ # rows of conversions give way to the conversions' own rows+ # (WiseItem::StatementMigration).+ def hand_over_to_statements(wise_account, payload)+ migration = WiseItem::StatementMigration.new(+ wise_account, payload,+ own_recipient_ids: own_recipient_ids,+ window: statement_coverage(wise_account),+ entry_ids: entry_ids_lookup(wise_account)+ ).call+ report_statement_migration(wise_account, migration.counts)+ migration.rows+ end++ # Which of the given external ids the balance's account has Wise entries+ # for; nil while the balance is not linked.+ def entry_ids_lookup(wise_account)+ account = wise_account.current_account+ return nil unless account++ ->(external_ids) { external_ids.empty? ? [] : account.entries.where(source: "wise", external_id: external_ids).pluck(:external_id) }+ end++ # Tells support, per balance and sync, what has no statement row yet:+ # transfers that book inside the statements' window (their rows keep+ # booking and transfers are still fetched for the balance) and dropped+ # activities (a statement row carries their movement under another+ # reference), and which rows left once their entries were renamed.+ def report_statement_migration(wise_account, counts)+ return if counts.values_at(:transfers_unmatched, :activities_unmatched, :retired).all?(&:zero?)++ capture_debug_log(+ category: "provider_sync",+ level: (counts[:transfers_unmatched] + counts[:activities_unmatched]).positive? ? "warn" : "info",+ message: "WiseItem::Importer - Wise statement rows took over #{counts[:transfers_matched]} transfers and " \+ "#{counts[:activities_matched]} activities; #{counts[:transfers_unmatched]} transfers inside the statements' " \+ "window have no statement row yet and keep booking, #{counts[:activities_unmatched]} activities without one were dropped",+ wise_account: wise_account,+ operation: "statement_migration",+ **counts+ )+ end++ # Replays the balances that can be replayed (#balances_to_replay) and puts+ # what it found on their rows: "wise_funding" on the transfers of each+ # balance that reconciled, "wise_split_parts" (and "wise_split_estimated")+ # on every copy of a split payment whose balances all reconciled. Rows of+ # any other balance keep their marks. A replay that raises changes nothing+ # and never fails the import.+ def annotate_with_balance_replay(payloads)+ balances = balances_to_replay(payloads)+ return payloads if balances.empty?++ # A savepoint, so a failed rate lookup cannot abort the transaction.+ result = WiseAccount.transaction(requires_new: true) do+ WiseItem::BalanceReplay.new(balances, own_recipient_ids: own_recipient_ids, feed: payloads.values.flatten).call+ end+ annotated = apply_balance_replay(payloads, result)+ report_balance_replay(result, payloads, annotated)+ annotated+ rescue => e+ Rails.logger.error "WiseItem::Importer - Wise balance replay failed: #{e.class} - #{e.message}"+ capture_debug_log(+ category: "provider_sync_error",+ level: "error",+ message: "WiseItem::Importer - Wise balance replay failed (#{e.class}); funding and split marks are unchanged",+ operation: "balance_replay",+ error_class: e.class.name+ )+ payloads+ end++ # A balance is replayed only when its rows can hold everything that moved+ # it: a full-history import whose fetches all succeeded and reached back+ # to the balance's creation, an open STANDARD balance not invested (its+ # holdings move without rows), without statement coverage (statement rows+ # are not replayed), no jar in its currency (jar moves and interest), no+ # other open balance in its currency, no stored credit for a transfer+ # Sure does not have (it may be a transfer Wise lists late), and Wise+ # held the same amount before and after the fetch.+ def balances_to_replay(payloads)+ return [] unless full_history? && @fetch_failures.zero? && @live_amounts.any?+ return [] unless @fetched_windows.key?(:transfers) && @fetched_windows.key?(:activities)+ # A deferred credit is in no payload yet.+ return [] if @deferred_activity_times.any?++ coverage = coverage_after_fetch+ jar_currencies = WiseAccount.where(wise_item_id: wise_item.id).select(&:jar?).map(&:currency).to_set+ open_standard = payloads.keys.reject { |wise_account| wise_account.jar? || wise_account.closed? }+ shared_currencies = open_standard.group_by(&:currency).select { |_currency, accounts| accounts.size > 1 }.keys++ open_standard.filter_map do |wise_account|+ live = @live_amounts[wise_account.balance_id.to_s]+ next unless live && replayable_balance?(wise_account, payloads[wise_account], coverage)+ next if jar_currencies.include?(wise_account.currency) || shared_currencies.include?(wise_account.currency)++ WiseItem::BalanceReplay::Balance.new(key: wise_account.id, currency: wise_account.currency, live: live,+ rows: payloads[wise_account])+ end+ end++ def replayable_balance?(wise_account, payload, coverage)+ snapshot = wise_account.raw_payload.is_a?(Hash) ? wise_account.raw_payload : {}+ created_at = parse_utc(snapshot["creationTime"])+ return false unless created_at && snapshot["investmentState"] == "NOT_INVESTED"+ return false if @statement_covered_account_ids.include?(wise_account.id)++ covered = %w[transfers activities].all? do |source|+ from = parse_utc(coverage.dig(source, "from"))+ from && from <= created_at+ end+ covered && payload.none? { |row| unmatched_transfer_activity?(row) }+ end++ # Activities of transfers are stored only for transfers Sure does not+ # have (#transfer_activity_route).+ def unmatched_transfer_activity?(row)+ WiseActivity::Processor.activity_row?(row) &&+ WiseActivity::Processor::TRANSFER_TYPES.include?(row["type"].to_s) &&+ row["resource"].is_a?(Hash) && row["resource"]["type"] == "TRANSFER"+ end++ def apply_balance_replay(payloads, result)+ payloads.to_h do |wise_account, payload|+ externals = result.funding[wise_account.id]+ rows = payload.map do |row|+ if externals && transfer_row?(row)+ external = externals.include?(row["id"].to_s)+ with_annotations(row, "wise_funding" => (WiseItem::BalanceReplay::EXTERNAL_FUNDING if external))+ elsif WiseActivity::Processor.activity_row?(row) && (annotations = result.split_annotations[row["id"].to_s])+ with_annotations(row, annotations)+ else+ row+ end+ end+ [ wise_account, rows ]+ end+ end++ # Whether an activity the balance stores has other split marks than its+ # stored copy (one stored for the first time with none has none).+ def split_marks_changed?(wise_account, payload)+ keys = %w[wise_split_parts wise_split_estimated]+ stored = Array(wise_account.raw_transactions_payload).select { |row| WiseActivity::Processor.activity_row?(row) }.index_by { |row| row["id"] }+ payload.any? { |row| WiseActivity::Processor.activity_row?(row) && row.slice(*keys) != stored[row["id"]].to_h.slice(*keys) }+ end++ # Replaces the given marks on a row; a nil value removes the mark.+ def with_annotations(row, annotations)+ row.except(*annotations.keys).merge(annotations.compact)+ end++ # Tells support, per balance, why a replay did not reconcile (its marks+ # stay as they were) or why one that did keeps its funding marks, and+ # once when the marks changed: which transfers are now externally+ # funded and how many split parts no rate bounded.+ def report_balance_replay(result, before, after)+ accounts = before.keys.index_by(&:id)+ result.outcomes.each do |outcome|+ next if outcome.success? && outcome.funding_withheld.nil?++ message =+ if outcome.success?+ "replays to its live amount, but part of it went into a split payment share Sure cannot confirm " \+ "(#{outcome.funding_withheld}); its funding marks stay as they were"+ else+ "does not replay to its live amount (#{outcome.reason}); its funding and split marks stay as they were"+ end+ capture_debug_log(+ category: "provider_sync",+ level: "warn",+ message: "WiseItem::Importer - The Wise #{outcome.currency} balance #{message}",+ wise_account: accounts[outcome.key],+ operation: "balance_replay",+ reason: (outcome.reason || outcome.funding_withheld).to_s,+ **outcome.counts+ )+ end++ changed = before.sum do |wise_account, rows|+ rows.zip(after[wise_account]).count do |old_row, new_row|+ old_row.slice(*WiseItem::BalanceReplay::ANNOTATION_KEYS) != new_row.slice(*WiseItem::BalanceReplay::ANNOTATION_KEYS)+ end+ end+ return if changed.zero?++ unbounded = result.outcomes.select(&:success?).sum { |outcome| outcome.notes.fetch(:unbounded_part_count, 0) }+ external_ids = result.funding.values.flat_map(&:to_a).sort+ capture_debug_log(+ category: "provider_sync",+ level: "info",+ message: "WiseItem::Importer - The Wise balance replay changed the funding or split marks of #{changed} rows",+ operation: "balance_replay",+ changed_row_count: changed,+ external_transfer_count: external_ids.size,+ external_transfer_ids: external_ids.first(MAX_LOGGED_TRANSFER_IDS).presence,+ unbounded_part_count: unbounded.nonzero?+ )+ end++ # The replay needs what Wise holds once the transfers and activities are+ # fetched, so the balances are read again: { balance id => amount ++ # reservedAmount (card holds are not booked) } for each balance that did+ # not move since the first read. One that did (a card payment settling+ # in between) cannot be told apart from a missing row, so it waits.+ def fetch_live_amounts(first_read)+ before = balance_amounts(first_read)+ balance_amounts(Provider::Wise.with_retries { wise_provider.get_balances(wise_item.profile_id) }).filter_map do |balance_id, amounts|+ [ balance_id, amounts.sum ] if before[balance_id] == amounts+ end.to_h+ rescue => e+ trace_wise_fetch(operation: "balances", status: "failed", level: "warn", error: e, purpose: "balance_replay")+ {}+ end++ def balance_amounts(balances)+ Array(balances).each_with_object({}) do |balance, amounts|+ next unless balance.is_a?(Hash) && balance["id"].present?++ amounts[balance["id"].to_s] = [ balance.dig("amount", "value").to_d, balance.dig("reservedAmount", "value").to_d ]+ end+ end++ # Only a full-history import whose fetches all succeeded replays, and+ # only balances Wise describes well enough (#replayable_balance?); the+ # second balance read is skipped otherwise.+ def balance_replay_wanted?(first_read)+ return false unless full_history? && @fetch_failures.zero?++ Array(first_read).any? do |balance|+ balance.is_a?(Hash) && balance["investmentState"] == "NOT_INVESTED" && balance["creationTime"].present?+ end+ end++ # A transfer goes to the balance it reaches (WiseEntry::Processor+ # .balance_route, the rule the balance books it by), created at a time+ # the balance takes rows (#takes_row?). Wise does not say whether a+ # balance paid for a pay-in ("send to myself"), so none is debited for it+ # (see #report_transfer_notes).+ def transfer_for_account?(transfer, wise_account)+ route = WiseEntry::Processor.balance_route(transfer, wise_account, own_recipient_ids: own_recipient_ids,+ recipient_owners: balance_recipient_owners)+ # The balance's own account details name it, whatever else shares its currency.+ route.present? && takes_row?(wise_account, by_currency: route == :currency, debit: !pay_in?(transfer)) { transfer_created_at(transfer) }+ end++ # Whether a balance takes a row created at the time the block returns+ # (read only when the balance has a window, see #routing_windows).+ # by_currency: false when the row names the balance itself, so only its+ # closure limits it. debit: the row takes money from the balance.+ def takes_row?(wise_account, by_currency: true, debit: false)+ window = routing_windows[wise_account.id] || {}+ window = window.slice(:through) unless by_currency+ return true if window.values.none?++ time = yield+ return false unless time++ from = (window[:debits_from] if debit) || window[:from]+ before = (window[:credits_before] unless debit) || window[:before]+ (from.nil? || time >= from) && (before.nil? || time < before) && (window[:through].nil? || time <= window[:through])+ end++ # The times whose rows each balance takes, { wise_account id => { from:,+ # before:, through:, debits_from:, credits_before: } }. A closed balance+ # takes the rows created until Sure found it closed (`through`), and a jar+ # those from a day before Wise opened it (`from`). Wise keeps one STANDARD+ # balance per currency, so two of them mean the currency was closed and+ # opened again under a new balance id: the older one takes the rows from+ # before Wise opened the newer one (`before`), the newer one those after,+ # so no movement books on both. In the day before (a pay-in can be dated+ # before the balance it reached existed), money that came in went to the+ # newer one (`from`, `credits_before`) and money that left, such as the+ # conversion that emptied the older one, left the older one, as the+ # newer held nothing yet (`debits_from`). Only balances Wise dated can be+ # ordered.+ def routing_windows+ @routing_windows ||= begin+ accounts = wise_item.wise_accounts.to_a+ windows = accounts.to_h do |wise_account|+ opened = wise_account.creation_time - 1.day if wise_account.jar? && wise_account.creation_time+ [ wise_account.id, { from: opened, before: nil, through: wise_account.closed_at } ]+ end+ accounts.reject(&:jar?).select(&:creation_time).group_by(&:currency).each_value do |standard|+ standard.sort_by(&:creation_time).each_cons(2) do |older, newer|+ margin = newer.creation_time - 1.day+ windows[older.id].merge!(before: newer.creation_time, credits_before: margin)+ windows[newer.id].merge!(from: margin, debits_from: newer.creation_time)+ end+ end+ windows+ end+ end++ def own_recipient_ids+ @own_recipient_ids ||= wise_item.own_recipient_ids+ end++ def balance_recipient_owners+ @balance_recipient_owners ||= wise_item.balance_recipient_owners+ end++ # Activities whose resource is a transfer, by transfer id.+ def transfer_activities_by_id(activities)+ Array(activities).each_with_object({}) do |activity, index|+ resource = activity["resource"] if activity.is_a?(Hash)+ next unless resource.is_a?(Hash) && resource["type"] == "TRANSFER" && resource["id"].present?++ (index[resource["id"].to_s] ||= []) << activity+ end+ end++ # Attaches the activity Wise shows for a transfer: it carries the gross+ # debit (sourceValue excludes the fee), the direction markup and the+ # counterparty's name. Several activities can share a transfer's id (a+ # refund credit, a send to the profile's own account details): the one+ # created closest to the transfer whose markup fits its direction becomes+ # "wise_activity" (with no recipient known, the closest one decides the+ # direction), and a credit on a payout becomes "wise_refund_activity": the+ # latest one Wise did not cancel, else the latest cancelled one, whose+ # snapshot then replaces one an earlier sync took while it was in+ # progress (WiseEntry::Processor.refund books no cancelled credit). A+ # transfer this sync saw no activity for keeps its stored ones+ # (#merge_transaction_payloads).+ def enrich_transfer(transfer, transfer_activities)+ candidates = transfer_activities[transfer["id"].to_s]+ return transfer if candidates.blank?++ direction = (WiseEntry::Processor.direction(transfer, own_recipient_ids: own_recipient_ids) if own_recipient_ids.any?)+ fitting = candidates.select { |activity| direction.nil? || credit_activity?(activity) == (direction == :incoming) }+ activity = closest_to_created(transfer, fitting)+ direction ||= activity && credit_activity?(activity) ? :incoming : :outgoing+ if direction == :outgoing+ credits = candidates.select { |candidate| credit_activity?(candidate) }+ refund = latest_created(credits.reject { |credit| credit["status"] == "CANCELLED" }) || latest_created(credits)+ end++ enrichment = { "wise_activity" => activity, "wise_refund_activity" => refund }.compact+ return transfer if enrichment.empty?++ transfer.merge(enrichment.transform_values { |snapshot| WiseEntry::Processor.activity_snapshot(snapshot) })+ end++ def credit_activity?(activity)+ WiseActivity::Processor.direction(activity) == :credit+ end++ def closest_to_created(transfer, activities)+ created = transfer_created_at(transfer)+ activities.min_by do |activity|+ time = activity_created_at(activity)+ [ created && time ? (time - created).abs : Float::INFINITY, time&.to_f || Float::INFINITY, activity["id"].to_s ]+ end+ end++ def latest_created(activities)+ activities.max_by { |activity| [ activity_created_at(activity)&.to_f || -Float::INFINITY, activity["id"].to_s ] }+ end++ # Tells support about transfers Sure cannot book in full, once per change+ # (a new transfer, a new status, a new enrichment): a status Sure does not+ # book (Wise's "unknown" or an undocumented one), several activities+ # sharing a transfer's id, and pay-ins whose activity shows a debit or+ # another currency. Another balance may have paid such a pay-in ("send to+ # myself"), but Wise does not say, so Sure books only the credit.+ def report_transfer_notes(transfers, stored_transfers, transfer_activities)+ unknown_status = []+ shared = []+ balance_funded = []++ transfers.each do |transfer|+ id = transfer["id"].to_s+ stored = stored_transfers[id]+ if WiseEntry::Processor.unknown_status?(transfer) && (stored.nil? || stored["status"] != transfer["status"])+ unknown_status << transfer+ end++ candidates = transfer_activities[id]+ next if candidates.blank? || (stored && enrichment_ids(stored) == enrichment_ids(transfer))++ shared << transfer if candidates.size > 1+ balance_funded << transfer if pay_in?(transfer) && possibly_balance_funded?(transfer, candidates)+ end++ log_transfer_note(unknown_status, level: "warn",+ message: "have a status Sure does not book; they stay unbooked until Wise moves them on",+ statuses: unknown_status.map { |transfer| transfer["status"].to_s }.uniq)+ log_transfer_note(shared, level: "info",+ message: "share their id with several activities; the one created closest to the transfer that fits its direction is used",+ activity_counts: shared.first(MAX_LOGGED_TRANSFER_IDS).map { |transfer| transfer_activities[transfer["id"].to_s].size })+ log_transfer_note(balance_funded, level: "warn",+ message: "into the profile's own account details show a debit or another currency in their activity; " \+ "if another balance paid them (\"send to myself\"), that debit is not booked")+ end++ def enrichment_ids(transfer)+ transfer.values_at(*ENRICHMENT_KEYS).map { |activity| activity["id"] if activity.is_a?(Hash) }+ end++ def pay_in?(transfer)+ WiseEntry::Processor.direction(transfer, own_recipient_ids: own_recipient_ids) == :incoming+ end++ # A pay-in's activities normally only credit its target currency.+ def possibly_balance_funded?(transfer, activities)+ target = transfer["targetCurrency"].presence+ activities.any? do |activity|+ currencies = %w[primaryAmount secondaryAmount].flat_map do |key|+ WiseActivity::Processor.parse_amount(activity[key])[:currencies]+ end+ !credit_activity?(activity) || (target.present? && (currencies - [ target ]).any?)+ end+ end++ def log_transfer_note(transfers, level:, message:, **metadata)+ return if transfers.empty?++ capture_debug_log(+ category: "provider_sync",+ level: level,+ message: "WiseItem::Importer - #{transfers.size} Wise transfers #{message}",+ operation: "transfers",+ transfer_count: transfers.size,+ transfer_ids: transfers.first(MAX_LOGGED_TRANSFER_IDS).map { |transfer| transfer["id"] },+ **metadata+ )+ end++ # A re-fetched row replaces its stored copy but keeps what Sure attached+ # to that copy (STICKY_ROW_KEYS) unless it brings its own.+ def merge_transaction_payloads(transactions)+ transactions.each_with_object({}) do |transaction, merged|+ key = payload_key(transaction)+ merged[key] = with_sticky_keys(transaction, merged[key])end.valuesend- def jar_activity?(transaction)- WiseActivity::Processor::JAR_ACTIVITY_TYPES.include?(transaction["type"])+ # What tells the copies of one row in a payload apart from other rows.+ def payload_key(row)+ if row["wise_statement"].present?+ statement_key(row)+ elsif WiseActivity::Processor.activity_row?(row)+ [ "activity", row["id"] || row.to_json ]+ else+ [ "transfer", row["id"] || row.to_json ]+ end+ end++ def with_sticky_keys(row, stored)+ kept = stored.is_a?(Hash) ? stored.slice(*STICKY_ROW_KEYS).except(*row.keys) : {}+ kept.empty? ? row : row.merge(kept)+ end++ # Wise reuses a transfer's reference on its refund, so a statement row is+ # told apart by its reference, type (DEBIT/CREDIT), time and amount.+ def statement_key(row)+ reference = row["referenceNumber"].presence+ return [ "statement", row["id"] || row.except(*WiseItem::StatementMigration::MARKER_KEYS).to_json ] unless reference++ posted_at = WiseStatement::Processor.posted_at(row)+ [ "statement", reference, row["type"].to_s, posted_at&.iso8601(3) || row["date"].to_s, row.dig("amount", "value").to_d.to_s("F") ]+ end++ # A source that failed to arrive in full: logged for support and counted,+ # so the import is neither successful nor complete and its coverage stays.+ def record_fetch_failure(operation, error, level: "warn", **metadata)+ @fetch_failures += 1+ trace_wise_fetch(operation: operation, status: "failed", level: level, error: error, **metadata)enddef trace_wise_fetch(operation:, status:, level:, wise_account: nil, error: nil, **metadata)@@ -449,8 +1548,21 @@ class WiseItem::Importerreturn Rails.logger.debug(message) unless errorRails.logger.public_send(level, message)+ capture_debug_log(+ category: "provider_sync_error",+ level: level,+ message: message,+ wise_account: wise_account,+ operation: operation,+ error_class: error.class.name,+ error_type: error.respond_to?(:error_type) ? error.error_type : nil,+ **metadata+ )+ end++ def capture_debug_log(category:, level:, message:, wise_account: nil, **metadata)DebugLogEntry.capture(- category: error ? "provider_sync_error" : "provider_sync",+ category: category,level: level,message: message,source: self.class.name,@@ -459,142 +1571,441 @@ class WiseItem::Importeraccount_provider: wise_account&.account_provider,metadata: {wise_item_id: wise_item.id,- operation: operation,wise_account_id: wise_account&.id,balance_id: wise_account&.balance_id,currency: wise_account&.currency,- sca_private_key_configured: wise_item.sca_private_key.present?,- error_class: error&.class&.name,- error_type: error&.respond_to?(:error_type) ? error.error_type : nil- }.compact.merge(metadata)+ sca_private_key_configured: wise_item.sca_private_key.present?+ }.merge(metadata).compact)rescue => trace_error- Rails.logger.warn "WiseItem::Importer - Failed to capture statement trace: #{trace_error.message}"+ Rails.logger.warn "WiseItem::Importer - Failed to capture Wise debug log: #{trace_error.message}"end- # Routes an activity to the given WiseAccount.- # JAR: receives INTERBALANCE where the activity title's <strong> tag matches the JAR name,- # plus BALANCE_CASHBACK and BALANCE_ASSET_FEE.- # STANDARD: receives all INTERBALANCE activities (outflow side of JAR transfers).- def activity_for_account?(activity, wise_account)- type = activity["type"]+ # Whether the given balance stores an activity (see #activity_route).+ # Activities are fetched profile-wide, so without this filter every+ # balance would show every activity.+ # - Conversions (INTERBALANCE, AUTO_CONVERSION): the jar of a jar move+ # (#jar_move) and the STANDARD balance on its other side; a STANDARD+ # balance on either side of a conversion between two balances.+ # - Interest, cashback and fees on holdings: the jar or invested balance+ # in their currency, else the balance in it (#holding_balance).+ # - Single-leg activities: each open STANDARD balance that paid or+ # received it (several for a split payment), unless statements cover+ # that balance, whose statement rows then carry the movement.+ # Activities reach a closed balance only if created before it closed, a+ # jar only once it was opened, and in a currency Wise closed and opened+ # again only the balance of their time (#takes_row?).+ # stored: re-routes a row an earlier sync stored on this balance.+ # ignore_statements: as if statements did not cover the balance, for+ # stored rows its statement rows take over (#hand_over_to_statements).+ def activity_for_account?(activity, wise_account, stored: false, ignore_statements: false)+ case activity_route(activity, stored: stored)+ when :conversion+ routed =+ if wise_account.jar?+ move = jar_move(activity)+ # While several jars fit, each keeps the copy an earlier sync+ # stored on it, so the clean-up deletes none of their entries.+ move[:jar]&.id == wise_account.id || (stored && Array(move[:candidates]).include?(wise_account))+ else+ standard_interbalance_for_account?(activity, wise_account)+ end+ routed && takes_row?(wise_account, debit: leaves_balance?(activity, wise_account)) { activity_created_at(activity) }+ when :holding+ holding_balance(activity)[:balance]&.id == wise_account.id &&+ (wise_account.jar? || ignore_statements || !statement_covered?(wise_account) { activity_created_at(activity) })+ when :single_leg+ single_leg_for_account?(activity, wise_account, ignore_statements: ignore_statements)+ else+ false+ end+ end- case type- when "INTERBALANCE"- if wise_account.jar?- jar_name_in_title = activity["title"].to_s.scan(/<strong>([^<]+)<\/strong>/).flatten.last.to_s.strip- jar_name_in_title.present? && jar_name_in_title.casecmp?(wise_account.name.to_s.strip)+ # The jar a move between a balance and a jar belongs to, decided once+ # per sync and activity: { jar: } or { state: } when there is none:+ # :conversion a conversion between two balances, no jar named+ # :unidentified a move in one currency whose jar Sure cannot tell+ # :ambiguous several jars fit (`candidates:`)+ # A move first routed to a jar stays with it (#routing_decision). Else+ # the title decides: a jar in the currency of the move's jar side+ # (#jar_currency) that Wise has called by the name it gives+ # (WiseAccount#known_names); in one currency, a title naming that+ # currency (the balance) is a withdrawal from the only jar in it. Of+ # several that fit, the one an earlier sync stored the move on keeps it.+ def jar_move(activity)+ (@jar_moves ||= {})[decision_key(activity)] ||= begin+ time = activity_created_at(activity)+ currency = jar_currency(activity)+ decided = routing_decision(activity, time)+ if decided&.jar? && decided.currency == currency+ { jar: decided }else- true+ named = WiseActivity::Processor.named_balance(activity)+ candidates, none =+ if WiseActivity::Processor.conversion_currencies(activity) then [ jars_named(named, [ currency ], time), :conversion ]+ elsif named.present? && named.casecmp?(currency.to_s) then [ jars_in(currency, time), :unidentified ]+ else [ jars_named(named, [ currency ].compact, time), :unidentified ]+ end+ pick_jar(activity, candidates, none: none)end- when "BALANCE_ASSET_FEE", "BALANCE_CASHBACK"- wise_account.jar?- else- falseendend- # Called after entries have been created to link interbalance pairs as Sure Transfers.- def link_interbalance_transfers!- Array(@interbalance_activities).each do |activity|- resource_id = activity.dig("resource", "id").to_s- next if resource_id.blank?+ # The one jar that fits; of several, the one an earlier sync stored the+ # move on, as no title tells them apart (several or none of them hold+ # it: :ambiguous, see #activity_for_account?).+ def pick_jar(activity, candidates, none:)+ return { state: none } if candidates.empty?+ return { jar: candidates.first } if candidates.one?- inflow_entry = entry_by_external_id("wise_interbalance_#{resource_id}_inflow")- outflow_entry = entry_by_external_id("wise_interbalance_#{resource_id}_outflow")+ holders = candidates.select { |jar| stored_on?(jar, activity) }+ holders.one? ? { jar: holders.first } : { state: :ambiguous, candidates: candidates }+ end- next unless inflow_entry && outflow_entry+ # The currency of a jar move's jar side. Between two currencies the+ # title points at it: a deposit ("To <strong>Holiday</strong>") credits+ # the jar in the primary currency, money taken "From" a jar is debited+ # from it in the secondary one (WiseActivity::Processor.jar_deposit?).+ # So a jar of that name in the other currency is never it.+ def jar_currency(activity)+ conversion = WiseActivity::Processor.conversion_currencies(activity)+ return move_currencies(activity).first unless conversion- inflow_txn = inflow_entry.entryable- outflow_txn = outflow_entry.entryable+ WiseActivity::Processor.jar_deposit?(activity) ? conversion[:target] : conversion[:source]+ end- next unless inflow_txn.is_a?(Transaction) && outflow_txn.is_a?(Transaction)- next if Transfer.exists?(inflow_transaction_id: inflow_txn.id)- next if Transfer.exists?(outflow_transaction_id: outflow_txn.id)+ # Whether the activity is in the balance's payload as an earlier sync+ # stored it.+ def stored_on?(wise_account, activity)+ key = decision_key(activity)+ Array(wise_account.raw_transactions_payload).any? { |row| WiseActivity::Processor.activity_row?(row) && decision_key(row) == key }+ end- transfer = Transfer.new(- inflow_transaction: inflow_txn,- outflow_transaction: outflow_txn,- status: "confirmed"- )+ # The balance interest, cashback or a fee on holdings goes to, once per+ # sync and activity: { balance: } or { state: } when there is none+ # (:ambiguous, :unrouted). A row first routed to a balance stays with it+ # (#routing_decision). Else the jar or invested balance in its currency,+ # the jar the title names when there are several, and without one the+ # balance in its currency (`fallback: true`).+ def holding_balance(activity)+ (@holding_balances ||= {})[decision_key(activity)] ||= begin+ time = activity_created_at(activity)+ currency = WiseActivity::Processor.balance_amount(activity)&.dig(:currency)+ debit = WiseActivity::Processor.direction(activity) == :debit+ decided = routing_decision(activity, time)+ if decided && decided.currency == currency+ { balance: decided }+ else+ holders = jars_in(currency, time) + standard_balances_in(currency, time, debit: debit).select { |wise_account| invested?(wise_account) }+ if holders.size > 1+ named = jars_named(WiseActivity::Processor.named_balance(activity), [ currency ], time) & holders+ named.one? ? { balance: named.first } : { state: :ambiguous }+ elsif holders.one?+ { balance: holders.first }+ else+ standard = standard_balances_in(currency, time, debit: debit)+ if standard.one? then { balance: standard.first, fallback: true }+ elsif standard.empty? then { state: :unrouted }+ else { state: :ambiguous }+ end+ end+ end+ end+ end++ # The balance a stored copy of the row says it was first routed to+ # (ROUTING_DECISION_KEY), as long as that balance still takes it.+ def routing_decision(activity, time)+ balance_id = activity[ROUTING_DECISION_KEY].presence || routing_decisions[decision_key(activity)]+ decided = accounts_by_balance_id[balance_id.to_s] if balance_id.present?+ decided if decided && takes_row?(decided, debit: WiseActivity::Processor.direction(activity) == :debit) { time }+ end- unless transfer.save- Rails.logger.warn "WiseItem::Importer - Could not link interbalance #{resource_id}: #{transfer.errors.full_messages.join(", ")}"+ # { activity id => balance id } from every stored copy that carries one.+ def routing_decisions+ @routing_decisions ||= wise_item.wise_accounts.each_with_object({}) do |wise_account, decisions|+ Array(wise_account.raw_transactions_payload).each do |row|+ next unless WiseActivity::Processor.activity_row?(row) && row[ROUTING_DECISION_KEY].present?++ decisions[decision_key(row)] ||= row[ROUTING_DECISION_KEY].to_send- rescue => e- Rails.logger.error "WiseItem::Importer - Error linking interbalance #{resource_id}: #{e.message}"endend- def entry_by_external_id(external_id)- Entry.joins(account: :account_providers)- .where(external_id: external_id, source: "wise")- .where(account_providers: { provider_type: "WiseAccount" })- .joins("INNER JOIN wise_accounts ON wise_accounts.id = account_providers.provider_id")- .where(wise_accounts: { wise_item_id: wise_item.id })- .first+ # Writes where a jar move or a row of interest or fees was routed onto+ # the copy about to be stored, and removes a stale mark. Other rows are+ # left as they are. Interest that fell back to the balance in its+ # currency while the jar list failed is not marked, so the jar it may+ # belong to takes it once listed.+ def with_routing_decision(row)+ return row unless WiseActivity::Processor.activity_row?(row)++ type = row["type"].to_s+ decided =+ if WiseActivity::Processor::TWO_LEG_TYPES.include?(type) then jar_move(row)[:jar]+ elsif WiseActivity::Processor::HOLDING_TYPES.include?(type)+ route = holding_balance(row)+ route[:balance] unless route[:fallback] && @balance_list_failed+ else return row+ end+ decided ? row.merge(ROUTING_DECISION_KEY => decided.balance_id.to_s) : row.except(ROUTING_DECISION_KEY)end- def with_rate_limit_retry(max_retries: 3)- retries = 0- begin- yield- rescue Provider::Wise::WiseError => e- raise unless e.error_type == :rate_limited && retries < max_retries- retries += 1- sleep(2 ** retries)- retry+ def decision_key(activity)+ activity["id"].presence&.to_s || activity.to_json+ end++ # The currencies a move between two balances is in: the credited+ # (primary) one first.+ def move_currencies(activity)+ %w[primaryAmount secondaryAmount].filter_map { |key| WiseActivity::Processor.parse_money(activity[key]).last }.uniq+ end++ def jars_in(currency, time)+ jars.select { |jar| jar.currency == currency && takes_row?(jar) { time } }+ end++ # Jars in one of the currencies that Wise calls by this name now or, if+ # none, that Wise called by it before (WiseAccount#known_names): a title+ # names a jar as it was called then, but a jar opened under a name+ # another jar had before takes the moves naming it. A bare currency+ # code names that currency's STANDARD balance ("To <strong>EUR</strong>"),+ # not a jar called like it.+ def jars_named(named, currencies, time)+ return [] if named.blank? || standard_currencies.include?(named.upcase)++ named_jars = jars.select do |jar|+ currencies.include?(jar.currency) && jar.known_names.any? { |name| name.casecmp?(named) } && takes_row?(jar) { time }end+ named_jars.select { |jar| jar.current_name&.casecmp?(named) }.presence || named_jarsend- def transfer_cutoff- return sync_start_date_value.to_time if sync_start_date.present? || wise_item.sync_start_date.present?+ def standard_balances_in(currency, time, debit: false)+ wise_item.wise_accounts.reject(&:jar?).select { |wise_account| wise_account.currency == currency && takes_row?(wise_account, debit: debit) { time } }+ end- # Use last_synced_at only if we actually have stored transfers — otherwise fall back to full history.- has_stored_transfers = wise_item.wise_accounts.any? { |wa| wa.raw_transactions_payload.present? }+ def invested?(wise_account)+ INVESTED_STATES.include?(wise_account.raw_payload["investmentState"]) if wise_account.raw_payload.is_a?(Hash)+ end- if has_stored_transfers && wise_item.last_synced_at.present?- wise_item.last_synced_at - 7.days- elsif full_history?- FULL_HISTORY_START_DATE.beginning_of_day- else- DEFAULT_HISTORY_DAYS.days.ago+ def jars+ @jars ||= wise_item.wise_accounts.select(&:jar?)+ end++ def accounts_by_balance_id+ @accounts_by_balance_id ||= wise_item.wise_accounts.index_by { |wise_account| wise_account.balance_id.to_s }+ end++ # Every STANDARD balance's currency, closed ones included.+ def standard_currencies+ @standard_currencies ||= wise_item.wise_accounts.reject(&:jar?).map(&:currency).to_set+ end++ # How an activity reaches the balances:+ # :conversion both sides of a move between the profile's own balances+ # :holding interest, cashback and fees on holdings+ # :single_leg the balance(s) that paid or received it+ # :transfer none: it enriches a transfer Sure has (#enrich_transfer)+ # :deferred none yet: a credit for a transfer this sync could not+ # look for, as its transfer list did not arrive+ # :unbooked none: a type Sure does not book (wrapper types whose+ # money moves as /v1/transfers transfers, card checks,+ # types not seen yet), or a debit for an unknown transfer+ def activity_route(activity, stored: false)+ type = activity["type"].to_s+ if WiseActivity::Processor::TWO_LEG_TYPES.include?(type) then :conversion+ elsif WiseActivity::Processor::HOLDING_TYPES.include?(type) then :holding+ elsif WiseActivity::Processor::SINGLE_LEG_TYPES.include?(type) then :single_leg+ elsif WiseActivity::Processor::TRANSFER_TYPES.include?(type) then transfer_activity_route(activity, stored: stored)+ else :unbookedendend- def sync_start_date_value- (sync_start_date.presence || wise_item.sync_start_date.presence || DEFAULT_HISTORY_DAYS.days.ago).to_date+ # The activity of a transfer Sure has only enriches it. A credit for one+ # it does not have (paid into the account details from a bank or another+ # Wise profile, which /v1/transfers does not list) is booked, but a new+ # one only when this sync's transfer list would show that transfer: not+ # when the list did not arrive, nor for an activity created after the+ # list was read (its transfer may be younger than the list). So a+ # transfer that is merely late is not booked twice. A row stored that+ # way stays.+ def transfer_activity_route(activity, stored:)+ resource = activity["resource"].is_a?(Hash) ? activity["resource"] : {}+ of_transfer = resource["type"] == "TRANSFER"+ return :transfer if of_transfer && @known_transfer_ids.include?(resource["id"].to_s)+ return :unbooked unless WiseActivity::Processor.direction(activity) == :credit+ return :deferred if of_transfer && !stored && !transfer_list_covers?(activity)++ :single_legend- def full_history?- wise_item.import_all_history?+ # Whether this sync's transfer list arrived and was read after the+ # activity was created (#transfer_activity_route).+ def transfer_list_covers?(activity)+ listed = @fetched_windows[:transfers]+ return false unless listed++ created_at = activity_created_at(activity)+ created_at.nil? || created_at < listed[:through]end- # Full-history imports start from the balance's creation time when Wise- # reports one, falling back to a far-past date so every historical row is- # fetched regardless.- def full_history_start_date(wise_account)- raw = wise_account.raw_payload&.dig("creationTime")- return FULL_HISTORY_START_DATE if raw.blank?+ def single_leg_for_account?(activity, wise_account, ignore_statements: false)+ return false if wise_account.jar?+ return false if !ignore_statements && statement_covered?(wise_account) { activity_created_at(activity) }- Time.parse(raw.to_s).to_date- rescue ArgumentError, TypeError- FULL_HISTORY_START_DATE+ funding = WiseActivity::Processor.balance_amount(activity)+ funding.present? && funding[:currencies].include?(wise_account.currency) &&+ takes_row?(wise_account, debit: funding[:direction] == :debit) { activity_created_at(activity) }end- def parse_transaction_date(transaction)- raw = transaction["created"] || transaction["createdOn"] || transaction["date"]- return nil if raw.blank?+ # Whether a balance's leg of a move between two balances takes money from+ # it: a conversion's source, a balance's move into a jar, a jar's move out.+ def leaves_balance?(activity, wise_account)+ conversion = WiseActivity::Processor.conversion_currencies(activity)+ return conversion[:source] == wise_account.currency if conversion- Time.parse(raw.to_s).to_date- rescue ArgumentError, TypeError- nil+ wise_account.jar? != WiseActivity::Processor.jar_deposit?(activity)+ end++ # Transfers Sure has: listed or read this sync, or stored on any balance.+ def known_transfer_ids(transfers)+ stored = wise_item.wise_accounts.flat_map do |wise_account|+ Array(wise_account.raw_transactions_payload).select { |row| transfer_row?(row) }+ end+ (transfers + stored).filter_map { |transfer| transfer["id"].presence&.to_s }.to_set+ end++ # Balances whose statements carry their card payments and other+ # single-leg movements: those that hold statement rows, and those whose+ # statements this sync returned rows for.+ def statement_covered_account_ids(statements)+ wise_item.wise_accounts.filter_map do |wise_account|+ stored = Array(wise_account.raw_transactions_payload).any? { |row| row["wise_statement"].present? }+ wise_account.id if stored || Array(statements[wise_account.id]).any?+ end.to_set+ end++ # Whether a balance's statements carry its movement of the time the block+ # returns (see #statement_covered_account_ids). Once Wise refuses them,+ # they carry what happened until they last reached (#statement_cutoffs),+ # and the balance takes what happened after from transfers and+ # activities, which hand it over to the statement rows when they work+ # again (WiseItem::StatementMigration).+ def statement_covered?(wise_account)+ return false unless @statement_covered_account_ids.include?(wise_account.id)++ cutoff = @statement_cutoffs[wise_account.id]+ return true unless cutoff++ time = yield+ time.nil? || time <= cutoff+ end++ # { wise_account id => time } for each balance whose statements Wise+ # refused this sync: the end of their coverage, else its latest statement+ # row.+ def statement_cutoffs+ wise_item.wise_accounts.select { |wise_account| @statements_refused_accounts.include?(wise_account.id) }.to_h do |wise_account|+ statement_rows = Array(wise_account.raw_transactions_payload).select { |row| row["wise_statement"].present? }+ latest = statement_rows.filter_map { |row| WiseStatement::Processor.posted_at(row) }.max+ [ wise_account.id, wise_account.statements_coverage&.dig(:through) || latest ]+ end.compactend- def parse_transfer_date(raw)- DateTime.parse(raw.to_s).to_time- rescue- Time.current+ def open_standard_currencies+ @open_standard_currencies ||= wise_item.wise_accounts.reject { |wise_account| wise_account.jar? || wise_account.closed? }+ .map(&:currency).to_set+ end++ # Tells support, once per sync, about this sync's activities that book on+ # no balance or that Sure books on its own judgement: types it does not+ # book (counted per type), credits for transfers it does not have+ # (booked, or deferred while the transfer list failed), activities in a+ # currency no balance holds, split payments in a currency none of their+ # balances is in (booked in full on the first one until the balance+ # replay finds the parts), jar moves whose jar the title does not tell+ # (#jar_move: booked on no jar) and interest or fees several jars or+ # invested balances could hold (#holding_balance: booked nowhere).+ # Counts and currencies only.+ def report_activity_routing(activities)+ unbooked = Hash.new(0)+ unmatched = 0+ deferred = 0+ unrouted = 0+ unrouted_currencies = Set.new+ foreign_splits = 0+ unclear_jar_moves = Hash.new(0)+ ambiguous_holdings = 0++ activities.each do |activity|+ case activity_route(activity)+ when :unbooked+ unbooked[activity["type"].to_s.presence || "unknown"] += 1+ when :deferred+ deferred += 1+ when :conversion+ state = jar_move(activity)[:state]+ unclear_jar_moves[state] += 1 if %i[ambiguous unidentified].include?(state)+ when :holding+ case holding_balance(activity)[:state]+ when :ambiguous+ ambiguous_holdings += 1+ when :unrouted+ unrouted += 1+ unrouted_currencies.merge(Array(WiseActivity::Processor.balance_amount(activity)&.dig(:currencies)))+ end+ when :single_leg+ unmatched += 1 if WiseActivity::Processor::TRANSFER_TYPES.include?(activity["type"].to_s)+ funding = WiseActivity::Processor.balance_amount(activity)+ currencies = Array(funding&.dig(:currencies))+ foreign_splits += 1 if funding&.dig(:split) && currencies.exclude?(funding[:currency])+ next if currencies.any? { |currency| open_standard_currencies.include?(currency) }++ unrouted += 1+ unrouted_currencies.merge(currencies)+ end+ end+ unclear = unrouted + foreign_splits + unclear_jar_moves.values.sum + ambiguous_holdings+ return if unbooked.empty? && (unmatched + deferred + unclear).zero?++ capture_debug_log(+ category: "provider_sync",+ level: unclear.positive? ? "warn" : "info",+ message: "WiseItem::Importer - Wise activities this sync that book on no balance or on one side only, or that " \+ "are booked as payments into the account for transfers Sure does not have",+ operation: "activity_routing",+ unbooked_type_counts: unbooked.presence,+ unmatched_transfer_count: unmatched.nonzero?,+ deferred_transfer_count: deferred.nonzero?,+ unrouted_count: unrouted.nonzero?,+ unrouted_currencies: unrouted_currencies.to_a.presence,+ foreign_split_count: foreign_splits.nonzero?,+ ambiguous_jar_move_count: unclear_jar_moves[:ambiguous].nonzero?,+ unidentified_jar_move_count: unclear_jar_moves[:unidentified].nonzero?,+ ambiguous_holding_count: ambiguous_holdings.nonzero?+ )+ end++ # A STANDARD balance takes its side of a conversion, the source or the+ # target currency, unless a jar holds that side: a jar move between two+ # currencies, whose jar side is in the currency its title points at+ # (#jar_currency), also while it is unclear which of several jars it+ # was. It always takes its side of a jar move in its own currency, also+ # when the jar is unknown.+ def standard_interbalance_for_account?(activity, wise_account)+ conversion = WiseActivity::Processor.conversion_currencies(activity)++ if conversion+ jar_side = jar_currency(activity) unless jar_move(activity)[:state] == :conversion+ conversion.values.include?(wise_account.currency) && wise_account.currency != jar_side+ else+ currency = WiseActivity::Processor.parse_money(activity["primaryAmount"]).last+ currency.blank? || currency == wise_account.currency+ end+ end++ def full_history?+ wise_item.import_all_history?enddef credentials_error?(error)@@ -612,6 +2023,9 @@ class WiseItem::Importerdef failed_result(error){success: false,+ complete: false,+ coverage_upgraded: false,+ fetch_failures: [ @fetch_failures, 1 ].max,error: error,accounts_created: 0,accounts_updated: 0,diff --git a/app/models/wise_item/interbalance_linker.rb b/app/models/wise_item/interbalance_linker.rbnew file mode 100644index 0000000000..e9853ba1c2--- /dev/null+++ b/app/models/wise_item/interbalance_linker.rb@@ -0,0 +1,329 @@+# frozen_string_literal: true++# Links the two legs of each move between one Wise profile's own balances -- a+# currency conversion or a Jar move -- as a confirmed Transfer.+#+# WiseActivity::Processor books such a move (INTERBALANCE, and AUTO_CONVERSION+# through the same two-leg path) as wise_interbalance_<resource id>_outflow on+# the balance the money left and wise_interbalance_<resource id>_inflow on the+# balance it reached, both as standard transactions. Wise's activity feed is+# the authority on that pair, so the link is confirmed straight away and the+# legs get the kinds Transfer#confirm! gives a match the user confirms;+# without them every conversion counts as income on one balance and spending+# on the other. A transfer from one balance into another's own account+# details ("send to myself") is linked the same way from the two statement+# rows that carry it (#link_sends_to_own_balances).+class WiseItem::InterbalanceLinker+ LEG_EXTERNAL_ID = /\Awise_interbalance_(?<resource_id>.+)_(?<side>inflow|outflow)\z/+ # The entry of a transfer's statement row, under the reference Wise gives+ # the transfer in every balance's statement (WiseStatement::Processor).+ TRANSFER_STATEMENT_EXTERNAL_ID = /\Awise_statement_(?<reference>TRANSFER-\d+)(?:_(?<suffix>.+))?\z/+ # Activity types whose payload rows describe a two-leg move (the ones+ # WiseActivity::Processor books as these legs), used to find the currency+ # the money left in.+ TWO_LEG_ACTIVITY_TYPES = WiseActivity::Processor::TWO_LEG_TYPES+ # A pair that cannot be linked fails again on every sync, so problems go into+ # one debug log entry per run, with this many listed.+ MAX_LOGGED_PROBLEMS = 20++ attr_reader :wise_item, :stats++ # Whether a transfer is a link of the kind this linker makes: the inflow+ # and the outflow leg of one move (the same resource id) on the given+ # accounts, with nothing a person added to it (notes, or a fee, which goes+ # with the transfer when a leg is deleted).+ def self.system_link?(transfer, account_ids)+ sides = { "inflow" => transfer.inflow_transaction&.entry, "outflow" => transfer.outflow_transaction&.entry }+ resource_ids = sides.map do |side, entry|+ match = LEG_EXTERNAL_ID.match(entry.external_id.to_s) if entry&.source == "wise" && account_ids.include?(entry.account_id)+ match[:resource_id] if match && match[:side] == side+ end++ resource_ids.first.present? && resource_ids.uniq.one? && transfer.notes.blank? && !transfer.fee_transactions.exists?+ end++ # Whether the linker links a transfer's legs again on the next sync after+ # a person removes the transfer: one of the links it makes, between two+ # balances of one connection. Removing such a link rejects it instead+ # (TransfersController#destroy), so it stays removed.+ def self.relinks?(transfer)+ entries = [ transfer.inflow_transaction&.entry, transfer.outflow_transaction&.entry ]+ return false unless entries.all? { |entry| entry&.source == "wise" }++ item_ids = WiseAccount.joins(:account_provider).where(account_providers: { account_id: entries.map(&:account_id) }).distinct.pluck(:wise_item_id)+ return false unless item_ids.one?++ system_link?(transfer, WiseItem.find(item_ids.first).accounts.pluck(:id).to_set) || send_link?(transfer)+ end++ # A link of the two statement rows of a "send to myself": one reference,+ # money out of one balance and into another, nothing a person added.+ def self.send_link?(transfer)+ inflow, outflow = transfer.inflow_transaction&.entry, transfer.outflow_transaction&.entry+ references = [ inflow, outflow ].map { |entry| transfer_reference(entry&.external_id) }+ references.first.present? && references.uniq.one? && inflow.account_id != outflow.account_id &&+ transfer.notes.blank? && !transfer.fee_transactions.exists?+ end++ # The TRANSFER-<id> reference of a transfer's statement row entry; nil for+ # its fee's and any other entry.+ def self.transfer_reference(external_id)+ match = TRANSFER_STATEMENT_EXTERNAL_ID.match(external_id.to_s)+ match[:reference] if match && !match[:suffix].to_s.end_with?("fee")+ end++ def initialize(wise_item)+ @wise_item = wise_item+ @stats = Hash.new(0)+ @problems = []+ end++ def link!+ return stats if wise_accounts_by_account_id.empty?++ legs_by_resource_id.each do |resource_id, legs|+ legs[:inflow].each { |inflow| link_leg(resource_id, inflow, legs[:outflow]) }+ end+ link_sends_to_own_balances+ discard_suggestions_within_item!+ log_outcome+ stats+ end++ private++ def wise_accounts_by_account_id+ @wise_accounts_by_account_id ||= wise_item.wise_accounts+ .joins(:account_provider)+ .includes(:account_provider)+ .index_by { |wise_account| wise_account.account_provider.account_id }+ end++ def item_account_ids+ wise_accounts_by_account_id.keys+ end++ # { resource_id => { inflow: [entries], outflow: [entries] } }+ def legs_by_resource_id+ Entry.where(source: "wise", account_id: item_account_ids, entryable_type: "Transaction")+ .where("external_id LIKE ?", "#{Entry.sanitize_sql_like("wise_interbalance_")}%")+ .includes(:entryable)+ .order(:date, :external_id)+ .each_with_object({}) do |entry, legs|+ match = LEG_EXTERNAL_ID.match(entry.external_id)+ next unless match++ sides = legs[match[:resource_id]] ||= { inflow: [], outflow: [] }+ sides[match[:side].to_sym] << entry+ end+ end++ def link_leg(resource_id, inflow, outflows)+ outflow = outflow_for(resource_id, inflow, outflows)+ link_entries(inflow, outflow, resource_id: resource_id) if outflow+ end++ def link_entries(inflow, outflow, **details)+ # A savepoint even when the caller holds a transaction (a lock, say), so+ # a refused link rolls back only its own changes, the replaced+ # suggestions included.+ outcome = Transfer.transaction(requires_new: true) { link_pair(inflow.entryable, outflow.entryable) }+ stats[outcome] += 1+ add_problem(:kept_link_to_copy, inflow, **details) if outcome == :kept_link_to_copy+ rescue => e+ stats[:failed] += 1+ errors = e.is_a?(ActiveRecord::RecordInvalid) ? e.record.errors.full_messages : [ e.message ]+ add_problem(:link_failed, inflow, **details, error_class: e.class.name, errors: errors)+ end++ # A transfer from one of the profile's balances into another's own+ # account details is in both balances' statements under one+ # TRANSFER-<id> reference: a debit where the money left and a credit+ # where it arrived. Linked like a conversion when the reference has one+ # of each on two balances (a refund credit is on the paying balance);+ # the automatic matcher pairs no two balances of one connection.+ def link_sends_to_own_balances+ sends = Entry.where(source: "wise", account_id: item_account_ids, entryable_type: "Transaction")+ .where("external_id LIKE ?", "#{Entry.sanitize_sql_like("wise_statement_TRANSFER-")}%")+ .includes(:entryable)+ .group_by { |entry| self.class.transfer_reference(entry.external_id) }+ sends.except(nil).each do |reference, entries|+ outflows, inflows = entries.partition { |entry| entry.amount.positive? }+ next unless outflows.one? && inflows.one? && outflows.first.account_id != inflows.first.account_id++ link_entries(inflows.first, outflows.first, reference: reference)+ end+ end++ # The leg on another balance of this item with the same resource id. An+ # install synced before conversions were routed by currency can also hold+ # legs that routing booked on every STANDARD balance (the inflow's own one+ # included), so only the leg on the balance in the move's source currency+ # qualifies; without the move's stored row, only a leg that is not such+ # a copy (#pre_routing_copy?). Anything still ambiguous stays unlinked+ # and is logged rather than guessed.+ def outflow_for(resource_id, inflow, outflows)+ candidates = outflows.reject { |leg| leg.account_id == inflow.account_id }+ return if candidates.empty?++ source_currency = source_currency_for(resource_id)+ matches =+ if source_currency+ candidates.select { |leg| balance_currency(leg) == source_currency }+ else+ candidates.reject { |leg| pre_routing_copy?(leg) }+ end+ return matches.first if matches.one?++ stats[:ambiguous] += 1+ add_problem(:no_single_outflow_leg, inflow, resource_id: resource_id, candidate_count: candidates.size,+ source_currency_match_count: source_currency ? matches.size : nil)+ nil+ end++ def link_pair(inflow_txn, outflow_txn)+ pair, others = transfers_touching(inflow_txn, outflow_txn).partition do |transfer|+ transfer.inflow_transaction_id == inflow_txn.id && transfer.outflow_transaction_id == outflow_txn.id+ end+ pair = pair.first++ return repair_kinds(pair, inflow_txn, outflow_txn) if pair&.confirmed?++ # A leg the user confirmed against another transaction is their call,+ # but not a link this linker made to a copy of the other leg that+ # routing by currency has since replaced (#linked_to_copy?), or one it+ # made the wrong way round (#reversed_link?).+ leg_ids = [ inflow_txn.id, outflow_txn.id ]+ stale, confirmed = others.select(&:confirmed?).partition do |transfer|+ reversed_link?(transfer, inflow_txn, outflow_txn) ||+ (linked_to_copy?(transfer, leg_ids) && self.class.system_link?(transfer, item_account_ids))+ end+ if confirmed.any?+ return confirmed.any? { |transfer| linked_to_copy?(transfer, leg_ids) } ? :kept_link_to_copy : :kept_confirmed_elsewhere+ end+ return :rejected if RejectedTransfer.exists?(inflow_transaction_id: inflow_txn.id, outflow_transaction_id: outflow_txn.id)++ # Pending transfers are the automatic matcher's guesses; Uniqueness+ # allows one transfer per leg, so they make way for the feed's pair. An+ # exact guess is confirmed in place.+ others.each(&:destroy!)+ transfer = pair || Transfer.new(inflow_transaction: inflow_txn, outflow_transaction: outflow_txn, status: "confirmed")+ transfer.save! if transfer.new_record?+ transfer.confirm!++ stats[:replaced_stale_links] += stale.size+ stats[:replaced_suggestions] += others.size - stale.size+ :linked+ end++ # A link of these two legs with inflow and outflow swapped, nothing a+ # person added: what the linker made of a jar withdrawal an older build+ # booked as a deposit, before the legs' sides followed the money+ # (WiseActivity::Processor#superseded_external_ids renames them).+ def reversed_link?(transfer, inflow_txn, outflow_txn)+ transfer.inflow_transaction_id == outflow_txn.id && transfer.outflow_transaction_id == inflow_txn.id &&+ transfer.notes.blank? && !transfer.fee_transactions.exists?+ end++ # Whether a transfer pairs one of the given legs with a copy of the other+ # leg (#pre_routing_copy?): the linker before routing by currency+ # confirmed a jar move's leg against whichever copy it found first.+ def linked_to_copy?(transfer, leg_ids)+ counterpart = [ transfer.inflow_transaction, transfer.outflow_transaction ].compact.find { |txn| leg_ids.exclude?(txn.id) }+ counterpart&.entry.present? && pre_routing_copy?(counterpart.entry)+ end++ # A leg booked in another currency than its balance's: routing before+ # conversions and jar moves went by currency booked a copy of each on+ # every STANDARD balance, in the move's currency, while+ # WiseActivity::Processor books every leg in its own balance's currency.+ def pre_routing_copy?(entry)+ currency = balance_currency(entry)+ entry.source == "wise" && currency.present? && entry.currency != currency+ end++ def transfers_touching(*transactions)+ ids = transactions.map(&:id)+ Transfer.where(inflow_transaction_id: ids).or(Transfer.where(outflow_transaction_id: ids)).to_a+ end++ # Links made before the legs got transfer kinds left both standard.+ def repair_kinds(transfer, inflow_txn, outflow_txn)+ return :already_linked unless inflow_txn.standard? || outflow_txn.standard?++ transfer.confirm!+ :repaired+ end++ # The automatic matcher no longer pairs two balances of one item (see+ # Family::AutoTransferMatchable#auto_match_transfers!), but suggestions it+ # made before -- a GBP top-up "matching" a USD payout -- would stay+ # pending forever.+ def discard_suggestions_within_item!+ item_transaction_ids = Entry.where(account_id: item_account_ids, entryable_type: "Transaction").select(:entryable_id)++ Transfer.pending+ .where(inflow_transaction_id: item_transaction_ids, outflow_transaction_id: item_transaction_ids)+ .find_each do |transfer|+ transfer.destroy!+ stats[:discarded_suggestions] += 1+ end+ rescue => e+ add_problem(:discard_failed, nil, error_class: e.class.name, errors: [ e.message ])+ end++ # The currency the money left in, from the activity row the legs were+ # booked from: secondaryAmount for a conversion, primaryAmount for a move+ # within one currency. Nil when no stored row describes the move.+ def source_currency_for(resource_id)+ row = two_leg_rows[resource_id]+ return unless row++ money_currency(row["secondaryAmount"]) || money_currency(row["primaryAmount"])+ end++ def two_leg_rows+ @two_leg_rows ||= wise_accounts_by_account_id.each_value.with_object({}) do |wise_account, rows|+ Array(wise_account.raw_transactions_payload).each do |row|+ next unless row.is_a?(Hash) && TWO_LEG_ACTIVITY_TYPES.include?(row["type"])++ resource_id = row.dig("resource", "id").to_s+ rows[resource_id] ||= row if resource_id.present?+ end+ end+ end++ def money_currency(amount)+ WiseActivity::Processor.parse_money(amount).last.presence+ end++ def balance_currency(leg)+ wise_accounts_by_account_id[leg.account_id]&.currency+ end++ def add_problem(reason, inflow, **details)+ wise_account = inflow && wise_accounts_by_account_id[inflow.account_id]+ @problems << { reason: reason, wise_account_id: wise_account&.id, **details }.compact+ end++ def log_outcome+ counts = stats.slice(:linked, :repaired, :replaced_suggestions, :replaced_stale_links, :discarded_suggestions, :already_linked,+ :kept_confirmed_elsewhere, :kept_link_to_copy, :rejected, :ambiguous, :failed)+ message = "WiseItem::InterbalanceLinker - #{counts.map { |key, count| "#{key}: #{count}" }.join(", ").presence || "nothing to link"}"+ Rails.logger.public_send(@problems.any? ? :warn : :info, message)++ # Problems, kinds changed on existing entries, or links and suggestions+ # that went away are worth a trace for support. Routine new links are not.+ return if @problems.empty? && stats.values_at(:repaired, :replaced_suggestions, :replaced_stale_links, :discarded_suggestions).sum.zero?++ DebugLogEntry.capture(+ category: @problems.any? ? "provider_sync_error" : "provider_sync",+ level: @problems.any? ? "warn" : "info",+ message: message,+ source: self.class.name,+ provider_key: "wise",+ family: wise_item.family,+ metadata: { wise_item_id: wise_item.id, **counts, problems: @problems.first(MAX_LOGGED_PROBLEMS).presence }.compact+ )+ end+enddiff --git a/app/models/wise_item/statement_migration.rb b/app/models/wise_item/statement_migration.rbnew file mode 100644index 0000000000..04dc9ba4dc--- /dev/null+++ b/app/models/wise_item/statement_migration.rb@@ -0,0 +1,400 @@+# frozen_string_literal: true++# Hands a balance's movements over to its statement rows. Before the+# balance had statements, Sure booked them from /v1/transfers rows+# (wise_transfer_<id>, wise_fee_<id>, wise_refund_<id>) and activity rows+# (wise_activity_<id>); its statement rows carry the same movements under+# their own ids. Each such row is matched to the statement row carrying it,+# which takes the row's entries over (WiseAccount::Transactions::Processor+# renames them before it books, so they keep what a person did to them)+# instead of booking the movement a second time:+#+# - a transfer by the statement row's reference ("TRANSFER-<id>") with the+# sign of its movement, else by a TRANSFER statement row in its currency,+# of its amount (a payout's gross debit, what a pay-in credited) and+# within a day of it;+# - an activity by "CARD-<resource id>", else by a statement row of the+# same sign and amount within a day. Wise documents neither reference+# format.+#+# A matched row books nothing more ("wise_superseded_by"; the statement row+# names the entries it takes over in "wise_supersedes") and leaves the+# payload once the account has no entry under its ids. While a transfer that+# books, created inside the statements' window, has no statement row, the+# balance keeps its /v1/transfers rows: they keep booking, Sure keeps+# fetching transfers for it, and none leaves. An activity inside the window+# that matches nothing is dropped, as some statement row carries its+# movement; one from before the window stays.+#+# Conversions between the profile's own balances (INTERBALANCE,+# AUTO_CONVERSION) stay on the balance: their rows are verified and link as+# transfers. A statement CONVERSION or *_CROSS_BALANCE row books nothing when+# such a conversion moved the same amount in the same currency and direction+# on this balance within a day.+#+# Wise reuses a transfer's reference on its refund, so statement rows that+# share one get their own ids ("wise_statement_id"): the earliest keeps+# wise_statement_<ref>, a later one wise_statement_<ref>_<type>_<yyyymmdd>+# (its amount is added when that is taken too). An id stays with its row+# once given, and a stored row without one booked under the plain reference+# (.with_booked_ids): a row that turns up later with the reference, such as+# the debit of a refund whose window grew back, gets an id of its own+# rather than taking over the entry the refund booked.+#+# The other marks are worked out again from the rows on every sync.+class WiseItem::StatementMigration+ MARKER_KEYS = %w[wise_superseded_by wise_supersedes wise_statement_id].freeze+ WORKED_OUT_KEYS = %w[wise_superseded_by wise_supersedes].freeze+ # Amounts within this are the same movement.+ TOLERANCE = BigDecimal("0.01")+ TRANSFER_DETAILS_TYPE = "TRANSFER"++ # rows: what is left of the payload; counts: transfers_matched,+ # activities_matched, conversions_matched, transfers_unmatched (booked+ # transfers inside the window without a statement row), activities_unmatched+ # (booked activities dropped without one) and retired.+ Result = Data.define(:rows, :counts)++ # The stored statement rows of a balance with the id each booked under:+ # one without an id booked under its plain reference, as Sure gave that id+ # to the only, else the earliest, row with a reference (an older build+ # kept one row per reference). Of several such rows only that one keeps+ # it.+ def self.with_booked_ids(statement_rows)+ unmarked = statement_rows.select { |row| row["wise_statement_id"].blank? && row["referenceNumber"].present? }+ marked = statement_rows.filter_map { |row| row["wise_statement_id"].presence }.to_set+ booked = unmarked.group_by { |row| row["referenceNumber"] }.filter_map do |reference, rows|+ earliest_first(rows).first unless marked.include?(reference)+ end.to_set.compare_by_identity+ statement_rows.map { |row| booked.include?(row) ? row.merge("wise_statement_id" => row["referenceNumber"]) : row }+ end++ # Rows by time, the debit first among rows at the same time.+ def self.earliest_first(rows)+ rows.each_with_index.sort_by do |row, index|+ [ WiseStatement::Processor.posted_at(row)&.to_f || Float::INFINITY, row["type"].to_s == "DEBIT" ? 0 : 1, index ]+ end.map(&:first)+ end++ # rows: the balance's merged payload. window: its statement coverage,+ # { from:, through: } UTC times, or nil. entry_ids: a callable that tells+ # which of the given external ids the balance's account has entries for;+ # nil when the balance is not linked, and then no row leaves.+ def initialize(wise_account, rows, own_recipient_ids:, window:, entry_ids: nil)+ @wise_account = wise_account+ @rows = Array(rows).map { |row| row.except(*WORKED_OUT_KEYS) }+ @own_recipient_ids = own_recipient_ids+ @window = window+ @entry_ids = entry_ids+ @transfer_bookings = {}.compare_by_identity+ @activity_bookings = {}.compare_by_identity+ @times = {}.compare_by_identity+ end++ def call+ statements = @rows.select { |row| row["wise_statement"].present? }+ transfers = @rows.select { |row| transfer_row?(row) }+ conversions, activities = @rows.select { |row| activity_row?(row) }+ .partition { |row| WiseActivity::Processor::TWO_LEG_TYPES.include?(row["type"].to_s) }++ assign_statement_ids(statements)+ conversions_matched = mark_conversions(statements, conversions)+ index_free(statements.reject { |row| superseded?(row) })+ match_transfers_by_reference(transfers)+ match_activities_by_reference(activities)+ match_transfers_by_amount(transfers)+ match_activities_by_amount(activities)++ unmatched = transfers.select { |row| !superseded?(row) && transfer_booking(row)[:books] && inside_window?(transfer_booking(row)[:at]) }+ dropped = activities.select { |row| !superseded?(row) && inside_window?(activity_time(row)) }+ retired = retirable((unmatched.empty? ? transfers : []) + activities)+ gone = Set.new.compare_by_identity.merge(dropped + retired)++ Result.new(+ rows: @rows.reject { |row| gone.include?(row) },+ counts: {+ transfers_matched: transfers.count { |row| superseded?(row) },+ activities_matched: activities.count { |row| superseded?(row) },+ conversions_matched: conversions_matched,+ transfers_unmatched: unmatched.size,+ activities_unmatched: dropped.count { |row| activity_booking(row) },+ retired: retired.size+ }+ )+ end++ private++ def transfer_row?(row)+ row["wise_statement"].blank? && !activity_row?(row) && row["id"].present?+ end++ def activity_row?(row)+ WiseActivity::Processor.activity_row?(row)+ end++ def superseded?(row)+ row["wise_superseded_by"].present?+ end++ # A row keeps the id it has. Of the others, the earliest with a+ # reference gets it as its id unless a row already has that; rows at the+ # same time put the debit first.+ def assign_statement_ids(statements)+ statements.group_by { |row| row["referenceNumber"].presence }.each do |reference, rows|+ next if reference.nil?++ taken = rows.filter_map { |row| row["wise_statement_id"].presence }.to_set+ self.class.earliest_first(rows.reject { |row| row["wise_statement_id"].present? }).each do |row|+ # The plain reference, while no row has it, needs no mark.+ next if taken.add?(reference)++ base = [ reference, row["type"].to_s.upcase.presence, statement_time(row)&.strftime("%Y%m%d") ].compact.join("_")+ base = "#{base}_#{statement_amount(row).abs.to_s('F')}" if taken.include?(base)+ id = base+ counter = 1+ id = "#{base}_#{counter += 1}" while taken.include?(id)+ taken << id+ row["wise_statement_id"] = id+ end+ end+ end++ # A statement row of a move between the profile's balances books nothing+ # when a conversion's leg on this balance carries it.+ def mark_conversions(statements, conversions)+ legs = conversions.filter_map do |row|+ booking = activity_booking(row)+ booking&.merge(at: activity_time(row))+ end+ legs_by_cents = legs.group_by { |leg| [ leg[:currency], cents(leg[:amount]) ] }+ taken = Set.new.compare_by_identity++ by_time(statements.select { |row| balance_move?(row) }) { |row| statement_time(row) }.count do |row|+ candidates = near(legs_by_cents, statement_currency(row), statement_amount(row)).select do |leg|+ !taken.include?(leg) && same_movement?(row, leg[:currency], leg[:amount], leg[:at])+ end+ leg = closest(candidates, statement_time(row)) { |candidate| candidate[:at] }+ next false unless leg++ taken << leg+ row["wise_superseded_by"] = leg[:external_id]+ true+ end+ end++ def balance_move?(row)+ type = row.dig("details", "type").to_s+ type == "CONVERSION" || type.end_with?("CROSS_BALANCE")+ end++ # The statement rows no movement has claimed yet, by reference and by+ # currency and amount in cents (TOLERANCE is a cent), so matching stays+ # linear however long the balance's history grows.+ def index_free(statements)+ @free = Set.new.compare_by_identity.merge(statements)+ @free_by_reference = statements.group_by { |row| row["referenceNumber"].presence }+ @free_by_cents = statements.group_by { |row| [ statement_currency(row), cents(statement_amount(row)) ] }+ end++ def free_with_reference(reference)+ Array(@free_by_reference[reference]).select { |row| @free.include?(row) }+ end++ def free_near(currency, amount)+ near(@free_by_cents, currency, amount).select { |row| @free.include?(row) }+ end++ # What an index by [currency, cents] holds within a cent of the amount.+ def near(index, currency, amount)+ center = cents(amount)+ (center - 1..center + 1).flat_map { |key| Array(index[[ currency, key ]]) }+ end++ def cents(amount)+ (amount.abs * 100).round+ end++ # TRANSFER-<id> names the transfer: its earliest row with the sign of+ # the transfer's own movement takes it over, and a refunded payout's+ # refund credit, which shares the reference, its refund entry. When the+ # payout was made before the statements' window, only that credit is+ # in it; it then books nothing, as the transfer's row keeps booking the+ # payout, its fee and the refund (or, without a refund it knows of,+ # none of them). Any other row of the wrong sign books on its own.+ def match_transfers_by_reference(transfers)+ transfers.each do |transfer|+ id = transfer["id"].to_s+ candidates = free_with_reference("TRANSFER-#{id}")+ next if candidates.empty?++ booking = transfer_booking(transfer)+ main = by_time(candidates.select { |row| transfer_sign_fits?(row, booking) }) { |row| statement_time(row) }.first+ refund = by_time(candidates.select { |row| !row.equal?(main) && statement_amount(row).positive? }) { |row| statement_time(row) }.first+ if main+ take_over(transfer, main, "main" => "wise_transfer_#{id}", "fee" => "wise_fee_#{id}")+ take_over(nil, refund, "main" => "wise_refund_#{id}") if refund && booking[:refund]+ elsif refund && booking[:refunded]+ give_way(refund, "wise_refund_#{id}")+ end+ end+ end++ def match_transfers_by_amount(transfers)+ waiting = transfers.select { |row| !superseded?(row) && transfer_booking(row)[:books] && transfer_booking(row)[:at] }+ by_time(waiting) { |row| transfer_booking(row)[:at] }.each do |transfer|+ booking = transfer_booking(transfer)+ candidates = free_near(booking[:currency], booking[:amount]).select do |row|+ row.dig("details", "type") == TRANSFER_DETAILS_TYPE && transfer_sign_fits?(row, booking) &&+ (statement_amount(row).abs - booking[:amount]).abs <= TOLERANCE && within_a_day?(statement_time(row), booking[:at])+ end+ statement = closest(candidates, booking[:at]) { |row| statement_time(row) }+ id = transfer["id"].to_s+ take_over(transfer, statement, "main" => "wise_transfer_#{id}", "fee" => "wise_fee_#{id}") if statement+ end+ end++ def match_activities_by_reference(activities)+ by_time(activities) { |row| activity_time(row) }.each do |activity|+ resource_id = activity.dig("resource", "id").to_s+ next if resource_id.blank?++ booking = activity_booking(activity)+ candidates = free_with_reference("CARD-#{resource_id}").select do |row|+ booking.nil? || statement_amount(row).negative? == booking[:amount].positive?+ end+ statement = by_time(candidates) { |row| statement_time(row) }.first+ take_over(activity, statement, "main" => "wise_activity_#{activity['id']}") if statement+ end+ end++ def match_activities_by_amount(activities)+ by_time(activities) { |row| activity_time(row) }.each do |activity|+ booking = activity_booking(activity)+ at = activity_time(activity)+ next if superseded?(activity) || booking.nil? || at.nil?++ candidates = free_near(booking[:currency], booking[:amount]).select do |row|+ !balance_move?(row) && same_movement?(row, booking[:currency], booking[:amount], at)+ end+ statement = closest(candidates, at) { |row| statement_time(row) }+ take_over(activity, statement, "main" => booking[:external_id]) if statement+ end+ end++ def take_over(row, statement, supersedes)+ @free.delete(statement)+ statement["wise_supersedes"] = supersedes+ row["wise_superseded_by"] = "wise_statement_#{WiseStatement::Processor.transaction_id(statement)}" if row+ end++ # The statement row books nothing: the entry another row books carries+ # its movement.+ def give_way(statement, external_id)+ @free.delete(statement)+ statement["wise_superseded_by"] = external_id+ end++ # Rows a statement row took over leave once the account has no entry+ # under their ids any more (renamed by the processing that followed).+ def retirable(rows)+ superseded = rows.select { |row| superseded?(row) }+ return [] if superseded.empty? || @entry_ids.nil?++ ids = {}.compare_by_identity+ superseded.each { |row| ids[row] = legacy_external_ids(row) }+ existing = @entry_ids.call(ids.values.flatten.uniq).to_set+ superseded.reject { |row| ids[row].any? { |id| existing.include?(id) } }+ end++ def legacy_external_ids(row)+ return [ "wise_activity_#{row['id']}" ] if activity_row?(row)++ %w[transfer fee refund].map { |kind| "wise_#{kind}_#{row['id']}" }+ end++ # What a transfer moved on the balance, as WiseEntry::Processor books it.+ def transfer_booking(row)+ @transfer_bookings[row] ||= begin+ direction = WiseEntry::Processor.direction(row, own_recipient_ids: @own_recipient_ids)+ incoming = direction == :incoming+ refunded = !incoming && row["status"] == WiseEntry::Processor::REFUNDED_STATUS+ {+ incoming: incoming,+ books: WiseEntry::Processor.skip_reason(row, direction: direction).nil?,+ currency: (incoming ? row["targetCurrency"] : row["sourceCurrency"]).presence || @wise_account.currency,+ amount: incoming ? row["targetValue"].to_d.abs : row["sourceValue"].to_d.abs + WiseEntry::Processor.fee(row),+ at: readable { WiseEntry::Processor.created_at(row) },+ refunded: refunded,+ # The transfer books a refund entry (WiseEntry::Processor.refund).+ refund: refunded && WiseEntry::Processor.refund(row).present?+ }+ end+ end++ # What an activity books on the balance, as WiseActivity::Processor+ # does, or nil.+ def activity_booking(row)+ return @activity_bookings[row] if @activity_bookings.key?(row)++ @activity_bookings[row] = readable { WiseActivity::Processor.new(row, wise_account: @wise_account).booking }+ end++ def activity_time(row)+ @times.fetch(row) { @times[row] = readable { WiseActivity::Processor.created_at(row) } }+ end++ # Rows in the order of the time the block gives, rows without one last.+ def by_time(rows)+ rows.each_with_index.sort_by { |row, index| [ yield(row)&.to_f || Float::INFINITY, index ] }.map(&:first)+ end++ def transfer_sign_fits?(statement, booking)+ booking[:incoming] ? statement_amount(statement).positive? : statement_amount(statement).negative?+ end++ # amount has Sure's sign: positive (money out) matches a debit row.+ def same_movement?(statement, currency, amount, at)+ amount.nonzero? && statement_currency(statement) == currency &&+ statement_amount(statement).negative? == amount.positive? &&+ (statement_amount(statement).abs - amount.abs).abs <= TOLERANCE &&+ within_a_day?(statement_time(statement), at)+ end++ def within_a_day?(time, other)+ time.present? && other.present? && (time.to_date - other.to_date).abs <= 1+ end++ # The statements' window ends where they last reached: Wise may have+ # refused them since, and then no statement row carries what came after.+ def inside_window?(time)+ @window.present? && time.present? && time >= @window[:from] && (@window[:through].nil? || time <= @window[:through])+ end++ # The candidate nearest in time (the block gives its time) to `at`.+ def closest(candidates, at)+ candidates.min_by do |candidate|+ time = yield(candidate)+ [ time && at ? (time - at).abs : Float::INFINITY, time&.to_f || Float::INFINITY ]+ end+ end++ def statement_amount(row)+ row.dig("amount", "value").to_d+ end++ def statement_currency(row)+ row.dig("amount", "currency").presence || @wise_account.currency+ end++ def statement_time(row)+ @times.fetch(row) { @times[row] = WiseStatement::Processor.posted_at(row) }+ end++ # nil for a row the processors cannot read (they raise ArgumentError).+ def readable+ yield+ rescue ArgumentError+ nil+ end+enddiff --git a/app/models/wise_item/syncer.rb b/app/models/wise_item/syncer.rbindex a77f31c4da..e890fb97c1 100644--- a/app/models/wise_item/syncer.rb+++ b/app/models/wise_item/syncer.rb@@ -39,9 +39,10 @@ class WiseItem::Syncerif linked_count.positive?update_status(sync, :processing_transactions)mark_import_started(sync)- process_results = wise_item.process_accounts+ process_results = wise_item.process_accounts(import_complete: import_complete?(import_result))sync_errors.concat(result_failure_errors(process_results, category: :account_processing_error, message_key: :account_processing_failed))capture_transaction_processing_summary(process_results)+ collect_wise_prune_stats(sync, process_results)wise_item.link_jar_transfers!@@ -102,10 +103,17 @@ class WiseItem::Syncererrors = []errors << sync_error(:account_import_error, :accounts_failed, count: result[:accounts_failed]) if result[:accounts_failed].to_i.positive?errors << sync_error(:transaction_import_error, :transactions_failed, count: result[:transactions_failed]) if result[:transactions_failed].to_i.positive?+ errors << sync_error(:fetch_error, :fetch_failed, count: result[:fetch_failures]) if result[:fetch_failures].to_i.positive?errors << sync_error(:import_error, :import_failed) if errors.empty?errorsend+ # Only an import that fetched every source may drive steps that delete+ # or rewrite entries.+ def import_complete?(result)+ result.is_a?(Hash) && result[:complete] == true+ end+def result_failure_errors(results, category:, message_key:)failed = Array(results).count { |r| r.is_a?(Hash) && r[:success] == false }return [] unless failed.positive?@@ -113,6 +121,18 @@ class WiseItem::Syncer[ sync_error(category, message_key, count: failed) ]end+ # Stale Wise entries the processing deleted (see+ # WiseAccount::Transactions::Processor), summed over the accounts.+ def collect_wise_prune_stats(sync, results)+ return unless sync.respond_to?(:sync_stats)++ merge_sync_stats(sync, { "wise_pruned_entries" => pruned_entry_count(results) })+ end++ def pruned_entry_count(results)+ Array(results).sum { |result| result.is_a?(Hash) && result[:result].is_a?(Hash) ? result[:result][:pruned].to_i : 0 }+ end+def capture_transaction_processing_summary(results)account_results = Array(results)transaction_results = account_results.filter_map { |result| result[:result] if result.is_a?(Hash) }@@ -136,7 +156,8 @@ class WiseItem::Syncerprocessed_account_count: account_results.size,imported_transaction_count: imported,skipped_transaction_count: skipped,- failed_transaction_count: failed+ failed_transaction_count: failed,+ pruned_entry_count: pruned_entry_count(account_results)})rescue => ediff --git a/app/models/wise_statement/processor.rb b/app/models/wise_statement/processor.rbindex 7f8da746af..3cf257f172 100644--- a/app/models/wise_statement/processor.rb+++ b/app/models/wise_statement/processor.rb@@ -1,6 +1,25 @@# frozen_string_literal: trueclass WiseStatement::Processor+ # A statement row's date is a UTC ISO-8601 timestamp; nil when it has+ # none or it does not parse.+ def self.posted_at(statement)+ raw = statement["date"]+ ActiveSupport::TimeZone["UTC"].parse(raw.to_s) if raw.present?+ rescue ArgumentError+ nil+ end++ # What a statement row's entries are keyed by (wise_statement_<id>). Wise+ # reuses a transfer's reference on its refund, so rows after the first+ # with a reference carry their own id ("wise_statement_id", see+ # WiseItem::StatementMigration). Sure's own marks stay out of the+ # fallback digest, as they change between syncs.+ def self.transaction_id(statement)+ statement["wise_statement_id"].presence || statement["referenceNumber"].presence || statement["id"].presence ||+ Digest::SHA256.hexdigest(statement.except(*WiseItem::StatementMigration::MARKER_KEYS).to_json)[0, 24]+ end+def initialize(statement, wise_account:)@statement = statement.with_indifferent_access@wise_account = wise_account@@ -12,9 +31,14 @@ class WiseStatement::Processorreturn :skippedend+ if superseded?+ Rails.logger.debug "WiseStatement::Processor - Statement #{safe_id} is booked as #{statement[:wise_superseded_by]}, skipping"+ return :skipped+ end+result = import_main_transaction- if fee.positive?+ if booked_fee.positive?beginimport_fee_transactionrescue => e@@ -31,6 +55,38 @@ class WiseStatement::Processorraiseend+ # The external ids of the entries processing this statement row keeps on+ # its balance (see WiseAccount::Transactions::Processor's prune): none+ # for a conversion its activity books instead.+ def expected_external_ids+ return [] if superseded?++ ids = [ main_external_id ]+ ids << fee_external_id if booked_fee.positive?+ ids+ end++ # The entries a row booked before the balance had statements, which this+ # row takes over (WiseItem::StatementMigration): { old external id =>+ # this row's external id }, the fee only when this row books one.+ # WiseAccount::Transactions::Processor renames them before it books.+ def superseded_external_ids+ supersedes = statement[:wise_supersedes]+ return {} if superseded? || !supersedes.is_a?(Hash)++ ids = {}+ ids[supersedes[:main]] = main_external_id if supersedes[:main].present?+ ids[supersedes[:fee]] = fee_external_id if supersedes[:fee].present? && booked_fee.positive?+ ids+ end++ # The day the row books on; nil when it has no readable date.+ def booking_date+ date if account.present?+ rescue ArgumentError+ nil+ end+privateattr_reader :statement, :wise_account@@ -43,34 +99,59 @@ class WiseStatement::Processor@import_adapter ||= Account::ProviderImportAdapter.new(account)end+ # Imports through the adapter; Wise's amount also reaches an entry a+ # person acted on (WiseItem::AmountCorrection).+ def import_entry(**attributes)+ entry = import_adapter.import_transaction(**attributes)+ WiseItem::AmountCorrection.apply(entry, amount: attributes[:amount], currency: attributes[:currency])+ end+def import_main_transaction- import_adapter.import_transaction(- external_id: "wise_statement_#{transaction_id}",+ import_entry(+ external_id: main_external_id,amount: amount,currency: currency,date: date,name: name,source: "wise",- extra: extra+ extra: extra,+ # extra[:wise] is the full snapshot, so a flag Wise stops reporting clears.+ replace_extra_namespaces: [ "wise" ])end- # The statement amount excludes fees, so the fee is imported as its own- # entry (mirroring WiseEntry::Processor) to preserve the balance impact.+ # A debit's statement amount includes its fee, so the fee is imported as+ # its own entry (mirroring WiseEntry::Processor) to preserve the balance+ # impact.def import_fee_transaction- import_adapter.import_transaction(- external_id: "wise_statement_#{transaction_id}_fee",- amount: fee,+ import_entry(+ external_id: fee_external_id,+ amount: booked_fee,currency: currency,date: date,name: I18n.t("wise_items.entries.fee_name"),source: "wise",- extra: { wise: { statement_id: transaction_id, type: "FEE", fee: fee } }+ extra: { wise: { statement_id: transaction_id, type: "FEE", fee: booked_fee } },+ replace_extra_namespaces: [ "wise" ])end+ # A conversion Wise's activity books on this balance (an INTERBALANCE+ # leg), so this row books nothing (WiseItem::StatementMigration).+ def superseded?+ statement[:wise_superseded_by].present?+ end++ def main_external_id+ "wise_statement_#{transaction_id}"+ end++ def fee_external_id+ "wise_statement_#{transaction_id}_fee"+ end+def transaction_id- statement[:referenceNumber].presence || statement[:id].presence || digest+ @transaction_id ||= self.class.transaction_id(statement)enddef safe_id@@ -79,14 +160,20 @@ class WiseStatement::Processor# Wise statements use a signed amount: credits are positive and debits are# negative. Sure uses the opposite sign convention for imported entries.- # The statement amount is the full balance impact and includes fees, so the- # reported totalFees are excluded to match the transfer importer's net amount.+ # A debit's amount is its whole balance impact, so the fee (booked on its+ # own) is taken out to match the transfer importer's net amount. A+ # credit's amount is what reached the balance, already net of its fee,+ # which is only kept in extra.def amount- signed = statement.dig(:amount, :value).to_d- net = signed.abs - fee- net = 0 if net.negative?+ signed = signed_amount+ return -signed unless signed.negative?- signed.negative? ? net : -net+ net = signed.abs - booked_fee+ net.negative? ? 0.to_d : net+ end++ def signed_amount+ statement.dig(:amount, :value).to_denddef currency@@ -97,11 +184,10 @@ class WiseStatement::Processorraw = statement[:date].presenceraise ArgumentError, "Wise statement missing date" unless raw- Time.parse(raw.to_s).in_time_zone(account.family.timezone).to_date- rescue ArgumentError- raise- rescue => e- raise ArgumentError, "Unable to parse Wise statement date #{raw.inspect}: #{e.message}"+ posted_at = self.class.posted_at(statement)+ raise ArgumentError, "Unable to parse Wise statement date #{raw.inspect}" unless posted_at++ posted_at.in_time_zone(wise_account.wise_item.time_zone).to_dateenddef name@@ -125,24 +211,25 @@ class WiseStatement::Processor}end- # Fee reported by Wise in totalFees. Only subtracted when denominated in the+ # Fee reported by Wise in totalFees. Only counted when denominated in the# transaction's currency so values are never mixed.def feetotal_fees = statement[:totalFees]- return 0 unless total_fees.is_a?(Hash)+ return 0.to_d unless total_fees.is_a?(Hash)amount_currency = statement.dig(:amount, :currency)fee_currency = total_fees[:currency].presence- return 0 if amount_currency.present? && fee_currency.present? && amount_currency != fee_currency+ return 0.to_d if amount_currency.present? && fee_currency.present? && amount_currency != fee_currencytotal_fees[:value].to_dend- def payment_reference- statement.dig(:details, :paymentReference).presence+ # Only a debit books its fee as an entry of its own (see #amount).+ def booked_fee+ signed_amount.negative? ? fee : 0.to_dend- def digest- Digest::SHA256.hexdigest(statement.to_json)[0, 24]+ def payment_reference+ statement.dig(:details, :paymentReference).presenceendenddiff --git a/app/views/wise_items/_wise_item.html.erb b/app/views/wise_items/_wise_item.html.erbindex 50db852bbb..f808572213 100644--- a/app/views/wise_items/_wise_item.html.erb+++ b/app/views/wise_items/_wise_item.html.erb@@ -68,6 +68,14 @@<%= render "accounts/index/account_groups", accounts: visible_accounts %><% end %>+ <%# The accounts index preloads one stats row per item; a standalone render has to look it up itself. %>+ <% stats = if defined?(@wise_sync_stats_map) && @wise_sync_stats_map+ @wise_sync_stats_map[wise_item.id] || {}+ else+ wise_item.latest_sync_record&.sync_stats || {}+ end %>+ <%= render ProviderSyncSummary.new(stats: stats, provider_item: wise_item, show_account_details: visible_accounts.size == wise_item.accounts.size) %>+<% unlinked = wise_item.unlinked_accounts_count %><% total = wise_item.total_accounts_count %><% linked = wise_item.linked_accounts_count %>diff --git a/config/locales/views/wise_items/ca.yml b/config/locales/views/wise_items/ca.ymlindex 59439faac2..c9b381c65a 100644--- a/config/locales/views/wise_items/ca.yml+++ b/config/locales/views/wise_items/ca.yml@@ -15,7 +15,7 @@ ca:sync_start_date_label: Importa transaccions des desync_start_date_help: Els extractes de Wise s'importen a partir d'aquesta data. Deixa el valor per defecte per obtenir fins a un any d'historial.import_all_history_label: Importa tot l'historial de transaccions- import_all_history_help: Obté tots els extractes històrics de Wise en lloc de només el darrer any.+ import_all_history_help: Importa tot l'historial de Wise (transferències, activitats i extractes) en lloc de només el darrer any. Cada saldo comença llavors a 0 el dia que Wise el va obrir.connect: Connecta Wiseupdate_connection: Actualitza la connexiósetup_accounts: Configura comptes@@ -43,6 +43,7 @@ ca:entries:default_name: Transacció Wisefee_name: Comissió de Wise+ refund_name: Reemborsament de Wiseactivities:jar_deposit: Transferència a la guardiolajar_withdrawal: Transferència des de la guardiola@@ -90,6 +91,9 @@ ca:account_sync_failed:one: No s'ha pogut programar la sincronització de %{count} compte Wise.other: No s'ha pogut programar la sincronització de %{count} comptes Wise.+ fetch_failed:+ one: "%{count} sol·licitud a Wise ha fallat. La propera sincronització la tornarà a provar."+ other: "%{count} sol·licituds a Wise han fallat. La propera sincronització les tornarà a provar."provider_connection:default_name: Wisedefault_description: Connecta el teu compte multidivisa de Wise@@ -151,6 +155,9 @@ ca:failed: No s'ha pogut enllaçar el saldo de Wise. Torna-ho a provar.link_existing_account:not_found: No s'ha trobat el compte o el saldo de Wise.+ account_already_linked: Aquest compte ja està enllaçat a un proveïdor.+ unsupported_account_type: Els saldos de Wise només es poden enllaçar a comptes d'efectiu.+ currency_mismatch: "Aquest saldo de Wise és en %{balance_currency}, però el compte és en %{account_currency}. Tria un saldo en la moneda del compte."success: S'ha enllaçat correctament %{account_name} amb Wisefailed: No s'ha pogut enllaçar el compte. Torna-ho a provar.complete_account_setup:diff --git a/config/locales/views/wise_items/de.yml b/config/locales/views/wise_items/de.ymlindex aa519bb27e..d01e9c7f3a 100644--- a/config/locales/views/wise_items/de.yml+++ b/config/locales/views/wise_items/de.yml@@ -22,6 +22,7 @@ de:entries:default_name: Wise-Transaktionfee_name: Wise-Gebühr+ refund_name: Wise-Rückerstattunggenerate_sca_keypair:failed: Das neue SCA-Schlüsselpaar ließ sich nicht erzeugen. Versuch es noch einmal.success: Neues SCA-Schlüsselpaar erzeugt. Registriere den öffentlichen Schlüssel bei Wise, um die Einrichtung abzuschließen.@@ -30,9 +31,12 @@ de:not_found: Wise-Guthaben nicht gefunden.success: Wise-Guthaben mit dem Konto verknüpft.link_existing_account:+ account_already_linked: Dieses Konto ist bereits mit einem Anbieter verknüpft.+ currency_mismatch: "Dieses Wise-Guthaben lautet auf %{balance_currency}, das Konto auf %{account_currency}. Wähl ein Guthaben in der Währung des Kontos."failed: Das Konto ließ sich nicht verknüpfen. Versuch es noch einmal.not_found: Konto oder Wise-Guthaben nicht gefunden.success: "%{account_name} mit Wise verknüpft"+ unsupported_account_type: Wise-Guthaben lassen sich nur mit Bankkonten verknüpfen.link_profiles:already_connected: Alle gewählten Profile sind bereits verbunden.no_profiles_selected: Wähl mindestens ein Profil.@@ -76,7 +80,7 @@ de:generate: Schlüsselpaar erzeugenregenerate: Neues Schlüsselpaar erzeugenregenerate_confirm: "Dadurch wird ein neues Schlüsselpaar erzeugt. Wise akzeptiert den bisherigen öffentlichen Schlüssel weiterhin, bis du ihn selbst in deinem Wise-Konto entfernst – Sure kann ihn nicht aus der Ferne widerrufen. Du musst den neuen öffentlichen Schlüssel bei Wise registrieren, bevor Kontoauszüge wieder synchronisiert werden können. Fortfahren?"- import_all_history_help: Holt alle historischen Wise-Kontoauszüge statt nur das letzte Jahr.+ import_all_history_help: Importiert die gesamte Wise-Historie (Überweisungen, Aktivitäten und Kontoauszüge) statt nur das letzte Jahr. Jedes Guthaben beginnt dann bei 0 an dem Tag, an dem Wise es eröffnet hat.import_all_history_label: Vollständige Transaktionshistorie importierenkeep_token_placeholder: Leer lassen, um den bisherigen Token zu behaltennot_configured: Nicht eingerichtet@@ -145,6 +149,9 @@ de:checking_account_configuration: Kontokonfiguration wird geprüft …credentials_invalid: Ungültiger Wise-API-Token oder fehlende Berechtigungenfailed: Der Sync ist fehlgeschlagen. Versuch es noch einmal oder wende dich an den Support.+ fetch_failed:+ one: "%{count} Wise-Anfrage ist fehlgeschlagen. Der nächste Sync versucht es erneut."+ other: "%{count} Wise-Anfragen sind fehlgeschlagen. Der nächste Sync versucht es erneut."import_failed: Der Wise-Import ist fehlgeschlagen.importing_accounts: Konten werden aus Wise importiert …processing_transactions: Transaktionen werden verarbeitet …diff --git a/config/locales/views/wise_items/en.yml b/config/locales/views/wise_items/en.ymlindex d6c671d7c1..76801e57a6 100644--- a/config/locales/views/wise_items/en.yml+++ b/config/locales/views/wise_items/en.yml@@ -7,6 +7,7 @@ en:entries:default_name: Wise transactionfee_name: Wise fee+ refund_name: Wise refundactivities:jar_deposit: Transfer to Jarjar_withdrawal: Transfer from Jar@@ -54,6 +55,9 @@ en:account_sync_failed:one: "%{count} Wise account sync could not be scheduled."other: "%{count} Wise account syncs could not be scheduled."+ fetch_failed:+ one: "%{count} Wise request failed. The next sync will retry it."+ other: "%{count} Wise requests failed. The next sync will retry them."provider_panel:add_connection: Add Wise connectiontoken_label: API token@@ -64,7 +68,7 @@ en:sync_start_date_label: Import transactions fromsync_start_date_help: Wise statements are imported from this date onward. Leave the default for up to one year of history.import_all_history_label: Import full transaction history- import_all_history_help: Fetch all historical Wise statements instead of only the last year.+ import_all_history_help: Import the whole Wise history (transfers, activities and statements) instead of only the last year. Each balance then starts at 0 on the day Wise opened it.connect: Connect Wiseupdate_connection: Update connectionsetup_accounts: Set up accounts@@ -152,6 +156,9 @@ en:failed: Failed to link Wise balance. Please try again.link_existing_account:not_found: Account or Wise balance not found.+ account_already_linked: This account is already linked to a provider.+ unsupported_account_type: Wise balances can only be linked to cash accounts.+ currency_mismatch: "This Wise balance is in %{balance_currency}, but the account is in %{account_currency}. Choose a balance in the account's currency."success: "Successfully linked %{account_name} with Wise"failed: Failed to link account. Please try again.complete_account_setup:diff --git a/config/locales/views/wise_items/fr.yml b/config/locales/views/wise_items/fr.ymlindex e876d5e68e..10b3c1449a 100644--- a/config/locales/views/wise_items/fr.yml+++ b/config/locales/views/wise_items/fr.yml@@ -24,6 +24,7 @@ fr:entries:default_name: Transaction Wisefee_name: Frais Wise+ refund_name: Remboursement Wisegenerate_sca_keypair:failed: Impossible de générer une nouvelle paire de clés SCA. Veuillez réessayer.success: Nouvelle paire de clés SCA générée. Enregistrez la clé publique auprès de Wise pour terminer l'activation.@@ -32,9 +33,12 @@ fr:not_found: Solde Wise introuvable.success: Solde Wise lié au compte avec succès.link_existing_account:+ account_already_linked: Ce compte est déjà lié à un fournisseur.+ currency_mismatch: "Ce solde Wise est en %{balance_currency}, mais le compte est en %{account_currency}. Choisissez un solde dans la devise du compte."failed: Échec de la liaison du compte. Veuillez réessayer.not_found: Compte ou solde Wise introuvable.success: "Liaison de %{account_name} à Wise réussie"+ unsupported_account_type: Les soldes Wise ne peuvent être liés qu'à des comptes de liquidités.link_profiles:already_connected: Tous les profils sélectionnés sont déjà connectés.no_profiles_selected: Veuillez sélectionner au moins un profil.@@ -68,7 +72,7 @@ fr:sync_start_date_label: Importer les transactions à partir desync_start_date_help: Les relevés Wise sont importés à partir de cette date. Conservez la valeur par défaut pour importer jusqu'à un an d'historique.import_all_history_label: Importer tout l'historique des transactions- import_all_history_help: Récupère tous les relevés Wise historiques au lieu de seulement la dernière année.+ import_all_history_help: Importe tout l'historique Wise (virements, activités et relevés) au lieu de seulement la dernière année. Chaque solde commence alors à 0 le jour où Wise l'a ouvert.disconnect: Déconnecterdisconnect_confirm: Voulez-vous vraiment déconnecter %{name} ? Cela supprimeratoutes les données de compte synchronisées.@@ -154,6 +158,9 @@ fr:checking_account_configuration: Vérification de la configuration du compte…credentials_invalid: Jeton API Wise invalide ou autorisations insuffisantesfailed: Échec de la synchronisation. Veuillez réessayer ou contacter le support.+ fetch_failed:+ one: "%{count} requête Wise a échoué. La prochaine synchronisation la relancera."+ other: "%{count} requêtes Wise ont échoué. La prochaine synchronisation les relancera."import_failed: Échec de l'importation Wise.importing_accounts: Importation des comptes depuis Wise…processing_transactions: Traitement des transactions…diff --git a/config/locales/views/wise_items/pl.yml b/config/locales/views/wise_items/pl.ymlindex 511ab19d92..55cc6230ce 100644--- a/config/locales/views/wise_items/pl.yml+++ b/config/locales/views/wise_items/pl.yml@@ -22,6 +22,7 @@ pl:entries:default_name: Transakcja Wisefee_name: Opłata Wise+ refund_name: Zwrot Wisegenerate_sca_keypair:failed: Nie udało się wygenerować nowej pary kluczy SCA. Spróbuj ponownie.success: Wygenerowano nową parę kluczy SCA. Zarejestruj klucz publiczny w Wise,@@ -31,9 +32,12 @@ pl:not_found: Nie znaleziono salda Wise.success: Połączono saldo Wise z kontem.link_existing_account:+ account_already_linked: To konto jest już połączone z dostawcą.+ currency_mismatch: "To saldo Wise jest w %{balance_currency}, a konto w %{account_currency}. Wybierz saldo w walucie konta."failed: Nie można połączyć konta. Spróbuj ponownie.not_found: Nie znaleziono konta lub salda Wise.success: Połączono %{account_name} z Wise+ unsupported_account_type: Salda Wise można połączyć tylko z kontami gotówkowymi.link_profiles:already_connected: Wszystkie wybrane profile są już połączone.no_profiles_selected: Wybierz co najmniej jeden profil.@@ -65,8 +69,9 @@ pl:Wise w produkcji. Bez szyfrowania tokeny są przechowywane w postaci zwykłegotekstu.title: Szyfrowanie bazy danych nie jest skonfigurowane- import_all_history_help: Pobiera wszystkie historyczne wyciągi Wise zamiast- tylko ostatniego roku.+ import_all_history_help: Importuje całą historię Wise (przelewy, aktywności i wyciągi)+ zamiast tylko ostatniego roku. Każde saldo zaczyna się wtedy od 0 w dniu,+ w którym Wise je otworzył.import_all_history_label: Importuj pełną historię transakcjiinstructions:copy_token_html: Skopiuj token i wklej go poniżej. Sure używa go tylko do@@ -174,6 +179,11 @@ pl:credentials_invalid: Nieprawidłowy token API Wise lub niewystarczające uprawnieniafailed: Synchronizacja nie powiodła się. Spróbuj ponownie lub skontaktuj sięz pomocą techniczną.+ fetch_failed:+ few: "%{count} żądania do Wise nie powiodły się. Następna synchronizacja ponowi próbę."+ many: "%{count} żądań do Wise nie powiodło się. Następna synchronizacja ponowi próbę."+ one: "%{count} żądanie do Wise nie powiodło się. Następna synchronizacja ponowi próbę."+ other: "%{count} żądań do Wise nie powiodło się. Następna synchronizacja ponowi próbę."import_failed: Import Wise nie powiódł się.importing_accounts: Importowanie kont z Wise...processing_transactions: Przetwarzanie transakcji...diff --git a/config/locales/views/wise_items/pt-PT.yml b/config/locales/views/wise_items/pt-PT.ymlindex 13cf1b1d2f..d2d71a94b2 100644--- a/config/locales/views/wise_items/pt-PT.yml+++ b/config/locales/views/wise_items/pt-PT.yml@@ -7,6 +7,7 @@ pt-PT:entries:default_name: Transação Wisefee_name: Comissão da Wise+ refund_name: Reembolso da Wiseactivities:jar_deposit: Depósito no jarjar_withdrawal: Levantamento do jar@@ -54,6 +55,9 @@ pt-PT:account_sync_failed:one: "%{count} sincronização de conta da Wise não pôde ser agendada."other: "%{count} sincronizações de contas da Wise não puderam ser agendadas."+ fetch_failed:+ one: "%{count} pedido à Wise falhou. A próxima sincronização volta a tentar."+ other: "%{count} pedidos à Wise falharam. A próxima sincronização volta a tentar."provider_panel:add_connection: Adicionar ligação à Wisetoken_label: Token de API@@ -64,7 +68,7 @@ pt-PT:sync_start_date_label: Importar transações a partir desync_start_date_help: Os extratos da Wise são importados a partir desta data. Deixe o valor predefinido para até um ano de histórico.import_all_history_label: Importar o histórico completo de transações- import_all_history_help: Obter todos os extratos históricos da Wise em vez de apenas o último ano.+ import_all_history_help: Importar todo o histórico da Wise (transferências, atividades e extratos) em vez de apenas o último ano. Cada saldo começa então em 0 no dia em que a Wise o abriu.connect: Ligar à Wiseupdate_connection: Atualizar ligaçãosetup_accounts: Configurar contas@@ -142,6 +146,9 @@ pt-PT:failed: Falha ao associar o saldo da Wise. Tente novamente.link_existing_account:not_found: Conta ou saldo da Wise não encontrado.+ account_already_linked: Esta conta já está associada a um serviço.+ unsupported_account_type: Os saldos da Wise só podem ser associados a contas de dinheiro.+ currency_mismatch: "Este saldo da Wise está em %{balance_currency}, mas a conta está em %{account_currency}. Escolha um saldo na moeda da conta."success: "%{account_name} associada com sucesso à Wise"failed: Falha ao associar a conta. Tente novamente.complete_account_setup:diff --git a/config/locales/views/wise_items/ru.yml b/config/locales/views/wise_items/ru.ymlindex abf15d3603..d7e130b405 100644--- a/config/locales/views/wise_items/ru.yml+++ b/config/locales/views/wise_items/ru.yml@@ -15,7 +15,7 @@ ru:sync_start_date_label: Импортировать операции сsync_start_date_help: Выписки Wise импортируются начиная с этой даты. Оставьте значение по умолчанию, чтобы получить историю максимум за год.import_all_history_label: Импортировать всю историю операций- import_all_history_help: Загружать все выписки Wise за всё время, а не только за последний год.+ import_all_history_help: Импортировать всю историю Wise (переводы, операции и выписки), а не только за последний год. Тогда каждый баланс начинается с 0 в день, когда Wise его открыл.connect: Подключить Wiseupdate_connection: Обновить подключениеsetup_accounts: Настроить счета@@ -43,6 +43,7 @@ ru:entries:default_name: Операция Wisefee_name: Комиссия Wise+ refund_name: Возврат Wiseactivities:jar_deposit: Перевод в копилкуjar_withdrawal: Перевод из копилки@@ -102,6 +103,11 @@ ru:few: Не удалось запланировать синхронизацию %{count} счетов Wise.many: Не удалось запланировать синхронизацию %{count} счетов Wise.other: Не удалось запланировать синхронизацию %{count} счёта Wise.+ fetch_failed:+ one: "%{count} запрос к Wise не выполнен. Следующая синхронизация повторит попытку."+ few: "%{count} запроса к Wise не выполнены. Следующая синхронизация повторит попытку."+ many: "%{count} запросов к Wise не выполнены. Следующая синхронизация повторит попытку."+ other: "%{count} запроса к Wise не выполнены. Следующая синхронизация повторит попытку."provider_connection:default_name: Wisedefault_description: Подключите мультивалютный счёт Wise@@ -165,6 +171,9 @@ ru:failed: Не удалось связать баланс Wise. Повторите попытку.link_existing_account:not_found: Счёт или баланс Wise не найден.+ account_already_linked: Этот счёт уже привязан к провайдеру.+ unsupported_account_type: Балансы Wise можно связать только с денежными счетами.+ currency_mismatch: "Этот баланс Wise в %{balance_currency}, а счёт — в %{account_currency}. Выберите баланс в валюте счёта."success: '%{account_name} успешно связан с Wise'failed: Не удалось связать счёт. Повторите попытку.complete_account_setup:diff --git a/config/locales/views/wise_items/tr.yml b/config/locales/views/wise_items/tr.ymlindex 2b77b10acf..f6c35b0c20 100644--- a/config/locales/views/wise_items/tr.yml+++ b/config/locales/views/wise_items/tr.yml@@ -22,14 +22,18 @@ tr:entries:default_name: Wise işlemifee_name: Wise ücreti+ refund_name: Wise iadesilink_accounts:failed: Wise bakiyesi bağlanamadı. Lütfen tekrar deneyin.not_found: Wise bakiyesi bulunamadı.success: Wise bakiyesi hesaba başarıyla bağlandı.link_existing_account:+ account_already_linked: Bu hesap zaten bir sağlayıcıya bağlı.+ currency_mismatch: "Bu Wise bakiyesi %{balance_currency}, hesap ise %{account_currency} cinsinden. Hesabın para biriminde bir bakiye seçin."failed: Hesap bağlanamadı. Lütfen tekrar deneyin.not_found: Hesap veya Wise bakiyesi bulunamadı.success: "%{account_name} Wise ile başarıyla bağlandı"+ unsupported_account_type: Wise bakiyeleri yalnızca nakit hesaplarına bağlanabilir.link_profiles:already_connected: Seçilen tüm profiller zaten bağlı.no_profiles_selected: Lütfen en az bir profil seçin.@@ -53,7 +57,7 @@ tr:sync_start_date_label: İşlemleri şu tarihten itibaren içe aktarsync_start_date_help: Wise hesap özetleri bu tarihten itibaren içe aktarılır. Varsayılanı bırakırsanız bir yıla kadar geçmiş yüklenir.import_all_history_label: Tüm işlem geçmişini içe aktar- import_all_history_help: Yalnızca son bir yıl yerine tüm geçmiş Wise hesap özetlerini getirir.+ import_all_history_help: Yalnızca son bir yıl yerine tüm Wise geçmişini (transferler, işlemler ve hesap özetleri) içe aktarır. Her bakiye bu durumda Wise'ın onu açtığı gün 0'dan başlar.disconnect: Bağlantıyı kesdisconnect_confirm: "%{name} bağlantısını kesmek istediğinizden emin misiniz?Bu, tüm eşitlenmiş hesap verilerini kaldıracaktır."@@ -147,6 +151,9 @@ tr:credentials_invalid: Geçersiz Wise API token'ı veya yetersiz izinlerfailed: Eşitleme başarısız oldu. Lütfen tekrar deneyin veya destek ile iletişimegeçin.+ fetch_failed:+ one: "%{count} Wise isteği başarısız oldu. Sonraki eşitleme yeniden deneyecek."+ other: "%{count} Wise isteği başarısız oldu. Sonraki eşitleme yeniden deneyecek."import_failed: Wise içe aktarma başarısız oldu.importing_accounts: Wise'dan hesaplar içe aktarılıyor...processing_transactions: İşlemler işleniyor...diff --git a/config/locales/views/wise_items/uk.yml b/config/locales/views/wise_items/uk.ymlindex 5b8ec02efb..2ad1602c13 100644--- a/config/locales/views/wise_items/uk.yml+++ b/config/locales/views/wise_items/uk.yml@@ -6,6 +6,7 @@ uk:entries:default_name: Транзакція Wisefee_name: Комісія Wise+ refund_name: Повернення Wiseactivities:jar_deposit: Переказ у Jarjar_withdrawal: Переказ із Jar@@ -65,6 +66,11 @@ uk:other: "Синхронізацію %{count} рахунків Wise не вдалося запланувати."few: Синхронізацію %{count} рахунків Wise не вдалося запланувати.many: Синхронізацію %{count} рахунків Wise не вдалося запланувати.+ fetch_failed:+ one: "%{count} запит до Wise не вдався. Наступна синхронізація спробує знову."+ other: "%{count} запитів до Wise не вдалися. Наступна синхронізація спробує знову."+ few: "%{count} запити до Wise не вдалися. Наступна синхронізація спробує знову."+ many: "%{count} запитів до Wise не вдалися. Наступна синхронізація спробує знову."provider_panel:add_connection: Додати з'єднання Wisetoken_label: Токен API@@ -91,7 +97,7 @@ uk:sync_start_date_label: Імпортувати транзакції зsync_start_date_help: Виписки Wise імпортуються починаючи з цієї дати. Залиште значення за замовчуванням, щоб отримати історію до одного року.import_all_history_label: Імпортувати всю історію транзакцій- import_all_history_help: Отримати всі історичні виписки Wise, а не лише за останній рік.+ import_all_history_help: Імпортувати всю історію Wise (перекази, операції та виписки), а не лише за останній рік. Тоді кожен баланс починається з 0 у день, коли Wise його відкрив.sca:title: Строга автентифікація клієнта (SCA)description: Щоб читати повні виписки за транзакціями, зокрема вхідні платежі, Wise вимагає підписаний одноразовий токен-запит. Згенеруйте тут пару ключів і зареєструйте відкритий ключ у Wise, щоб увімкнути цю функцію.@@ -165,6 +171,9 @@ uk:failed: Не вдалося пов'язати баланс Wise. Спробуйте ще раз.link_existing_account:not_found: Рахунок або баланс Wise не знайдено.+ account_already_linked: Цей рахунок уже пов'язано з постачальником.+ unsupported_account_type: Баланси Wise можна пов'язати лише з грошовими рахунками.+ currency_mismatch: "Цей баланс Wise у %{balance_currency}, а рахунок — у %{account_currency}. Виберіть баланс у валюті рахунку."success: "Успішно пов'язано %{account_name} з Wise"failed: Не вдалося пов'язати рахунок. Спробуйте ще раз.complete_account_setup:diff --git a/config/locales/views/wise_items/zh-TW.yml b/config/locales/views/wise_items/zh-TW.ymlindex 2b4dd224e2..1c6e81ec9d 100644--- a/config/locales/views/wise_items/zh-TW.yml+++ b/config/locales/views/wise_items/zh-TW.yml@@ -7,6 +7,7 @@ zh-TW:entries:default_name: Wise 交易fee_name: Wise 手續費+ refund_name: Wise 退款activities:jar_deposit: 轉入 Jarjar_withdrawal: 從 Jar 轉出@@ -54,6 +55,9 @@ zh-TW:account_sync_failed:one: '%{count} 個 Wise 帳戶同步無法排程。'other: '%{count} 個 Wise 帳戶同步無法排程。'+ fetch_failed:+ one: '%{count} 個 Wise 請求失敗,下次同步時會重試。'+ other: '%{count} 個 Wise 請求失敗,下次同步時會重試。'provider_panel:add_connection: 新增 Wise 連線token_label: API 權杖 (API Token)@@ -138,6 +142,9 @@ zh-TW:failed: 無法連結 Wise 餘額。請再試一次。link_existing_account:not_found: 找不到帳戶或 Wise 餘額。+ account_already_linked: 此帳戶已與供應商連結。+ unsupported_account_type: Wise 餘額只能連結至現金/存款帳戶。+ currency_mismatch: "此 Wise 餘額的幣別為 %{balance_currency},但帳戶的幣別為 %{account_currency}。請選擇與帳戶幣別相同的餘額。"success: 已成功將 %{account_name} 與 Wise 連結failed: 無法連結帳戶。請再試一次。complete_account_setup:diff --git a/docs/llm-guides/providers.md b/docs/llm-guides/providers.mdindex 057c9b16c1..4cc27be7f1 100644--- a/docs/llm-guides/providers.md+++ b/docs/llm-guides/providers.md@@ -216,3 +216,45 @@ putting the token in the **URL path**, so neither [the client](../../app/models/nor the importer may put a resolved URL into an exception message, a log line or debugmetadata; requests are labelled with a static operation name instead. Fio reports nopending state, so it is deliberately absent from `Transaction::PENDING_PROVIDERS`.++## Wise payloads and clean-up++Each Wise balance stores the rows it books in `raw_transactions_payload`, and Sure+re-routes them on every sync. Keep these rules when changing the importer, the row+processors or the payload keys:++- A Wise amount reaches an entry a person categorized, noted or excluded, unless they+ changed its amount or currency themselves (a lock), an import owns it, or it is+ reconciled, split or in a transfer ([`WiseItem::AmountCorrection`](../../app/models/wise_item/amount_correction.rb)).+- [`WiseItem::Importer`](../../app/models/wise_item/importer.rb) fetches each source+ from where its coverage ends (`sync_metadata["coverage"]`, raised by+ `WiseItem::COVERAGE_VERSION`), and the whole history while none is recorded.+ `import[:complete]` is true only when every source arrived in full, and coverage+ moves on only when the rows reached every payload. A statement 403 is a refusal, not+ a failure.+- Rows carry Sure-owned keys: a transfer's `wise_activity` and `wise_refund_activity`,+ which a re-fetched copy keeps unless it brings its own (`STICKY_ROW_KEYS`), and+ `wise_missing_count` while Wise no longer finds the transfer by id.+- [`WiseItem::BalanceReplay`](../../app/models/wise_item/balance_replay.rb) writes+ `wise_funding` and `wise_split_parts`/`wise_split_estimated` only for a full-history+ import whose balances reconcile to Wise's live amounts, and a split payment's parts+ only when every balance it lists reconciled and a rate bounds each part.+- [`WiseAccount::Transactions::Processor`](../../app/models/wise_account/transactions/processor.rb)+ deletes the Wise entries no stored row books only after a complete import, where+ coverage reaches, from the payload's earliest row on, for entries booked since the+ balance was linked, never for an entry a person acted on, and at most max(5, 10 %)+ of the account's Wise entries per sync. Balance markers in `raw_payload`+ (`WiseAccount::PRESERVED_KEYS`) survive a new snapshot and are merged into the stored+ one.+- [`WiseItem::StatementMigration`](../../app/models/wise_item/statement_migration.rb)+ hands a balance's transfer and activity rows over to the statement rows that carry+ them (`wise_superseded_by`, `wise_supersedes`), renaming their entries, and keeps+ each statement row's id (`wise_statement_id`) once given. A sync that re-fetched the+ whole history may delete beyond the cap the entries whose rows it moved out of the+ balance's payload or left booking nothing on it (`prune_cap_bypass`).+- A jar move and interest stay on the balance they were first routed to+ (`wise_jar_balance_id`), and a row processor books nothing a payload holds for+ another balance.+- [`WiseItem::InterbalanceLinker`](../../app/models/wise_item/interbalance_linker.rb)+ links each conversion, jar move and send to the profile's own account details as a+ confirmed transfer; removing such a link from the transfer drawer rejects it.diff --git a/test/controllers/transfers_controller_test.rb b/test/controllers/transfers_controller_test.rbindex 7fed75a24b..1dc48cbffe 100644--- a/test/controllers/transfers_controller_test.rb+++ b/test/controllers/transfers_controller_test.rb@@ -562,6 +562,33 @@ class TransfersControllerTest < ActionDispatch::IntegrationTestendend+ # The Wise sync links a conversion's legs again on its own, so removing+ # that link rejects it, and the legs stay unlinked.+ test "rejects a link the Wise sync makes, so it stays removed" do+ family = users(:family_admin).family+ wise_item = WiseItem.create!(family: family, name: "Wise", token: "test_token", profile_id: "123", profile_type: :business)+ legs = { "EUR" => -117.5, "GBP" => 100 }.to_h do |currency, amount|+ wise_account = wise_item.wise_accounts.create!(balance_id: "1000000#{currency == 'EUR' ? 1 : 2}", name: "Wise #{currency}",+ currency: currency, raw_payload: { "type" => "STANDARD" })+ account = Account.create!(family: family, name: "Wise #{currency}", balance: 0, currency: currency,+ accountable: Depository.new(subtype: "checking"))+ AccountProvider.create!(account: account, provider: wise_account)+ side = amount.negative? ? "inflow" : "outflow"+ [ currency, account.entries.create!(external_id: "wise_interbalance_8001_#{side}", source: "wise", amount: amount, currency: currency,+ date: Date.current, name: "Conversion", entryable: Transaction.new) ]+ end+ wise_item.link_jar_transfers!+ transfer = Transfer.find_by!(inflow_transaction_id: legs["EUR"].entryable_id)++ delete transfer_url(transfer)++ assert RejectedTransfer.exists?(inflow_transaction_id: legs["EUR"].entryable_id, outflow_transaction_id: legs["GBP"].entryable_id)+ assert_no_difference -> { Transfer.count } do+ wise_item.link_jar_transfers!+ end+ assert_equal %w[standard standard], legs.values.map { |entry| entry.entryable.reload.kind }+ end+test "can create transfer with tags on both sides" dotag = tags(:one)diff --git a/test/controllers/wise_items_controller_test.rb b/test/controllers/wise_items_controller_test.rbindex 180d7e5618..4b53fdf2b9 100644--- a/test/controllers/wise_items_controller_test.rb+++ b/test/controllers/wise_items_controller_test.rb@@ -31,6 +31,126 @@ class WiseItemsControllerTest < ActionDispatch::IntegrationTestassert_redirected_to accounts_urlend+ # Linking a balance to a Sure account++ # A sync in flight has already picked the accounts it processes, and+ # sync_later only reuses it, so the new account used to stay empty until the+ # next sync.+ test "a balance set up while the connection syncs is processed straight away" do+ wise_account = wise_accounts(:checking)+ wise_account.update!(raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [+ { "id" => 4711, "targetAccount" => 1234, "sourceCurrency" => "EUR", "targetCurrency" => "EUR",+ "sourceValue" => 25.0, "targetValue" => 25.0, "status" => "outgoing_payment_sent",+ "created" => 2.days.ago.utc.strftime("%Y-%m-%d %H:%M:%S") }+ ])+ running = @wise_item.syncs.create!+ running.start!+ @wise_item.process_accounts # the balances linked when the running sync began (none)++ perform_enqueued_jobs(only: WiseItem::ProcessLinkedAccountJob) do+ post complete_account_setup_wise_item_url(@wise_item), params: { wise_account_id: wise_account.id }+ end++ account = wise_account.reload.account+ assert_equal [ "wise_transfer_4711" ], account.entries.where(source: "wise").pluck(:external_id)+ assert_equal [ running.id ], @wise_item.syncs.pluck(:id)+ assert account.syncs.exists?, "the account's balances are recalculated"+ end++ test "a balance linked from the account form while the connection syncs gets its own processing" do+ @wise_item.syncs.create!.start!+ wise_account = wise_accounts(:checking)++ assert_no_difference "@wise_item.syncs.count" do+ assert_enqueued_with(job: WiseItem::ProcessLinkedAccountJob, args: [ wise_account ]) do+ post link_accounts_wise_items_url, params: { wise_account_id: wise_account.id }+ end+ end+ assert wise_account.reload.account.present?+ end++ test "link_existing_account links a cash account in the balance's currency and syncs the connection" do+ account = manual_account(currency: "EUR")+ wise_account = wise_accounts(:checking)++ assert_difference "@wise_item.syncs.count", 1 do+ post link_existing_account_wise_items_url, params: { account_id: account.id, wise_account_id: wise_account.id }+ end++ assert_redirected_to accounts_path+ assert_equal wise_account, account.reload.provider_account_for("WiseAccount")+ assert_no_enqueued_jobs only: WiseItem::ProcessLinkedAccountJob+ end++ test "link_existing_account while the connection syncs gets the balance its own processing" do+ @wise_item.syncs.create!.start!+ account = manual_account(currency: "EUR")+ wise_account = wise_accounts(:checking)++ assert_no_difference "@wise_item.syncs.count" do+ assert_enqueued_with(job: WiseItem::ProcessLinkedAccountJob, args: [ wise_account ]) do+ post link_existing_account_wise_items_url, params: { account_id: account.id, wise_account_id: wise_account.id }+ end+ end+ assert_equal wise_account, account.reload.provider_account_for("WiseAccount")+ end++ # The rule is meant for an account another provider feeds; for another Wise+ # balance AccountProvider's own one-link-per-provider validation already+ # refuses it (with another message).+ test "link_existing_account refuses an account already linked to a provider" do+ fed_by_lunch_flow = manual_account(currency: "EUR")+ AccountProvider.create!(account: fed_by_lunch_flow, provider: lunchflow_accounts(:investment_account))+ linked_to_jar = Account.create!(family: @family, name: "Manual Jar", accountable: Depository.new(subtype: "savings"),+ balance: 0, currency: "EUR")+ AccountProvider.create!(account: linked_to_jar, provider: wise_accounts(:jar))++ [ fed_by_lunch_flow, linked_to_jar ].each do |account|+ assert_link_existing_account_refused account, I18n.t("wise_items.link_existing_account.account_already_linked")+ end+ assert_nil fed_by_lunch_flow.reload.provider_account_for("WiseAccount")+ end++ test "link_existing_account refuses an account that is not a cash account" do+ card = Account.create!(family: @family, name: "EUR card", accountable: CreditCard.new, balance: 0, currency: "EUR")++ assert_link_existing_account_refused card, I18n.t("wise_items.link_existing_account.unsupported_account_type")+ end++ # A sync overwrites the account's currency with the balance's, which would+ # leave the account's own entries in another currency.+ test "link_existing_account refuses an account in another currency than the balance" do+ account = manual_account(currency: "USD")++ assert_link_existing_account_refused account, I18n.t("wise_items.link_existing_account.currency_mismatch",+ account_currency: "USD", balance_currency: "EUR")+ end++ # Every balance in another currency would be refused, so the dialog offers+ # only those in the account's, and none here.+ test "select_existing_account offers only the balances in the account's currency" do+ { "EUR" => [ "Jar", "Wise EUR" ], "USD" => [] }.each do |currency, offered|+ account = manual_account(currency: currency)++ get select_existing_account_wise_items_url(account_id: account.id, wise_item_id: @wise_item.id)++ assert_response :success+ assert_equal offered, wise_items(:one).wise_accounts.unlinked.where(id: css_select("input[name='wise_account_id']").map { |input| input["value"] })+ .pluck(:name).sort+ assert_includes response.body, I18n.t("wise_items.select_existing_account.no_accounts_found") if offered.empty?+ end+ end++ test "link_existing_account goes back where it came from when it refuses a balance" do+ account = manual_account(currency: "USD")++ post link_existing_account_wise_items_url, params: { account_id: account.id, wise_account_id: wise_accounts(:checking).id,+ return_to: "/accounts/#{account.id}" }++ assert_redirected_to "/accounts/#{account.id}"+ end+# create redirects to select_profiles (Turbo requires a redirect from a standard# form submission) — the encrypted token travels via the session, not the response body.@@ -227,4 +347,22 @@ class WiseItemsControllerTest < ActionDispatch::IntegrationTestassert_redirected_to settings_providers_pathassert_equal I18n.t("wise_items.select_accounts.no_connection"), flash[:alert]end++ private++ def manual_account(currency:)+ Account.create!(family: @family, name: "Manual #{currency}", accountable: Depository.new(subtype: "checking"),+ balance: 0, currency: currency)+ end++ def assert_link_existing_account_refused(account, message)+ assert_no_difference [ "AccountProvider.count", "@wise_item.syncs.count" ] do+ assert_no_enqueued_jobs only: WiseItem::ProcessLinkedAccountJob do+ post link_existing_account_wise_items_url, params: { account_id: account.id, wise_account_id: wise_accounts(:checking).id }+ end+ end++ assert_redirected_to accounts_path+ assert_equal message, flash[:alert]+ endenddiff --git a/test/fixtures/files/wise/multi_currency_profile.json b/test/fixtures/files/wise/multi_currency_profile.jsonnew file mode 100644index 0000000000..b20f441d27--- /dev/null+++ b/test/fixtures/files/wise/multi_currency_profile.json@@ -0,0 +1,67 @@+{+ "multi_currency_account": {"id": 21000407, "recipientId": 41000017, "creationTime": "2026-02-16T13:08:52.271Z"},+ "balances": [+ {"id": 31000501, "currency": "CHF", "type": "STANDARD", "name": null, "icon": null, "investmentState": "NOT_INVESTED", "amount": {"value": 343.52, "currency": "CHF"}, "reservedAmount": {"value": 0.0, "currency": "CHF"}, "cashAmount": {"value": 343.52, "currency": "CHF"}, "totalWorth": {"value": 343.52, "currency": "CHF"}, "creationTime": "2026-02-16T13:09:04.118352Z", "modificationTime": "2026-08-06T23:21:53.327402Z", "recipientId": 41000101, "primary": true, "visible": true},+ {"id": 31000502, "currency": "SEK", "type": "STANDARD", "name": null, "icon": null, "investmentState": "NOT_INVESTED", "amount": {"value": 147.62, "currency": "SEK"}, "reservedAmount": {"value": 0.0, "currency": "SEK"}, "cashAmount": {"value": 147.62, "currency": "SEK"}, "totalWorth": {"value": 147.62, "currency": "SEK"}, "creationTime": "2026-02-16T13:09:04.902517Z", "modificationTime": "2026-06-03T15:40:47.713402Z", "recipientId": 41000102, "primary": false, "visible": true},+ {"id": 31000503, "currency": "PLN", "type": "STANDARD", "name": null, "icon": null, "investmentState": "NOT_INVESTED", "amount": {"value": 26.45, "currency": "PLN"}, "reservedAmount": {"value": 0.0, "currency": "PLN"}, "cashAmount": {"value": 26.45, "currency": "PLN"}, "totalWorth": {"value": 26.45, "currency": "PLN"}, "creationTime": "2026-03-19T06:41:27.553908Z", "modificationTime": "2026-03-30T13:04:22.809402Z", "recipientId": 41000103, "primary": false, "visible": true},+ {"id": 31000504, "currency": "NOK", "type": "STANDARD", "name": null, "icon": null, "investmentState": "NOT_INVESTED", "amount": {"value": 0.0, "currency": "NOK"}, "reservedAmount": {"value": 0.0, "currency": "NOK"}, "cashAmount": {"value": 0.0, "currency": "NOK"}, "totalWorth": {"value": 0.0, "currency": "NOK"}, "creationTime": "2026-05-11T17:26:45.287144Z", "modificationTime": "2026-05-20T10:48:55.713402Z", "recipientId": 41000104, "primary": false, "visible": true}+ ],+ "transfers": [+ {"id": 62000101, "user": 5200009, "targetAccount": 41000101, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.0, "created": "2026-02-24 08:47:15", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "CHF", "sourceValue": 2350.0, "targetCurrency": "CHF", "targetValue": 2350.0},+ {"id": 62000102, "user": 5200009, "targetAccount": 47000021, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 7.9811, "created": "2026-02-24 09:02:38", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "CHF", "sourceValue": 512.4, "targetCurrency": "DKK", "targetValue": 4089.52},+ {"id": 62000103, "user": 5200009, "targetAccount": 41000017, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.0, "created": "2026-03-05 10:22:51", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "SEK", "sourceValue": 18400.0, "targetCurrency": "SEK", "targetValue": 18400.0},+ {"id": 62000104, "user": 5200009, "targetAccount": 47000025, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.0, "created": "2026-03-05 16:08:30", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "SEK", "sourceValue": 15926.4, "targetCurrency": "SEK", "targetValue": 15926.4},+ {"id": 62000105, "user": 5200009, "targetAccount": 47000022, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 26.418, "created": "2026-03-19 14:52:06", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "CHF", "sourceValue": 1622.28, "targetCurrency": "CZK", "targetValue": 42857.39},+ {"id": 62000106, "user": 5200009, "targetAccount": 41000101, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.0, "created": "2026-03-19 17:20:44", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "CHF", "sourceValue": 300.0, "targetCurrency": "CHF", "targetValue": 300.0},+ {"id": 62000107, "user": 5200009, "targetAccount": 47000023, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.6237, "created": "2026-04-02 09:37:51", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "CHF", "sourceValue": 418.65, "targetCurrency": "CAD", "targetValue": 679.76},+ {"id": 62000108, "user": 5200009, "targetAccount": 41000101, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.0, "created": "2026-04-14 18:31:20", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "CHF", "sourceValue": 260.0, "targetCurrency": "CHF", "targetValue": 260.0},+ {"id": 62000109, "user": 5200009, "targetAccount": 47000024, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.0, "created": "2026-05-20 10:48:55", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "NOK", "sourceValue": 1101.0, "targetCurrency": "NOK", "targetValue": 1101.0},+ {"id": 62000110, "user": 5200009, "targetAccount": 41000102, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.0, "created": "2026-06-03 15:22:14", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "SEK", "sourceValue": 9750.0, "targetCurrency": "SEK", "targetValue": 9750.0},+ {"id": 62000111, "user": 5200009, "targetAccount": 47000025, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.0, "created": "2026-06-03 15:40:47", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "SEK", "sourceValue": 11414.57, "targetCurrency": "SEK", "targetValue": 11414.57},+ {"id": 62000112, "user": 5200009, "targetAccount": 41000101, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 1.0, "created": "2026-08-06 23:04:37", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "CHF", "sourceValue": 420.0, "targetCurrency": "CHF", "targetValue": 420.0},+ {"id": 62000113, "user": 5200009, "targetAccount": 47000021, "sourceAccount": null, "status": "outgoing_payment_sent", "reference": "", "rate": 7.9346, "created": "2026-08-06 23:43:08", "business": null, "details": {"reference": ""}, "hasActiveIssues": false, "sourceCurrency": "CHF", "sourceValue": 482.95, "targetCurrency": "DKK", "targetValue": 3832.02}+ ],+ "activities": [+ {"id": "evt-141", "type": "TRANSFER", "resource": {"type": "TRANSFER", "id": "62000113"}, "title": "<strong>Payee</strong>", "description": "Sent", "primaryAmount": "3,832.02 DKK", "secondaryAmount": "486.40 CHF", "status": "COMPLETED", "createdOn": "2026-08-06T23:43:09.779Z", "updatedOn": "2026-08-06T23:43:29.097Z"},+ {"id": "evt-140", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-21"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "214.85 CHF", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-08-06T23:21:52.614Z", "updatedOn": "2026-08-07T10:39:52.614Z"},+ {"id": "evt-139", "type": "BALANCE_DEPOSIT", "resource": {"type": "TRANSFER", "id": "62000112"}, "title": "To <strong>CHF</strong>", "description": "Added", "primaryAmount": "<positive>+ 420 CHF</positive>", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-08-06T23:04:37.644Z", "updatedOn": "2026-08-06T23:05:31.526Z"},+ {"id": "evt-138", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-20"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "113.45 CHF", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-07-09T16:54:02.819Z", "updatedOn": "2026-07-11T16:24:02.819Z"},+ {"id": "evt-137", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-19"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "58.90 CHF", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-06-18T12:06:31.257Z", "updatedOn": "2026-06-19T11:18:31.257Z"},+ {"id": "evt-136", "type": "TRANSFER", "resource": {"type": "TRANSFER", "id": "62000111"}, "title": "<strong>Payee</strong>", "description": "Sent", "primaryAmount": "11,414.57 SEK", "secondaryAmount": "11,443.87 SEK", "status": "COMPLETED", "createdOn": "2026-06-03T15:40:48.127Z", "updatedOn": "2026-06-03T15:41:13.445Z"},+ {"id": "evt-135", "type": "TRANSFER", "resource": {"type": "TRANSFER", "id": "62000110"}, "title": "<strong>Profile owner</strong>", "description": "", "primaryAmount": "<positive>+ 9,750 SEK</positive>", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-06-03T15:22:14.968Z", "updatedOn": "2026-06-03T15:22:54.732Z"},+ {"id": "evt-134", "type": "TRANSFER", "resource": {"type": "TRANSFER", "id": "62000109"}, "title": "<strong>Payee</strong>", "description": "Sent", "primaryAmount": "1,101 NOK", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-05-20T10:48:56.515Z", "updatedOn": "2026-05-20T10:49:14.585Z"},+ {"id": "evt-133", "type": "DIRECT_DEBIT_TRANSACTION", "resource": {"type": "DIRECT_DEBIT_TRANSACTION", "id": "dd-01"}, "title": "<strong>Utility</strong>", "description": "Sent", "primaryAmount": "349 NOK", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-05-15T04:12:37.468Z", "updatedOn": "2026-05-15T13:06:37.468Z"},+ {"id": "evt-132", "type": "INTERBALANCE", "resource": {"type": "BALANCE_TRANSACTION", "id": "bt-06"}, "title": "To <strong>NOK</strong>", "description": "Moved", "primaryAmount": "1,450 NOK", "secondaryAmount": "116.82 CHF", "status": "COMPLETED", "createdOn": "2026-05-11T17:33:08.925Z", "updatedOn": "2026-05-11T17:33:08.983Z"},+ {"id": "evt-131", "type": "BALANCE_DEPOSIT", "resource": {"type": "TRANSFER", "id": "62000108"}, "title": "To <strong>CHF</strong>", "description": "Added", "primaryAmount": "<positive>+ 260 CHF</positive>", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-04-14T18:31:20.402Z", "updatedOn": "2026-04-14T18:31:48.953Z"},+ {"id": "evt-130", "type": "TRANSFER", "resource": {"type": "TRANSFER", "id": "62000107"}, "title": "<strong>Payee</strong>", "description": "Sent", "primaryAmount": "679.76 CAD", "secondaryAmount": "421.86 CHF", "status": "COMPLETED", "createdOn": "2026-04-02T09:37:52.348Z", "updatedOn": "2026-04-02T09:38:05.274Z"},+ {"id": "evt-129", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-18"}, "title": "<strong>Shop</strong>", "description": "Refunded", "primaryAmount": "<positive>+ 19.80 PLN</positive>", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-30T13:04:22.096Z", "updatedOn": "2026-04-01T00:52:22.096Z"},+ {"id": "evt-128", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-17"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "23.35 PLN", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-22T07:42:58.643Z", "updatedOn": "2026-03-23T01:18:58.643Z"},+ {"id": "evt-127", "type": "INTERBALANCE", "resource": {"type": "BALANCE_TRANSACTION", "id": "bt-05"}, "title": "To <strong>PLN</strong>", "description": "Moved", "primaryAmount": "30 PLN", "secondaryAmount": "6.62 CHF", "status": "COMPLETED", "createdOn": "2026-03-22T07:20:31.177Z", "updatedOn": "2026-03-22T07:20:31.235Z"},+ {"id": "evt-126", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-16"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "18.40 PLN", "secondaryAmount": "4.06 CHF", "status": "COMPLETED", "createdOn": "2026-03-22T06:57:13.809Z", "updatedOn": "2026-03-24T01:15:13.809Z"},+ {"id": "evt-125", "type": "CARD_CHECK", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-15"}, "title": "<strong>Shop</strong>", "description": "Card checked", "primaryAmount": "0 PLN", "secondaryAmount": "", "status": "CANCELLED", "createdOn": "2026-03-21T21:26:40.552Z", "updatedOn": "2026-03-21T21:26:40.599Z"},+ {"id": "evt-124", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-14"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "152.60 PLN", "secondaryAmount": "CHF, PLN", "status": "COMPLETED", "createdOn": "2026-03-21T19:11:07.316Z", "updatedOn": "2026-03-23T00:17:07.316Z"},+ {"id": "evt-123", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-13"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "38.95 PLN", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-21T13:30:54.981Z", "updatedOn": "2026-03-22T04:24:54.981Z"},+ {"id": "evt-122", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-12"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "47.20 PLN", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-21T11:48:25.430Z", "updatedOn": "2026-03-23T02:30:25.430Z"},+ {"id": "evt-121", "type": "INTERBALANCE", "resource": {"type": "BALANCE_TRANSACTION", "id": "bt-04"}, "title": "To <strong>PLN</strong>", "description": "Moved", "primaryAmount": "180 PLN", "secondaryAmount": "39.66 CHF", "status": "COMPLETED", "createdOn": "2026-03-21T08:05:39.712Z", "updatedOn": "2026-03-21T08:05:39.770Z"},+ {"id": "evt-120", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-11"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "139.80 PLN", "secondaryAmount": "SEK, PLN", "status": "COMPLETED", "createdOn": "2026-03-20T20:38:16.249Z", "updatedOn": "2026-03-21T17:02:16.249Z"},+ {"id": "evt-119", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-10"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "71.90 PLN", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-20T18:02:33.874Z", "updatedOn": "2026-03-21T00:14:33.874Z"},+ {"id": "evt-118", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-09"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "112.30 PLN", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-20T15:26:09.127Z", "updatedOn": "2026-03-22T00:56:09.127Z"},+ {"id": "evt-117", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-08"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "54.75 PLN", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-20T12:57:21.605Z", "updatedOn": "2026-03-21T01:03:21.605Z"},+ {"id": "evt-116", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-07"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "86.40 PLN", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-20T10:13:40.388Z", "updatedOn": "2026-03-22T13:49:40.388Z"},+ {"id": "evt-115", "type": "INTERBALANCE", "resource": {"type": "BALANCE_TRANSACTION", "id": "bt-03"}, "title": "To <strong>PLN</strong>", "description": "Moved", "primaryAmount": "120 PLN", "secondaryAmount": "330.71 SEK", "status": "COMPLETED", "createdOn": "2026-03-20T07:49:02.517Z", "updatedOn": "2026-03-20T07:49:02.575Z"},+ {"id": "evt-114", "type": "INTERBALANCE", "resource": {"type": "BALANCE_TRANSACTION", "id": "bt-02"}, "title": "To <strong>PLN</strong>", "description": "Moved", "primaryAmount": "250 PLN", "secondaryAmount": "55.04 CHF", "status": "COMPLETED", "createdOn": "2026-03-20T07:31:18.040Z", "updatedOn": "2026-03-20T07:31:18.098Z"},+ {"id": "evt-113", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-06"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "63.90 PLN", "secondaryAmount": "14.13 CHF", "status": "COMPLETED", "createdOn": "2026-03-19T19:44:57.362Z", "updatedOn": "2026-03-20T22:32:57.362Z"},+ {"id": "evt-112", "type": "BALANCE_DEPOSIT", "resource": {"type": "TRANSFER", "id": "62000106"}, "title": "To <strong>CHF</strong>", "description": "Added", "primaryAmount": "<positive>+ 300 CHF</positive>", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-19T17:20:44.731Z", "updatedOn": "2026-03-19T17:21:31.834Z"},+ {"id": "evt-111", "type": "TRANSFER", "resource": {"type": "TRANSFER", "id": "62000105"}, "title": "<strong>Payee</strong>", "description": "Sent", "primaryAmount": "42,857.39 CZK", "secondaryAmount": "1,626.70 CHF", "status": "COMPLETED", "createdOn": "2026-03-19T14:52:07.873Z", "updatedOn": "2026-03-19T14:52:30.521Z"},+ {"id": "evt-110", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-05"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "27.60 PLN", "secondaryAmount": "6.10 CHF", "status": "COMPLETED", "createdOn": "2026-03-19T11:35:28.914Z", "updatedOn": "2026-03-19T15:17:28.914Z"},+ {"id": "evt-109", "type": "CASH_WITHDRAWAL", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-04"}, "title": "<strong>ATM</strong>", "description": "", "primaryAmount": "400 PLN", "secondaryAmount": "CHF, PLN", "status": "COMPLETED", "createdOn": "2026-03-19T07:19:03.655Z", "updatedOn": "2026-03-21T04:31:03.655Z"},+ {"id": "evt-108", "type": "CASH_WITHDRAWAL", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-03"}, "title": "<strong>ATM</strong>", "description": "Declined", "primaryAmount": "600 PLN", "secondaryAmount": "612.50 PLN", "status": "CANCELLED", "createdOn": "2026-03-19T07:16:47.093Z", "updatedOn": "2026-03-19T07:16:47.140Z"},+ {"id": "evt-107", "type": "INTERBALANCE", "resource": {"type": "BALANCE_TRANSACTION", "id": "bt-01"}, "title": "To <strong>PLN</strong>", "description": "Moved", "primaryAmount": "400 PLN", "secondaryAmount": "88.14 CHF", "status": "COMPLETED", "createdOn": "2026-03-19T06:58:12.486Z", "updatedOn": "2026-03-19T06:58:12.544Z"},+ {"id": "evt-106", "type": "TRANSFER", "resource": {"type": "TRANSFER", "id": "62000104"}, "title": "<strong>Payee</strong>", "description": "Sent", "primaryAmount": "15,926.40 SEK", "secondaryAmount": "15,965.35 SEK", "status": "COMPLETED", "createdOn": "2026-03-05T16:08:30.556Z", "updatedOn": "2026-03-05T16:09:31.765Z"},+ {"id": "evt-105", "type": "TRANSFER", "resource": {"type": "TRANSFER", "id": "62000103"}, "title": "<strong>Profile owner</strong>", "description": "", "primaryAmount": "<positive>+ 18,400 SEK</positive>", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-05T10:22:52.204Z", "updatedOn": "2026-03-05T10:23:02.019Z"},+ {"id": "evt-104", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-02"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "74.25 CHF", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-03-02T12:40:09.731Z", "updatedOn": "2026-03-03T19:34:09.731Z"},+ {"id": "evt-103", "type": "CARD_PAYMENT", "resource": {"type": "CARD_TRANSACTION", "id": "ctx-01"}, "title": "<strong>Shop</strong>", "description": "", "primaryAmount": "36.80 CHF", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-02-26T18:15:42.208Z", "updatedOn": "2026-02-27T21:33:42.208Z"},+ {"id": "evt-102", "type": "TRANSFER", "resource": {"type": "TRANSFER", "id": "62000102"}, "title": "<strong>Payee</strong>", "description": "Sent", "primaryAmount": "4,089.52 DKK", "secondaryAmount": "516.27 CHF", "status": "COMPLETED", "createdOn": "2026-02-24T09:02:38.917Z", "updatedOn": "2026-02-24T09:03:12.354Z"},+ {"id": "evt-101", "type": "BALANCE_DEPOSIT", "resource": {"type": "TRANSFER", "id": "62000101"}, "title": "To <strong>CHF</strong>", "description": "Added", "primaryAmount": "<positive>+ 2,350 CHF</positive>", "secondaryAmount": "", "status": "COMPLETED", "createdOn": "2026-02-24T08:47:16.689Z", "updatedOn": "2026-02-24T08:47:31.011Z"}+ ]+}diff --git a/test/integration/wise_item_render_test.rb b/test/integration/wise_item_render_test.rbnew file mode 100644index 0000000000..3a28ecc8f3--- /dev/null+++ b/test/integration/wise_item_render_test.rb@@ -0,0 +1,22 @@+require "test_helper"++class WiseItemRenderTest < ActiveSupport::TestCase+ # A failed Wise fetch leaves the sync completed, so the card's only signal+ # is the sync summary built from the latest sync's stats.+ test "the connection card shows the latest sync's errors" do+ Current.reset+ wise_item = wise_items(:one)+ message = I18n.t("wise_items.syncer.fetch_failed", count: 1)+ wise_item.syncs.create!(status: :completed, completed_at: Time.current, sync_stats: {+ "import_started" => true, "total_errors" => 1, "errors" => [ { "message" => message, "category" => "fetch_error" } ]+ })++ html = ApplicationController.render(+ partial: "wise_items/wise_item",+ locals: { wise_item: wise_item, visible_accounts: wise_item.accounts }+ )++ assert_includes html, I18n.t("provider_sync_summary.title")+ assert_includes html, message+ end+enddiff --git a/test/jobs/wise_item/process_linked_account_job_concurrency_test.rb b/test/jobs/wise_item/process_linked_account_job_concurrency_test.rbnew file mode 100644index 0000000000..25216edc8a--- /dev/null+++ b/test/jobs/wise_item/process_linked_account_job_concurrency_test.rb@@ -0,0 +1,60 @@+# frozen_string_literal: true++require "test_helper"+require "concurrent"++# The job used to book the payload and link inside one transaction under the+# balance's row lock. Its first Account save locked the owner's users row+# (Account#owner_belongs_to_family) until that transaction ended, so the next+# link click, an Account save for the same owner, waited for the whole job.+# Real threads and commits, so no test transaction.+class WiseItem::ProcessLinkedAccountJobConcurrencyTest < ActiveSupport::TestCase+ self.use_transactional_tests = false++ setup do+ @family = families(:empty)+ @wise_item = WiseItem.create!(family: @family, name: "Wise", token: "test_token", profile_id: "job-#{SecureRandom.hex(4)}",+ profile_type: :personal)+ payout = { "id" => 4711, "targetAccount" => 1234, "sourceCurrency" => "GBP", "targetCurrency" => "GBP", "sourceValue" => 25.0,+ "targetValue" => 25.0, "status" => "outgoing_payment_sent", "created" => "2026-10-10 12:00:00" }+ @gbp = WiseAccount.create!(wise_item: @wise_item, balance_id: "job-#{SecureRandom.hex(3)}", name: "Wise GBP", currency: "GBP",+ current_balance: 0, raw_payload: { "type" => "STANDARD" }, raw_transactions_payload: [ payout ])+ @account = Account.create!(family: @family, name: "Wise GBP", accountable: Depository.new(subtype: "checking"), balance: 0, currency: "GBP")+ AccountProvider.create!(account: @account, provider: @gbp)+ end++ # Nothing here is rolled back, and account providers and debug log entries+ # have no fixtures, so rows pointing at deleted accounts would trip the+ # next fixture load.+ teardown do+ DebugLogEntry.where(family_id: @family.id).delete_all+ AccountProvider.where(provider_type: "WiseAccount", provider_id: @gbp.id).delete_all+ Account.where(id: @account.id).or(Account.where(family: @family, name: "Wise USD")).find_each(&:destroy!)+ @wise_item.reload.destroy!+ end++ test "the next account saved for the same owner does not wait for the job" do+ booked = Concurrent::Event.new+ resume = Concurrent::Event.new+ # Holds the job after it booked the balance, before it links.+ WiseItem.any_instance.stubs(:link_jar_transfers!).with { booked.set && resume.wait(30) }+ job = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection { WiseItem::ProcessLinkedAccountJob.perform_now(WiseAccount.find(@gbp.id)) }+ end+ assert booked.wait(30), "the job booked the balance"++ next_account = Account.transaction do+ # A save that must wait for the job's locks fails instead of hanging.+ Account.connection.execute("SET LOCAL lock_timeout = '2s'")+ Account.create!(family: @family, name: "Wise USD", accountable: Depository.new(subtype: "checking"), balance: 0, currency: "USD")+ end+ resume.set+ job.join(30)++ assert next_account.persisted?+ assert_equal [ "wise_transfer_4711" ], @account.entries.where(source: "wise").pluck(:external_id)+ ensure+ resume&.set+ job&.join(30)+ end+enddiff --git a/test/jobs/wise_item/process_linked_account_job_test.rb b/test/jobs/wise_item/process_linked_account_job_test.rbnew file mode 100644index 0000000000..1cb2aa2084--- /dev/null+++ b/test/jobs/wise_item/process_linked_account_job_test.rb@@ -0,0 +1,160 @@+# frozen_string_literal: true++require "test_helper"++class WiseItem::ProcessLinkedAccountJobTest < ActiveJob::TestCase+ setup do+ @family = families(:empty)+ @wise_item = WiseItem.create!(family: @family, name: "Test Wise", token: "test_token", profile_id: "123", profile_type: :personal)+ @eur = link_balance("EUR", "10000001")+ @gbp = link_balance("GBP", "10000003")++ conversion = {+ "id" => "interbalance_activity_9000000106",+ "type" => "INTERBALANCE",+ "resource" => { "type" => "BALANCE_TRANSACTION", "id" => "9000000106" },+ "title" => "To <strong>EUR</strong>",+ "primaryAmount" => "1,234.56 EUR",+ "secondaryAmount" => "1,000 GBP",+ "status" => "COMPLETED",+ "createdOn" => "2026-06-23T17:28:46.305Z"+ }+ [ @eur, @gbp ].each { |wise_account| wise_account.update!(raw_transactions_payload: [ conversion ]) }++ # The connection's sync booked Wise EUR; Wise GBP was linked after that+ # sync had picked the accounts it processes.+ WiseAccount::Processor.new(@eur).process+ @inflow = @eur.current_account.entries.find_by!(external_id: "wise_interbalance_9000000106_inflow")+ end++ test "books the balance, links its conversions and recalculates the account" do+ assert_difference -> { @gbp.current_account.syncs.count }, 1 do+ WiseItem::ProcessLinkedAccountJob.perform_now(@gbp)+ end++ outflow = @gbp.current_account.entries.find_by!(external_id: "wise_interbalance_9000000106_outflow")+ transfer = Transfer.find_by!(inflow_transaction_id: @inflow.entryable_id)+ assert_equal outflow.entryable_id, transfer.outflow_transaction_id+ assert transfer.confirmed?+ assert_equal %w[funds_movement funds_movement], [ @inflow, outflow ].map { |entry| entry.entryable.reload.kind }+ assert_empty @wise_item.syncs, "the connection's own sync is left alone"+ end++ # The balance's processing lock keeps the job from interleaving with the+ # connection's sync processing the same balance.+ test "books nothing outside the balance's processing lock" do+ WiseAccount.any_instance.expects(:with_processing_lock).once # never yields++ WiseItem::ProcessLinkedAccountJob.perform_now(@gbp)++ assert_empty @gbp.current_account.entries.where(source: "wise")+ assert_not Transfer.exists?(inflow_transaction_id: @inflow.entryable_id)+ end++ # The job books what a sync stored without knowing whether that sync's+ # import was complete, so it never counts as one (import_complete: false):+ # an entry no stored row books and the opening balance made with the account+ # stay, although the history is covered from before the balance opened.+ test "deletes no entry and leaves the opening balance where it is" do+ @wise_item.update!(import_all_history: true)+ @wise_item.merge_sync_metadata!("coverage" => %w[transfers activities].index_with {+ { "from" => "2020-01-01T00:00:00Z", "through" => Time.current.utc.iso8601, "version" => WiseItem::COVERAGE_VERSION }+ })+ @gbp.update!(raw_payload: @gbp.raw_payload.merge("creationTime" => "2026-04-01T10:00:00Z"))+ account = @gbp.current_account+ # As made with the account: its balance, two years back.+ Account::OpeningBalanceManager.new(account).set_opening_balance(balance: 1250)+ stale = account.entries.create!(external_id: "wise_transfer_999", source: "wise", amount: 10, currency: "GBP",+ date: Date.new(2026, 9, 9), name: "Old payout", entryable: Transaction.new)++ WiseItem::ProcessLinkedAccountJob.perform_now(@gbp)++ assert account.entries.exists?(external_id: "wise_interbalance_9000000106_outflow")+ assert Entry.exists?(stale.id), "the job deleted an entry no stored row books"+ anchor = account.valuations.opening_anchor.sole.entry.reload+ assert_equal [ 2.years.ago.to_date, BigDecimal("1250") ], [ anchor.date, anchor.amount ]+ end++ # The job can run before the connection's sync stores this build's+ # payloads, on what an older build stored: every conversion and jar move of+ # the profile on every balance. None of them books on a balance they never+ # touched.+ test "books no conversion or jar move of other currencies an older build stored on the balance" do+ usd = link_balance("USD", "10000004")+ old_build_rows = [+ { "id" => "interbalance_activity_77", "type" => "INTERBALANCE", "resource" => { "type" => "BALANCE_TRANSACTION", "id" => "77" },+ "title" => "To <strong>GBP</strong>", "primaryAmount" => "860 GBP", "secondaryAmount" => "1,000 EUR", "status" => "COMPLETED",+ "createdOn" => "2024-05-02T10:00:00.000Z" },+ { "id" => "interbalance_activity_78", "type" => "INTERBALANCE", "resource" => { "type" => "BALANCE_TRANSACTION", "id" => "78" },+ "title" => "To <strong>Holiday</strong>", "primaryAmount" => "200 EUR", "status" => "COMPLETED", "createdOn" => "2024-06-02T10:00:00.000Z" }+ ]+ usd.update!(raw_transactions_payload: old_build_rows)++ WiseItem::ProcessLinkedAccountJob.perform_now(usd)++ assert_empty usd.current_account.entries.where(source: "wise")+ end++ # Quietly: without linking or a log entry.+ test "does nothing for a balance unlinked before the job ran" do+ account = @gbp.current_account+ @gbp.account_provider.destroy!+ WiseItem.any_instance.expects(:link_jar_transfers!).never++ assert_no_difference "DebugLogEntry.count" do+ WiseItem::ProcessLinkedAccountJob.perform_now(@gbp.reload)+ end++ assert_empty account.entries.where(source: "wise")+ assert_empty account.syncs+ end++ test "does nothing while the connection is being deleted" do+ @wise_item.update_column(:scheduled_for_deletion, true)++ WiseItem::ProcessLinkedAccountJob.perform_now(@gbp)++ assert_empty @gbp.current_account.entries.where(source: "wise")+ assert_empty @gbp.current_account.syncs+ end++ # The next sync processes the balance anyway, so a failure is logged for+ # support rather than retried for weeks.+ test "logs a processing failure for support instead of raising" do+ WiseAccount::Processor.any_instance.stubs(:process).raises(StandardError, "boom")++ assert_difference "DebugLogEntry.count", 1 do+ WiseItem::ProcessLinkedAccountJob.perform_now(@gbp)+ end++ log = DebugLogEntry.order(:created_at).last+ assert_equal "provider_sync_error", log.category+ assert_equal "wise", log.provider_key+ assert_equal @gbp.account_provider, log.account_provider+ assert_equal "StandardError", log.metadata["error_class"]+ assert_empty @gbp.current_account.syncs+ end++ test "retries a deadlock with the connection's sync" do+ WiseAccount::Processor.any_instance.stubs(:process).raises(ActiveRecord::Deadlocked)++ assert_no_difference "DebugLogEntry.count" do+ assert_enqueued_with(job: WiseItem::ProcessLinkedAccountJob, args: [ @gbp ]) do+ WiseItem::ProcessLinkedAccountJob.perform_now(@gbp)+ end+ end+ end++ private++ def link_balance(currency, balance_id)+ wise_account = WiseAccount.create!(wise_item: @wise_item, balance_id: balance_id, name: "Wise #{currency}",+ currency: currency, current_balance: 0, raw_payload: { "type" => "STANDARD" })+ AccountProvider.create!(+ account: Account.create!(family: @family, name: "Wise #{currency}", accountable: Depository.new(subtype: "checking"),+ balance: 0, currency: currency),+ provider: wise_account+ )+ wise_account+ end+enddiff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rbindex 2bc4eacfc8..ad620ac3fa 100644--- a/test/models/account/provider_import_adapter_test.rb+++ b/test/models/account/provider_import_adapter_test.rb@@ -1241,6 +1241,21 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseendend+ test "never claims a part of a split entry for a matching provider transaction" do+ parent = @account.entries.create!(date: Date.today, amount: 37.50, currency: "USD", name: "Market", entryable: Transaction.new)+ parent.split!([ { name: "Groceries", amount: 25, category_id: nil }, { name: "Household", amount: 12.50, category_id: nil } ])+ household = parent.child_entries.find_by!(name: "Household")++ entry = nil+ assert_difference "@account.entries.count", 1 do+ entry = @adapter.import_transaction(external_id: "lunchflow_678", amount: 12.50, currency: "USD", date: Date.today,+ name: "Hardware store", source: "lunchflow")+ end++ assert_not_equal household.id, entry.id+ assert_equal [ nil, nil, "Household", parent.id ], household.reload.values_at(:external_id, :source, :name, :parent_entry_id)+ end+test "claims CSV imported transaction when provider syncs matching transaction" do# Create a CSV imported transaction (has import_id but no external_id)import = Import.create!(diff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rbindex a35203ecc8..a8f9671302 100644--- a/test/models/family/auto_transfer_matchable_test.rb+++ b/test/models/family/auto_transfer_matchable_test.rb@@ -842,6 +842,52 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseassert_includes sql, "EXISTS (SELECT 1 FROM account_providers WHERE account_providers.account_id = outflow_accounts.id)"assert_includes sql, ":restrict_cross_currency_to_linked_accounts = FALSE"assert_equal 2, sql.scan(":require_common_writer = FALSE").size+ assert_equal 2, sql.scan(":exclude_same_wise_item = FALSE").size+ end++ # Moves between one Wise connection's balances are linked from Wise's own+ # activity feed (WiseItem#link_jar_transfers!); anything else the matcher+ # pairs across them is a coincidence, like a GBP top-up "matching" a USD payout.+ test "does not auto-match two balances of the same Wise connection" do+ wise_item = wise_items(:one)+ eur = link_wise_balance!(wise_item, "EUR")+ eur_jar = link_wise_balance!(wise_item, "EUR")+ gbp = link_wise_balance!(wise_item, "GBP")+ usd = link_wise_balance!(wise_item, "USD")+ ExchangeRate.create!(from_currency: "USD", to_currency: "GBP", date: Date.current, rate: 0.8156)++ # Same currency, exact amount (first UNION branch)+ jar_out = create_transaction(date: Date.current, account: eur, amount: 250.75, currency: "EUR")+ jar_in = create_transaction(date: Date.current, account: eur_jar, amount: -250.75, currency: "EUR")+ # Cross-currency inside the FX tolerance (second UNION branch)+ top_up = create_transaction(date: Date.current, account: gbp, amount: -2465, currency: "GBP")+ payout = create_transaction(date: Date.current, account: usd, amount: 3022.31, currency: "USD")++ @family.auto_match_transfers!++ assert_not Transfer.exists?(inflow_transaction_id: [ jar_in.entryable_id, top_up.entryable_id ])+ assert_not Transfer.exists?(outflow_transaction_id: [ jar_out.entryable_id, payout.entryable_id ])++ # The manual "match as transfer" dialog still offers both pairs.+ assert_includes jar_in.transaction.transfer_match_candidates.map(&:outflow_transaction_id), jar_out.entryable_id+ assert_includes top_up.transaction.transfer_match_candidates.map(&:outflow_transaction_id), payout.entryable_id+ end++ test "still auto-matches a Wise balance with a bank account or another Wise connection" do+ usd = link_wise_balance!(wise_items(:one), "USD")+ other_connection = WiseItem.create!(family: @family, name: "Personal Wise", token: "token", profile_id: "22222222",+ profile_type: :personal)+ other_usd = link_wise_balance!(other_connection, "USD")++ payout = create_transaction(date: Date.current, account: usd, amount: 5482.37)+ bank_credit = create_transaction(date: Date.current, account: @depository, amount: -5482.37)+ move_out = create_transaction(date: Date.current, account: usd, amount: 512.34)+ move_in = create_transaction(date: Date.current, account: other_usd, amount: -512.34)++ @family.auto_match_transfers!++ assert Transfer.exists?(inflow_transaction_id: bank_credit.entryable_id, outflow_transaction_id: payout.entryable_id)+ assert Transfer.exists?(inflow_transaction_id: move_in.entryable_id, outflow_transaction_id: move_out.entryable_id)endtest "does not auto-match transfers when the family has disabled auto match" do@@ -925,6 +971,15 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseAccountProvider.create!(account: account, provider: plaid_account)end+ # A new account linked to a balance of the given Wise connection.+ def link_wise_balance!(wise_item, currency)+ wise_account = wise_item.wise_accounts.create!(balance_id: SecureRandom.hex(6), name: "Wise #{currency}", currency: currency)+ account = Account.create!(family: @family, owner: users(:family_admin), name: "Wise #{currency}",+ accountable: Depository.new(subtype: "checking"), balance: 0, currency: currency)+ AccountProvider.create!(account: account, provider: wise_account)+ account+ end+def candidate_pairs@family.transfer_match_candidates.map do |candidate|[ candidate.inflow_transaction_id, candidate.outflow_transaction_id ]diff --git a/test/models/provider/wise_test.rb b/test/models/provider/wise_test.rbindex d91dfeacc1..ca7415fd4d 100644--- a/test/models/provider/wise_test.rb+++ b/test/models/provider/wise_test.rb@@ -16,54 +16,60 @@ class Provider::WiseTest < ActiveSupport::TestCaseendend+ # Intervals are UTC instants (the window a statement fetch asks for starts+ # at the moment given, not at midnight in the job's zone), chunked into+ # MAX_STATEMENT_DAYS windows that each start where the previous one ended.test "chunks balance statement requests into windows under the 469-day limit" do- start_date = Date.new(2015, 4, 12)- end_date = Date.new(2018, 4, 30)-- expected_windows = []- window_start = start_date- while window_start <= end_date- window_end = [ window_start + (Provider::Wise::MAX_STATEMENT_DAYS - 1), end_date ].min- expected_windows << {- interval_start: window_start.beginning_of_day,- interval_end: window_end.end_of_day- }- window_start = window_end + 1.day- end- assert_operator expected_windows.size, :>, 1+ interval_start = Time.utc(2015, 4, 12, 10, 30)+ interval_end = Time.utc(2018, 4, 30, 12)+ window = Provider::Wise::MAX_STATEMENT_DAYS.days+ expected = [+ [ interval_start, interval_start + window ],+ [ interval_start + window, interval_start + 2 * window ],+ [ interval_start + 2 * window, interval_end ]+ ]- expected_windows.each do |window|+ expected.each do |window_start, window_end|@provider.expects(:get_balance_statement)- .with("111", "222", currency: "EUR",- interval_start: window[:interval_start],- interval_end: window[:interval_end])- .returns({ "transactions" => [] })+ .with("111", "222", currency: "EUR", interval_start: window_start, interval_end: window_end)+ .returns({ "transactions" => [ { "referenceNumber" => window_start.iso8601 } ] }).onceend- result = @provider.get_balance_statements("111", "222", currency: "EUR", start_date: start_date, end_date: end_date)+ result = @provider.get_balance_statements("111", "222", currency: "EUR", interval_start: interval_start, interval_end: interval_end)- assert_equal [], result+ assert_equal expected.map { |window_start, _| window_start.iso8601 }, result.map { |row| row["referenceNumber"] }endtest "uses a single request when the range fits within the limit" do- @provider.stubs(:get_balance_statement)- .with("111", "222", currency: "EUR",- interval_start: Date.new(2018, 1, 1).beginning_of_day,- interval_end: Date.new(2018, 4, 30).end_of_day)+ @provider.expects(:get_balance_statement)+ .with("111", "222", currency: "EUR", interval_start: Time.utc(2018, 1, 1, 8), interval_end: Time.utc(2018, 4, 30, 17)).returns({ "transactions" => [] })+ .once- result = @provider.get_balance_statements(- "111",- "222",- currency: "EUR",- start_date: Date.new(2018, 1, 1),- end_date: Date.new(2018, 4, 30)- )+ result = @provider.get_balance_statements("111", "222", currency: "EUR", interval_start: Time.utc(2018, 1, 1, 8),+ interval_end: Time.utc(2018, 4, 30, 17))assert_equal [], resultend+ # A job keeps the zone of the request that enqueued it, and+ # Date#beginning_of_day in America/New_York started the window five hours+ # after the balance was created.+ test "sends statement intervals as UTC instants whatever zone the job runs in" do+ sent = nil+ Provider::Wise.expects(:get)+ .with { |_url, options| sent = options[:query] }+ .returns(fake_response(code: 200, body: '{"transactions":[]}'))++ Time.use_zone("America/New_York") do+ @provider.get_balance_statements("111", "222", currency: "USD", interval_start: Time.utc(2025, 11, 26, 6, 52, 41),+ interval_end: Time.zone.local(2025, 12, 3, 9))+ end++ assert_equal({ currency: "USD", intervalStart: "2025-11-26T06:52:41Z", intervalEnd: "2025-12-03T14:00:00Z" }, sent)+ end+test "signs the SCA challenge and retries once when a private key is configured" dokey = OpenSSL::PKey::RSA.new(2048)provider = Provider::Wise.new("test_token", base_url: "https://api.wise.com", sca_private_key: key.to_pem)@@ -105,23 +111,151 @@ class Provider::WiseTest < ActiveSupport::TestCasetest "retries a rate-limited window without restarting earlier windows" doerror = Provider::Wise::WiseError.new("rate limited", :rate_limited)- @provider.stubs(:sleep)+ # The retry helper is shared with the importer and sleeps at class level.+ Provider::Wise.stubs(:sleep)@provider.stubs(:get_balance_statement).raises(error).then.returns({ "transactions" => [] }).then.returns({ "transactions" => [] })- result = @provider.get_balance_statements(- "111",- "222",- currency: "EUR",- start_date: Date.new(2018, 1, 1),- end_date: Date.new(2018, 4, 30)- )+ result = @provider.get_balance_statements("111", "222", currency: "EUR", interval_start: Time.utc(2018, 1, 1),+ interval_end: Time.utc(2018, 4, 30))assert_equal [], resultend+ # Wise ignores `cursor`: only `nextCursor` reaches the next page.+ test "pages activities with nextCursor and bounds them with since" do+ sent = nil+ Provider::Wise.expects(:get)+ .with { |url, options| sent = [ url, options[:query] ] }+ .returns(fake_response(code: 200, body: '{"activities":[],"cursor":null}'))++ @provider.get_activities(123, cursor: "abc", since: Time.utc(2025, 7, 9, 16, 45))++ assert_equal "https://api.wise.com/v1/profiles/123/activities", sent.first+ assert_equal({ size: 100, nextCursor: "abc", since: "2025-07-09T16:45:00Z" }, sent.last)+ end++ test "filters transfers by their UTC creation date" do+ sent = nil+ Provider::Wise.expects(:get)+ .with { |_url, options| sent = options[:query] }+ .returns(fake_response(code: 200, body: "[]"))++ @provider.get_transfers(123, limit: 100, offset: 200, created_date_start: Time.utc(2025, 10, 7, 23, 59))++ assert_equal({ profile: 123, limit: 100, offset: 200, createdDateStart: "2025-10-07" }, sent)+ end++ test "reads the multi-currency account from the v4 endpoint" do+ Provider::Wise.expects(:get)+ .with { |url, _options| url == "https://api.wise.com/v4/profiles/123/multi-currency-account" }+ .returns(fake_response(code: 200, body: '{"recipientId":12345678}'))++ assert_equal({ "recipientId" => 12345678 }, @provider.get_multi_currency_account(123))+ end++ test "a rate-limited response carries Wise's Retry-After" do+ Provider::Wise.expects(:get).returns(fake_response(code: 429, headers: { "Retry-After" => "30" }))++ error = assert_raises(Provider::Wise::WiseError) { @provider.get_activities(123) }++ assert_equal :rate_limited, error.error_type+ assert_equal 30, error.retry_after+ end++ test "rate-limit retries wait for Retry-After when it is longer than the backoff, capped" do+ Provider::Wise.stubs(:rand).returns(0.5)+ waits = sequence("waits")+ Provider::Wise.expects(:sleep).with(30.5).in_sequence(waits)+ Provider::Wise.expects(:sleep).with(4.5).in_sequence(waits)+ Provider::Wise.expects(:sleep).with(Provider::Wise::RETRY_MAX_WAIT).in_sequence(waits)+ errors = [ 30, nil, 60 ].map { |seconds| Provider::Wise::WiseError.new("rate limited", :rate_limited, retry_after: seconds) }+ attempts = 0++ result = Provider::Wise.with_retries do+ attempts += 1+ raise errors[attempts - 1] if attempts <= errors.size++ :fetched+ end++ assert_equal :fetched, result+ end++ # Asking again before Wise's Retry-After is over would be refused too.+ test "does not wait out a Retry-After beyond the cap" do+ Provider::Wise.expects(:sleep).never+ attempts = 0++ error = assert_raises(Provider::Wise::WiseError) do+ Provider::Wise.with_retries do+ attempts += 1+ raise Provider::Wise::WiseError.new("rate limited", :rate_limited, retry_after: 300)+ end+ end++ assert_equal [ :rate_limited, 1 ], [ error.error_type, attempts ]+ end++ test "gives up after three rate-limited retries" do+ Provider::Wise.stubs(:sleep)+ attempts = 0++ assert_raises(Provider::Wise::WiseError) do+ Provider::Wise.with_retries do+ attempts += 1+ raise Provider::Wise::WiseError.new("rate limited", :rate_limited)+ end+ end+ assert_equal 4, attempts+ end++ # One 5xx answer or timeout on page 150 of a long history used to drop+ # the whole source for the sync.+ test "retries a server error and a request that failed on the way, but not an answer that will not change" do+ Provider::Wise.stubs(:sleep)+ outcomes = { server_error: :fetched, request_failed: :fetched, fetch_failed: :raised, access_forbidden: :raised, not_found: :raised }++ outcomes.each do |error_type, expected|+ attempts = 0+ outcome = begin+ Provider::Wise.with_retries do+ attempts += 1+ raise Provider::Wise::WiseError.new("failed", error_type) if attempts == 1++ :fetched+ end+ rescue Provider::Wise::WiseError+ :raised+ end+ assert_equal expected, outcome, error_type+ end+ end++ test "tells a server error from another unexpected response" do+ { 502 => :server_error, 503 => :server_error, 422 => :fetch_failed }.each do |code, error_type|+ Provider::Wise.expects(:get).returns(fake_response(code: code, body: "{}"))++ error = assert_raises(Provider::Wise::WiseError) { @provider.get_balances(123) }++ assert_equal error_type, error.error_type, code+ end+ end++ test "tells a 403 that carried an SCA challenge from one that did not" do+ Provider::Wise.expects(:get).returns(fake_response(code: 403, headers: { "x-2fa-approval" => "abc" }))+ challenged = assert_raises(Provider::Wise::WiseError) { @provider.send(:get, "/v1/me") }++ Provider::Wise.expects(:get).returns(fake_response(code: 403))+ refused = assert_raises(Provider::Wise::WiseError) { @provider.send(:get, "/v1/me") }++ assert_equal [ :access_forbidden, :access_forbidden ], [ challenged.error_type, refused.error_type ]+ assert challenged.sca_challenged?+ assert_not refused.sca_challenged?+ end+privateFakeResponse = Struct.new(:code, :body, :headers)diff --git a/test/models/wise_account/processor_test.rb b/test/models/wise_account/processor_test.rbnew file mode 100644index 0000000000..d4d81e259d--- /dev/null+++ b/test/models/wise_account/processor_test.rb@@ -0,0 +1,342 @@+require "test_helper"++class WiseAccount::ProcessorTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ @wise_item = WiseItem.create!(family: @family, name: "Test Wise", token: "test_token", profile_id: "123", profile_type: :business)+ @wise_account = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR", current_balance: 0,+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 })+ end++ # Current balance: an anchor left by another provider follows the Wise+ # balance in place, so a card payment Wise completes after a sync, dated on+ # that day, does not shift the days before it.+ test "keeps another provider's current anchor on the live balance without reconciliations" do+ @family.update!(timezone: "Europe/Dublin")+ account = link(@wise_account)+ account.entries.create!(date: Date.new(2025, 7, 21), name: "Current balance", amount: 40, currency: "EUR",+ entryable: Valuation.new(kind: "current_anchor"))+ top_up = { "id" => 1, "targetAccount" => 99999001, "sourceCurrency" => "EUR", "targetCurrency" => "EUR",+ "sourceValue" => 100.0, "targetValue" => 100.0, "status" => "outgoing_payment_sent", "created" => "2025-08-08 09:00:00" }+ card = { "id" => "card_1", "type" => "CARD_PAYMENT", "resource" => { "type" => "CARD_TRANSACTION", "id" => "1" },+ "title" => "<strong>Bakery</strong>", "primaryAmount" => "30 EUR", "secondaryAmount" => "",+ "status" => "IN_PROGRESS", "createdOn" => "2025-08-13T19:00:00.000Z" }++ # The hold is counted back in while the payment is pending.+ before = travel_to(Time.utc(2025, 8, 13, 20)) do+ sync(account, current_balance: 100, rows: [ top_up, card ])+ end+ assert_equal [ Date.new(2025, 8, 13), BigDecimal("100") ], current_anchor(account)++ # A day later (23:30 UTC is already 15 August in Dublin) the payment+ # completed, dated the 13th: yesterday's anchor is moved, not kept as a+ # reconciliation that would put the payment back onto every earlier day.+ after = travel_to(Time.utc(2025, 8, 14, 23, 30)) do+ sync(account, current_balance: 70, rows: [ top_up, card.merge("status" => "COMPLETED") ])+ end++ assert_equal [ Date.new(2025, 8, 15), BigDecimal("70") ], current_anchor(account)+ assert_empty account.valuations.reconciliation+ assert_equal before.select { |date, _| date < Date.new(2025, 8, 13) }, after.select { |date, _| date < Date.new(2025, 8, 13) }+ assert_equal BigDecimal("100"), after[Date.new(2025, 8, 10)]+ assert_equal BigDecimal("70"), after[Date.new(2025, 8, 13)]+ end++ # The history used to stop at the stale anchor (1 September, 500) although+ # Wise reported 800.+ test "an account linked from another provider follows the Wise balance" do+ travel_to Time.utc(2026, 10, 17, 12) do+ account = @family.accounts.create!(name: "Wise (EUR)", balance: 500, cash_balance: 500, currency: "EUR", accountable: Depository.new)+ account.entries.create!(date: Date.new(2025, 11, 26), name: "Opening balance", amount: 0, currency: "EUR",+ entryable: Valuation.new(kind: "opening_anchor"))+ account.entries.create!(date: Date.new(2026, 9, 1), name: "Current balance", amount: 500, currency: "EUR",+ entryable: Valuation.new(kind: "current_anchor"))+ AccountProvider.create!(account: account, provider: @wise_account)+ top_up = { "id" => 554, "targetAccount" => 99999001, "sourceCurrency" => "EUR", "targetCurrency" => "EUR",+ "sourceValue" => 600.0, "targetValue" => 600.0, "status" => "outgoing_payment_sent", "created" => "2026-09-15 10:00:00" }+ sent = payout(555, created: "2026-10-10 10:00:00").merge("sourceValue" => 300.0, "targetValue" => 300.0)+ @wise_account.update!(current_balance: 800, raw_transactions_payload: [ top_up, sent ])++ WiseAccount::Processor.new(@wise_account).process+ Balance::Materializer.new(Account.find(account.id), strategy: :reverse).materialize_balances++ latest = account.balances.order(:date).last+ assert_equal [ Date.current, BigDecimal("800") ], [ latest.date, latest.balance ]+ assert_equal BigDecimal("1100"), account.balances.find_by!(date: Date.new(2026, 10, 9)).balance+ end+ end++ test "sets the account balance without an anchor of its own" do+ account = link(@wise_account)+ @wise_account.update!(current_balance: 25.5)++ WiseAccount::Processor.new(@wise_account).process++ assert_equal BigDecimal("25.5"), account.reload.balance+ assert_empty account.valuations.current_anchor+ end++ # Processing and the clean-up run under the balance's lock, on the payload+ # as it stands once the lock is held.+ test "processes under the balance's lock the payload a sync stored meanwhile" do+ account = link(@wise_account)+ waiting = WiseAccount.find(@wise_account.id)+ WiseAccount.find(@wise_account.id).update!(raw_transactions_payload: [ payout(4711) ])++ WiseAccount::Processor.new(waiting).process++ assert_equal [ "wise_transfer_4711" ], account.entries.pluck(:external_id)+ end++ test "books nothing unless it holds the balance's lock" do+ account = link(@wise_account)+ @wise_account.update!(current_balance: 25.5, raw_transactions_payload: [ payout(4711) ])+ @wise_account.expects(:with_processing_lock).returns(nil)++ WiseAccount::Processor.new(@wise_account).process++ assert_empty account.entries+ assert_equal 0, account.reload.balance+ end++ # The opening balance repair.+ test "moves an opening balance made at the live balance to 0 the day before Wise opened the balance, once" do+ @family.update!(timezone: "Europe/Dublin")+ account = full_history_account(creation_time: "2025-03-26T08:00:00Z")+ assert_equal [ 2.years.ago.to_date, BigDecimal("80") ], opening_anchor(account)++ assert_difference -> { anchor_notes.where(level: "info").count }, 1 do+ WiseAccount::Processor.new(@wise_account, import_complete: true).process+ end+ assert_equal [ Date.new(2025, 3, 25), BigDecimal("0") ], opening_anchor(account)++ assert_no_difference -> { anchor_notes.count } do+ WiseAccount::Processor.new(@wise_account, import_complete: true).process+ end+ assert_equal [ Date.new(2025, 3, 25), BigDecimal("0") ], opening_anchor(account)+ end++ # A pay-in that makes Wise open the balance can be created before it, and+ # may only be listed after the opening balance was moved.+ test "opens the balance before a row booked earlier than the day before Wise opened it" do+ account = full_history_account(creation_time: "2025-10-29T00:10:00Z")+ WiseAccount::Processor.new(@wise_account, import_complete: true).process+ assert_equal [ Date.new(2025, 10, 28), BigDecimal("0") ], opening_anchor(account)++ @wise_account.update!(raw_transactions_payload: [ payout(4711, created: "2025-10-24 20:00:00") ])+ WiseAccount::Processor.new(@wise_account, import_complete: true).process++ assert_equal [ Date.new(2025, 10, 23), BigDecimal("0") ], opening_anchor(account)+ end++ # A connection whose balances all have statements lists no transfers, so+ # no transfers coverage is recorded; the balance's statements, fetched+ # from when Wise opened it, carry what its transfers did.+ test "moves the opening balance of a balance its statements cover in place of a transfer list" do+ account = full_history_account(creation_time: "2025-03-26T08:00:00Z")+ @wise_item.update!(raw_payload: { "coverage" => { "activities" => @wise_item.sync_metadata.dig("coverage", "activities") } })+ statements = { "from" => "2025-03-26T08:00:00Z", "through" => "2026-10-17T12:00:00Z" }++ WiseAccount::Processor.new(@wise_account.reload, import_complete: true).process+ assert_equal [ 2.years.ago.to_date, BigDecimal("80") ], opening_anchor(account)++ @wise_account.update!(raw_payload: @wise_account.raw_payload.merge("statements_coverage" => statements))+ WiseAccount::Processor.new(@wise_account.reload, import_complete: true).process+ assert_equal [ Date.new(2025, 3, 25), BigDecimal("0") ], opening_anchor(account)+ end++ test "creates the opening balance at 0 the day before Wise opened a full-history balance" do+ @family.update!(timezone: "Europe/Dublin")+ @wise_item.update!(import_all_history: true)+ @wise_account.update!(current_balance: 80, raw_payload: @wise_account.raw_payload.merge("creationTime" => "2025-04-16T10:00:00Z"))++ account = Account.create_from_wise_account(@wise_account)++ assert_equal [ Date.new(2025, 4, 15), BigDecimal("0") ], opening_anchor(account)+ assert_equal BigDecimal("80"), account.balance+ end++ test "creates the opening balance as before without the full history" do+ @wise_account.update!(current_balance: 80, raw_payload: @wise_account.raw_payload.merge("creationTime" => "2025-11-12T10:00:00Z"))++ account = Account.create_from_wise_account(@wise_account)++ assert_equal [ 2.years.ago.to_date, BigDecimal("80") ], opening_anchor(account)+ end++ test "leaves the opening balance alone unless every condition for moving it holds" do+ {+ "after an incomplete import" => [ {}, { import_complete: false } ],+ "without the full history" => [ { full_history: false }, {} ],+ "with coverage starting after the balance opened" => [ { covered_from: "2025-12-09T00:00:00Z" }, {} ],+ "on an account with a transaction of its own" => [ { manual_entry: true }, {} ]+ }.each do |label, (setup, options)|+ @wise_account.account_provider&.destroy!+ account = full_history_account(creation_time: "2025-12-03T08:00:00Z", **setup)++ WiseAccount::Processor.new(@wise_account.reload, import_complete: options.fetch(:import_complete, true)).process++ assert_equal [ 2.years.ago.to_date, BigDecimal("80") ], opening_anchor(account), label+ end+ assert_empty anchor_notes+ end++ # The current anchor another provider left moves to today before the repair+ # looks for the oldest entry, so its old date never pulls the opening+ # balance back.+ test "repairs the opening balance of an account another provider anchored by the Wise rows alone" do+ account = full_history_account(creation_time: "2026-04-08T08:00:00Z")+ account.entries.create!(date: Date.new(2026, 3, 1), name: "Current balance", amount: 80, currency: "EUR",+ entryable: Valuation.new(kind: "current_anchor"))++ WiseAccount::Processor.new(@wise_account.reload, import_complete: true).process++ assert_equal [ Date.new(2026, 4, 7), BigDecimal("0") ], opening_anchor(account)+ assert_equal [ Date.current, BigDecimal("80") ], current_anchor(account)+ end++ # The valuation drawer saves a person's edit through+ # Account#update_reconciliation, which does not mark the entry+ # user_modified, so the repair replaced the opening balance they entered. It+ # now moves only an anchor Sure set: the default made with the account,+ # never changed since, or the one it wrote last.+ test "keeps an opening balance a person changed, and says so" do+ {+ "edited in the valuation drawer" => ->(account, anchor) {+ assert account.update_reconciliation(anchor, balance: 120, date: Date.new(2026, 3, 1)).success?+ },+ "marked as edited" => ->(_account, anchor) { anchor.update!(user_modified: true) },+ "edited after Sure had moved it" => ->(account, anchor) {+ WiseAccount::Processor.new(@wise_account.reload, import_complete: true).process+ @wise_account.update!(raw_transactions_payload: [ payout(4711, created: "2026-03-20 12:00:00") ])+ assert account.update_reconciliation(anchor.reload, balance: 0, date: Date.new(2026, 3, 26)).success?+ }+ }.each do |label, change|+ @wise_account.account_provider&.destroy!+ account = full_history_account(creation_time: "2026-04-02T08:00:00Z")+ anchor = account.valuations.opening_anchor.sole.entry+ change.call(account, anchor)+ kept = opening_anchor(account)++ assert_difference -> { anchor_notes.where(level: "info").count }, 1, label do+ WiseAccount::Processor.new(@wise_account.reload, import_complete: true).process+ end++ assert_equal kept, opening_anchor(account), label+ assert_equal kept.first.iso8601, anchor_notes.order(:created_at).last.metadata["kept_opening_date"], label+ end+ end++ # An anchor Sure set (here when it created the account) stays Sure's to+ # move, e.g. for a pay-in listed later that Wise created before it opened+ # the balance.+ test "moves again the opening balance it set when it created the account" do+ @wise_item.update!(import_all_history: true)+ @wise_item.merge_sync_metadata!("coverage" => %w[transfers activities].index_with {+ { "from" => "2025-06-24T07:59:00Z", "through" => "2026-10-17T12:00:00Z", "version" => WiseItem::COVERAGE_VERSION }+ })+ @wise_account.update!(raw_payload: @wise_account.raw_payload.merge("creationTime" => "2025-06-25T08:00:00Z"))+ account = Account.create_from_wise_account(@wise_account)+ AccountProvider.create!(account: account, provider: @wise_account)+ assert_equal [ Date.new(2025, 6, 24), BigDecimal("0") ], opening_anchor(account)++ @wise_account.update!(raw_transactions_payload: [ payout(4711, created: "2025-06-11 12:00:00") ])+ WiseAccount::Processor.new(@wise_account.reload, import_complete: true).process++ assert_equal [ Date.new(2025, 6, 10), BigDecimal("0") ], opening_anchor(account)+ end++ # The default opening balance was dated two years back in the zone of the+ # request that created the account (the family's zone then), and a sync runs+ # in the zone of the request that started it, or in UTC when scheduled. An+ # account created at 22:15 UTC from a request in Honolulu (UTC-10) has its+ # anchor dated 9 Jul 2024; a sync running in Tokyo, where that instant is+ # 10 Jul, took it for an anchor a person set and never moved it.+ test "moves a default opening balance dated in another time zone than the sync runs in" do+ @family.update!(timezone: "Europe/Dublin")+ {+ "made at 22:15 UTC in Honolulu, synced in Tokyo" => [ Time.utc(2026, 7, 9, 22, 15, 15), "Pacific/Honolulu", "Asia/Tokyo" ],+ "made at 00:30 in Dublin, synced in UTC" => [ Time.utc(2026, 6, 18, 23, 30), "Europe/Dublin", "UTC" ],+ "made at 20:30 in New York, synced in UTC" => [ Time.utc(2026, 6, 10, 0, 30), "America/New_York", "UTC" ]+ }.each do |label, (made_at, made_in, synced_in)|+ @wise_account.account_provider&.destroy!+ account = travel_to(made_at) { Time.use_zone(made_in) { full_history_account(creation_time: "2026-03-12T08:00:00Z") } }+ assert_equal made_at.in_time_zone(made_in).to_date - 2.years, opening_anchor(account).first, label++ travel_to(Time.utc(2026, 10, 18, 12)) do+ Time.use_zone(synced_in) { WiseAccount::Processor.new(@wise_account.reload, import_complete: true).process }+ end++ assert_equal [ Date.new(2026, 3, 11), BigDecimal("0") ], opening_anchor(account), label+ end+ assert_empty anchor_notes.select { |note| note.metadata.key?("kept_opening_date") }+ end++ test "reports an opening balance it cannot move and processes the account anyway" do+ account = full_history_account(creation_time: "2024-11-20T08:00:00Z", rows: [ payout(4711) ])+ Account::OpeningBalanceManager.any_instance.stubs(:set_opening_balance)+ .returns(Account::OpeningBalanceManager::Result.new(success?: false, changes_made?: false,+ error: "Opening balance date must be before the oldest entry date"))++ result = WiseAccount::Processor.new(@wise_account, import_complete: true).process++ assert_equal 1, result[:imported]+ assert_equal [ "wise_transfer_4711" ], account.entries.where(source: "wise").pluck(:external_id)+ assert_equal "warn", anchor_notes.sole.level+ end++ private++ def link(wise_account, balance: 0)+ account = Account.create!(family: @family, name: wise_account.name, balance: balance, currency: wise_account.currency,+ accountable: Depository.new(subtype: "checking"))+ AccountProvider.create!(account: account, provider: wise_account)+ account+ end++ # An account set up by an older build: its opening anchor is today's+ # balance two years back. The item imports the full history and covered+ # the balance back to `covered_from`.+ def full_history_account(creation_time:, rows: [], full_history: true, covered_from: "2024-11-06T05:13:00Z",+ manual_entry: false)+ @wise_item.update!(import_all_history: full_history, raw_payload: nil)+ @wise_item.merge_sync_metadata!("coverage" => %w[transfers activities].index_with {+ { "from" => covered_from, "through" => "2026-10-17T12:00:00Z", "version" => WiseItem::COVERAGE_VERSION }+ })+ @wise_account.update!(current_balance: 80, raw_transactions_payload: rows,+ raw_payload: @wise_account.raw_payload.merge("creationTime" => creation_time))+ account = Account.create_and_sync({ family: @family, name: "Wise EUR", balance: 80, currency: "EUR",+ accountable_type: "Depository", accountable_attributes: { subtype: "checking" } },+ skip_initial_sync: true)+ AccountProvider.create!(account: account, provider: @wise_account)+ account.entries.create!(date: Date.new(2026, 6, 1), name: "Cash", amount: 5, currency: "EUR", entryable: Transaction.new) if manual_entry+ account+ end++ def payout(id, created: "2026-10-10 12:00:00")+ { "id" => id, "targetAccount" => 4242, "sourceCurrency" => "EUR", "targetCurrency" => "EUR",+ "sourceValue" => 25.0, "targetValue" => 25.0, "status" => "outgoing_payment_sent", "created" => created }+ end++ # Processes the balance as a sync's processing would, then the balance+ # history as the account sync after it does, on a freshly loaded account+ # (it memoizes its anchors): { date => end balance }.+ def sync(account, current_balance:, rows:)+ @wise_account.update!(current_balance: current_balance, raw_transactions_payload: rows)+ WiseAccount::Processor.new(@wise_account, import_complete: true).process+ Balance::Materializer.new(Account.find(account.id), strategy: :reverse).materialize_balances+ account.balances.order(:date).to_h { |balance| [ balance.date, balance.balance ] }+ end++ def current_anchor(account)+ account.valuations.current_anchor.sole.entry.then { |entry| [ entry.date, entry.amount ] }+ end++ def opening_anchor(account)+ account.valuations.opening_anchor.sole.entry.reload.then { |entry| [ entry.date, entry.amount ] }+ end++ def anchor_notes+ DebugLogEntry.where(provider_key: "wise").where("metadata ->> 'operation' = ?", "opening_anchor")+ end+enddiff --git a/test/models/wise_account/transactions/processor_test.rb b/test/models/wise_account/transactions/processor_test.rbnew file mode 100644index 0000000000..c7f22da9be--- /dev/null+++ b/test/models/wise_account/transactions/processor_test.rb@@ -0,0 +1,559 @@+require "test_helper"++# The stale-entry clean-up after processing.+class WiseAccount::Transactions::ProcessorTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ @wise_item = WiseItem.create!(family: @family, name: "Test Wise", token: "test_token", profile_id: "123", profile_type: :business)+ @wise_account = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 })+ @account = link(@wise_account)+ # Fetched since early December (the clean-up judges only days Sure+ # fetched).+ covered(transfers: "2025-12-08T00:00:00Z", activities: "2025-12-08T00:00:00Z")+ end++ test "deletes the entries no stored row books any more" do+ # Booked by an earlier sync: a payout Wise has since cancelled, and a+ # conversion leg an older routing rule put on this balance.+ stale_entry("wise_transfer_701", date: Date.new(2026, 10, 10))+ stale_entry("wise_interbalance_9001_outflow", date: Date.new(2026, 10, 11))+ store(payout(701, status: "cancelled"), payout(702))++ result = nil+ assert_difference -> { prune_notes.count }, 1 do+ result = process+ end++ assert_equal [ "wise_transfer_702" ], wise_external_ids+ assert_equal [ 1, 2, 0 ], result.values_at(:imported, :pruned, :prune_kept)+ note = prune_notes.sole+ assert_equal "info", note.level+ assert_equal [ "wise_transfer_701", "wise_interbalance_9001_outflow" ], note.metadata["destroyed_external_ids"]+ assert_equal [ @wise_account.id, "EUR" ], note.metadata.values_at("wise_account_id", "currency")+ assert_equal @wise_account.account_provider, note.account_provider+ end++ # An account linked to the balance can hold another connection's Wise+ # history (one removed since, or another profile's). Those entries were+ # booked before the link, so the clean-up leaves them alone even where they+ # overlap the balance's own rows.+ test "keeps the Wise entries an account held before the balance was linked to it" do+ earlier = stale_entry("wise_transfer_88000001", date: Date.new(2026, 10, 11))+ earlier.update_columns(created_at: @wise_account.account_provider.created_at - 1.day)+ stale_entry("wise_transfer_701", date: Date.new(2026, 10, 11))+ store(payout(702))++ result = process++ assert_equal [ 1 ], result.values_at(:pruned)+ assert_equal [ "wise_transfer_702", "wise_transfer_88000001" ], wise_external_ids.sort+ end++ # A split parent and a fee another transfer carries are kept too; deleting+ # them would take the person's split parts or the transfer's fee with them.+ test "keeps and reports the stale entries a person acted on" do+ tag = @family.tags.create!(name: "Receipts")+ bank = Account.create!(family: @family, name: "Bank", balance: 0, currency: "EUR", accountable: Depository.new(subtype: "checking"))+ savings = Account.create!(family: @family, name: "Savings", balance: 0, currency: "EUR", accountable: Depository.new(subtype: "savings"))+ store(payout(702))+ protections = {+ "edited" => ->(entry) { entry.update!(user_modified: true) },+ "import-locked" => ->(entry) { entry.update!(import_locked: true) },+ "with a locked field" => ->(entry) { entry.update!(locked_attributes: { "date" => Time.current.iso8601 }) },+ "with a locked category" => ->(entry) { entry.entryable.update!(locked_attributes: { "category_id" => Time.current.iso8601 }) },+ "with notes" => ->(entry) { entry.update!(notes: "Paid back in cash") },+ "tagged" => ->(entry) { entry.entryable.update!(tag_ids: [ tag.id ]) },+ "with a receipt" => ->(entry) {+ entry.entryable.attachments.attach(io: StringIO.new("%PDF-1.4"), filename: "receipt.pdf", content_type: "application/pdf")+ },+ "reconciled" => ->(entry) { entry.update!(reconciled_at: Time.current) },+ "in a transfer the person confirmed with another bank" => ->(entry) {+ credit = bank.entries.create!(amount: -10, currency: "EUR", date: entry.date, name: "From Wise", entryable: Transaction.new)+ Transfer.create!(inflow_transaction: credit.entryable, outflow_transaction: entry.entryable, status: "confirmed")+ },+ # Parts under the entry without the edit mark Entry#split! also sets.+ "split into parts" => ->(entry) {+ entry.child_entries.create!(account: @account, date: entry.date, name: "Lunch", amount: 10, currency: "EUR", entryable: Transaction.new)+ },+ "the fee of another transfer" => ->(entry) {+ credit = savings.entries.create!(amount: -50, currency: "EUR", date: entry.date, name: "Saved", entryable: Transaction.new)+ debit = bank.entries.create!(amount: 50, currency: "EUR", date: entry.date, name: "To savings", entryable: Transaction.new)+ transfer = Transfer.create!(inflow_transaction: credit.entryable, outflow_transaction: debit.entryable, status: "confirmed")+ entry.entryable.update!(transfer_id: transfer.id)+ }+ }++ protections.each_with_index do |(label, protect), index|+ entry = stale_entry("wise_transfer_#{800 + index}")+ protect.call(entry)++ result = process++ assert Entry.exists?(entry.id), "#{label} entry was deleted"+ assert_equal [ 0, index + 1 ], result.values_at(:pruned, :prune_kept), label+ assert_includes prune_notes.order(:created_at).last.metadata["kept_external_ids"], entry.external_id, label+ end+ end++ # Exclusion does not take an entry out of the balance, and Wise's own links+ # (a suggestion, a conversion linked to another balance of this item) are+ # restored by the next link run where they still apply.+ test "deletes a stale entry that is only excluded, and Wise's own transfer links with stale legs" do+ gbp = @wise_item.wise_accounts.create!(balance_id: "10000002", name: "Wise GBP", currency: "GBP", raw_payload: { "type" => "STANDARD" })+ gbp_account = link(gbp)+ bank = Account.create!(family: @family, name: "Bank", balance: 0, currency: "EUR", accountable: Depository.new(subtype: "checking"))+ excluded = stale_entry("wise_transfer_801", excluded: true)+ eur_leg = stale_entry("wise_interbalance_77_outflow")+ gbp_leg = gbp_account.entries.create!(external_id: "wise_interbalance_77_inflow", source: "wise", amount: -8.6, currency: "GBP",+ date: eur_leg.date, name: "Moved", entryable: Transaction.new)+ conversion = Transfer.create!(inflow_transaction: gbp_leg.entryable, outflow_transaction: eur_leg.entryable, status: "confirmed")+ conversion.confirm!+ suggested = stale_entry("wise_transfer_802")+ credit = bank.entries.create!(amount: -10, currency: "EUR", date: suggested.date, name: "From Wise", entryable: Transaction.new)+ suggestion = Transfer.create!(inflow_transaction: credit.entryable, outflow_transaction: suggested.entryable, status: "pending")+ store(payout(702))++ assert_equal 3, process[:pruned]++ assert_not Entry.exists?(excluded.id)+ assert_not Entry.exists?(eur_leg.id)+ assert_not Entry.exists?(suggested.id)+ assert_not Transfer.exists?(conversion.id)+ assert_not Transfer.exists?(suggestion.id)+ assert_equal "standard", gbp_leg.entryable.reload.kind+ assert Entry.exists?(credit.id)+ end++ # A link is Wise's own only when the linker made it, the two legs of one+ # conversion or jar move on this item, and nobody added to it. The clean-up+ # deleted a stale leg's transfer with the fee entry a person had added in+ # the transfer drawer (a transfer's fee transactions go with it), and a+ # transfer a person matched between two Wise balances.+ test "keeps the stale legs of transfers a person made or added to" do+ gbp_account = link(@wise_item.wise_accounts.create!(balance_id: "10000002", name: "Wise GBP", currency: "GBP",+ raw_payload: { "type" => "STANDARD" }))+ linked_conversion = lambda do |resource_id, **attributes|+ eur_leg = stale_entry("wise_interbalance_#{resource_id}_outflow")+ gbp_leg = gbp_account.entries.create!(external_id: "wise_interbalance_#{resource_id}_inflow", source: "wise", amount: -8.6,+ currency: "GBP", date: eur_leg.date, name: "Moved", entryable: Transaction.new)+ Transfer.create!(inflow_transaction: gbp_leg.entryable, outflow_transaction: eur_leg.entryable, status: "confirmed", **attributes)+ .tap(&:confirm!)+ end+ with_fee = linked_conversion.call("78")+ fee = gbp_account.entries.create!(amount: 1.5, currency: "GBP", date: Date.new(2026, 10, 12), name: "Conversion fee",+ entryable: Transaction.new(transfer_id: with_fee.id))+ with_notes = linked_conversion.call("79", notes: "Holiday money")+ pay_in = gbp_account.entries.create!(external_id: "wise_transfer_9000000101", source: "wise", amount: -8.6, currency: "GBP",+ date: Date.new(2026, 10, 12), name: "Top-up", entryable: Transaction.new)+ matched = Transfer.create!(inflow_transaction: pay_in.entryable, outflow_transaction: stale_entry("wise_transfer_9000000101").entryable,+ status: "confirmed")+ store(payout(702))++ result = process++ assert_equal [ 0, 3 ], result.values_at(:pruned, :prune_kept)+ assert [ with_fee, with_notes, matched ].all? { |transfer| Transfer.exists?(transfer.id) }+ assert Entry.exists?(fee.id)+ assert_equal %w[wise_interbalance_78_outflow wise_interbalance_79_outflow wise_transfer_9000000101],+ prune_notes.sole.metadata["kept_external_ids"].sort+ end++ test "deletes nothing after an incomplete import, without a payload, on a closed balance or when a row fails" do+ entry = stale_entry("wise_transfer_701")+ {+ "an incomplete import" => -> { store(payout(702)); process(import_complete: false) },+ "no payload" => -> { @wise_account.update!(raw_transactions_payload: nil); process },+ "a closed balance" => -> {+ @wise_account.update!(raw_payload: @wise_account.raw_payload.merge("closed_at" => 1.day.ago.utc.iso8601))+ store(payout(702))+ process.tap { @wise_account.update!(raw_payload: @wise_account.raw_payload.except("closed_at")) }+ },+ "a row that fails" => -> { store(payout(702), payout(703).except("created")); process }+ }.each do |label, run|+ result = run.call++ assert Entry.exists?(entry.id), "deleted after #{label}"+ assert_equal 0, result[:pruned], label+ end+ assert_empty prune_notes+ end++ # A shorter history (or an account linked from elsewhere) says nothing+ # about the entries before its first row.+ test "never deletes entries dated before the payload's earliest row" do+ older = stale_entry("wise_transfer_700", date: Date.new(2026, 10, 9))+ same_day = stale_entry("wise_transfer_701", date: Date.new(2026, 10, 10))+ store(payout(702, created: "2026-10-10 06:00:00"))++ process++ assert Entry.exists?(older.id)+ assert_not Entry.exists?(same_day.id)+ assert_equal [ "wise_transfer_701" ], prune_notes.sole.metadata["destroyed_external_ids"]+ end++ # A balance whose re-routed payload is empty (one that only held misrouted+ # copies) is exactly where the misrouted legs sit.+ test "on an empty payload deletes only the entries of rows routing moves" do+ routed = %w[wise_interbalance_5_outflow wise_transfer_6 wise_fee_6 wise_activity_card_1].map { |id| stale_entry(id) }+ statement = stale_entry("wise_statement_TRANSFER-9")+ store++ assert_equal 4, process[:pruned]++ assert routed.none? { |entry| Entry.exists?(entry.id) }+ assert Entry.exists?(statement.id)+ end++ # Beyond the cap, only the entries whose rows a sync that re-fetched the+ # whole history moved out of the payload go+ # (WiseAccount#prune_cap_bypass_ids). That stays pending through incomplete+ # imports and is spent once the clean-up has run; any other stale entry+ # waits. It used to be any number of any stale entries, but only in the+ # re-fetching sync itself, which an incomplete import wasted.+ test "deletes nothing beyond the cap but the entries whose rows a full re-fetch moved out" do+ stale = (801..806).map { |id| stale_entry("wise_transfer_#{id}") }+ store(payout(702))++ result = nil+ assert_difference -> { prune_notes.where(level: "warn").count }, 1 do+ result = process+ end++ assert_equal 0, result[:pruned]+ assert stale.all? { |entry| Entry.exists?(entry.id) }+ note = prune_notes.sole+ assert_equal [ 6, 0 ], note.metadata.values_at("capped_count", "destroyed_count")+ assert_equal stale.map(&:external_id), note.metadata["capped_external_ids"]++ moved = stale.first(5).map(&:external_id) + [ "wise_fee_801" ]+ @wise_account.update!(raw_payload: @wise_account.raw_payload.merge("prune_cap_bypass" => moved))+ assert_equal 0, process(import_complete: false)[:pruned]+ assert_equal moved, @wise_account.reload.prune_cap_bypass_ids++ assert_equal 5, process[:pruned]+ assert_equal %w[wise_transfer_702 wise_transfer_806], wise_external_ids+ note = prune_notes.order(:created_at).last+ assert_equal [ true, 5, [ "wise_transfer_806" ] ], note.metadata.values_at("cap_bypassed", "destroyed_count", "capped_external_ids")+ assert_empty @wise_account.reload.prune_cap_bypass_ids+ end++ test "spends a pending cap bypass whenever the clean-up runs, also with nothing stale" do+ store(payout(702))+ @wise_account.update!(raw_payload: @wise_account.raw_payload.merge("prune_cap_bypass" => [ "wise_transfer_801" ]))++ process++ assert_not @wise_account.reload.raw_payload.key?("prune_cap_bypass")+ assert_empty prune_notes+ end++ # The clean-up used to leave every activity entry of a balance with+ # statement rows alone until the statement rows could take them over. Now+ # the statement row matched to a card payment (WiseItem::StatementMigration)+ # renames its entry before the clean-up, keeping the person's category, and+ # an activity entry no row books is stale like any other.+ test "a statement row takes its card payment's entry over before the stale clean-up" do+ card = stale_entry("wise_activity_card_1")+ card.entryable.update!(locked_attributes: { "category_id" => Time.current.iso8601 })+ forgotten = stale_entry("wise_activity_card_2")+ cancelled = stale_entry("wise_transfer_701")+ store(payout(701, status: "cancelled"), card_payment("card_1").merge("wise_superseded_by" => "wise_statement_CARD-555"),+ statement_row("CARD-555", -12.5, supersedes: { "main" => "wise_activity_card_1" }))++ result = process++ assert_equal [ 1, 2 ], result.values_at(:imported, :pruned)+ assert_equal [ [ card.id, "wise_statement_CARD-555", BigDecimal("12.5") ] ], @account.entries.where(source: "wise").pluck(:id, :external_id, :amount)+ assert card.entryable.reload.locked_attributes.key?("category_id")+ assert_not Entry.exists?(forgotten.id)+ assert_not Entry.exists?(cancelled.id)+ assert_equal({ "renamed_count" => 1 }, rekey_notes.sole.metadata.slice("renamed_count", "replaced_count", "dropped_count"))+ end++ test "renames a transfer's entry and its fee to its statement row's, keeping what a person did" do+ main = stale_entry("wise_transfer_801", amount: 100, notes: "Rent for October")+ fee = stale_entry("wise_fee_801", amount: 2.5)+ store(payout(801).merge("wise_superseded_by" => "wise_statement_TRANSFER-801"),+ statement_row("TRANSFER-801", -102.5, fee: 2.5, supersedes: { "main" => "wise_transfer_801", "fee" => "wise_fee_801" }))++ result = process++ assert_equal [ 1, 1, 0 ], result.values_at(:imported, :skipped, :pruned)+ assert_equal [ [ main.id, "wise_statement_TRANSFER-801", BigDecimal("100") ], [ fee.id, "wise_statement_TRANSFER-801_fee", BigDecimal("2.5") ] ],+ @account.entries.where(source: "wise").order(:external_id).pluck(:id, :external_id, :amount)+ assert_equal "Rent for October", main.reload.notes+ assert_equal 2, rekey_notes.sole.metadata["renamed_count"]+ end++ # The old migration booked a pay-in again from its statement row, so both+ # entries exist. The one a person acted on (or that sits in a transfer, or+ # that they did not hide) stays under the statement id, the other goes; when+ # a person acted on both, both stay and support is told.+ test "keeps one entry when an older migration booked a transfer twice" do+ acted_on = stale_entry("wise_transfer_901", amount: -50, notes: "Salary")+ duplicate_901 = stale_entry("wise_statement_TRANSFER-901", amount: -50)+ plain = stale_entry("wise_transfer_902", amount: -60)+ linked = stale_entry("wise_statement_TRANSFER-902", amount: -60)+ bank = Account.create!(family: @family, name: "Bank", balance: 0, currency: "EUR", accountable: Depository.new(subtype: "checking"))+ payout_leg = bank.entries.create!(amount: 60, currency: "EUR", date: linked.date, name: "To Wise", entryable: Transaction.new)+ Transfer.create!(inflow_transaction: linked.entryable, outflow_transaction: payout_leg.entryable, status: "pending")+ kept_legacy = stale_entry("wise_transfer_903", amount: -70, notes: "Gift")+ kept_statement = stale_entry("wise_statement_TRANSFER-903", amount: -70, user_modified: true)+ shown = stale_entry("wise_transfer_904", amount: -80)+ hidden = stale_entry("wise_statement_TRANSFER-904", amount: -80, excluded: true)+ rows = [ 901, 902, 903, 904 ].flat_map do |id|+ [ pay_in(id).merge("wise_superseded_by" => "wise_statement_TRANSFER-#{id}"),+ statement_row("TRANSFER-#{id}", 50 + (id - 901) * 10, supersedes: { "main" => "wise_transfer_#{id}", "fee" => "wise_fee_#{id}" }) ]+ end+ store(*rows)++ process++ assert_equal acted_on.id, @account.entries.find_by!(external_id: "wise_statement_TRANSFER-901").id+ assert_not Entry.exists?(duplicate_901.id)+ assert_not Entry.exists?(plain.id)+ assert_equal linked.id, @account.entries.find_by!(external_id: "wise_statement_TRANSFER-902").id+ assert Entry.exists?(kept_legacy.id)+ assert Entry.exists?(kept_statement.id)+ assert_equal shown.id, @account.entries.find_by!(external_id: "wise_statement_TRANSFER-904").id+ assert_not Entry.exists?(hidden.id)+ note = rekey_notes.sole+ assert_equal "warn", note.level+ assert_equal [ 2, 1, 1 ], note.metadata.values_at("replaced_count", "dropped_count", "kept_both_count")+ assert_equal [ "wise_transfer_903" ], note.metadata["kept_both_external_ids"]+ end++ # The payload's rows start in September, but the item holds the row that+ # booked an older entry here (WiseAccount#prune_cap_bypass_ids), so that+ # entry is judged too.+ test "judges an entry dated before the payload's earliest row when a row the item holds booked it" do+ explained = stale_entry("wise_interbalance_77_inflow", date: Date.new(2025, 12, 20), amount: -860)+ unexplained = stale_entry("wise_transfer_77001", date: Date.new(2025, 12, 21))+ @wise_account.update!(raw_payload: @wise_account.raw_payload.merge("prune_cap_bypass" => [ "wise_interbalance_77_inflow" ]))+ store(payout(702, created: "2026-09-01 12:00:00"))++ assert_equal 1, process[:pruned]+ assert_not Entry.exists?(explained.id)+ assert Entry.exists?(unexplained.id)+ end++ # Every jar move names an id its other side could have had; the account's+ # ids are read once for them all, not once per row.+ test "reads the account's entry ids once for the renames of a whole payload" do+ moves = (1..5).map { |i| jar_move("880#{i}", "To <strong>Jar</strong>") }+ stale_entry("wise_interbalance_8801_inflow", amount: -500)+ store(*moves)+ lookups = []+ callback = ->(*, payload) { lookups << payload[:sql] if payload[:sql].match?(/FROM "entries" WHERE .*"entries"\."external_id" IN/) }++ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") { process }++ assert_empty lookups+ assert_equal [ "wise_interbalance_8801_outflow", "wise_interbalance_8802_outflow" ], wise_external_ids.first(2)+ end++ # Another processor may hold the balance's lock once its session ended, so+ # nothing is deleted then; the next sync cleans up.+ test "deletes nothing once the balance's processing lock was lost" do+ stale = stale_entry("wise_transfer_701")+ store(payout(702))+ @wise_account.stubs(:processing_lock_lost?).returns(true)++ result = WiseAccount::Transactions::Processor.new(@wise_account, import_complete: true).process++ assert_equal [ 1, 0 ], result.values_at(:imported, :pruned)+ assert Entry.exists?(stale.id)+ end++ test "deletes neither of two entries for one transfer after an incomplete import" do+ legacy = stale_entry("wise_transfer_904", amount: -50)+ booked = stale_entry("wise_statement_TRANSFER-904", amount: -50)+ store(pay_in(904).merge("wise_superseded_by" => "wise_statement_TRANSFER-904"),+ statement_row("TRANSFER-904", 50, supersedes: { "main" => "wise_transfer_904" }))++ process(import_complete: false)++ assert Entry.exists?(legacy.id)+ assert Entry.exists?(booked.id)+ assert_equal 1, rekey_notes.sole.metadata["deferred_count"]+ end++ # The row fails rather than book a second entry beside the old one; the+ # next sync tries again (and nothing is pruned meanwhile).+ test "a statement row whose entry cannot be renamed fails without booking a second entry" do+ old = stale_entry("wise_transfer_905", amount: 100)+ old.update_column(:date, 40.years.ago.to_date)+ store(payout(905).merge("wise_superseded_by" => "wise_statement_TRANSFER-905"),+ statement_row("TRANSFER-905", -100, supersedes: { "main" => "wise_transfer_905" }))++ result = process++ assert_equal [ 1, 0 ], result.values_at(:failed, :pruned)+ assert_equal [ "wise_transfer_905" ], wise_external_ids+ assert_equal 1, rekey_notes.sole.metadata["failed_count"]+ end++ # Sure booked a jar withdrawal on the balance's "_outflow" side whatever way+ # the money went. Its leg is the inflow now, and the entry is renamed in+ # place, keeping what a person did to it, rather than deleted as stale and+ # booked again.+ test "renames a jar withdrawal's entry to the side it is booked on" do+ old = stale_entry("wise_interbalance_5501_outflow", amount: 500, notes: "Back from savings")+ store(jar_move("5501", "To <strong>EUR</strong>"))++ result = process++ assert_equal [ 1, 0 ], result.values_at(:imported, :pruned)+ assert_equal [ [ old.id, "wise_interbalance_5501_inflow", BigDecimal("-500") ] ],+ @account.entries.where(source: "wise").pluck(:id, :external_id, :amount)+ assert_equal "Back from savings", old.reload.notes+ assert_equal({ "operation" => "leg_side_rekey", "renamed_count" => 1 },+ DebugLogEntry.where(provider_key: "wise").sole.metadata.slice("operation", "renamed_count", "replaced_count"))++ # Booked on its side, the next run renames nothing.+ assert_no_difference -> { DebugLogEntry.count } do+ process+ end+ end++ # A family zone tzdata does not know (Family checks it only when it changes)+ # failed every Wise row; they are dated in UTC instead, and support is told+ # once.+ test "books every kind of row in UTC for a family whose stored time zone is unknown" do+ @family.update_column(:timezone, "Invalid/Timezone")+ store(payout(702, created: "2026-10-10 23:30:00"), card_payment("card_1").merge("createdOn" => "2026-10-10T23:40:00Z"),+ statement_row("CARD-555", -12.5).merge("date" => "2026-10-10T23:50:00Z"))++ result = nil+ assert_difference -> { DebugLogEntry.where(provider_key: "wise").where("metadata ->> 'operation' = ?", "time_zone").count }, 1 do+ result = process+ end++ assert_equal [ 3, 0 ], result.values_at(:imported, :failed)+ assert_equal [ [ "wise_activity_card_1", Date.new(2026, 10, 10) ], [ "wise_statement_CARD-555", Date.new(2026, 10, 10) ],+ [ "wise_transfer_702", Date.new(2026, 10, 10) ] ],+ @account.entries.where(source: "wise").order(:external_id).pluck(:external_id, :date)+ end++ # An account linked to the balance can hold an earlier connection's history+ # from before the window Sure fetched, which no row will ever book again, so+ # the clean-up judges only days Sure fetched every row of an entry's kind: a+ # transfer's entries also need its activities' days, a statement row's the+ # balance's statements.+ test "deletes only entries dated where Sure fetched every row of their kind" do+ covered(transfers: "2026-10-11T00:00:00Z", activities: "2026-10-10T09:00:00Z", statements: "2026-10-11T00:00:00Z")+ kinds = %w[wise_transfer_80 wise_interbalance_80_outflow wise_statement_TRANSFER-80]+ earlier = kinds.map { |id| stale_entry("#{id}1", date: Date.new(2026, 10, 10)) }+ fetched = kinds.map { |id| stale_entry("#{id}2", date: Date.new(2026, 10, 11)) }+ store(payout(702, created: "2026-10-09 12:00:00"))++ assert_equal 3, process[:pruned]++ assert earlier.all? { |entry| Entry.exists?(entry.id) }+ assert fetched.none? { |entry| Entry.exists?(entry.id) }+ end++ test "judges an empty payload by the same days, and nothing without coverage" do+ covered(transfers: "2026-10-12T00:00:00Z", activities: "2026-10-12T00:00:00Z")+ earlier = stale_entry("wise_activity_card_1", date: Date.new(2026, 10, 11))+ fetched = stale_entry("wise_activity_card_2", date: Date.new(2026, 10, 12))+ store++ assert_equal 1, process[:pruned]+ assert Entry.exists?(earlier.id)+ assert_not Entry.exists?(fetched.id)++ @wise_item.update!(raw_payload: nil)+ @wise_account.update!(raw_payload: @wise_account.raw_payload.merge("prune_cap_bypass" => [ "wise_activity_card_3" ]))+ unjudged = stale_entry("wise_activity_card_3")+ [ [], [ payout(702) ] ].each do |rows|+ store(*rows)+ assert_equal 0, process[:pruned]+ end+ assert Entry.exists?(unjudged.id)+ assert_equal [ "wise_activity_card_3" ], @wise_account.reload.prune_cap_bypass_ids, "a clean-up that judged nothing spends no bypass"+ end++ test "an empty payload without a complete import is processed as before" do+ store++ assert_equal({ success: true, total: 0, imported: 0, skipped: 0, failed: 0, errors: [], pruned: 0, prune_kept: 0 },+ process(import_complete: false))+ end++ private++ def link(wise_account)+ account = Account.create!(family: @family, name: wise_account.name, balance: 0, currency: wise_account.currency,+ accountable: Depository.new(subtype: "checking"))+ AccountProvider.create!(account: account, provider: wise_account)+ account+ end++ # A same-currency payout to someone else, booked as wise_transfer_<id>.+ def payout(id, status: "outgoing_payment_sent", created: "2026-10-10 12:00:00")+ { "id" => id, "targetAccount" => 4242, "sourceCurrency" => "EUR", "targetCurrency" => "EUR",+ "sourceValue" => 25.0, "targetValue" => 25.0, "status" => status, "created" => created }+ end++ # An entry an earlier sync booked from a row no longer stored here.+ def stale_entry(external_id, date: Date.new(2026, 10, 12), amount: 10, **attributes)+ @account.entries.create!(external_id: external_id, source: "wise", amount: amount, currency: "EUR", date: date,+ name: "Wise row", entryable: Transaction.new, **attributes)+ end++ def store(*rows)+ @wise_account.update!(raw_transactions_payload: rows)+ end++ # What the importer records once it fetched a source in full since the+ # given time (ISO-8601 UTC); statements are the balance's own.+ def covered(transfers: nil, activities: nil, statements: nil)+ window = ->(from) { { "from" => from, "through" => "2026-10-17T12:00:00Z", "version" => WiseItem::COVERAGE_VERSION } }+ @wise_item.update!(raw_payload: { "coverage" => { "transfers" => transfers, "activities" => activities }.compact.transform_values(&window) })+ @wise_account.update!(raw_payload: @wise_account.raw_payload.except("statements_coverage")+ .merge({ "statements_coverage" => statements && window.call(statements).except("version") }.compact))+ end++ def process(import_complete: true)+ WiseAccount::Transactions::Processor.new(@wise_account.reload, import_complete: import_complete).process+ end++ def wise_external_ids+ @account.entries.where(source: "wise").order(:external_id).pluck(:external_id)+ end++ def prune_notes+ DebugLogEntry.where(provider_key: "wise").where("metadata ->> 'operation' = ?", "prune")+ end++ def rekey_notes+ DebugLogEntry.where(provider_key: "wise").where("metadata ->> 'operation' = ?", "statement_rekey")+ end++ # A same-currency transfer into the account recipient (a pay-in).+ def pay_in(id)+ payout(id).merge("targetAccount" => 99999001)+ end++ # A move between this balance and a jar, both in EUR.+ def jar_move(resource_id, title)+ { "id" => "interbalance_#{resource_id}", "type" => "INTERBALANCE", "resource" => { "type" => "BALANCE_TRANSACTION", "id" => resource_id },+ "title" => title, "primaryAmount" => "500 EUR", "status" => "COMPLETED", "createdOn" => "2026-10-10T08:00:00Z" }+ end++ def card_payment(id)+ { "id" => id, "type" => "CARD_PAYMENT", "resource" => { "type" => "CARD_TRANSACTION", "id" => "555" },+ "title" => "<strong>Merchant</strong>", "primaryAmount" => "12.50 EUR", "secondaryAmount" => "", "status" => "COMPLETED",+ "createdOn" => "2026-10-10T08:00:00Z" }+ end++ # supersedes: the entries the importer matched to it (WiseItem::StatementMigration).+ def statement_row(reference, value, fee: nil, supersedes: nil)+ { "type" => value.negative? ? "DEBIT" : "CREDIT", "date" => "2026-10-10T08:00:00Z",+ "amount" => { "value" => value, "currency" => "EUR" }, "totalFees" => ({ "value" => fee, "currency" => "EUR" } if fee),+ "referenceNumber" => reference, "wise_statement" => true, "wise_supersedes" => supersedes }.compact+ end+enddiff --git a/test/models/wise_account_test.rb b/test/models/wise_account_test.rbindex 5d69a67695..ee4e2a38ee 100644--- a/test/models/wise_account_test.rb+++ b/test/models/wise_account_test.rb@@ -38,6 +38,8 @@ class WiseAccountTest < ActiveSupport::TestCase# upsert_wise_snapshot!+ # Card holds sit in reservedAmount and Sure books a card payment only once+ # Wise completes it, so the live balance counts the holds back in.test "upsert_wise_snapshot! updates balance from STANDARD response" dobalance_data = {"id" => "10000001",@@ -48,12 +50,22 @@ class WiseAccountTest < ActiveSupport::TestCase@checking.upsert_wise_snapshot!(balance_data)- assert_equal BigDecimal("2500.0"), @checking.current_balance+ assert_equal BigDecimal("2600.0"), @checking.current_balanceassert_equal BigDecimal("100.0"), @checking.reserved_balanceassert_equal "EUR", @checking.currencyassert_equal "STANDARD", @checking.raw_payload["type"]end+ test "upsert_wise_snapshot! keeps marks stored after the record was loaded" do+ @checking.update!(raw_payload: { "type" => "STANDARD" })+ loaded = WiseAccount.find(@checking.id)+ WiseAccount.find(@checking.id).send(:merge_raw_payload!, { "opening_anchor" => { "entry_id" => "e1" }, "closed_at" => "2026-01-02" })++ loaded.upsert_wise_snapshot!({ "id" => "10000001", "amount" => { "value" => 10.0, "currency" => "EUR" }, "type" => "STANDARD" })++ assert_equal [ { "entry_id" => "e1" }, "2026-01-02" ], @checking.reload.raw_payload.values_at("opening_anchor", "closed_at")+ end+test "upsert_wise_snapshot! uses totalWorth for SAVINGS balance" dobalance_data = {"id" => "10000002",@@ -84,6 +96,30 @@ class WiseAccountTest < ActiveSupport::TestCaseassert_equal 99999001, @checking.raw_payload["recipient_id"]end+ # A failed borderless/multi-currency-account lookup must not drop the ids+ # that decide transfer direction, nor Sure's own markers on the payload. A+ # pending clean-up cap bypass and the opening anchor Sure last set are among+ # those markers.+ test "upsert_wise_snapshot! keeps stored ids and markers the new payload lacks" do+ written = { "entry_id" => "f3a6c1d2-0000-4000-8000-000000000001", "date" => "2026-04-30", "amount" => "0.0" }+ @checking.update!(raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "borderless_account_id" => 88888001,+ "recipientId" => 77777001, "absent_count" => 1, "amount" => { "value" => 1.0 },+ "prune_cap_bypass" => [ "wise_transfer_1" ], "opening_anchor" => written })+ balance_data = {+ "id" => "10000001",+ "amount" => { "value" => 2.0, "currency" => "EUR" },+ "recipientId" => 77777002+ }++ @checking.upsert_wise_snapshot!(balance_data)++ payload = @checking.reload.raw_payload+ assert_equal [ 99999001, 88888001, 77777002, 1 ], payload.values_at("recipient_id", "borderless_account_id", "recipientId", "absent_count")+ assert_equal 2.0, payload.dig("amount", "value")+ assert_equal [ "wise_transfer_1" ], @checking.prune_cap_bypass_ids+ assert_equal({ entry_id: written["entry_id"], date: Date.new(2026, 4, 30), amount: BigDecimal("0") }, @checking.written_opening_anchor)+ end+test "upsert_wise_snapshot! preserves existing name" do@checking.update!(name: "My Wise EUR")balance_data = {@@ -98,6 +134,142 @@ class WiseAccountTest < ActiveSupport::TestCaseassert_equal "My Wise EUR", @checking.nameend+ # Activity titles name a jar as it was called then, so a jar Wise renamed+ # keeps the names Sure saw before.+ test "upsert_wise_snapshot! keeps the names a renamed jar had" do+ @jar.update!(raw_payload: { "type" => "SAVINGS", "name" => "Holiday" })+ savings = ->(name) { { "id" => "10000002", "type" => "SAVINGS", "name" => name, "totalWorth" => { "value" => 1.0, "currency" => "EUR" } } }++ @jar.upsert_wise_snapshot!(savings.call("Holiday"))+ assert_nil @jar.reload.raw_payload["name_history"]++ @jar.upsert_wise_snapshot!(savings.call("Trip"))+ @jar.upsert_wise_snapshot!(savings.call("Trip"))+ @jar.upsert_wise_snapshot!(savings.call("Summer"))++ assert_equal %w[Holiday Trip], @jar.reload.raw_payload["name_history"]+ assert_equal "Summer", @jar.raw_payload["name"]+ # The name Sure stored when it first saw the balance counts too.+ assert_equal %w[Summer Holiday Trip Jar], @jar.known_names+ # Only the name Wise gives it now is its current one.+ assert_equal "Summer", @jar.current_name+ assert_nil WiseAccount.new(raw_payload: { "type" => "SAVINGS", "name" => " " }).current_name+ end++ # Processing a balance and deleting its stale entries hold a session-level+ # advisory lock, not a transaction.+ test "with_processing_lock holds the balance's advisory lock until the outermost block ends" do+ held_inside = nil+ held_after_inner = nil++ @checking.with_processing_lock do+ @checking.with_processing_lock { held_inside = processing_lock_held?(@checking) }+ held_after_inner = processing_lock_held?(@checking)+ assert_not processing_lock_held?(@jar)+ end++ assert held_inside+ assert held_after_inner+ assert_not processing_lock_held?(@checking)+ end++ test "with_processing_lock releases the lock when the block raises" do+ assert_raises(RuntimeError) { @checking.with_processing_lock { raise "boom" } }++ assert_not processing_lock_held?(@checking)+ end++ # Inside a caller's transaction (the linked-balance job used to wrap+ # processing in with_lock) a row's database error aborted it, the unlock+ # then failed and the lock stayed with the pooled connection, so every later+ # processing of the balance waited for it for good.+ test "with_processing_lock refuses to run inside a caller's transaction" do+ ran = false++ WiseAccount.transaction do+ assert_raises(WiseAccount::ProcessingInTransaction) { @checking.with_processing_lock { ran = true } }+ end++ assert_not ran+ assert_not processing_lock_held?(@checking)+ end++ # A broken connection Rails opened again runs the rest of the block on a+ # new session, which holds no lock: the block can tell, and the lock that+ # ended with the old session is not released twice.+ test "with_processing_lock tells when the session that took the lock ended" do+ sessions = [ 101, 101, 202, 202 ]+ @checking.stubs(:backend_pid).returns(*sessions)+ connection = WiseAccount.lease_connection+ connection.expects(:execute).with(regexp_matches(/pg_advisory_lock/)).once+ connection.expects(:execute).with(regexp_matches(/pg_advisory_unlock/)).never++ lost = []+ @checking.with_processing_lock { lost << @checking.processing_lock_lost? << @checking.processing_lock_lost? }++ assert_equal [ false, true ], lost+ assert_not @checking.processing_lock_lost?, "outside the lock"+ end++ test "with_processing_lock throws its connection away when the lock cannot be released" do+ connection = WiseAccount.lease_connection+ connection.expects(:throw_away!).once++ assert_raises(ActiveRecord::ConnectionFailed) do+ @checking.with_processing_lock do+ connection.stubs(:execute).raises(ActiveRecord::ConnectionFailed, "server closed the connection unexpectedly")+ end+ end+ ensure+ connection.unstub(:execute)+ connection.execute("SELECT pg_advisory_unlock_all()")+ end++ # The link request and a sync each write the snapshot from a copy they+ # loaded earlier; the opening anchor's mark is merged into the one stored+ # now, so neither loses the other's.+ test "remember_opening_anchor! keeps what another copy wrote meanwhile" do+ earlier_copy = WiseAccount.find(@checking.id)+ @checking.update!(raw_payload: { "type" => "STANDARD", "closed_at" => "2026-10-01T08:00:00Z" })+ anchor = Struct.new(:id, :date, :amount).new("anchor-1", Date.new(2024, 7, 9), 0)++ earlier_copy.remember_opening_anchor!(anchor)++ payload = @checking.reload.raw_payload+ assert_equal "2026-10-01T08:00:00Z", payload["closed_at"]+ assert_equal({ "entry_id" => "anchor-1", "date" => "2024-07-09", "amount" => "0.0" }, payload["opening_anchor"])+ end++ # A sync's statement coverage and clean-up marks are merged into the+ # snapshot as stored now, so an opening anchor recorded meanwhile stays.+ test "upsert_wise_transactions_snapshot! merges its marks into what another copy stored meanwhile" do+ earlier_copy = WiseAccount.find(@checking.id)+ @checking.update!(raw_payload: { "type" => "STANDARD", "opening_anchor" => { "entry_id" => "anchor-1" } })++ earlier_copy.upsert_wise_transactions_snapshot!([ { "id" => 1 } ], prune_cap_bypass: [ "wise_transfer_1" ])++ @checking.reload+ assert_equal [ { "id" => 1 } ], @checking.raw_transactions_payload+ assert_equal [ "anchor-1", [ "wise_transfer_1" ] ], @checking.raw_payload.values_at("opening_anchor", "prune_cap_bypass").then { |a, b| [ a["entry_id"], b ] }++ spending_copy = WiseAccount.find(@checking.id)+ @checking.update!(raw_payload: @checking.raw_payload.merge("closed_at" => "2026-10-01T08:00:00Z"))+ spending_copy.spend_prune_cap_bypass!+ payload = @checking.reload.raw_payload+ assert_equal "2026-10-01T08:00:00Z", payload["closed_at"]+ assert_not payload.key?("prune_cap_bypass")+ end++ test "closed_at and creation_time read Sure's and Wise's timestamps" do+ @checking.update!(raw_payload: { "type" => "STANDARD", "creationTime" => "2024-07-10T14:00:00.123Z" })+ assert_nil @checking.closed_at+ assert_equal Time.utc(2024, 7, 10, 14, 0, 0.123r), @checking.creation_time++ @checking.update!(raw_payload: { "closed_at" => "2026-10-01T08:00:00Z", "creationTime" => "not a time" })+ assert_equal Time.utc(2026, 10, 1, 8), @checking.closed_at+ assert_nil @checking.creation_time+ end+test "upsert_wise_snapshot! defaults name to Wise JAR currency for new SAVINGS account" do@jar.update!(name: nil)balance_data = {@@ -112,4 +284,17 @@ class WiseAccountTest < ActiveSupport::TestCaseassert_equal "Wise JAR EUR", @jar.nameend++ private++ # Whether this connection holds the balance's processing lock: an+ # advisory lock on two keys shows the first as classid and the second,+ # as an unsigned number, as objid.+ def processing_lock_held?(wise_account)+ ActiveRecord::Base.connection.select_value(ActiveRecord::Base.sanitize_sql_array([ <<~SQL.squish, WiseAccount::PROCESSING_LOCK_NAMESPACE, wise_account.id.to_s ])).positive?+ SELECT count(*) FROM pg_locks+ WHERE locktype = 'advisory' AND pid = pg_backend_pid() AND granted AND objsubid = 2+ AND classid = ? AND objid::bigint = (hashtext(?)::bigint & 4294967295)+ SQL+ endenddiff --git a/test/models/wise_activity/processor_test.rb b/test/models/wise_activity/processor_test.rbindex 2514146e23..184e170208 100644--- a/test/models/wise_activity/processor_test.rb+++ b/test/models/wise_activity/processor_test.rb@@ -56,17 +56,121 @@ class WiseActivity::ProcessorTest < ActiveSupport::TestCaseassert_equal I18n.t("wise_items.activities.jar_deposit"), entry.nameend+ # A leg's side now follows the money, so the jar's withdrawal leg is its+ # outflow and pairs with the balance's inflow.test "INTERBALANCE 'From Jar' on JAR account is expense (positive)" doactivity = build_interbalance("From <strong>EUR</strong>", amount: "500 EUR", resource_id: "5002")- # Simulates a withdrawal: title doesn't start with "To"entry = WiseActivity::Processor.new(activity, wise_account: @jar_account).processassert_equal BigDecimal("500.0"), entry.amount- assert_equal "wise_interbalance_5002_inflow", entry.external_id+ assert_equal "wise_interbalance_5002_outflow", entry.external_idassert_equal I18n.t("wise_items.activities.jar_withdrawal"), entry.nameend+ # Wise names where the money went, as in "To <strong>EUR</strong>" on every+ # conversion, so a title naming the balance's currency or the jar the money+ # left is a withdrawal.+ test "a jar withdrawal is an inflow on the balance and an outflow on the jar, however Wise titles it" do+ {+ "To <strong>EUR</strong>" => I18n.t("wise_items.activities.jar_withdrawal"),+ "From <strong>EUR</strong>" => I18n.t("wise_items.activities.jar_withdrawal"),+ "From <strong>Jar</strong>" => I18n.t("wise_items.activities.transfer_from_jar", jar: "Jar")+ }.each_with_index do |(title, balance_name), index|+ activity = build_interbalance(title, amount: "500 EUR", resource_id: "520#{index}")++ jar_leg = WiseActivity::Processor.new(activity, wise_account: @jar_account).process+ balance_leg = WiseActivity::Processor.new(activity, wise_account: @standard_account).process++ assert_equal [ "wise_interbalance_520#{index}_outflow", BigDecimal("500") ], [ jar_leg.external_id, jar_leg.amount ], title+ assert_equal [ "wise_interbalance_520#{index}_inflow", BigDecimal("-500"), balance_name ],+ [ balance_leg.external_id, balance_leg.amount, balance_leg.name ], title+ end+ end++ test "tells a jar deposit from a withdrawal by the balance its title names" do+ deposit = ->(title) { WiseActivity::Processor.jar_deposit?(build_interbalance(title, amount: "500 EUR", resource_id: "1")) }++ assert deposit.call("To <strong>Holiday</strong>")+ assert deposit.call("Moved to <strong>Tom & Jerry</strong>")+ assert_not deposit.call("From <strong>Holiday</strong>")+ assert_not deposit.call("To <strong>EUR</strong>")+ assert_not deposit.call("From <strong>eur</strong>")+ # Without a named balance only the wording is left, as before.+ assert deposit.call("Added to your jar")+ assert_not deposit.call("Moved out")+ end++ # A conversion debits its source currency and credits its target one, on a+ # jar as on any balance.+ test "a jar's leg of a move in two currencies is booked in the jar's currency" do+ gbp_jar = create_jar_account(currency: "GBP", balance_id: "10000004", name: "Holiday")+ into_jar = build_interbalance("To <strong>Jar</strong>", amount: "117.50 EUR", resource_id: "5301", secondary: "100 GBP")+ out_of_jar = build_interbalance("From <strong>Holiday</strong>", amount: "117.50 EUR", resource_id: "5302", secondary: "100 GBP")++ deposit = WiseActivity::Processor.new(into_jar, wise_account: @jar_account).process+ withdrawal = WiseActivity::Processor.new(out_of_jar, wise_account: gbp_jar).process++ assert_equal [ "wise_interbalance_5301_inflow", BigDecimal("-117.50"), "EUR", I18n.t("wise_items.activities.jar_deposit") ],+ [ deposit.external_id, deposit.amount, deposit.currency, deposit.name ]+ assert_equal [ "wise_interbalance_5302_outflow", BigDecimal("100"), "GBP", I18n.t("wise_items.activities.jar_withdrawal") ],+ [ withdrawal.external_id, withdrawal.amount, withdrawal.currency, withdrawal.name ]+ end++ # Sure used to book a jar's leg as "_inflow" and a balance's as "_outflow"+ # whichever way the money went, a conversion's leg on its target balance+ # too; the entry of a leg booked that way is renamed in place+ # (WiseAccount::Transactions::Processor), not replaced.+ test "names the entry a jar move's leg had before its side followed the money" do+ withdrawal = build_interbalance("To <strong>EUR</strong>", amount: "500 EUR", resource_id: "5401")+ deposit = build_interbalance("To <strong>Jar</strong>", amount: "500 EUR", resource_id: "5402")+ conversion = build_interbalance("To <strong>EUR</strong>", amount: "117.50 EUR", resource_id: "5403", secondary: "100 GBP")++ assert_equal({ "wise_interbalance_5401_inflow" => "wise_interbalance_5401_outflow" },+ WiseActivity::Processor.new(withdrawal, wise_account: @jar_account).superseded_external_ids)+ assert_equal({ "wise_interbalance_5401_outflow" => "wise_interbalance_5401_inflow" },+ WiseActivity::Processor.new(withdrawal, wise_account: @standard_account).superseded_external_ids)+ assert_equal({ "wise_interbalance_5402_outflow" => "wise_interbalance_5402_inflow" },+ WiseActivity::Processor.new(deposit, wise_account: @jar_account).superseded_external_ids)+ assert_equal({ "wise_interbalance_5403_outflow" => "wise_interbalance_5403_inflow" },+ WiseActivity::Processor.new(conversion, wise_account: @standard_account).superseded_external_ids)+ # Its source balance's leg always had the side it has now.+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ assert_empty WiseActivity::Processor.new(conversion, wise_account: gbp_account).superseded_external_ids+ assert_empty WiseActivity::Processor.new(withdrawal.merge("status" => "IN_PROGRESS"), wise_account: @jar_account).superseded_external_ids+ assert_empty WiseActivity::Processor.new(build_cashback(amount: "1.12 EUR", resource_id: "57010"), wise_account: @jar_account)+ .superseded_external_ids+ end++ # A payload an older build stored holds every conversion and jar move of+ # the profile, which processing must not book on a balance they never+ # touched (after a failed import, or for a balance linked mid-sync).+ test "books no move or payment of currencies the balance is not in, nor one routed to another balance" do+ usd_account = create_standard_account(currency: "USD", balance_id: "10000004")+ holiday = create_jar_account(currency: "EUR", balance_id: "10000005", name: "Holiday")+ conversion = build_interbalance("To <strong>GBP</strong>", amount: "860 GBP", resource_id: "77", secondary: "1,000 EUR")+ jar_move = build_interbalance("To <strong>Holiday</strong>", amount: "200 EUR", resource_id: "78")+ .merge(WiseItem::Importer::ROUTING_DECISION_KEY => holiday.balance_id)+ to_jar_from_gbp = build_interbalance("To <strong>Holiday</strong>", amount: "50 EUR", resource_id: "79", secondary: "43 GBP")+ .merge(WiseItem::Importer::ROUTING_DECISION_KEY => holiday.balance_id)+ interest = build_cashback(amount: "1.12 EUR", resource_id: "57011").merge(WiseItem::Importer::ROUTING_DECISION_KEY => holiday.balance_id)+ gbp_interest = build_cashback(amount: "0.10 GBP", resource_id: "57012")+ card = build_activity("CARD_PAYMENT", "12 GBP", id: "gbp_card")++ {+ [ conversion, usd_account ] => :skipped, [ conversion, @standard_account ] => Entry,+ [ jar_move, usd_account ] => :skipped, [ jar_move, @jar_account ] => :skipped, [ jar_move, holiday ] => Entry,+ [ to_jar_from_gbp, @standard_account ] => :skipped, [ to_jar_from_gbp, holiday ] => Entry,+ [ interest, @jar_account ] => :skipped, [ interest, holiday ] => Entry, [ gbp_interest, @jar_account ] => :skipped,+ [ card, @standard_account ] => :skipped+ }.each do |(row, wise_account), outcome|+ processor = WiseActivity::Processor.new(row, wise_account: wise_account)+ result = processor.process+ assert(outcome == :skipped ? result == :skipped : result.is_a?(Entry), "#{row['id']} on #{wise_account.name}")+ assert_empty processor.expected_external_ids if outcome == :skipped+ end+ end+# INTERBALANCE — STANDARD sidetest "INTERBALANCE 'To Jar' on STANDARD account is expense (positive outflow)" do@@ -78,6 +182,49 @@ class WiseActivity::ProcessorTest < ActiveSupport::TestCaseassert_equal "wise_interbalance_5003_outflow", entry.external_idend+ # INTERBALANCE — currency conversion between STANDARD balances++ test "conversion on the source STANDARD balance is an outflow in the source currency" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ activity = build_interbalance("To <strong>EUR</strong>", amount: "117.50 EUR", resource_id: "8001",+ secondary: "100 GBP")++ entry = WiseActivity::Processor.new(activity, wise_account: gbp_account).process++ assert_equal BigDecimal("100.0"), entry.amount+ assert_equal "GBP", entry.currency+ assert_equal "wise_interbalance_8001_outflow", entry.external_id+ assert_equal I18n.t("wise_items.activities.transfer_to_jar", jar: "EUR"), entry.name+ end++ # An older build booked the leg in the target currency (primaryAmount). A+ # person's category does not freeze that figure.+ test "corrects a conversion leg an older build booked in the other currency, also after a person categorized it" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ old = gbp_account.current_account.entries.create!(external_id: "wise_interbalance_8003_outflow", source: "wise", amount: 117.5,+ currency: "EUR", date: Date.new(2026, 5, 1), name: "To EUR",+ user_modified: true, entryable: Transaction.new)+ activity = build_interbalance("To <strong>EUR</strong>", amount: "117.50 EUR", resource_id: "8003", secondary: "100 GBP")++ entry = WiseActivity::Processor.new(activity, wise_account: gbp_account).process++ assert_equal old.id, entry.id+ assert_equal [ BigDecimal("100"), "GBP" ], old.reload.values_at(:amount, :currency)+ assert old.user_modified?+ end++ test "conversion on the target STANDARD balance is an inflow in the target currency" do+ activity = build_interbalance("To <strong>EUR</strong>", amount: "1,234.56 EUR", resource_id: "8002",+ secondary: "900 GBP")++ entry = WiseActivity::Processor.new(activity, wise_account: @standard_account).process++ assert_equal BigDecimal("-1234.56"), entry.amount+ assert_equal "EUR", entry.currency+ assert_equal "wise_interbalance_8002_inflow", entry.external_id+ assert_equal I18n.t("wise_items.activities.transfer_from_jar", jar: "GBP"), entry.name+ end+# Amount parsingtest "parses comma-formatted amount" do@@ -104,6 +251,353 @@ class WiseActivity::ProcessorTest < ActiveSupport::TestCaseassert_equal BigDecimal("0.83"), entry.amountend+ # Amount strings, in the shapes Wise returns++ test "parse_amount reads value, currency and markup" do+ assert_equal({ value: BigDecimal("1618.42"), currency: "USD", currencies: [ "USD" ], marked: nil, sign: nil },+ WiseActivity::Processor.parse_amount("1,618.42 USD"))+ assert_equal({ value: BigDecimal("2465"), currency: "GBP", currencies: [ "GBP" ], marked: :positive, sign: 1 },+ WiseActivity::Processor.parse_amount("<positive>+ 2,465 GBP</positive>"))+ assert_equal({ value: BigDecimal("0"), currency: "EUR", currencies: [ "EUR" ], marked: nil, sign: nil },+ WiseActivity::Processor.parse_amount("0 EUR"))+ end++ test "parse_amount reads a split-funding list as currencies without a value" do+ assert_equal({ value: nil, currency: "GBP", currencies: %w[GBP EUR], marked: nil, sign: nil },+ WiseActivity::Processor.parse_amount("GBP, EUR"))+ assert_equal({ value: nil, currency: "AUD", currencies: %w[AUD EUR], marked: nil, sign: nil },+ WiseActivity::Processor.parse_amount("AUD, EUR"))+ end++ test "parse_amount tells positive from negative amounts" do+ positive = WiseActivity::Processor.parse_amount("<positive>+ 0.64 EUR</positive>")+ negative = WiseActivity::Processor.parse_amount("<negative>- 0.64 EUR</negative>")++ assert_equal [ BigDecimal("0.64"), :positive, 1 ], positive.values_at(:value, :marked, :sign)+ assert_equal [ BigDecimal("0.64"), :negative, -1 ], negative.values_at(:value, :marked, :sign)+ # A leading sign without markup counts as well.+ assert_equal :positive, WiseActivity::Processor.parse_amount("+ 1.12 EUR")[:marked]+ assert_equal :negative, WiseActivity::Processor.parse_amount("-3 EUR")[:marked]+ end++ test "parse_amount of a missing amount is empty" do+ empty = { value: nil, currency: nil, currencies: [], marked: nil, sign: nil }++ assert_equal empty, WiseActivity::Processor.parse_amount("")+ assert_equal empty, WiseActivity::Processor.parse_amount(nil)+ end++ test "parse_money needs a digit, so a split-funding list has no amount" do+ # The old pattern read the lone comma in "GBP, EUR" as 0 GBP.+ assert_equal [ nil, "GBP" ], WiseActivity::Processor.parse_money("GBP, EUR")+ assert_equal [ nil, "AUD" ], WiseActivity::Processor.parse_money("AUD, EUR")+ assert_equal [ BigDecimal("1618.42"), "USD" ], WiseActivity::Processor.parse_money("1,618.42 USD")+ assert_equal [ BigDecimal("2465"), "GBP" ], WiseActivity::Processor.parse_money("<positive>+ 2,465 GBP</positive>")+ assert_equal [ BigDecimal("0"), "EUR" ], WiseActivity::Processor.parse_money("0 EUR")+ end++ # Direction of single-leg activities++ test "a positive-marked activity is a credit whatever its type" do+ assert_equal :credit, direction_of("CARD_PAYMENT", "<positive>+ 0.64 EUR</positive>")+ assert_equal :credit, direction_of("TRANSFER", "<positive>+ 2,465 GBP</positive>")+ assert_equal :credit, direction_of("BALANCE_DEPOSIT", "<positive>+ 715 GBP</positive>")+ assert_equal :credit, direction_of("CARD_PAYMENT", "7.40 EUR", "<positive>+ 6.42 GBP</positive>")+ end++ test "an unmarked activity is a debit unless its type only ever pays in" do+ assert_equal :debit, direction_of("CARD_PAYMENT", "7.40 EUR", "6.42 GBP")+ assert_equal :debit, direction_of("TRANSFER", "1,618.42 USD", "1,620.79 USD")+ assert_equal :debit, direction_of("CASH_WITHDRAWAL", "150 CHF", "GBP, CHF")+ assert_equal :debit, direction_of("DIRECT_DEBIT_TRANSACTION", "64.20 CAD")+ assert_equal :debit, direction_of("BALANCE_ASSET_FEE", "0.06 EUR")++ %w[REWARD CARD_CASHBACK BALANCE_INTEREST BALANCE_CASHBACK].each do |type|+ assert_equal :credit, direction_of(type, "1.12 EUR"), type+ assert_equal :debit, direction_of(type, "<negative>- 1.12 EUR</negative>"), type+ end+ end++ test "a conversion between two balances has no single direction" do+ assert_nil direction_of("INTERBALANCE", "117.50 EUR", "100 GBP")+ assert_nil direction_of("AUTO_CONVERSION", "117.50 EUR", "100 GBP")+ end++ # Amount a single-leg activity moved on its balance++ test "a debit books what left the paying balance" do+ # Card payment auto-converted from GBP: the merchant got 7.40 EUR.+ assert_equal [ BigDecimal("6.42"), "GBP" ], booked("CARD_PAYMENT", "7.40 EUR", "6.42 GBP")+ assert_equal [ BigDecimal("3.29"), "EUR" ], booked("CARD_PAYMENT", "2.84 GBP", "3.29 EUR")+ # Payouts: the secondary is the gross debit, fee included.+ assert_equal [ BigDecimal("1620.79"), "USD" ], booked("TRANSFER", "1,618.42 USD", "1,620.79 USD")+ assert_equal [ BigDecimal("212.86"), "GBP" ], booked("TRANSFER", "41,500 JPY", "212.86 GBP")+ # Same currency and no fee: Wise leaves the secondary empty.+ assert_equal [ BigDecimal("37.65"), "EUR" ], booked("CARD_PAYMENT", "37.65 EUR", "")+ assert_equal [ BigDecimal("0"), "CHF" ], booked("CARD_CHECK", "0 CHF", "")+ end++ test "a credit books the primary amount, which is what Wise credited" do+ refund = build_activity("CARD_PAYMENT", "<positive>+ 0.64 EUR</positive>", "")++ assert_equal({ value: BigDecimal("0.64"), currency: "EUR", direction: :credit, split: false, currencies: [ "EUR" ] },+ WiseActivity::Processor.balance_amount(refund))+ assert_equal [ BigDecimal("6.42"), "GBP" ], booked("CARD_PAYMENT", "<positive>+ 6.42 GBP</positive>", "7.40 EUR")+ assert_equal [ BigDecimal("2465"), "GBP" ], booked("TRANSFER", "<positive>+ 2,465 GBP</positive>", "")+ end++ test "a debit funded from several balances is split without per-balance amounts" do+ atm = build_activity("CASH_WITHDRAWAL", "150 CHF", "GBP, CHF")+ card = build_activity("CARD_PAYMENT", "17.60 CHF", "AUD, CHF")++ assert WiseActivity::Processor.split?(atm)+ assert_equal({ value: BigDecimal("150"), currency: "CHF", direction: :debit, split: true, currencies: %w[GBP CHF] },+ WiseActivity::Processor.balance_amount(atm))+ assert WiseActivity::Processor.split?(card)+ assert_equal %w[AUD CHF], WiseActivity::Processor.balance_amount(card)[:currencies]+ end++ test "only debits are split" do+ refund = build_activity("CARD_PAYMENT", "<positive>+ 26.80 EUR</positive>", "GBP, EUR")+ single = build_activity("CARD_PAYMENT", "7.40 EUR", "6.42 GBP")++ assert_not WiseActivity::Processor.split?(refund)+ assert_equal({ value: BigDecimal("26.80"), currency: "EUR", direction: :credit, split: false, currencies: [ "EUR" ] },+ WiseActivity::Processor.balance_amount(refund))+ assert_not WiseActivity::Processor.split?(single)+ end++ test "a conversion has no single balance amount" do+ conversion = build_interbalance("To <strong>EUR</strong>", amount: "117.50 EUR", resource_id: "8003", secondary: "100 GBP")++ assert_nil WiseActivity::Processor.balance_amount(conversion)+ assert_not WiseActivity::Processor.split?(conversion)+ end++ test "books a single-leg activity with its markup's sign and the paying balance's amount" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ refund = build_activity("CARD_PAYMENT", "<positive>+ 0.64 EUR</positive>", "", id: "card_refund_1")+ payment = build_activity("CARD_PAYMENT", "7.40 EUR", "6.42 GBP", id: "card_payment_1")++ refund_entry = WiseActivity::Processor.new(refund, wise_account: @standard_account).process+ payment_entry = WiseActivity::Processor.new(payment, wise_account: gbp_account).process++ assert_equal [ BigDecimal("-0.64"), "EUR" ], [ refund_entry.amount, refund_entry.currency ]+ assert_equal [ BigDecimal("6.42"), "GBP" ], [ payment_entry.amount, payment_entry.currency ]+ end++ test "a negative-marked cashback is booked as an expense" do+ activity = build_cashback(amount: "<negative>- 0.10 EUR</negative>", resource_id: "57005")++ entry = WiseActivity::Processor.new(activity, wise_account: @jar_account).process++ assert_equal BigDecimal("0.10"), entry.amount+ end++ # Status: only a completed activity moved money++ test "books an activity only once Wise has completed it" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")++ %w[IN_PROGRESS UPCOMING REQUIRES_ATTENTION CANCELLED].each do |status|+ payment = build_activity("CARD_PAYMENT", "7.40 EUR", "6.42 GBP", id: "card_#{status.downcase}").merge("status" => status)+ processor = WiseActivity::Processor.new(payment, wise_account: gbp_account)++ assert_equal [], processor.expected_external_ids, status+ assert_equal :skipped, processor.process, status+ end+ assert_equal 0, gbp_account.current_account.entries.count++ completed = WiseActivity::Processor.new(build_activity("CARD_PAYMENT", "7.40 EUR", "6.42 GBP", id: "card_done"),+ wise_account: gbp_account)+ assert_equal [ "wise_activity_card_done" ], completed.expected_external_ids+ assert_equal "wise_activity_card_done", completed.process.external_id+ end++ # What WiseItem::StatementMigration compares statement rows with.+ test "tells what it books on a balance, without a linked account" do+ gbp = WiseAccount.create!(wise_item: @wise_item, balance_id: "10000003", name: "Wise GBP", currency: "GBP",+ raw_payload: { "type" => "STANDARD" })+ payment = build_activity("CARD_PAYMENT", "7.40 EUR", "6.42 GBP", id: "card_1")+ conversion = build_interbalance("To <strong>EUR</strong>", amount: "22.91 EUR", resource_id: "777", secondary: "20 GBP")++ assert_equal({ external_id: "wise_activity_card_1", amount: BigDecimal("6.42"), currency: "GBP" },+ WiseActivity::Processor.new(payment, wise_account: gbp).booking)+ assert_equal({ external_id: "wise_interbalance_777_inflow", amount: BigDecimal("-22.91"), currency: "EUR" },+ WiseActivity::Processor.new(conversion, wise_account: @standard_account).booking)+ assert_nil WiseActivity::Processor.new(payment.merge("status" => "IN_PROGRESS"), wise_account: gbp).booking+ end++ # WiseItem::StatementMigration: a statement row carries it now.+ test "books nothing once a statement row took it over" do+ payment = build_activity("CARD_PAYMENT", "12 EUR", id: "card_1").merge("wise_superseded_by" => "wise_statement_CARD-3000001")+ processor = WiseActivity::Processor.new(payment, wise_account: @standard_account)++ assert_equal :skipped, processor.process+ assert_empty processor.expected_external_ids+ assert_nil processor.booking+ assert_empty @standard_sure_account.entries+ end++ # A cancelled activity is not booked.+ test "a cancelled conversion books neither leg" do+ activity = build_interbalance("To <strong>EUR</strong>", amount: "22.91 EUR", resource_id: "778", secondary: "20 GBP")+ .merge("status" => "CANCELLED")+ processor = WiseActivity::Processor.new(activity, wise_account: @standard_account)++ assert_equal [], processor.expected_external_ids+ assert_equal :skipped, processor.process+ assert_nil Entry.find_by(external_id: "wise_interbalance_778_inflow")+ end++ # Split funding: Wise names the balances ("GBP, EUR"), not what each paid++ test "books the balance replay's part of a split payment on each balance that paid" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ payment = build_activity("CARD_PAYMENT", "26.80 EUR", "GBP, EUR", id: "split_card")+ .merge("wise_split_parts" => { "EUR" => "12.35", "GBP" => "12.42" }, "wise_split_estimated" => [ "GBP" ])++ eur_entry = WiseActivity::Processor.new(payment, wise_account: @standard_account).process+ gbp_entry = WiseActivity::Processor.new(payment, wise_account: gbp_account).process++ assert_equal [ "wise_activity_split_card", BigDecimal("12.35"), "EUR" ], [ eur_entry.external_id, eur_entry.amount, eur_entry.currency ]+ assert_equal [ "wise_activity_split_card", BigDecimal("12.42"), "GBP" ], [ gbp_entry.external_id, gbp_entry.amount, gbp_entry.currency ]+ assert_equal({ "split_part" => true }, split_flags(eur_entry))+ assert_equal({ "split_part" => true, "split_estimated" => true }, split_flags(gbp_entry))+ end++ # Documented limitation: without a replay (no full history) Sure cannot tell+ # the parts, so the merchant-currency balance books the whole amount.+ test "without replayed parts a split payment books its full amount on the merchant-currency balance only" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ atm = build_activity("CASH_WITHDRAWAL", "150 EUR", "GBP, EUR", id: "split_atm")+ eur_processor = WiseActivity::Processor.new(atm, wise_account: @standard_account)+ gbp_processor = WiseActivity::Processor.new(atm, wise_account: gbp_account)++ assert_equal [ "wise_activity_split_atm" ], eur_processor.expected_external_ids+ assert_equal [], gbp_processor.expected_external_ids++ entry = eur_processor.process+ assert_equal [ BigDecimal("150"), "EUR" ], [ entry.amount, entry.currency ]+ assert_equal({ "split_unresolved" => true }, split_flags(entry))+ assert_equal :skipped, gbp_processor.process+ assert_equal 0, gbp_account.current_account.entries.count+ end++ # Wise drew on GBP and EUR for a payment in a currency the profile does not+ # hold, so no balance the payment lists is in the merchant's currency: the+ # first one books it in full rather than none of them.+ test "without replayed parts a split payment in another currency books in full on the first balance it lists" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ payment = build_activity("CARD_PAYMENT", "100 USD", "GBP, EUR", id: "split_usd")+ gbp_processor = WiseActivity::Processor.new(payment, wise_account: gbp_account)+ eur_processor = WiseActivity::Processor.new(payment, wise_account: @standard_account)++ assert_equal [ [ "wise_activity_split_usd" ], [] ], [ gbp_processor.expected_external_ids, eur_processor.expected_external_ids ]+ entry = gbp_processor.process+ assert_equal [ BigDecimal("100"), "USD" ], [ entry.amount, entry.currency ]+ assert_equal({ "split_unresolved" => true }, split_flags(entry))+ assert_equal :skipped, eur_processor.process++ parts = WiseActivity::Processor.new(payment.merge("wise_split_parts" => { "GBP" => "40.10", "EUR" => "45.60" }), wise_account: gbp_account).process+ assert_equal [ entry.id, BigDecimal("40.10"), "GBP" ], [ parts.id, parts.amount, parts.currency ]+ end++ # A person's share of a split entry is not a copy of a new Wise row of the+ # same amount and day, so it is never claimed for it.+ test "books a card payment of a split part's amount and day as its own entry" do+ parent = @standard_sure_account.entries.create!(date: Date.new(2025, 9, 17), amount: 37.5, currency: "EUR", name: "Market",+ entryable: Transaction.new)+ parent.split!([ { name: "Groceries", amount: 25, category_id: nil }, { name: "Household", amount: 12.5, category_id: nil } ])+ household = parent.child_entries.find_by!(name: "Household")++ entry = WiseActivity::Processor.new(build_activity("CARD_PAYMENT", "12.50 EUR", id: "card_b"), wise_account: @standard_account).process++ assert_not_equal household.id, entry.id+ assert_equal [ nil, nil, "Household" ], household.reload.values_at(:external_id, :source, :name)+ end++ # The extra.wise namespace is replaced on every import, not merged, so the+ # flag a split payment had before the balance replay found its parts does+ # not stay on the entry.+ test "re-importing a split payment drops the flag its earlier booking had" do+ atm = build_activity("CASH_WITHDRAWAL", "150 EUR", "GBP, EUR", id: "split_atm")+ WiseActivity::Processor.new(atm, wise_account: @standard_account).process++ entry = WiseActivity::Processor.new(atm.merge("wise_split_parts" => { "EUR" => "145.18", "GBP" => "4.50" }),+ wise_account: @standard_account).process++ assert_equal [ BigDecimal("145.18"), { "split_part" => true } ], [ entry.amount, split_flags(entry.reload) ]+ end++ test "a split part of zero books nothing on that balance" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ atm = build_activity("CASH_WITHDRAWAL", "150 EUR", "GBP, EUR", id: "split_atm")+ .merge("wise_split_parts" => { "EUR" => "150.00", "GBP" => "0.00" })+ processor = WiseActivity::Processor.new(atm, wise_account: gbp_account)++ assert_equal [], processor.expected_external_ids+ assert_equal :skipped, processor.process+ end++ # AUTO_CONVERSION moves money between two balances like a conversion++ test "an auto-conversion books both legs the way a conversion does" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ conversion = build_interbalance("To <strong>EUR</strong>", amount: "117.50 EUR", resource_id: "9001", secondary: "100 GBP")+ .merge("type" => "AUTO_CONVERSION", "id" => "auto_conversion_9001")++ outflow = WiseActivity::Processor.new(conversion, wise_account: gbp_account).process+ inflow = WiseActivity::Processor.new(conversion, wise_account: @standard_account).process++ assert_equal [ "wise_interbalance_9001_outflow", BigDecimal("100"), "GBP" ], [ outflow.external_id, outflow.amount, outflow.currency ]+ assert_equal [ "wise_interbalance_9001_inflow", BigDecimal("-117.50"), "EUR" ], [ inflow.external_id, inflow.amount, inflow.currency ]+ assert_equal I18n.t("wise_items.activities.transfer_to_jar", jar: "EUR"), outflow.name+ assert_equal I18n.t("wise_items.activities.transfer_from_jar", jar: "GBP"), inflow.name+ end++ # Names and metadata++ test "names a single-leg activity after its title and keeps Wise's amounts in extra" do+ gbp_account = create_standard_account(currency: "GBP", balance_id: "10000003")+ payment = build_activity("CARD_PAYMENT", "7.40 EUR", "6.42 GBP", id: "named_card")+ .merge("title" => "<strong>Tom & Jerry</strong>", "description" => "Spent")++ entry = WiseActivity::Processor.new(payment, wise_account: gbp_account).process++ assert_equal "Tom & Jerry", entry.name+ assert_equal({ "activity_id" => "named_card", "activity_type" => "CARD_PAYMENT", "resource_type" => "CARD_TRANSACTION",+ "resource_id" => "3000001", "description" => "Spent", "primary_amount" => "7.40 EUR",+ "secondary_amount" => "6.42 GBP" }, entry.entryable.extra["wise"])+ end++ test "names balance interest like cashback" do+ interest = build_activity("BALANCE_INTEREST", "0.42 EUR", id: "interest_1")++ entry = WiseActivity::Processor.new(interest, wise_account: @standard_account).process++ assert_equal [ BigDecimal("-0.42"), I18n.t("wise_items.activities.interest") ], [ entry.amount, entry.name ]+ end++ # Dates++ test "dates an activity in the family time zone, like transfers and statements" do+ @family.update!(timezone: "Europe/Dublin")+ activity = build_interbalance("To <strong>EUR</strong>", amount: "15 EUR", resource_id: "8004", secondary: "13 GBP")+ .merge("createdOn" => "2026-08-11T23:52:27.164Z")++ entry = WiseActivity::Processor.new(activity, wise_account: @standard_account).process++ # 23:52 UTC on 11 August is 00:52 on 12 August in Dublin (IST).+ assert_equal Date.new(2026, 8, 12), entry.date+ end++ test "created_at is the UTC instant of createdOn" do+ assert_equal Time.utc(2026, 9, 16, 22, 41, 38.553r),+ WiseActivity::Processor.created_at({ "createdOn" => "2026-09-16T22:41:38.553Z" })+ assert_nil WiseActivity::Processor.created_at({ "createdOn" => "" })+ end+# BALANCE_CASHBACK (interest)test "BALANCE_CASHBACK is imported as income (negative)" do@@ -174,16 +668,71 @@ class WiseActivity::ProcessorTest < ActiveSupport::TestCaseprivate- def build_interbalance(title, amount:, resource_id:)+ def build_interbalance(title, amount:, resource_id:, secondary: nil){"id" => "interbalance_activity_#{resource_id}","type" => "INTERBALANCE","resource" => { "type" => "BALANCE_TRANSACTION", "id" => resource_id },"title" => title,"primaryAmount" => amount,+ "secondaryAmount" => secondary,"status" => "COMPLETED","createdOn" => "2026-05-01T06:12:11.597Z"- }+ }.compact+ end++ def create_standard_account(currency:, balance_id:)+ wise_account = WiseAccount.create!(+ wise_item: @wise_item,+ balance_id: balance_id,+ name: "Wise #{currency}",+ currency: currency,+ raw_payload: { "type" => "STANDARD" }+ )+ AccountProvider.create!(+ account: Account.create!(+ family: @family,+ name: "Wise #{currency}",+ accountable: Depository.new(subtype: "checking"),+ balance: 0,+ currency: currency+ ),+ provider: wise_account+ )+ wise_account+ end++ def create_jar_account(currency:, balance_id:, name:)+ wise_account = WiseAccount.create!(wise_item: @wise_item, balance_id: balance_id, name: name, currency: currency,+ raw_payload: { "type" => "SAVINGS", "name" => name })+ account = Account.create!(family: @family, name: name, accountable: Depository.new(subtype: "savings"), balance: 0, currency: currency)+ AccountProvider.create!(account: account, provider: wise_account)+ wise_account+ end++ def build_activity(type, primary, secondary = nil, id: "#{type.downcase}_activity")+ {+ "id" => id,+ "type" => type,+ "resource" => { "type" => "CARD_TRANSACTION", "id" => "3000001" },+ "title" => "<strong>Merchant</strong>",+ "primaryAmount" => primary,+ "secondaryAmount" => secondary,+ "status" => "COMPLETED",+ "createdOn" => "2025-09-17T15:33:48.972Z"+ }.compact+ end++ def direction_of(type, primary, secondary = nil)+ WiseActivity::Processor.direction(build_activity(type, primary, secondary))+ end++ def booked(type, primary, secondary = nil)+ WiseActivity::Processor.balance_amount(build_activity(type, primary, secondary)).values_at(:value, :currency)+ end++ def split_flags(entry)+ entry.entryable.extra["wise"].slice("split_part", "split_estimated", "split_unresolved")enddef build_cashback(amount:, resource_id:)diff --git a/test/models/wise_entry/processor_test.rb b/test/models/wise_entry/processor_test.rbindex f2d1292bb7..b849a847b9 100644--- a/test/models/wise_entry/processor_test.rb+++ b/test/models/wise_entry/processor_test.rb@@ -47,18 +47,236 @@ class WiseEntry::ProcessorTest < ActiveSupport::TestCaseassert_equal "incoming", entry.entryable.extra.dig("wise", "direction")end- test "uses status-based fallback when no recipient_id stored" do+ test "imports a transfer into the balance's own recipient as negative income" do+ # Top-ups and payments into a balance's account details target the balance's+ # own recipientId, not the multi-currency account's recipient_id.+ @wise_account.update!(raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "recipientId" => 99999002 })+ transfer = build_transfer(id: 1005, target_account: 99999002, source_value: 2400.0, target_value: 2400.0)++ entry = WiseEntry::Processor.new(transfer, wise_account: @wise_account).process++ assert_equal BigDecimal("-2400.0"), entry.amount+ assert_equal "incoming", entry.entryable.extra.dig("wise", "direction")+ end++ test "books an incoming cross-currency transfer in the target currency" do+ transfer = build_transfer(id: 1003, target_account: 99999001, source_value: 100.0, target_value: 115.4,+ source_currency: "GBP", target_currency: "EUR")++ entry = WiseEntry::Processor.new(transfer, wise_account: @wise_account).process++ assert_equal BigDecimal("-115.4"), entry.amount+ assert_equal "EUR", entry.currency+ end++ # An older build booked these pay-ins in their source currency. A+ # person's category does not make that figure theirs, so the corrected+ # one reaches the entry; an amount they changed themselves stays.+ test "corrects an entry a person categorized, but not one whose amount they changed" do+ categorized, changed = [ 1007, 1008 ].map do |id|+ @account.entries.create!(external_id: "wise_transfer_#{id}", source: "wise", amount: -100, currency: "GBP", date: Date.new(2026, 1, 15),+ name: "Top-up", user_modified: true, entryable: Transaction.new)+ end+ changed.update!(locked_attributes: { "amount" => Time.current.iso8601 })++ [ 1007, 1008 ].each do |id|+ WiseEntry::Processor.new(build_transfer(id: id, target_account: 99999001, source_value: 100.0, target_value: 115.4,+ source_currency: "GBP", target_currency: "EUR"), wise_account: @wise_account).process+ end++ assert_equal [ BigDecimal("-115.4"), "EUR" ], categorized.reload.values_at(:amount, :currency)+ assert_equal [ BigDecimal("-100"), "GBP" ], changed.reload.values_at(:amount, :currency)+ end++ # Wise ends top-ups in outgoing_payment_sent like payouts, so the status+ # says nothing about direction; with no recipient known, the markup on the+ # transfer's activity decides instead.+ test "takes the direction from the activity markup when no recipient is known" do+ @wise_account.update!(raw_payload: { "type" => "STANDARD" })++ top_up = build_transfer(id: 1003, target_account: 9999, source_value: 100.0)+ .merge("wise_activity" => snapshot(primary: "<positive>+ 100 EUR</positive>"))+ entry = WiseEntry::Processor.new(top_up, wise_account: @wise_account).process+ assert_equal BigDecimal("-100.0"), entry.amount++ payout = build_transfer(id: 1004, target_account: 9999, source_value: 100.0)+ .merge("wise_activity" => snapshot(primary: "100 EUR"))+ entry = WiseEntry::Processor.new(payout, wise_account: @wise_account).process+ assert_equal BigDecimal("100.0"), entry.amount++ unenriched = build_transfer(id: 1006, target_account: 9999, source_value: 100.0)+ assert_equal BigDecimal("100.0"), WiseEntry::Processor.new(unenriched, wise_account: @wise_account).process.amount+ end++ # A top-up stays income when neither recipient id is stored.+ test "a top-up stays income without recipient ids" do@wise_account.update!(raw_payload: { "type" => "STANDARD" })+ top_up = build_transfer(id: 9000000104, target_account: 1_000_001, source_value: 2465.0)+ .merge("wise_activity" => snapshot(primary: "<positive>+ 2,465 EUR</positive>", title: "To EUR"))++ entry = WiseEntry::Processor.new(top_up, wise_account: @wise_account).process++ assert_equal BigDecimal("-2465"), entry.amount+ end++ # A transfer into a balance's own account details reaches that balance only,+ # the rule the importer routes by. It used to book as income on whichever+ # balance's payload held it, such as the funding side an older build stored+ # it on. A since-closed balance keeps its WiseAccount, so a top-up into it+ # stays a pay-in there and never turns into a payout when its history is+ # processed again.+ test "a transfer into a balance's own account details books on that balance only, closed balances included" do+ usd = linked_balance("USD", "10000077", raw_payload: { "type" => "STANDARD", "recipientId" => 77777001,+ "closed_at" => "2026-09-01T00:00:00Z" })+ top_up = build_transfer(id: 1007, target_account: 77777001, source_value: 300.0, source_currency: "USD")+ on_eur = WiseEntry::Processor.new(top_up, wise_account: @wise_account)++ entry = WiseEntry::Processor.new(top_up, wise_account: usd).process++ assert_equal [ BigDecimal("-300.0"), "USD", "incoming" ], [ entry.amount, entry.currency, entry.entryable.extra.dig("wise", "direction") ]+ assert_equal [], on_eur.expected_external_ids+ assert_equal :skipped, on_eur.process+ assert_empty @account.entries+ end++ # An import that fails before it stores the payloads leaves them as they+ # were, and processing still books them, rows an older build put on a+ # balance included (a payout's copy on its target currency's).+ test "books nothing for a payout stored on a balance in another currency than it was paid from" do+ payout = build_transfer(id: 1009, target_account: 9999, source_currency: "GBP", target_currency: "EUR")+ processor = WiseEntry::Processor.new(payout, wise_account: @wise_account)++ assert_equal [], processor.expected_external_ids+ assert_equal :skipped, processor.process+ assert_empty @account.entries+ end++ test "own recipients come from the given list when the caller passes one" do+ transfer = build_transfer(id: 1008, target_account: 5555, source_value: 40.0)++ entry = WiseEntry::Processor.new(transfer, wise_account: @wise_account, own_recipient_ids: [ "5555" ]).process++ assert_equal BigDecimal("-40.0"), entry.amount+ end++ # Status++ test "books an outgoing transfer once Wise has funded it" do+ %w[outgoing_payment_sent processing funds_converted bounced_back waiting_recipient_input_to_proceed].each_with_index do |status, i|+ processor = WiseEntry::Processor.new(build_transfer(id: 8100 + i, target_account: 9999, status: status), wise_account: @wise_account)++ assert_equal [ "wise_transfer_#{8100 + i}" ], processor.expected_external_ids, status+ assert_kind_of Entry, processor.process, status+ end+ end++ test "skips an outgoing transfer Wise has not funded, cancelled, charged back or cannot place" do+ %w[incoming_payment_waiting incoming_payment_initiated cancelled charged_back unknown funds_credited].each_with_index do |status, i|+ processor = WiseEntry::Processor.new(build_transfer(id: 8200 + i, target_account: 9999, status: status), wise_account: @wise_account)++ assert_equal [], processor.expected_external_ids, status+ assert_equal :skipped, processor.process, status+ end+ assert_equal 0, @account.entries.where(source: "wise").count+ end++ test "books a pay-in only once Wise has sent it" do+ sent = WiseEntry::Processor.new(build_transfer(id: 8300, target_account: 99999001), wise_account: @wise_account)+ assert_equal BigDecimal("-100.0"), sent.process.amount++ %w[incoming_payment_waiting incoming_payment_initiated processing funds_converted bounced_back cancelled+ funds_refunded charged_back unknown].each_with_index do |status, i|+ processor = WiseEntry::Processor.new(build_transfer(id: 8301 + i, target_account: 99999001, status: status),+ wise_account: @wise_account)++ assert_equal :skipped, processor.process, status+ end+ assert_equal [ "wise_transfer_8300" ], @account.entries.where(source: "wise").pluck(:external_id)+ end++ # A cancelled payout was never funded.+ test "a cancelled transfer does not book money leaving the balance" do+ cancelled = build_transfer(id: 999001, target_account: 55555555, source_value: 158.4, target_value: 213.0,+ source_currency: "EUR", target_currency: "USD", status: "cancelled")++ assert_equal :skipped, WiseEntry::Processor.new(cancelled, wise_account: @wise_account).process++ assert_equal 0, @account.entries.where(external_id: "wise_transfer_999001").count+ end++ test "a refunded payout books its gross debit and the refund Wise credited back" do+ refunded = build_transfer(id: 8400, target_account: 9999, source_value: 100.0, status: "funds_refunded")+ .merge("wise_activity" => snapshot(primary: "100 EUR", secondary: "101.50 EUR"),+ "wise_refund_activity" => snapshot(primary: "<positive>+ 99.20 EUR</positive>", id: "refund-1",+ created_on: "2026-01-20T09:00:00Z"))+ processor = WiseEntry::Processor.new(refunded, wise_account: @wise_account)++ assert_equal %w[wise_transfer_8400 wise_fee_8400 wise_refund_8400], processor.expected_external_ids+ processor.process++ amounts = @account.entries.where(source: "wise").pluck(:external_id, :amount, :date).to_h { |id, amount, date| [ id, [ amount, date ] ] }+ assert_equal({ "wise_transfer_8400" => [ BigDecimal("100"), Date.new(2026, 1, 15) ],+ "wise_fee_8400" => [ BigDecimal("1.5"), Date.new(2026, 1, 15) ],+ "wise_refund_8400" => [ BigDecimal("-99.2"), Date.new(2026, 1, 20) ] }, amounts)+ refund_entry = @account.entries.find_by!(external_id: "wise_refund_8400")+ assert_equal I18n.t("wise_items.entries.refund_name"), refund_entry.name+ assert_equal({ "transfer_id" => 8400, "type" => "REFUND", "activity_id" => "refund-1" }, refund_entry.entryable.extra["wise"])+ end++ test "a refunded payout without a visible refund books nothing" do+ refunded = build_transfer(id: 8401, target_account: 9999, status: "funds_refunded")+ .merge("wise_activity" => snapshot(primary: "100 EUR"))+ processor = WiseEntry::Processor.new(refunded, wise_account: @wise_account)++ assert_equal [], processor.expected_external_ids+ assert_equal :skipped, processor.process+ end++ # A refund credit Wise cancelled brought nothing back, so the refunded+ # payout books nothing (net zero), as without a refund.+ test "a refunded payout whose refund credit Wise cancelled books nothing" do+ refunded = build_transfer(id: 8404, target_account: 9999, status: "funds_refunded")+ .merge("wise_activity" => snapshot(primary: "100 EUR", secondary: "101.20 EUR"),+ "wise_refund_activity" => snapshot(primary: "<positive>+ 101.20 EUR</positive>", id: "refund-4", status: "CANCELLED"))+ processor = WiseEntry::Processor.new(refunded, wise_account: @wise_account)++ assert_equal [], processor.expected_external_ids+ assert_equal :skipped, processor.process+ assert_empty @account.entries+ end++ test "a refund credit on a payout Wise did not refund is not booked" do+ sent = build_transfer(id: 8402, target_account: 9999)+ .merge("wise_refund_activity" => snapshot(primary: "<positive>+ 100 EUR</positive>", id: "refund-2"))- outgoing = build_transfer(id: 1003, target_account: 9999, source_value: 100.0,- status: "outgoing_payment_sent")- entry = WiseEntry::Processor.new(outgoing, wise_account: @wise_account).process- assert entry.amount.positive?+ WiseEntry::Processor.new(sent, wise_account: @wise_account).process- incoming = build_transfer(id: 1004, target_account: 9999, source_value: 100.0,- status: "funds_credited")- entry = WiseEntry::Processor.new(incoming, wise_account: @wise_account).process- assert entry.amount.negative?+ assert_equal [ "wise_transfer_8402" ], @account.entries.where(source: "wise").pluck(:external_id)+ end++ test "skips a transfer whose activity Wise cancelled" do+ transfer = build_transfer(id: 8500, target_account: 9999)+ .merge("wise_activity" => snapshot(primary: "100 EUR", status: "CANCELLED"))++ assert_equal :skipped, WiseEntry::Processor.new(transfer, wise_account: @wise_account).process+ end++ test "skips a payout the balance replay found externally funded" do+ transfer = build_transfer(id: 8501, target_account: 9999).merge("wise_funding" => "external")+ processor = WiseEntry::Processor.new(transfer, wise_account: @wise_account)++ assert_equal [], processor.expected_external_ids+ assert_equal :skipped, processor.process+ end++ # WiseItem::StatementMigration: the balance's statement row carries it now.+ test "skips a transfer a statement row took over" do+ transfer = build_transfer(id: 8502, target_account: 9999).merge("wise_superseded_by" => "wise_statement_TRANSFER-8502")+ processor = WiseEntry::Processor.new(transfer, wise_account: @wise_account)++ assert_equal [], processor.expected_external_ids+ assert_equal :skipped, processor.process+ assert_empty @account.entriesend# External ID and deduplication@@ -92,9 +310,36 @@ class WiseEntry::ProcessorTest < ActiveSupport::TestCaseassert_equal I18n.t("wise_items.entries.default_name"), entry.nameend+ # Transfers used to be all named "Wise transaction".+ test "names a transfer without a reference after the counterparty in its activity" do+ payout = build_transfer(id: 3004, target_account: 9999, reference: nil)+ .merge("wise_activity" => snapshot(primary: "100 EUR", title: "Tom & Jerry"))+ referenced = build_transfer(id: 3005, target_account: 9999, reference: "Invoice #44")+ .merge("wise_activity" => snapshot(primary: "100 EUR", title: "Tom & Jerry"))++ assert_equal "Tom & Jerry", WiseEntry::Processor.new(payout, wise_account: @wise_account).process.name+ assert_equal "Invoice #44", WiseEntry::Processor.new(referenced, wise_account: @wise_account).process.name+ end++ test "renames an existing entry when the transfer's name changes" do+ # Renaming logs a DataEnrichment under source "wise", which the enum used+ # to reject, failing the row on every later sync.+ WiseEntry::Processor.new(build_transfer(id: 3003, target_account: 9999, reference: nil),+ wise_account: @wise_account).process++ entry = WiseEntry::Processor.new(build_transfer(id: 3003, target_account: 9999, reference: "Invoice #43"),+ wise_account: @wise_account).process++ assert_equal "Invoice #43", entry.reload.name+ end+# Fee handling- test "creates separate fee entry when sourceValue exceeds targetValue in same currency" do+ # sourceValue excludes Wise's fee (it equals targetValue on a same-currency+ # payout), so the fee now comes from the gross debit in the transfer's+ # activity; this gap is only the fallback for a transfer whose activity Sure+ # never saw.+ test "falls back to the same-currency gap between sourceValue and targetValue without an activity" dotransfer = build_transfer(id: 4001, target_account: 9999, source_value: 100.5, target_value: 100.0)WiseEntry::Processor.new(transfer, wise_account: @wise_account).process@@ -116,7 +361,9 @@ class WiseEntry::ProcessorTest < ActiveSupport::TestCaseassert_equal 1, @account.entries.where(source: "wise").countend- test "does not create fee entry for cross-currency transfers" do+ # With its activity a cross-currency payout does get a fee (see below);+ # without it there is nothing in the source currency to compare.+ test "does not guess a cross-currency fee without an activity" dotransfer = build_transfer(id: 4003, target_account: 9999, source_value: 100.0, target_value: 90.0,source_currency: "EUR", target_currency: "GBP")@@ -125,11 +372,109 @@ class WiseEntry::ProcessorTest < ActiveSupport::TestCaseassert_equal 1, @account.entries.where(source: "wise").countend+ # A payout that debited 5,492.01 USD for a 5,482.37 sourceValue.+ test "a same-currency payout lowers the balance by what Wise debited, fee included" do+ transfer = build_transfer(id: 9000000103, target_account: 55555555, source_value: 5482.37)+ .merge("wise_activity" => snapshot(primary: "5,482.37 EUR", secondary: "5,492.01 EUR"))++ WiseEntry::Processor.new(transfer, wise_account: @wise_account).process++ amounts = @account.entries.where(source: "wise").pluck(:external_id, :amount).to_h+ assert_equal({ "wise_transfer_9000000103" => BigDecimal("5482.37"), "wise_fee_9000000103" => BigDecimal("9.64") }, amounts)+ end++ test "takes a cross-currency payout's fee from the gross debit in its source currency" do+ # A payout of 158.40 GBP converted to 213.00 USD, 160.25 GBP debited.+ gbp = linked_balance("GBP", "10000003")+ transfer = build_transfer(id: 9000000102, target_account: 55555555, source_value: 158.4, target_value: 213.0,+ source_currency: "GBP", target_currency: "USD", rate: 1.3874)+ .merge("wise_activity" => snapshot(primary: "213 USD", secondary: "160.25 GBP"))+ processor = WiseEntry::Processor.new(transfer, wise_account: gbp)++ assert_equal %w[wise_transfer_9000000102 wise_fee_9000000102], processor.expected_external_ids+ entry = processor.process++ assert_equal BigDecimal("158.40"), entry.amount+ assert_equal BigDecimal("1.85"), gbp.current_account.entries.find_by!(external_id: "wise_fee_9000000102").amount+ assert_equal BigDecimal("1.85"), entry.entryable.extra.dig("wise", "fee").to_d+ assert_equal "act-1", entry.entryable.extra.dig("wise", "activity_id")+ end++ test "books no fee when the activity shows no more than sourceValue" do+ transfer = build_transfer(id: 4005, target_account: 9999, source_value: 100.5, target_value: 100.0)+ .merge("wise_activity" => snapshot(primary: "100.50 EUR", secondary: "100.504 EUR"))++ WiseEntry::Processor.new(transfer, wise_account: @wise_account).process++ assert_equal [ "wise_transfer_4005" ], @account.entries.where(source: "wise").pluck(:external_id)+ end++ test "never books a fee on a pay-in" do+ transfer = build_transfer(id: 4006, target_account: 99999001, source_value: 100.5, target_value: 100.0)+ .merge("wise_activity" => snapshot(primary: "<positive>+ 100 EUR</positive>", secondary: "101.20 EUR"))+ processor = WiseEntry::Processor.new(transfer, wise_account: @wise_account)++ assert_equal [ "wise_transfer_4006" ], processor.expected_external_ids+ processor.process++ assert_equal({ "wise_transfer_4006" => BigDecimal("-100") }, @account.entries.where(source: "wise").pluck(:external_id, :amount).to_h)+ end++ test "re-importing a transfer drops wise metadata Wise no longer reports" do+ WiseEntry::Processor.new(build_transfer(id: 4004, target_account: 9999, source_value: 100.5, target_value: 100.0),+ wise_account: @wise_account).process++ entry = WiseEntry::Processor.new(build_transfer(id: 4004, target_account: 9999, source_value: 100.0, target_value: 100.0),+ wise_account: @wise_account).process++ assert_nil entry.entryable.reload.extra.dig("wise", "fee")+ end++ # A fee's and a refund's wise namespace is replaced on every import too, so+ # a key Sure no longer writes there goes.+ test "re-importing a refunded payout drops wise metadata its fee and refund no longer carry" do+ refunded = build_transfer(id: 8403, target_account: 9999, status: "funds_refunded")+ .merge("wise_activity" => snapshot(primary: "100 EUR", secondary: "101.50 EUR"),+ "wise_refund_activity" => snapshot(primary: "<positive>+ 99.20 EUR</positive>", id: "refund-3"))+ WiseEntry::Processor.new(refunded, wise_account: @wise_account).process+ fee, refund = %w[wise_fee_8403 wise_refund_8403].map { |id| @account.entries.find_by!(external_id: id).entryable }+ fee.update_column(:extra, fee.extra.deep_merge("wise" => { "status" => "outgoing_payment_sent" }))++ WiseEntry::Processor.new(refunded.merge("wise_refund_activity" => refunded["wise_refund_activity"].except("id")),+ wise_account: @wise_account).process++ assert_equal({ "transfer_id" => 8403, "type" => "FEE" }, fee.reload.extra["wise"])+ assert_equal({ "transfer_id" => 8403, "type" => "REFUND" }, refund.reload.extra["wise"])+ end++ # Dates++ test "reads created as UTC whatever the server time zone" do+ @family.update!(timezone: "Europe/Dublin")+ transfer = build_transfer(id: 7001, target_account: 9999).merge("created" => "2026-06-30 23:30:00")++ entry = with_server_time_zone("Europe/Dublin") do+ WiseEntry::Processor.new(transfer, wise_account: @wise_account).process+ end++ # Wise sends created in UTC without a zone designator: 23:30 UTC is 00:30+ # on 1 July in Dublin (IST).+ assert_equal Date.new(2026, 7, 1), entry.date+ end++ test "created_at is the UTC instant of created" do+ with_server_time_zone("Asia/Tokyo") do+ assert_equal Time.utc(2026, 6, 30, 23, 30), WiseEntry::Processor.created_at({ "created" => "2026-06-30 23:30:00" })+ end+ assert_nil WiseEntry::Processor.created_at({ "created" => nil })+ end+# Exchange rate for balance conversiontest "stores the Wise exchange rate for cross-currency transfers" do+ # Paid from the balance's currency.transfer = build_transfer(id: 6001, target_account: 9999, source_value: 1828.25,- target_value: 1372.47, source_currency: "CAD",+ target_value: 1372.47, source_currency: "EUR",target_currency: "USD", rate: 0.7507)entry = WiseEntry::Processor.new(transfer, wise_account: @wise_account).process@@ -179,6 +524,32 @@ class WiseEntry::ProcessorTest < ActiveSupport::TestCaseprivate+ def linked_balance(currency, balance_id, raw_payload: { "type" => "STANDARD" })+ wise_account = WiseAccount.create!(wise_item: @wise_item, balance_id: balance_id, name: "Wise #{currency}",+ currency: currency, raw_payload: raw_payload)+ account = Account.create!(family: @family, name: "Wise #{currency}", accountable: Depository.new(subtype: "checking"),+ balance: 0, currency: currency)+ AccountProvider.create!(account: account, provider: wise_account)+ wise_account+ end++ # Time.parse reads a zone-less string in the process time zone (ENV["TZ"]).+ def with_server_time_zone(zone)+ previous = ENV["TZ"]+ ENV["TZ"] = zone+ yield+ ensure+ ENV["TZ"] = previous+ end++ # The transfer's activity as the importer attaches it ("wise_activity"):+ # Wise's amount strings with their markup and a plain-text title.+ def snapshot(primary:, secondary: nil, status: "COMPLETED", title: "Recipient", id: "act-1",+ created_on: "2026-01-15T10:00:01Z")+ { "id" => id, "type" => "TRANSFER", "status" => status, "primaryAmount" => primary, "secondaryAmount" => secondary,+ "title" => title, "description" => "Sent", "createdOn" => created_on, "updatedOn" => created_on }.compact+ end+def build_transfer(id:, target_account:, source_value: 100.0, target_value: nil,source_currency: "EUR", target_currency: nil, status: "outgoing_payment_sent",reference: nil, rate: 1.0)diff --git a/test/models/wise_item/amount_correction_test.rb b/test/models/wise_item/amount_correction_test.rbnew file mode 100644index 0000000000..dd62c4770d--- /dev/null+++ b/test/models/wise_item/amount_correction_test.rb@@ -0,0 +1,55 @@+require "test_helper"++class WiseItem::AmountCorrectionTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ @account = Account.create!(family: @family, name: "Wise EUR", balance: 0, currency: "EUR",+ accountable: Depository.new(subtype: "checking"))+ end++ test "Wise's amount reaches an entry a person categorized, noted or excluded" do+ categorized = booked(user_modified: true)+ categorized.entryable.update!(locked_attributes: { "category_id" => Time.current.iso8601 })+ noted = booked(user_modified: true, notes: "Rent")+ excluded = booked(excluded: true)++ [ categorized, noted, excluded ].each do |entry|+ WiseItem::AmountCorrection.apply(entry, amount: BigDecimal("-115.4"), currency: "EUR")+ assert_equal [ BigDecimal("-115.4"), "EUR" ], entry.reload.values_at(:amount, :currency)+ end+ assert_equal "Rent", noted.notes+ assert excluded.excluded?+ end++ test "keeps the amount a person set, and that of entries an import, a reconciliation, a split or a transfer owns" do+ amount_locked = booked(user_modified: true, locked_attributes: { "amount" => Time.current.iso8601 })+ currency_locked = booked(user_modified: true, locked_attributes: { "currency" => Time.current.iso8601 })+ import_locked = booked(import_locked: true)+ reconciled = booked(user_modified: true, reconciled_at: Time.current)+ split = booked(user_modified: true)+ split.split!([ { name: "Groceries", amount: 60, category_id: nil }, { name: "Household", amount: 40, category_id: nil } ])+ in_transfer = booked(user_modified: true)+ bank = Account.create!(family: @family, name: "Bank", balance: 0, currency: "EUR", accountable: Depository.new(subtype: "checking"))+ deposit = bank.entries.create!(amount: -100, currency: "EUR", date: in_transfer.date, name: "From Wise", entryable: Transaction.new)+ Transfer.create!(inflow_transaction: deposit.entryable, outflow_transaction: in_transfer.entryable, status: "confirmed")++ [ amount_locked, currency_locked, import_locked, reconciled, split, in_transfer ].each do |entry|+ WiseItem::AmountCorrection.apply(entry.reload, amount: BigDecimal("80"), currency: "EUR")+ assert_equal BigDecimal("100"), entry.reload.amount, entry.name+ end+ end++ test "leaves an entry the adapter could update alone" do+ entry = booked+ assert_no_changes -> { entry.reload.updated_at } do+ WiseItem::AmountCorrection.apply(entry, amount: BigDecimal("80"), currency: "EUR")+ end+ end++ private++ def booked(**attributes)+ @account.entries.create!(external_id: "wise_transfer_#{SecureRandom.hex(4)}", source: "wise", amount: 100, currency: "EUR",+ date: Date.current, name: "Payout", entryable: Transaction.new, **attributes)+ end+enddiff --git a/test/models/wise_item/balance_replay_test.rb b/test/models/wise_item/balance_replay_test.rbnew file mode 100644index 0000000000..29e515f185--- /dev/null+++ b/test/models/wise_item/balance_replay_test.rb@@ -0,0 +1,414 @@+require "test_helper"++class WiseItem::BalanceReplayTest < ActiveSupport::TestCase+ OWN_RECIPIENT = 90000001++ test "drains the merchant-currency balance and gives the rest of a split payment to the other balance" do+ conversion = conversion("conversion-1", "13 EUR", "11.31 GBP", "2026-03-01T10:00:00Z")+ payment = card("card-1", "25 EUR", "GBP, EUR", "2026-03-01T12:00:00Z")+ eur = balance("EUR", "0", [ conversion, payment ])+ gbp = balance("GBP", "28.25", [ top_up(1, "50", "GBP", "2026-03-01 09:00:00"), conversion, payment ])++ result = replay(eur, gbp)++ assert result.outcomes.all?(&:success?)+ assert_equal({ "card-1" => { "wise_split_parts" => { "GBP" => "10.44", "EUR" => "13.00" }, "wise_split_estimated" => nil } },+ result.split_annotations)+ assert_equal({ "EUR" => Set.new, "GBP" => Set.new }, result.funding)+ end++ # Low-water rule: a part is at most the balance's lowest point until its+ # next split payment, so GBP is not left below zero after the conversion.+ test "gives each earlier split payment at most the balance's low point before the next one" do+ first = card("card-1", "20 EUR", "GBP, EUR", "2026-03-02T10:00:00Z")+ conversion = conversion("conversion-1", "94.94 EUR", "82.60 GBP", "2026-03-02T11:00:00Z")+ second = card("card-2", "10 EUR", "GBP, EUR", "2026-03-05T10:00:00Z")+ eur = balance("EUR", "0", [ first, conversion, card("card-3", "94.94 EUR", "", "2026-03-02T12:00:00Z"), second ])+ gbp = balance("GBP", "41.30", [+ top_up(1, "100", "GBP", "2026-03-01 09:00:00"), first, conversion, top_up(2, "50", "GBP", "2026-03-04 09:00:00"), second+ ])++ result = replay(eur, gbp)++ assert result.outcomes.all?(&:success?)+ assert_equal({ "GBP" => "17.40", "EUR" => "0.00" }, result.split_annotations.dig("card-1", "wise_split_parts"))+ assert_equal({ "GBP" => "8.70", "EUR" => "0.00" }, result.split_annotations.dig("card-2", "wise_split_parts"))+ # GBP paid two split payments, so its parts are estimates.+ assert_equal [ [ "GBP" ], [ "GBP" ] ], result.split_annotations.values.map { |marks| marks["wise_split_estimated"] }+ end++ # EUR reconciled, but its 13 EUR share of the payment is not written (GBP+ # did not reconcile), so what it held could hide a credit Sure misses; its+ # funding marks stay too (they used to be replaced).+ test "fails a currency whose part of a split payment is beyond the payment at the nearest rate" do+ conversion = conversion("conversion-1", "13 EUR", "11.31 GBP", "2026-03-01T10:00:00Z")+ payment = card("card-1", "25 EUR", "GBP, EUR", "2026-03-01T12:00:00Z")+ eur = balance("EUR", "0", [ conversion, payment ])+ # 30 GBP left the balance without a row, which would make GBP's part 40.44+ # for the 12 EUR the euro balance did not pay.+ gbp = balance("GBP", "28.25", [ top_up(1, "80", "GBP", "2026-03-01 09:00:00"), conversion, payment ])++ result = replay(eur, gbp)++ assert_equal({ "EUR" => nil, "GBP" => :implausible_split_part }, result.outcomes.to_h { |outcome| [ outcome.currency, outcome.reason ] })+ # EUR reconciled, but a split payment's parts are all or nothing.+ assert_empty result.split_annotations+ assert_equal :split_parts_withheld, outcome(result, "EUR").funding_withheld+ assert_empty result.funding+ end++ test "marks a payout the balance could not have paid as externally funded" do+ gbp = balance("GBP", "100", [+ top_up(1, "120", "GBP", "2025-07-29 07:26:51"),+ payout(2, "158.40", "GBP", "2025-07-30 16:09:38", target: "213 USD", gross: "160.25", updated_on: "2025-07-30T16:11:00.972Z"),+ card("card-1", "20 GBP", "", "2025-08-03T11:00:00Z")+ ])++ result = replay(gbp)++ assert result.outcomes.sole.success?+ assert_equal({ "GBP" => Set["2"] }, result.funding)+ end++ # A transfer's creation time has no fractions of a second, so the payout+ # sorts after the conversion that paid for it in the same second.+ test "puts credits before debits within the same second" do+ usd = balance("USD", "0", [+ payout(3, "100", "USD", "2026-03-01 10:00:00"),+ conversion("conversion-1", "100 USD", "80 GBP", "2026-03-01T10:00:00.700Z")+ ])++ result = replay(usd)++ assert result.outcomes.sole.success?+ assert_equal({ "USD" => Set.new }, result.funding)+ end++ # The balance could pay the payout once its activity completed, so it is+ # not externally funded; booked on its creation day it would leave the+ # balance below zero for a moment, so the currency keeps its old marks.+ test "does not call a payout externally funded when the balance could pay it once its activity completed" do+ gbp = balance("GBP", "0", [+ payout(4, "100", "GBP", "2026-03-01 10:00:00", gross: "100", updated_on: "2026-03-01T10:05:00Z"),+ top_up(5, "100", "GBP", "2026-03-01 10:01:00")+ ])++ result = replay(gbp)++ assert_equal :negative_running_balance, result.outcomes.sole.reason+ assert_empty result.funding+ end++ # A missing inflow makes a payout look unpaid, but then the replay cannot+ # end at the live amount, so nothing is marked.+ test "marks no payout when a missing inflow leaves the replay short of the live amount" do+ gbp = balance("GBP", "50", [+ top_up(1, "100", "GBP", "2026-03-01 09:00:00"),+ # A 200 GBP top-up on 2 March is missing.+ payout(6, "250", "GBP", "2026-03-03 09:00:00")+ ])++ result = replay(gbp)++ assert_equal :leftover_unexplained, result.outcomes.sole.reason+ assert_empty result.funding+ end++ test "fails a split payment the merchant-currency balance could have paid in full" do+ eur = balance("EUR", "140", [+ conversion("conversion-1", "300 EUR", "261 GBP", "2026-03-01T10:00:00Z"),+ card("card-1", "160 EUR", "GBP, EUR", "2026-03-01T12:00:00Z")+ ])++ result = replay(eur)++ assert_equal :split_payment_affordable, result.outcomes.sole.reason+ assert_empty result.split_annotations+ end++ # Wise splits a payment only when the merchant-currency balance cannot pay+ # it with its fees (up to 3 % + 2 units): holding 154 for a 150 EUR+ # withdrawal, it pays all it holds; holding 159 it could have paid it alone.+ test "drains a merchant balance holding up to the fee allowance more than the split payment" do+ atm = activity("atm-1", "CASH_WITHDRAWAL", "150 EUR", "GBP, EUR", "2026-03-04T09:00:00Z", title: "<strong>ATM</strong>")+ gbp = balance("GBP", "10", [ top_up(2, "10", "GBP", "2026-03-01 09:00:00"), atm ])++ within = replay(balance("EUR", "0", [ top_up(1, "154", "EUR", "2026-03-01 09:00:00"), atm ]), gbp)+ beyond = replay(balance("EUR", "9", [ top_up(1, "159", "EUR", "2026-03-01 09:00:00"), atm ]), gbp)++ assert within.outcomes.all?(&:success?)+ assert_equal({ "GBP" => "0.00", "EUR" => "154.00" }, within.split_annotations.dig("atm-1", "wise_split_parts"))+ assert_equal :split_payment_affordable, outcome(beyond, "EUR").reason+ end++ test "replays the rows Wise reported, not the marks an earlier replay left on them" do+ paid = payout(7, "160.25", "GBP", "2026-03-02 09:00:00").merge("wise_funding" => "external")+ split = card("card-1", "25 EUR", "GBP, EUR", "2026-03-03T09:00:00Z").merge("wise_split_parts" => { "GBP" => "9.99", "EUR" => "15.01" })+ gbp = balance("GBP", "39.75", [ top_up(1, "200", "GBP", "2026-03-01 09:00:00"), paid, split ])+ eur = balance("EUR", "0", [ top_up(2, "25", "EUR", "2026-03-01 09:00:00"), split ])++ result = replay(gbp, eur)++ assert result.outcomes.all?(&:success?)+ assert_equal Set.new, result.funding["GBP"]+ # The euro balance could pay it all; GBP lists the payment but paid nothing.+ assert_equal({ "GBP" => "0.00", "EUR" => "25.00" }, result.split_annotations.dig("card-1", "wise_split_parts"))+ end++ # Nothing bounds what CHF paid, so a debit Sure does not book could pass+ # for its part: the payment gets no parts, and both balances, whose money+ # went into it, keep their funding marks.+ test "writes no parts for a split payment one of whose parts no exchange rate bounds" do+ payment = card("card-1", "25 EUR", "CHF, EUR", "2026-03-01T12:00:00Z")+ eur = balance("EUR", "0", [ top_up(1, "11", "EUR", "2026-03-01 09:00:00"), payment ])+ chf = balance("CHF", "36", [ top_up(2, "50", "CHF", "2026-03-01 09:00:00"), payment ])++ result = replay(eur, chf)++ assert result.outcomes.all?(&:success?)+ assert_empty result.split_annotations+ assert_equal({ unbounded_part_count: 1 }, outcome(result, "CHF").notes)+ assert_equal [ :split_parts_withheld ] * 2, %w[CHF EUR].map { |currency| outcome(result, currency).funding_withheld }+ assert_empty result.funding+ end++ # The family's currency is USD, so Sure holds rates from EUR and from GBP+ # to it but none between them. 50 GBP left GBP by a debit Sure does not+ # book; without a rate that leftover would pass for GBP's part.+ test "bounds a split part with the cross rate of the rates Sure stored to a third currency" do+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.new(2026, 3, 1), rate: 1.08)+ ExchangeRate.create!(from_currency: "GBP", to_currency: "USD", date: Date.new(2026, 3, 2), rate: 1.26)+ payment = card("card-1", "25 EUR", "GBP, EUR", "2026-03-01T12:00:00Z")+ eur = balance("EUR", "0", [ top_up(1, "13", "EUR", "2026-03-01 09:00:00"), payment ])+ gbp = balance("GBP", "39.56", [ top_up(2, "100", "GBP", "2026-03-01 09:00:00"), payment ])++ result = WiseItem::BalanceReplay.new([ eur, gbp ], own_recipient_ids: [ OWN_RECIPIENT ]).call++ assert_equal :implausible_split_part, outcome(result, "GBP").reason+ assert_empty result.split_annotations+ end++ # A move between the balance and a jar Sure does not have is read by its+ # title like the processor books it (WiseActivity::Processor.jar_deposit?):+ # into the jar when the title names the jar, back into the balance when it+ # names the balance's currency.+ test "replays the moves to and from a jar Sure does not have the way they are booked" do+ gbp = balance("GBP", "70", [+ top_up(1, "100", "GBP", "2026-03-01 09:00:00"),+ activity("jar-in", "INTERBALANCE", "50 GBP", nil, "2026-03-02T10:00:00Z", title: "To <strong>Trip</strong>"),+ activity("jar-out", "INTERBALANCE", "20 GBP", nil, "2026-03-03T10:00:00Z", title: "To <strong>GBP</strong>")+ ])++ assert replay(gbp).outcomes.sole.success?+ end++ test "bounds a split part with a rate Sure stored when the feed has none" do+ payment = card("card-1", "25 EUR", "CHF, EUR", "2026-03-01T12:00:00Z")+ eur = balance("EUR", "0", [ top_up(1, "10", "EUR", "2026-03-01 09:00:00"), payment ])+ chf = balance("CHF", "6", [ top_up(2, "50", "CHF", "2026-03-01 09:00:00"), payment ])++ result = replay(eur, chf, stored_rate: ->(from, to, date) { BigDecimal("0.95") if [ from, to, date ] == [ "EUR", "CHF", Date.new(2026, 3, 1) ] })++ # 44 CHF for the 15 EUR the euro balance did not pay is beyond 0.95 CHF/EUR.+ assert_equal :implausible_split_part, result.outcomes.find { |outcome| outcome.currency == "CHF" }.reason+ end++ test "writes no parts for a split payment when one of its balances is not replayed" do+ eur = balance("EUR", "0", [ top_up(1, "10", "EUR", "2026-03-01 09:00:00"), card("card-1", "25 EUR", "GBP, EUR", "2026-03-01T12:00:00Z") ])++ result = replay(eur)++ assert result.outcomes.sole.success?+ assert_empty result.split_annotations+ # Nor does EUR replace its funding marks while its share is unwritten.+ assert_equal :split_parts_withheld, result.outcomes.sole.funding_withheld+ assert_empty result.funding+ end++ # A credit Sure does not book (4 GBP) makes the 93 GBP payout look unpaid;+ # with the payout taken as externally funded, the balance reconciled by+ # giving its leftover to the ATM withdrawal it shares with a euro balance+ # that is not replayed, a part never written and bounded by the whole+ # withdrawal. The balance keeps the payout booked, which its replay did not,+ # so it does not reconcile, and the payout is not marked.+ test "marks no payout when the balance's leftover went into a split part that is not written" do+ gbp = balance("GBP", "5.58", [+ top_up(1, "90", "GBP", "2026-03-01 09:00:00"),+ # missing: + 4 GBP on 2026-03-01 10:00+ payout(2, "93", "GBP", "2026-03-02 09:00:00"),+ top_up(3, "12", "GBP", "2026-03-03 09:00:00"),+ activity("atm-1", "CASH_WITHDRAWAL", "150 EUR", "GBP, EUR", "2026-03-04T09:00:00Z", title: "<strong>ATM</strong>")+ ])++ result = replay(gbp, stored_rate: ->(from, to, _date) { BigDecimal("0.87") if [ from, to ] == %w[EUR GBP] })++ assert_equal [ :funding_unconfirmed, 1 ], result.outcomes.sole.then { |outcome| [ outcome.reason, outcome.counts[:external_candidate_count] ] }+ assert_empty result.funding+ assert_empty result.split_annotations+ end++ # The same balance, but the euro balance is replayed (it paid 145 EUR of the+ # withdrawal) and no EUR/GBP rate is known. GBP reconciles only with the+ # payout taken as externally funded and a 96.42 GBP share no rate bounds, so+ # it keeps the payout's marks (none: it is booked). Written next to them,+ # that share booked the payout's 93 a second time (GBP at -87.42 for a live+ # 5.58); now GBP does not reconcile and the withdrawal keeps its parts, all+ # or nothing.+ test "writes no split part a balance worked out with a payout taken as externally funded that it keeps booked" do+ atm = activity("atm-1", "CASH_WITHDRAWAL", "150 EUR", "GBP, EUR", "2026-03-04T09:00:00Z", title: "<strong>ATM</strong>")+ eur = balance("EUR", "0", [ top_up(11, "145", "EUR", "2026-03-01 08:00:00"), atm ])+ gbp = balance("GBP", "5.58", [+ top_up(1, "90", "GBP", "2026-03-01 09:00:00"),+ # missing: + 4 GBP on 2026-03-01 10:00+ payout(2, "93", "GBP", "2026-03-02 09:00:00"),+ top_up(3, "12", "GBP", "2026-03-03 09:00:00"),+ atm+ ])++ result = replay(eur, gbp)++ assert_equal [ :funding_unconfirmed, 1 ], outcome(result, "GBP").then { |gbp_outcome| [ gbp_outcome.reason, gbp_outcome.counts[:external_candidate_count] ] }+ # The euro balance's share is unwritten too, so it keeps its marks as well.+ assert_equal [ nil, :split_parts_withheld ], outcome(result, "EUR").then { |eur_outcome| [ eur_outcome.reason, eur_outcome.funding_withheld ] }+ assert_empty result.funding+ assert_empty result.split_annotations+ end++ # The case the replay exists for: a card paid CHF's 40 CHF payout while it+ # held nothing; it then got 50 and paid 14 CHF of a 25 EUR card payment the+ # euro balance paid 11 EUR of. No EUR/CHF rate bounds the 14 CHF, so the+ # payment gets no parts and the payout keeps its marks. Unmarked, it stays+ # booked, which the replay did not do, so CHF does not reconcile (booked+ # with it, CHF came to -4 for a live 36). Marked by an earlier replay, the+ # marks fit what the replay found.+ test "a balance keeps its funding marks only when they fit the payouts its replay found externally funded" do+ payment = card("card-1", "25 EUR", "CHF, EUR", "2026-03-01T12:00:00Z")+ eur = balance("EUR", "0", [ top_up(11, "11", "EUR", "2026-03-01 09:00:00"), payment ])+ chf_rows = ->(funding) {+ [ payout(7, "40", "CHF", "2026-03-01 08:00:00").merge("wise_funding" => funding).compact,+ top_up(12, "50", "CHF", "2026-03-01 09:00:00"), payment ]+ }++ unmarked = replay(eur, balance("CHF", "36", chf_rows.call(nil)))+ marked = replay(eur, balance("CHF", "36", chf_rows.call("external")))++ assert_equal :funding_unconfirmed, outcome(unmarked, "CHF").reason+ assert_empty unmarked.funding+ assert_empty unmarked.split_annotations++ assert_equal [ nil, :split_parts_withheld ], outcome(marked, "CHF").then { |chf| [ chf.reason, chf.funding_withheld ] }+ assert_empty marked.funding+ assert_empty marked.split_annotations+ end++ # The other way round: an earlier replay marked the payout externally+ # funded, but this one finds CHF paid it, and gives its leftover (10 CHF) to+ # a split part no rate bounds. Written next to the mark CHF keeps, that part+ # would leave the payout booked nowhere.+ test "writes no split part a balance worked out with a payout it paid that its rows mark externally funded" do+ payment = card("card-1", "25 EUR", "CHF, EUR", "2026-03-01T12:00:00Z")+ eur = balance("EUR", "0", [ top_up(11, "10", "EUR", "2026-03-01 09:00:00"), payment ])+ chf = balance("CHF", "0", [+ top_up(12, "50", "CHF", "2026-03-01 08:00:00"),+ payout(7, "40", "CHF", "2026-03-01 09:00:00").merge("wise_funding" => "external"),+ payment+ ])++ result = replay(eur, chf)++ assert_equal [ :funding_unconfirmed, 0 ], outcome(result, "CHF").then { |chf_outcome| [ chf_outcome.reason, chf_outcome.counts[:external_candidate_count] ] }+ assert_empty result.funding+ assert_empty result.split_annotations+ end++ # CHF's part of a GBP card payment has no rate and was worked out with CHF's+ # payout as externally funded, so that payment keeps its parts. GBP's+ # drained part of it is then unwritten, so GBP keeps its funding marks too,+ # and its part of a euro card payment, worked out with GBP's own payout as+ # externally funded, is not written either.+ test "withholds in turn the parts of a balance whose share of a payment another balance withheld is unwritten" do+ gbp_card = card("card-gbp", "100 GBP", "CHF, GBP", "2026-03-02T12:00:00Z")+ eur_card = card("card-eur", "25 EUR", "GBP, EUR", "2026-03-04T12:00:00Z")+ chf = balance("CHF", "36", [ payout(7, "40", "CHF", "2026-03-01 08:00:00"), top_up(12, "50", "CHF", "2026-03-01 09:00:00"), gbp_card ])+ gbp = balance("GBP", "7", [+ payout(8, "30", "GBP", "2026-03-01 08:00:00"), top_up(13, "90", "GBP", "2026-03-01 09:30:00"), gbp_card,+ top_up(14, "20", "GBP", "2026-03-03 09:00:00"), eur_card+ ])+ eur = balance("EUR", "0", [ top_up(11, "10", "EUR", "2026-03-04 09:00:00"), eur_card ])++ result = replay(chf, gbp, eur, stored_rate: ->(from, to, _date) { BigDecimal("0.87") if [ from, to ] == %w[EUR GBP] })++ assert_equal({ "CHF" => [ :funding_unconfirmed, nil ], "GBP" => [ :funding_unconfirmed, nil ], "EUR" => [ nil, :split_parts_withheld ] },+ result.outcomes.to_h { |each| [ each.currency, [ each.reason, each.funding_withheld ] ] })+ assert_empty result.funding+ assert_empty result.split_annotations+ end++ test "reads a stored exchange rate within a few days, in either direction" do+ ExchangeRate.create!(from_currency: "CHF", to_currency: "SEK", date: Date.new(2026, 3, 3), rate: 12.5)+ ExchangeRate.create!(from_currency: "CHF", to_currency: "SEK", date: Date.new(2026, 4, 6), rate: 11)++ assert_equal BigDecimal("12.5"), WiseItem::BalanceReplay.stored_rate("CHF", "SEK", Date.new(2026, 3, 1))+ assert_equal BigDecimal("0.08"), WiseItem::BalanceReplay.stored_rate("SEK", "CHF", Date.new(2026, 3, 5))+ assert_nil WiseItem::BalanceReplay.stored_rate("CHF", "SEK", Date.new(2026, 3, 20))+ end++ test "reads a cross rate through a currency Sure holds rates for with both" do+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.new(2026, 3, 1), rate: 1.08)+ ExchangeRate.create!(from_currency: "USD", to_currency: "GBP", date: Date.new(2026, 3, 2), rate: 0.8)++ assert_in_delta 0.864, WiseItem::BalanceReplay.stored_rate("EUR", "GBP", Date.new(2026, 3, 1)), 0.0001+ assert_in_delta 1 / 0.864, WiseItem::BalanceReplay.stored_rate("GBP", "EUR", Date.new(2026, 3, 1)), 0.0001+ assert_nil WiseItem::BalanceReplay.stored_rate("EUR", "CHF", Date.new(2026, 3, 1))+ end++ private++ def outcome(result, currency)+ result.outcomes.find { |outcome| outcome.currency == currency }+ end++ def replay(*balances, stored_rate: ->(*) { nil })+ WiseItem::BalanceReplay.new(balances, own_recipient_ids: [ OWN_RECIPIENT ], stored_rate: stored_rate).call+ end++ def balance(currency, live, rows)+ WiseItem::BalanceReplay::Balance.new(key: currency, currency: currency, live: BigDecimal(live), rows: rows)+ end++ # A transfer into the profile's own account details.+ def top_up(id, value, currency, created)+ { "id" => id, "created" => created, "status" => "outgoing_payment_sent", "targetAccount" => OWN_RECIPIENT,+ "sourceCurrency" => currency, "sourceValue" => value.to_f, "targetCurrency" => currency, "targetValue" => value.to_f }+ end++ # A transfer to someone else; with gross, the activity Wise shows for it.+ def payout(id, value, currency, created, target: "#{value} #{currency}", gross: nil, updated_on: nil)+ target_value, target_currency = target.split+ row = { "id" => id, "created" => created, "status" => "outgoing_payment_sent", "targetAccount" => 55555555,+ "sourceCurrency" => currency, "sourceValue" => value.to_f,+ "targetCurrency" => target_currency, "targetValue" => target_value.to_f }+ return row unless gross++ created_on = "#{created.sub(' ', 'T')}.500Z"+ row.merge("wise_activity" => {+ "id" => "transfer-activity-#{id}", "type" => "TRANSFER", "status" => "COMPLETED",+ "primaryAmount" => target, "secondaryAmount" => "#{gross} #{currency}",+ "createdOn" => created_on, "updatedOn" => updated_on || created_on+ })+ end++ def conversion(id, primary, secondary, created_on)+ activity(id, "INTERBALANCE", primary, secondary, created_on, title: "To <strong>#{primary.split.last}</strong>")+ end++ def card(id, primary, secondary, created_on)+ activity(id, "CARD_PAYMENT", primary, secondary, created_on, title: "<strong>Merchant</strong>")+ end++ def activity(id, type, primary, secondary, created_on, title:)+ { "id" => id, "type" => type, "resource" => { "type" => "CARD_TRANSACTION", "id" => "resource-#{id}" }, "title" => title,+ "primaryAmount" => primary, "secondaryAmount" => secondary, "status" => "COMPLETED",+ "createdOn" => created_on, "updatedOn" => created_on }+ end+enddiff --git a/test/models/wise_item/importer_test.rb b/test/models/wise_item/importer_test.rbindex 154e4f4b88..49113804cf 100644--- a/test/models/wise_item/importer_test.rb+++ b/test/models/wise_item/importer_test.rb@@ -1,28 +1,54 @@require "test_helper"class WiseItem::ImporterTest < ActiveSupport::TestCase+ # Behaves like Wise where the importer depends on it: transfers come in+ # offset pages ending with an empty page, activities in nextCursor pages,+ # and a transfer is readable by id only when listed in transfer_details.+ # An offset that is not a multiple of the limit is refused as Wise refuses+ # it (HTTP 422 inconsistent.pagination).+ # transfer_pages: { offset => rows } instead of slices of `transfers`.+ # later_balances: what the balances read after the first one returns.+ # statements: the rows every balance's statement returns, or+ # statements_by_balance: { balance id => rows }; windowed_statements: only+ # the rows dated inside the requested interval come back, as from Wise.+ # windowed_activities: only the activities created at or after `since`+ # come back (the field Wise filters on is undocumented; this is the+ # narrowest reading).class FakeWiseProvider- attr_reader :calls, :statement_requests+ WiseResponse = Struct.new(:code, :body, :headers)- def initialize(balances: nil, savings_balances: nil, borderless_accounts: nil,- transfers: nil, activities: nil, statements: nil, raise_on: {},- statement_fail_balance_ids: [])+ attr_reader :calls, :statement_requests, :transfer_requests, :activity_requests, :transfer_reads++ def initialize(balances: nil, later_balances: nil, savings_balances: nil, borderless_accounts: nil, multi_currency_account: nil,+ transfers: nil, transfer_pages: nil, transfer_details: {}, activities: nil, activity_pages: nil, windowed_activities: false,+ statements: nil, statements_by_balance: nil, windowed_statements: false, raise_on: {}, statement_fail_balance_ids: [])@balances = balances || [ standard_balance ]+ @later_balances = later_balances@savings_balances = savings_balances || []@borderless_accounts = borderless_accounts || [ borderless_account ]+ @multi_currency_account = multi_currency_account || default_multi_currency_account@transfers = transfers || []+ @transfer_pages = transfer_pages+ @transfer_details = transfer_details@activities = activities || []+ @activity_pages = activity_pages+ @windowed_activities = windowed_activities@statements = statements || []+ @statements_by_balance = statements_by_balance+ @windowed_statements = windowed_statements@raise_on = raise_on@statement_fail_balance_ids = statement_fail_balance_ids@calls = []@statement_requests = []+ @transfer_requests = []+ @activity_requests = []+ @transfer_reads = []enddef get_balances(profile_id)@calls << :get_balancesraise_if(:get_balances)- @balances+ @later_balances && @calls.count(:get_balances) > 1 ? @later_balances : @balancesenddef get_savings_balances(profile_id)@@ -37,33 +63,74 @@ class WiseItem::ImporterTest < ActiveSupport::TestCase@borderless_accountsend- def get_transfers(profile_id, limit: 100, offset: 0)+ def get_multi_currency_account(profile_id)+ @calls << :get_multi_currency_account+ raise_if(:get_multi_currency_account)+ @multi_currency_account+ end++ def get_transfers(profile_id, limit: 100, offset: 0, created_date_start: nil, created_date_end: nil)@calls << :get_transfers- @transfers+ @transfer_requests << { offset: offset, limit: limit, created_date_start: created_date_start }+ raise_if(:get_transfers)+ refuse_inconsistent_pagination(offset) unless (offset % limit).zero?+ return Array(@transfer_pages[offset]) if @transfer_pages++ @transfers[offset, limit] || []end- def get_balance_statements(profile_id, balance_id, currency:, start_date:, end_date:)+ def get_transfer(transfer_id)+ @calls << :get_transfer+ @transfer_reads << transfer_id+ raise_if(:get_transfer)+ @transfer_details.fetch(transfer_id.to_s) { raise Provider::Wise::WiseError.new("Resource not found", :not_found) }+ end++ def get_balance_statements(profile_id, balance_id, currency:, interval_start:, interval_end:)@calls << :get_balance_statements@statement_requests << { profile_id: profile_id, balance_id: balance_id, currency: currency,- start_date: start_date, end_date: end_date }+ interval_start: interval_start, interval_end: interval_end }raise_if(:get_balance_statements)raise Provider::Wise::WiseError.new("forbidden", :fetch_failed) if @statement_fail_balance_ids.include?(balance_id)- @statements+ rows = @statements_by_balance ? Array(@statements_by_balance[balance_id.to_s]) : @statements+ return rows unless @windowed_statements++ rows.select { |row| (interval_start..interval_end).cover?(ActiveSupport::TimeZone["UTC"].parse(row["date"])) }end- def get_activities(profile_id, cursor: nil, size: 100)+ def get_activities(profile_id, cursor: nil, size: 100, since: nil, until_time: nil)@calls << :get_activities+ @activity_requests << { cursor: cursor, size: size, since: since }raise_if(:get_activities)- { "activities" => @activities, "cursor" => nil }+ return @activity_pages.fetch(cursor) if @activity_pages++ activities = @activities+ if @windowed_activities && since+ activities = activities.select { |activity| ActiveSupport::TimeZone["UTC"].parse(activity["createdOn"]) >= since }+ end+ { "activities" => activities, "cursor" => nil }endprivate+ # A message raises a generic fetch failure; an error instance is raised as is.def raise_if(method)error = @raise_on[method]+ raise error if error.is_a?(Exception)raise Provider::Wise::WiseError.new(error, :fetch_failed) if errorend+ # Wise's 422 body, raised as Provider::Wise raises it.+ def refuse_inconsistent_pagination(offset)+ body = { "errors" => [ { "code" => "inconsistent.pagination", "message" => "Inconsistent pagination in filter",+ "field" => "offset", "arguments" => [ "offset", offset ] } ] }.to_json+ Provider::Wise.new("test_token").send(:handle_response, WiseResponse.new(422, body, {}))+ end++ def default_multi_currency_account+ { "id" => 77001, "recipientId" => 99999001, "creationTime" => "2020-05-20T14:43:16.658Z" }+ end+def standard_balance{"id" => "10000001",@@ -145,13 +212,50 @@ class WiseItem::ImporterTest < ActiveSupport::TestCaseassert_equal "Jar", jar.nameend- test "continues if savings balances fetch fails" do- provider = FakeWiseProvider.new(raise_on: { get_savings_balances: "forbidden" })+ # A new balance Sure could not save (a database error, here an amount beyond+ # the column) stayed in the item's balances as an unsaved record, and the+ # import crashed on it ("comparison of WiseAccount with WiseAccount failed")+ # instead of counting it and storing the other balances' rows.+ test "counts a new balance that fails to save and imports the others" do+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [ build_transfer(id: 1) ])+ provider = FakeWiseProvider.new(balances: [ eur_balance("10000001", 10.0), standard_balance("10000002", "USD", 10**16) ],+ transfers: [ build_transfer(id: 1), build_transfer(id: 2) ],+ raise_on: { get_balance_statements: statements_forbidden })result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import- assert result[:success]- assert_equal 1, @wise_item.wise_accounts.count+ assert_not result[:success]+ assert_equal [ 0, 1, 1, 0 ], result.values_at(:accounts_created, :accounts_updated, :accounts_failed, :transactions_failed)+ assert_equal [ "10000001" ], @wise_item.wise_accounts.reload.map(&:balance_id)+ assert_equal [ 1, 2 ], eur.reload.raw_transactions_payload.map { |row| row["id"] }+ # The unsaved balance received none of the rows coverage would claim.+ assert_nil @wise_item.reload.raw_payload&.dig("coverage")+ end++ # A jar the failed list left out stores none of this sync's rows, so the+ # import is incomplete and its coverage stays: the next sync, which lists+ # the jar, fetches the same window again and the jar gets its moves.+ test "imports the other balances when the savings list fails, but neither completes nor moves coverage" do+ jar = { "id" => "10000002", "type" => "SAVINGS", "name" => "Holiday", "creationTime" => 200.days.ago.utc.iso8601,+ "amount" => { "value" => 1000.0, "currency" => "EUR" }, "totalWorth" => { "value" => 1000.0, "currency" => "EUR" } }+ deposit = build_interbalance("To <strong>Holiday</strong>", resource_id: "5001").merge("createdOn" => 120.days.ago.utc.iso8601)+ import = lambda do |**options|+ provider = FakeWiseProvider.new(savings_balances: [ jar ], activities: [ deposit ], windowed_activities: true,+ raise_on: { get_balance_statements: statements_forbidden }.merge(options))+ [ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import, provider ]+ end++ failed, = import.call(get_savings_balances: "Unexpected response 503")+ assert_equal [ false, false, 1 ], failed.values_at(:success, :complete, :fetch_failures)+ assert_equal [ "10000001" ], @wise_item.wise_accounts.reload.map(&:balance_id)+ assert_nil @wise_item.reload.raw_payload&.dig("coverage")++ listed, provider = import.call+ assert listed[:complete]+ assert_equal 365.days.ago.to_date, provider.activity_requests.first[:since].to_date+ assert_equal [ "interbalance_5001" ], payload_ids["10000002"]end# Transfer routing@@ -182,52 +286,424 @@ class WiseItem::ImporterTest < ActiveSupport::TestCaseassert_equal 1, eur_account.raw_transactions_payload.sizeend- test "imports standard account balance statements and honors configured history start" do- @wise_item.update!(sync_start_date: Date.new(2024, 1, 1))- statements = [- {- "type" => "CREDIT",- "date" => "2024-01-02T10:00:00Z",- "amount" => { "value" => "25.00", "currency" => "EUR" },- "details" => { "description" => "Salary" },- "referenceNumber" => "statement-1"- }+ test "routes an outgoing cross-currency payout only to the funding balance" do+ balances = %w[GBP PLN].each_with_index.map do |currency, i|+ { "id" => "3000000#{i}", "amount" => { "value" => 100.0, "currency" => currency }, "type" => "STANDARD" }+ end+ borderless = [ { "id" => 88888001, "recipientId" => 99999001,+ "balances" => [ { "id" => 30000000 }, { "id" => 30000001 } ] } ]+ payout = build_transfer(id: 9, source_currency: "GBP", target_currency: "PLN", target_account: 1234)+ provider = FakeWiseProvider.new(balances: balances, borderless_accounts: borderless, transfers: [ payout ],+ raise_on: { get_balance_statements: "forbidden" })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ 9 ], @wise_item.wise_accounts.find_by(currency: "GBP").raw_transactions_payload.map { |t| t["id"] }+ assert_empty Array(@wise_item.wise_accounts.find_by(currency: "PLN").raw_transactions_payload)+ end++ # A transfer into one of the profile's own recipients is a pay-in, booked+ # only on the balance it paid into. Wise does not say whether the GBP+ # balance, a card or a bank paid for it, so GBP is not debited (logged+ # instead), and a GBP copy stored by the old rule drops out of the payload.+ test "routes a transfer into a balance's own recipient only to that balance" do+ balances = [ %w[GBP 77777000], %w[USD 77777001] ].each_with_index.map do |(currency, recipient_id), i|+ { "id" => "3000000#{i}", "amount" => { "value" => 100.0, "currency" => currency }, "type" => "STANDARD",+ "recipientId" => recipient_id.to_i }+ end+ borderless = [ { "id" => 88888001, "recipientId" => 99999001,+ "balances" => [ { "id" => 30000000 }, { "id" => 30000001 } ] } ]+ top_up = build_transfer(id: 12, source_currency: "USD", target_currency: "USD", target_account: 77777001)+ funded = build_transfer(id: 13, source_currency: "GBP", target_currency: "USD", target_account: 77777001)+ gbp = @wise_item.wise_accounts.create!(balance_id: "30000000", currency: "GBP", name: "Wise GBP",+ raw_payload: { "type" => "STANDARD" }, raw_transactions_payload: [ funded ])+ provider = FakeWiseProvider.new(balances: balances, borderless_accounts: borderless, transfers: [ top_up, funded ],+ raise_on: { get_balance_statements: "forbidden" })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_empty gbp.reload.raw_transactions_payload+ assert_equal [ 12, 13 ], @wise_item.wise_accounts.find_by(currency: "USD").raw_transactions_payload.map { |t| t["id"] }.sort+ end++ # The own-recipient set includes every stored balance, so a past top-up into+ # a since-closed balance is not re-read as a payout of the open balance in+ # that currency.+ test "routes a pay-in into a balance Wise no longer lists to that balance only" do+ old_eur = @wise_item.wise_accounts.create!(balance_id: "10000009", currency: "EUR", name: "Wise EUR (old)",+ raw_payload: { "type" => "STANDARD", "recipientId" => 77777009 })+ top_up = build_transfer(id: 14, target_account: 77777009)+ provider = FakeWiseProvider.new(transfers: [ top_up ], raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_empty Array(@wise_item.wise_accounts.find_by!(balance_id: "10000001").raw_transactions_payload)+ assert_equal [ 14 ], old_eur.reload.raw_transactions_payload.map { |t| t["id"] }+ end++ # An import that fails before it stores the payloads leaves them as they+ # were, and processing still books them. An older build also stored a GBP to+ # USD top-up into the USD balance's own account details on the GBP balance+ # (and booked it there as a payout); that copy was then booked on the GBP+ # balance as a USD income.+ test "a failed import leaves an older build's funding-side copy of a pay-in unbooked" do+ gbp = @wise_item.wise_accounts.create!(balance_id: "30000000", currency: "GBP", name: "Wise GBP",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "recipientId" => 77777000 })+ @wise_item.wise_accounts.create!(balance_id: "30000001", currency: "USD", name: "Wise USD",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "recipientId" => 77777001 })+ top_up = build_transfer(id: 13, source_currency: "GBP", target_currency: "USD", target_account: 77777001)+ .merge("sourceValue" => 158.4, "targetValue" => 213.0, "created" => "2025-09-30 18:22:07")+ gbp.update!(raw_transactions_payload: [ top_up ])+ account = link_account(gbp).current_account+ Account::ProviderImportAdapter.new(account).import_transaction(external_id: "wise_transfer_13", amount: 158.4, currency: "GBP",+ date: Date.new(2025, 9, 30), name: "Wise transaction", source: "wise")++ result = WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(raise_on: { get_balances: "Bad gateway" })).import+ assert_not result[:complete]+ @wise_item.reload.process_accounts(import_complete: result[:complete])++ assert_equal [ [ BigDecimal("158.40"), "GBP" ] ], account.entries.where(source: "wise").pluck(:amount, :currency)+ end++ test "routes by the activity's markup when no recipient of the profile is known" do+ balances = %w[EUR USD].each_with_index.map do |currency, i|+ { "id" => "4000000#{i}", "amount" => { "value" => 10.0, "currency" => currency }, "type" => "STANDARD" }+ end+ top_up = build_transfer(id: 15, source_currency: "EUR", target_currency: "USD", target_account: 4242)+ payout = build_transfer(id: 16, source_currency: "EUR", target_currency: "USD", target_account: 4343)+ provider = FakeWiseProvider.new(+ balances: balances, borderless_accounts: [], multi_currency_account: { "id" => 77001 },+ transfers: [ top_up, payout ],+ activities: [ build_transfer_activity(15, primary: "<positive>+ 117.50 USD</positive>", secondary: "100 EUR"),+ build_transfer_activity(16, primary: "117.50 USD", secondary: "100 EUR") ],+ raise_on: { get_balance_statements: statements_forbidden }+ )++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ routed = @wise_item.wise_accounts.to_h { |wa| [ wa.currency, Array(wa.raw_transactions_payload).map { |t| t["id"] } ] }+ assert_equal({ "EUR" => [ 16 ], "USD" => [ 15 ] }, routed)+ end++ # Activity enrichment++ test "attaches the transfer's activity to its stored row" do+ payout = build_transfer(id: 17)+ activity = build_transfer_activity(17, primary: "100 EUR", secondary: "101.20 EUR", title: "<strong>Tom & Jerry</strong>")+ provider = FakeWiseProvider.new(transfers: [ payout ], activities: [ activity ],+ raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ stored = @wise_item.wise_accounts.first.raw_transactions_payload.sole+ assert_equal({ "id" => "transfer-activity-17", "type" => "TRANSFER", "status" => "COMPLETED", "primaryAmount" => "100 EUR",+ "secondaryAmount" => "101.20 EUR", "title" => "Tom & Jerry", "description" => "Sent",+ "createdOn" => activity["createdOn"], "updatedOn" => activity["updatedOn"] }, stored["wise_activity"])+ assert_equal 100.0, stored["sourceValue"]+ end++ # Re-listed and re-read transfers replace their stored copies; the+ # activity seen by an earlier sync must survive a sync that sees none.+ test "keeps a transfer's activity when a later sync does not see it" do+ payout = build_transfer(id: 18).merge("status" => "processing")+ activity = build_transfer_activity(18, primary: "100 EUR", secondary: "101.20 EUR")+ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(+ transfers: [ payout ], activities: [ activity ], raise_on: { get_balance_statements: statements_forbidden }+ )).import+ eur = @wise_item.wise_accounts.first+ assert_equal "transfer-activity-18", eur.raw_transactions_payload.sole.dig("wise_activity", "id")++ relisted = FakeWiseProvider.new(transfers: [ payout ], raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(@wise_item, wise_provider: relisted).import+ assert_equal "transfer-activity-18", eur.reload.raw_transactions_payload.sole.dig("wise_activity", "id")++ reread = FakeWiseProvider.new(transfer_details: { "18" => payout.merge("status" => "outgoing_payment_sent") },+ raise_on: { get_activities: "Unexpected response 502", get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(@wise_item, wise_provider: reread).import+ stored = eur.reload.raw_transactions_payload.sole+ assert_equal [ 18 ], reread.transfer_reads+ assert_equal [ "outgoing_payment_sent", "transfer-activity-18" ], [ stored["status"], stored.dig("wise_activity", "id") ]+ end++ test "attaches the activity closest to the transfer that fits its direction, and a refund credit" do+ payout = build_transfer(id: 19).merge("status" => "funds_refunded", "created" => "2026-10-10 12:00:00")+ activities = [+ build_transfer_activity(19, id: "19-later", primary: "100 EUR", created_on: "2026-10-12T12:00:00Z"),+ build_transfer_activity(19, id: "19-refund", primary: "<positive>+ 101.20 EUR</positive>", created_on: "2026-10-10T12:00:02Z"),+ build_transfer_activity(19, id: "19-sent", primary: "100 EUR", secondary: "101.20 EUR", created_on: "2026-10-10T12:00:05Z")]- provider = FakeWiseProvider.new(statements: statements)+ provider = FakeWiseProvider.new(transfers: [ payout ], activities: activities,+ raise_on: { get_balance_statements: statements_forbidden })++ assert_difference -> { transfer_notes.where(level: "info").count }, 1 do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end++ stored = @wise_item.wise_accounts.first.raw_transactions_payload.sole+ assert_equal [ "19-sent", "19-refund" ], [ stored.dig("wise_activity", "id"), stored.dig("wise_refund_activity", "id") ]+ assert_equal [ 1, [ 19 ], [ 3 ] ], transfer_notes.recent.first.metadata.values_at("transfer_count", "transfer_ids", "activity_counts")++ # Reported once: the next sync sees the same activities.+ assert_no_difference -> { transfer_notes.count } do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end+ end++ # The refund credit a refunded payout books with stays on its row through+ # syncs whose activity window no longer reaches it, like the payout's own+ # activity.+ test "keeps a refunded payout's refund credit through a sync that does not see its activities" do+ payout = build_transfer(id: 30).merge("status" => "funds_refunded", "created" => "2026-10-10 12:00:00")+ activities = [ build_transfer_activity(30, id: "30-sent", primary: "100 EUR", secondary: "101.20 EUR", created_on: "2026-10-10T12:00:01Z"),+ build_transfer_activity(30, id: "30-refund", primary: "<positive>+ 101.20 EUR</positive>", created_on: "2026-10-12T08:00:00Z") ]+ [ activities, [] ].each do |seen|+ provider = FakeWiseProvider.new(transfers: [ payout ], activities: seen, raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end++ eur = link_account(@wise_item.wise_accounts.sole)+ assert_equal [ "30-sent", "30-refund" ], eur.raw_transactions_payload.sole.values_at("wise_activity", "wise_refund_activity").map { |snapshot| snapshot&.dig("id") }+ WiseAccount::Transactions::Processor.new(eur).process+ assert_equal({ "wise_fee_30" => BigDecimal("1.2"), "wise_refund_30" => BigDecimal("-101.2"), "wise_transfer_30" => BigDecimal("100") },+ eur.current_account.entries.where(source: "wise").pluck(:external_id, :amount).to_h)+ end++ # Wise can cancel a refund credit after a sync saw it in progress; the+ # cancelled snapshot replaces the stored one, so the refund stops booking.+ test "stops booking a refund credit Wise cancelled after a sync saw it in progress" do+ payout = build_transfer(id: 33).merge("status" => "funds_refunded", "created" => 5.days.ago.utc.strftime("%Y-%m-%d %H:%M:%S"))+ sent = build_transfer_activity(33, id: "33-sent", primary: "100 EUR", secondary: "101.20 EUR", created_on: (5.days.ago + 1.second).utc.iso8601(3))+ %w[IN_PROGRESS CANCELLED].each do |status|+ refund = build_transfer_activity(33, id: "33-refund", primary: "<positive>+ 101.20 EUR</positive>", status: status,+ created_on: 3.days.ago.utc.iso8601(3))+ provider = FakeWiseProvider.new(transfers: [ payout ], activities: [ sent, refund ], raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ end++ eur = link_account(@wise_item.wise_accounts.sole)+ assert_equal "CANCELLED", eur.raw_transactions_payload.sole.dig("wise_refund_activity", "status")+ WiseAccount::Transactions::Processor.new(eur).process+ assert_empty eur.current_account.entries.where(source: "wise").pluck(:external_id)+ end++ # A sent payout is no longer listed 60 days after it was made, so when+ # Wise refunds it later only its refund credit shows up: the payout is read+ # again by id from the next sync on, and its refunded status books the+ # refund.+ test "books a refund Wise makes after the payout left the window it is listed in" do+ travel_to Time.utc(2026, 10, 17, 12) do+ payout = build_transfer(id: 900).merge("created" => "2026-07-01 12:00:00")+ sent = build_transfer_activity(900, id: "sent-900", primary: "100 EUR", created_on: "2026-07-01T12:00:01Z")+ coverage = %w[transfers activities].index_with { { "from" => "2025-01-01T00:00:00Z", "through" => "2026-10-10T12:00:00Z", "version" => WiseItem::COVERAGE_VERSION } }+ @wise_item.update!(raw_payload: { "coverage" => coverage })+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [ payout.merge("wise_activity" => WiseEntry::Processor.activity_snapshot(sent)) ])+ refund = build_transfer_activity(900, id: "refund-900", primary: "<positive>+ 100 EUR</positive>", created_on: "2026-10-15T09:00:00Z")+ readings = 2.times.map do+ provider = FakeWiseProvider.new(activities: [ refund ], transfer_details: { "900" => payout.merge("status" => "funds_refunded") },+ raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ provider.transfer_reads+ end++ assert_equal [ [], [ "900" ] ], readings.map { |reads| reads.map(&:to_s) }+ row = eur.reload.raw_transactions_payload.sole+ assert_equal [ "funds_refunded", "refund-900" ], [ row["status"], row.dig("wise_refund_activity", "id") ]+ link_account(eur)+ WiseAccount::Transactions::Processor.new(eur).process+ assert_equal({ "wise_refund_900" => BigDecimal("-100"), "wise_transfer_900" => BigDecimal("100") },+ eur.current_account.entries.where(source: "wise").pluck(:external_id, :amount).to_h)+ end+ end++ # A refund credit counts unless Wise cancelled it, since one seen in+ # progress may never be seen again.+ test "books a refund credit Wise still shows in progress, never a cancelled one" do+ payouts = [ 31, 32 ].map { |id| build_transfer(id: id).merge("status" => "funds_refunded", "created" => "2026-10-10 12:00:00") }+ activities = { 31 => "IN_PROGRESS", 32 => "CANCELLED" }.flat_map do |id, status|+ [ build_transfer_activity(id, id: "#{id}-sent", primary: "100 EUR", secondary: "101.20 EUR", created_on: "2026-10-10T12:00:01Z"),+ build_transfer_activity(id, id: "#{id}-refund", primary: "<positive>+ 101.20 EUR</positive>", status: status,+ created_on: "2026-10-12T08:00:00Z") ]+ end+ provider = FakeWiseProvider.new(transfers: payouts, activities: activities, raise_on: { get_balance_statements: statements_forbidden })WiseItem::Importer.new(@wise_item, wise_provider: provider).import- account = @wise_item.wise_accounts.find_by(currency: "EUR")- assert_equal statements.first.merge("wise_statement" => true), account.raw_transactions_payload.first- assert_equal Date.new(2024, 1, 1), provider.statement_requests.first[:start_date]- assert_equal Date.current, provider.statement_requests.first[:end_date]+ eur = link_account(@wise_item.wise_accounts.sole)+ rows = eur.raw_transactions_payload.index_by { |row| row["id"] }+ assert_equal [ "31-refund", "CANCELLED" ], [ rows[31].dig("wise_refund_activity", "id"), rows[32].dig("wise_refund_activity", "status") ]+ WiseAccount::Transactions::Processor.new(eur).process+ assert_equal({ "wise_fee_31" => BigDecimal("1.2"), "wise_refund_31" => BigDecimal("-101.2"), "wise_transfer_31" => BigDecimal("100") },+ eur.current_account.entries.where(source: "wise").pluck(:external_id, :amount).to_h)+ end++ test "reports a transfer in a status Sure does not book once" do+ stuck = build_transfer(id: 20).merge("status" => "unknown")+ provider = FakeWiseProvider.new(transfers: [ stuck ], transfer_details: { "20" => stuck },+ raise_on: { get_balance_statements: statements_forbidden })++ assert_difference -> { transfer_notes.where(level: "warn").count }, 1 do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end+ assert_equal [ [ "unknown" ], [ 20 ] ], transfer_notes.recent.first.metadata.values_at("statuses", "transfer_ids")++ assert_no_difference -> { transfer_notes.count } do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end+ end++ # Known limitation: Wise does not say whether a pay-in was drawn from+ # another balance ("send to myself"), so Sure books only its credit and+ # says so once.+ test "reports a pay-in whose activity shows a debit or another currency once" do+ balances = [ %w[GBP 77777000], %w[USD 77777001] ].each_with_index.map do |(currency, recipient_id), i|+ { "id" => "3000000#{i}", "amount" => { "value" => 100.0, "currency" => currency }, "type" => "STANDARD",+ "recipientId" => recipient_id.to_i }+ end+ to_myself = build_transfer(id: 21, source_currency: "GBP", target_currency: "USD", target_account: 77777001)+ top_up = build_transfer(id: 22, source_currency: "USD", target_currency: "USD", target_account: 77777001)+ debited = build_transfer(id: 23, source_currency: "USD", target_currency: "USD", target_account: 77777001)+ provider = FakeWiseProvider.new(+ balances: balances, borderless_accounts: [], transfers: [ to_myself, top_up, debited ],+ activities: [ build_transfer_activity(21, primary: "<positive>+ 213 USD</positive>", secondary: "160.25 GBP"),+ build_transfer_activity(22, primary: "<positive>+ 50 USD</positive>"),+ build_transfer_activity(23, primary: "50 USD") ],+ raise_on: { get_balance_statements: statements_forbidden }+ )++ assert_difference -> { transfer_notes.where(level: "warn").count }, 1 do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end+ assert_equal [ 21, 23 ], transfer_notes.recent.first.metadata["transfer_ids"]+ assert_empty Array(@wise_item.wise_accounts.find_by!(currency: "GBP").raw_transactions_payload)++ assert_no_difference -> { transfer_notes.count } do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end+ end++ # The fee reaches the balance through the activity attached on import.+ test "a payout lowers its balance by Wise's gross debit once imported and processed" do+ balance = { "id" => "900000201", "type" => "STANDARD", "recipientId" => 900000202,+ "amount" => { "value" => 0.0, "currency" => "USD" }, "reservedAmount" => { "value" => 0.0, "currency" => "USD" } }+ payout = build_transfer(id: 9000000103, source_currency: "USD", target_currency: "USD", target_account: 55555555)+ .merge("sourceValue" => 5482.37, "targetValue" => 5482.37)+ provider = FakeWiseProvider.new(+ balances: [ balance ], borderless_accounts: [],+ transfers: [ payout ], activities: [ build_transfer_activity(9000000103, primary: "5,482.37 USD", secondary: "5,492.01 USD") ],+ raise_on: { get_balance_statements: statements_forbidden }+ )++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ usd = link_account(@wise_item.wise_accounts.find_by!(currency: "USD"))+ WiseAccount::Transactions::Processor.new(usd).process++ assert_equal BigDecimal("5492.01"), usd.current_account.entries.where(source: "wise").sum(:amount)+ end++ test "drops previously stored transfers that did not move money in the STANDARD balance" do+ payout = build_transfer(id: 10, source_currency: "GBP", target_currency: "PLN", target_account: 1234)+ local = build_transfer(id: 11, source_currency: "PLN", target_currency: "PLN", target_account: 1234)+ pln = @wise_item.wise_accounts.create!(balance_id: "10000001", currency: "PLN", name: "Wise PLN",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [ payout, local ])+ balances = [ { "id" => "10000001", "amount" => { "value" => 0.0, "currency" => "PLN" }, "type" => "STANDARD" } ]+ provider = FakeWiseProvider.new(balances: balances, transfers: [],+ raise_on: { get_balance_statements: "forbidden" })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ 11 ], pln.reload.raw_transactions_payload.map { |t| t["id"] }+ end++ # Statement intervals are UTC instants, starting at midnight of the explicit+ # start date in the family's zone (UTC here) and ending when the fetch+ # started, instead of dates the provider read in the job's zone.+ test "imports standard account balance statements and honors configured history start" do+ travel_to Time.utc(2026, 10, 17, 12) do+ @wise_item.update!(sync_start_date: Date.new(2024, 1, 1))+ statements = [+ {+ "type" => "CREDIT",+ "date" => "2024-01-02T10:00:00Z",+ "amount" => { "value" => "25.00", "currency" => "EUR" },+ "details" => { "description" => "Salary" },+ "referenceNumber" => "statement-1"+ }+ ]+ provider = FakeWiseProvider.new(statements: statements)++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ account = @wise_item.wise_accounts.find_by(currency: "EUR")+ assert_equal statements.first.merge("wise_statement" => true), account.raw_transactions_payload.first+ assert_equal Time.utc(2024, 1, 1), provider.statement_requests.first[:interval_start]+ assert_equal Time.current, provider.statement_requests.first[:interval_end]+ endend+ # The sync start date starts a balance's statements as it starts transfers+ # and activities, once: with statement coverage reaching back to it, they+ # resume a week before the last statement fetch.+ test "fetches a balance's statements incrementally once their coverage reaches the sync start date" do+ travel_to Time.utc(2026, 10, 17, 12) do+ @wise_item.update!(sync_start_date: Date.new(2024, 1, 1))+ @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR", raw_payload: {+ "type" => "STANDARD", "statements_coverage" => { "from" => "2023-06-01T00:00:00Z", "through" => "2026-10-10T12:00:00Z" }+ })+ provider = FakeWiseProvider.new(statements: [])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal Time.utc(2026, 10, 3, 12), provider.statement_requests.sole[:interval_start]+ end+ end++ # A balance without its own creationTime starts its statements where a+ # full-history import starts transfers and activities, a day before Wise+ # opened the account; only when Wise does not say when that was do they+ # start on FULL_HISTORY_START_DATE.test "fetches full statement history when import_all_history is enabled" do@wise_item.update!(import_all_history: true)provider = FakeWiseProvider.new(statements: [])WiseItem::Importer.new(@wise_item, wise_provider: provider).import- assert_equal WiseItem::Importer::FULL_HISTORY_START_DATE, provider.statement_requests.first[:start_date]- assert_equal Date.current, provider.statement_requests.first[:end_date]+ assert_equal Time.utc(2020, 5, 20, 14, 43, 16.658r) - 1.day, provider.statement_requests.first[:interval_start]++ unknown = WiseItem.create!(family: @family, name: "Other Wise", token: "other_token", profile_id: "22222222",+ profile_type: :business, import_all_history: true)+ provider = FakeWiseProvider.new(statements: [], raise_on: { get_multi_currency_account: "server error" })++ WiseItem::Importer.new(unknown, wise_provider: provider).import++ assert_equal WiseItem::Importer::FULL_HISTORY_START_DATE.in_time_zone("UTC"), provider.statement_requests.first[:interval_start]end+ # The window starts at the moment Wise opened the balance (a job running in+ # New York used to start at midnight there, after an evening opening).test "starts full history from balance creation time when available" do@wise_item.update!(import_all_history: true)balance = {"id" => "10000001","amount" => { "value" => 100.0, "currency" => "EUR" },"type" => "STANDARD",- "creationTime" => "2015-04-12T10:00:00Z"+ "creationTime" => "2015-04-12T02:46:31Z"}provider = FakeWiseProvider.new(balances: [ balance ], statements: [])- WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ Time.use_zone("America/New_York") do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end- assert_equal Date.new(2015, 4, 12), provider.statement_requests.first[:start_date]+ assert_equal Time.utc(2015, 4, 12, 2, 46, 31), provider.statement_requests.first[:interval_start]end+ # The incremental window follows the balance's own statement coverage (a+ # week before the end of its last successful statement fetch, kept in its+ # raw_payload), not the item's last completed sync, which advanced through+ # statement outages.test "keeps incremental sync window after statements already exist" do@wise_item.update!(import_all_history: true)statements = [@@ -239,16 +715,20 @@ class WiseItem::ImporterTest < ActiveSupport::TestCase"referenceNumber" => "statement-1"}]- WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(statements: statements)).import-- sync = @wise_item.syncs.create!(status: :completed, completed_at: Time.current)+ first_fetch = Time.utc(2026, 10, 10, 12)+ travel_to(first_fetch) { WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(statements: statements)).import }+ account = @wise_item.wise_accounts.find_by(currency: "EUR")+ assert_equal({ from: Time.utc(2020, 5, 19, 14, 43, 16), through: first_fetch }, account.statements_coverage)- second_provider = FakeWiseProvider.new(statements: [])- WiseItem::Importer.new(@wise_item, wise_provider: second_provider).import+ travel_to Time.utc(2026, 10, 17, 12) do+ second_provider = FakeWiseProvider.new(statements: [])+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: second_provider).import- assert_equal (sync.completed_at - 7.days).to_date, second_provider.statement_requests.first[:start_date]- assert_equal Date.current, second_provider.statement_requests.first[:end_date]- refute_includes second_provider.calls, :get_transfers+ assert_equal first_fetch - 7.days, second_provider.statement_requests.first[:interval_start]+ assert_equal Time.current, second_provider.statement_requests.first[:interval_end]+ refute_includes second_provider.calls, :get_transfers+ assert_equal({ from: Time.utc(2020, 5, 19, 14, 43, 16), through: Time.current }, account.reload.statements_coverage)+ endendtest "falls back to transfers when every statement request fails" do@@ -275,7 +755,147 @@ class WiseItem::ImporterTest < ActiveSupport::TestCaseassert_equal "fetch_failed", entry.metadata["error_type"]end- test "surfaces partial statement fetch failures without the transfer fallback" do+ # A 403 without an SCA challenge means the token cannot read statements:+ # not a failed fetch, one info entry instead of a warning per balance, and+ # the other balances are not asked.+ test "treats statements refused without an SCA challenge as unavailable" do+ provider = two_balances_provider(statements_forbidden)++ result = nil+ assert_no_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error").count } do+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync", level: "info").count }, 1 do+ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end+ end++ assert result[:success]+ assert result[:complete]+ assert_equal 1, provider.calls.count(:get_balance_statements)+ assert_equal [ 1 ], @wise_item.wise_accounts.find_by(currency: "EUR").raw_transactions_payload.map { |t| t["id"] }++ entry = DebugLogEntry.where(provider_key: "wise", category: "provider_sync").recent.first+ assert_equal @wise_item.id, entry.metadata["wise_item_id"]+ assert_equal "access_forbidden", entry.metadata["error_type"]+ assert_equal 2, entry.metadata["balance_count"]+ assert_equal false, entry.metadata["sca_challenged"]+ end++ # A statement 403 that carries Wise's SCA challenge cannot be answered+ # without an SCA key. As for a 403 without one: unavailable this sync,+ # logged once (info) instead of a warning per balance on every sync, no+ # failed fetch, and the other balances are not asked.+ test "treats statements Wise asks to sign as unavailable while no SCA key is configured" do+ provider = two_balances_provider(statements_challenged)++ result = nil+ assert_no_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error").count } do+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync", level: "info").count }, 1 do+ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end+ end++ assert result[:success]+ assert result[:complete]+ assert_equal 1, provider.calls.count(:get_balance_statements)+ assert_equal [ 1 ], @wise_item.wise_accounts.find_by(currency: "EUR").raw_transactions_payload.map { |t| t["id"] }++ entry = DebugLogEntry.where(provider_key: "wise", category: "provider_sync").recent.first+ assert_equal({ "operation" => "balance_statement", "error_type" => "access_forbidden", "balance_count" => 2,+ "sca_challenged" => true, "sca_private_key_configured" => false },+ entry.metadata.slice("operation", "error_type", "balance_count", "sca_challenged", "sca_private_key_configured"))+ end++ # With a key configured Provider::Wise answers the challenge with a signed+ # retry, so a challenged 403 is Wise refusing that answer: every balance is+ # asked and warns. It fails nothing, also for a balance that holds+ # statement rows: no later sync would get past it until the key works.+ test "asks every balance and warns when Wise refuses the signed statement requests of a configured SCA key" do+ @wise_item.update_column(:sca_private_key, OpenSSL::PKey::RSA.new(2048).to_pem)+ @wise_item.wise_accounts.create!(+ balance_id: "10000003", name: "Wise GBP", currency: "GBP", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ statement_row("CARD-1", "-10.0", "GBP").merge("wise_statement" => true) ]+ )+ provider = two_balances_provider(statements_challenged, more_balances: [ standard_balance("10000003", "GBP", 10.0) ])++ result = nil+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error", level: "warn").count }, 3 do+ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end++ assert_equal %w[10000001 10000002 10000003], provider.statement_requests.map { |request| request[:balance_id] }.sort+ assert result[:complete]+ assert_equal 0, result[:fetch_failures]+ assert_empty DebugLogEntry.where(provider_key: "wise", category: "provider_sync").where("metadata ->> 'operation' = ?", "balance_statement")+ end++ # Only the balances without statement rows go unasked once statements prove+ # unavailable; one with statement rows is still asked, and is refused too,+ # which fails nothing. (Balances are read in no fixed order: a refusal of+ # either one leaves the EUR balance unasked or refused.)+ test "still asks a balance with statement rows after statements prove unavailable" do+ @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR", raw_payload: { "type" => "STANDARD" })+ @wise_item.wise_accounts.create!(+ balance_id: "10000002", name: "Wise USD", currency: "USD", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ { "wise_statement" => true, "date" => "2026-01-20T10:00:00Z",+ "amount" => { "value" => "10.0", "currency" => "USD" }, "referenceNumber" => "CARD-1" } ]+ )+ balances = %w[EUR USD].each_with_index.map do |currency, i|+ { "id" => (10000001 + i).to_s, "amount" => { "value" => 10.0, "currency" => currency }, "type" => "STANDARD" }+ end+ provider = FakeWiseProvider.new(balances: balances, raise_on: { get_balance_statements: statements_forbidden })++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_includes provider.statement_requests.map { |request| request[:balance_id] }, "10000002"+ assert result[:complete]+ assert_equal 0, result[:fetch_failures]+ note = DebugLogEntry.where(provider_key: "wise", category: "provider_sync").where("metadata ->> 'operation' = ?", "balance_statement").sole+ assert_equal 2, note.metadata["balance_count"]+ end++ test "a statement failure counts against the import for a balance that holds statement rows" do+ @wise_item.wise_accounts.create!(+ balance_id: "10000001", name: "Wise EUR", currency: "EUR", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ { "wise_statement" => true, "date" => "2026-01-20T10:00:00Z",+ "amount" => { "value" => "10.0", "currency" => "EUR" }, "referenceNumber" => "CARD-1" } ]+ )+ provider = FakeWiseProvider.new(raise_on: { get_balance_statements: "Unexpected response 502" })++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_not result[:success]+ assert_not result[:complete]+ assert_equal 1, result[:fetch_failures]+ assert_equal [ "CARD-1" ], @wise_item.wise_accounts.first.raw_transactions_payload.map { |t| t["referenceNumber"] }+ end++ # A refusal is no outage the next sync gets past: counted as a failure it+ # would keep every import incomplete (no clean-up, anchor repair or+ # replay for any balance) until the token or key changes. It is logged+ # once per sync instead, and the balance keeps its statement rows.+ test "a balance with statement rows whose statements Wise refuses fails nothing" do+ @wise_item.wise_accounts.create!(+ balance_id: "10000001", name: "Wise EUR", currency: "EUR", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ statement_row("CARD-1", "-10.0", "EUR", date: "2026-01-20T10:00:00Z").merge("wise_statement" => true) ]+ )++ results = 2.times.map do+ provider = FakeWiseProvider.new(raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ end++ assert_equal [ [ true, true, 0 ] ] * 2, results.map { |result| result.values_at(:success, :complete, :fetch_failures) }+ assert_equal 2, DebugLogEntry.where(provider_key: "wise", category: "provider_sync", level: "info")+ .where("metadata ->> 'operation' = ?", "balance_statement").count+ assert_equal [ "CARD-1" ], @wise_item.wise_accounts.first.raw_transactions_payload.map { |t| t["referenceNumber"] }+ end++ # A balance without statement rows is not covered by statements, so when+ # its statement request fails it takes its transfers and activities like+ # any balance without statements: its rows are stored and coverage moves+ # on for every source, which would otherwise wait as long as the failure+ # lasts and fetch the whole window again on every sync.+ test "a balance without statement rows whose statements fail takes its transfers and activities" dobalances = [{"id" => "10000001",@@ -288,16 +908,24 @@ class WiseItem::ImporterTest < ActiveSupport::TestCase"type" => "STANDARD"}]- provider = FakeWiseProvider.new(balances: balances, statement_fail_balance_ids: [ "10000002" ])+ payout = build_transfer(id: 77, source_currency: "USD", target_currency: "USD")+ provider = FakeWiseProvider.new(balances: balances, transfers: [ payout ], statement_fail_balance_ids: [ "10000002" ])result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import- assert_not result[:success]- assert_equal 1, result[:transactions_failed]- refute_includes provider.calls, :get_transfers+ assert result[:success]+ assert result[:complete]+ assert_equal 0, result[:transactions_failed]+ assert_includes provider.calls, :get_transfers+ assert_equal [ 77 ], @wise_item.wise_accounts.find_by!(balance_id: "10000002").raw_transactions_payload.map { |row| row["id"] }+ assert_equal %w[activities transfers], @wise_item.reload.raw_payload["coverage"].keys.sortend- test "backfills incoming statement rows into the window already covered by legacy transfers" do+ # The cutoff that dropped every outgoing statement row dated from the oldest+ # legacy transfer on is gone (it also dropped card payments and every later+ # debit); all statement rows stay. The legacy payout stays too: it predates+ # the statements' window, which no statement row from it carries.+ test "keeps every statement row in the window legacy transfers covered" do@wise_item.wise_accounts.create!(balance_id: "10000001",name: "Wise EUR",@@ -327,89 +955,113 @@ class WiseItem::ImporterTest < ActiveSupport::TestCaseaccount = @wise_item.wise_accounts.find_by(currency: "EUR")refs = account.raw_transactions_payload.filter_map { |t| t["referenceNumber"] }- assert_includes refs, "st-incoming-in-window"- assert_includes refs, "st-before-window"- refute_includes refs, "st-outgoing-in-window"+ assert_equal %w[st-outgoing-in-window st-incoming-in-window st-before-window], refs+ assert_equal [ [ 1, nil ] ], account.raw_transactions_payload.filter_map { |t| t.values_at("id", "wise_superseded_by") if t["id"] }end+ # A statement row takes a legacy transfer over only by its reference+ # (TRANSFER-<id>) or as a TRANSFER row of the same amount within a day. A+ # deposit on the same day for the same amount is neither, so it stays a+ # movement of its own; the pay-in it resembles keeps booking from its row,+ # transfers are still fetched for the balance, and support is told.test "keeps an incoming statement row that coincidentally shares its date and amount with a legacy transfer" do- # A same-day, same-amount external payment must never be dropped just- # because it looks like it could be the credit leg of a prior internal- # conversion -- silently losing a real transaction is worse than an- # occasional visible duplicate (see legacy_overlap_outgoing_row?).- @wise_item.wise_accounts.create!(- balance_id: "10000001",- name: "Wise EUR",- currency: "EUR",- raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },- raw_transactions_payload: [- {- "id" => 10,- "targetAccount" => 99999001,- "sourceCurrency" => "USD",- "targetCurrency" => "EUR",- "sourceValue" => 500.0,- "targetValue" => 450.0,- "status" => "incoming_payment_received",- "created" => "2024-02-01"- }+ travel_to Time.utc(2024, 2, 3, 12) do+ @wise_item.wise_accounts.create!(+ balance_id: "10000001",+ name: "Wise EUR",+ currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [+ {+ "id" => 10,+ "targetAccount" => 99999001,+ "sourceCurrency" => "USD",+ "targetCurrency" => "EUR",+ "sourceValue" => 500.0,+ "targetValue" => 455.0,+ "status" => "outgoing_payment_sent",+ "created" => "2024-02-01 09:00:00"+ }+ ]+ )+ statements = [+ { "type" => "CREDIT", "date" => "2024-02-01T09:00:00Z", "amount" => { "value" => "455.00", "currency" => "EUR" },+ "details" => { "type" => "DEPOSIT" }, "referenceNumber" => "st-same-date-and-amount" }]- )- statements = [- { "date" => "2024-02-01T09:00:00Z", "amount" => { "value" => "450.00", "currency" => "EUR" }, "referenceNumber" => "st-same-date-and-amount" }- ]- provider = FakeWiseProvider.new(statements: statements)- WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(statements: statements)).import- account = @wise_item.wise_accounts.find_by(currency: "EUR")- refs = account.raw_transactions_payload.filter_map { |t| t["referenceNumber"] }+ account = @wise_item.wise_accounts.find_by(currency: "EUR")+ payload = account.raw_transactions_payload+ assert_equal [ "st-same-date-and-amount" ], payload.filter_map { |t| t["referenceNumber"] }+ assert payload.none? { |t| t["wise_superseded_by"] || t["wise_supersedes"] }+ assert_equal [ 10 ], payload.filter_map { |t| t["id"] }+ note = statement_migration_notes.sole+ assert_equal "warn", note.level+ assert_equal 1, note.metadata["transfers_unmatched"]- assert_includes refs, "st-same-date-and-amount"+ provider = FakeWiseProvider.new(statements: statements)+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ assert_includes provider.calls, :get_transfers+ endend- test "stops fetching legacy transfers once an account has a successful statement row" do- @wise_item.wise_accounts.create!(- balance_id: "10000001",- name: "Wise EUR",- currency: "EUR",- raw_payload: { "type" => "STANDARD" },- raw_transactions_payload: [- {- "id" => 1,- "sourceCurrency" => "EUR",- "targetCurrency" => "EUR",- "sourceValue" => 100.0,- "targetValue" => 100.0,- "status" => "outgoing_payment_sent",- "created" => "2024-01-10"- },- {- "wise_statement" => true,- "date" => "2024-01-20",- "amount" => { "value" => "10.0", "currency" => "EUR" },- "referenceNumber" => "already-migrated"- }- ]- )- provider = FakeWiseProvider.new(statements: [])+ # Transfers stay fetched for a balance with statement rows until its+ # statements take over every transfer that books inside their window+ # (one-off: a statement row existing at all used to stop them, which lost+ # every later payout when TRANSFER-<id> rows were dropped).+ test "fetches transfers for a balance until its statements take over every transfer it booked" do+ travel_to Time.utc(2024, 1, 25, 12) do+ payout = build_transfer(id: 1).merge("created" => "2024-01-10 10:00:00", "status" => "processing")+ @wise_item.wise_accounts.create!(+ balance_id: "10000001",+ name: "Wise EUR",+ currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001,+ "statements_coverage" => { "from" => "2023-06-01T00:00:00Z", "through" => "2024-01-24T12:00:00Z" } },+ raw_transactions_payload: [+ payout,+ {+ "wise_statement" => true,+ "date" => "2024-01-20T10:00:00Z",+ "amount" => { "value" => "10.0", "currency" => "EUR" },+ "referenceNumber" => "already-migrated"+ }+ ]+ )+ import = lambda do |statements|+ provider = FakeWiseProvider.new(transfers: [ payout.merge("status" => "outgoing_payment_sent") ], statements: statements)+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ provider+ end- WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ assert_includes import.call([]).calls, :get_transfers+ account = @wise_item.wise_accounts.find_by(currency: "EUR")+ assert_equal "outgoing_payment_sent", account.raw_transactions_payload.find { |t| t["id"] == 1 }["status"]- refute_includes provider.calls, :get_transfers+ assert_includes import.call([ statement_row("TRANSFER-1", "-100", "EUR", date: "2024-01-10T10:05:00Z", details_type: "TRANSFER") ]).calls,+ :get_transfers+ assert_equal "wise_statement_TRANSFER-1", account.reload.raw_transactions_payload.find { |t| t["id"] == 1 }["wise_superseded_by"]++ refute_includes import.call([]).calls, :get_transfers+ endend+ # A balance with statements takes no new /v1/transfers row (its statement+ # rows carry them), only fresh copies of the rows it still holds.test "does not merge the profile-wide transfer fallback into an account that already migrated to statements" dobalances = [{ "id" => "10000001", "amount" => { "value" => 1000.0, "currency" => "EUR" }, "type" => "STANDARD" },{ "id" => "10000002", "amount" => { "value" => 500.0, "currency" => "USD" }, "type" => "STANDARD" }]+ held = build_transfer(id: 98, source_currency: "EUR", target_currency: "EUR", target_account: 9999).merge("status" => "processing")eur_account = @wise_item.wise_accounts.create!(balance_id: "10000001",name: "Wise EUR",currency: "EUR",raw_payload: { "type" => "STANDARD" },raw_transactions_payload: [+ held,{"wise_statement" => true,"date" => "2024-01-20",@@ -437,91 +1089,2467 @@ class WiseItem::ImporterTest < ActiveSupport::TestCase)# USD still needs the legacy fallback, so transfers get fetched profile-wide --# including this EUR-currency row, which must not land on the already-migrated- # EUR account.- transfers = [ build_transfer(id: 99, source_currency: "EUR", target_currency: "EUR", target_account: 9999) ]+ # EUR account, and a fresh copy of the payout EUR still holds.+ transfers = [ build_transfer(id: 99, source_currency: "EUR", target_currency: "EUR", target_account: 9999),+ held.merge("status" => "outgoing_payment_sent") ]provider = FakeWiseProvider.new(balances: balances, transfers: transfers, statement_fail_balance_ids: [ "10000002" ])WiseItem::Importer.new(@wise_item, wise_provider: provider).importeur_account.reloadassert_includes provider.calls, :get_transfers- refute_includes eur_account.raw_transactions_payload.filter_map { |t| t["id"] }, 99+ assert_equal [ [ 98, "outgoing_payment_sent" ] ], eur_account.raw_transactions_payload.filter_map { |t| t.values_at("id", "status") if t["id"] }assert_includes eur_account.raw_transactions_payload.filter_map { |t| t["referenceNumber"] }, "already-migrated-eur"end- test "keeps transfer cutoff incremental after the first sync when full history is enabled" do- @wise_item.update!(import_all_history: true)- @wise_item.wise_accounts.create!(- balance_id: "10000001",- name: "Wise EUR",- currency: "EUR",- raw_payload: { "type" => "STANDARD" },- raw_transactions_payload: [ { "id" => 1 } ]- )- sync = @wise_item.syncs.create!(status: :completed, completed_at: Time.current)-- importer = WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new)-- assert_equal sync.completed_at - 7.days, importer.send(:transfer_cutoff)+ # The documented SCA onboarding books /v1/transfers rows in the first sync,+ # as statements answer 403 until a key is registered. Once they work, each+ # statement row takes over the entry of the transfer its reference names+ # (the same entry, renamed), so every movement books once, the card payments+ # and later debits are all kept, and transfers stop.+ test "hands a balance over from its transfers to its statements once they work" do+ eur = link_account(@wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD" }))+ account = eur.current_account+ balance = standard_balance("10000001", "EUR", 80).merge("recipientId" => 77710001)+ top_up = build_transfer(id: 1001, target_account: 77710001)+ .merge("sourceValue" => 500.0, "targetValue" => 500.0, "created" => 20.days.ago.utc.strftime("%Y-%m-%d %H:%M:%S"))+ payout = build_transfer(id: 1002, target_account: 424242).merge("created" => 19.days.ago.utc.strftime("%Y-%m-%d %H:%M:%S"))+ sync = lambda do |**options|+ provider = FakeWiseProvider.new(balances: [ balance ], borderless_accounts: [], **options)+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ provider+ end+ entries = -> { account.entries.where(source: "wise").order(:external_id).pluck(:external_id, :amount, :id) }++ sync.call(transfers: [ top_up, payout ], raise_on: { get_balance_statements: statements_forbidden })+ legacy = entries.call+ assert_equal [ [ "wise_transfer_1001", BigDecimal("-500") ], [ "wise_transfer_1002", BigDecimal("100") ] ], legacy.map { |e| e.first(2) }++ sync.call(transfers: [ top_up, payout ], statements: [+ statement_row("TRANSFER-1001", "500", "EUR", date: 20.days.ago.utc.iso8601, details_type: "DEPOSIT"),+ statement_row("TRANSFER-1002", "-100", "EUR", date: 19.days.ago.utc.iso8601, details_type: "TRANSFER"),+ statement_row("CARD-9001", "-30", "EUR", date: 5.days.ago.utc.iso8601)+ ])+ assert_equal [ [ "wise_statement_CARD-9001", BigDecimal("30") ], [ "wise_statement_TRANSFER-1001", BigDecimal("-500"), legacy[0].last ],+ [ "wise_statement_TRANSFER-1002", BigDecimal("100"), legacy[1].last ] ],+ entries.call.map { |e| e.first.end_with?("9001") ? e.first(2) : e }++ payout_today = build_transfer(id: 1003, target_account: 424242).merge("sourceValue" => 250.0, "targetValue" => 250.0)+ last = sync.call(transfers: [ top_up, payout, payout_today ], statements: [+ statement_row("CARD-9002", "-40", "EUR", date: 1.hour.ago.utc.iso8601),+ statement_row("TRANSFER-1003", "-250", "EUR", date: 1.hour.ago.utc.iso8601, details_type: "TRANSFER")+ ])+ refute_includes last.calls, :get_transfers+ assert_equal BigDecimal("-80"), account.entries.where(source: "wise").sum(:amount)+ assert_includes entries.call.map(&:first), "wise_statement_CARD-9002"+ assert_empty eur.reload.raw_transactions_payload.select { |row| row["id"].present? }end- # Activity routing+ # The old statement migration booked a legacy top-up again from its+ # statement row, so both entries exist. The statement row keeps the one the+ # person edited under its id and the other goes; the top-up is income once.+ test "keeps one entry for a transfer the old statement migration booked twice" do+ top_up = build_transfer(id: 9000000104, target_account: 99999001).merge("sourceValue" => 2465.0, "targetValue" => 2465.0)+ credit = statement_row("TRANSFER-9000000104", "2465", "EUR", date: 7.days.ago.utc.iso8601, details_type: "DEPOSIT")+ eur = link_account(@wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ top_up, credit.merge("wise_statement" => true) ]))+ account = eur.current_account+ edited = account.entries.create!(external_id: "wise_transfer_9000000104", source: "wise", amount: -2465, currency: "EUR",+ date: 7.days.ago.to_date, name: "Top-up", notes: "From savings", entryable: Transaction.new)+ account.entries.create!(external_id: "wise_statement_TRANSFER-9000000104", source: "wise", amount: -2465, currency: "EUR",+ date: 7.days.ago.to_date, name: "Received money", entryable: Transaction.new)++ result = WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(statements: [ credit ])).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])++ assert_equal [ [ edited.id, "wise_statement_TRANSFER-9000000104", BigDecimal("-2465") ] ],+ account.entries.where(source: "wise").pluck(:id, :external_id, :amount)+ assert_equal "From savings", edited.reload.notes+ end- test "routes INTERBALANCE activities to both JAR and STANDARD accounts" do- savings = {- "id" => "10000002",- "amount" => { "value" => 1000.0, "currency" => "EUR" },- "totalWorth" => { "value" => 1000.0, "currency" => "EUR" },- "reservedAmount" => { "value" => 0.0, "currency" => "EUR" },- "type" => "SAVINGS",- "name" => "Jar"+ # A conversion is in both balances' statements and in the activity feed. Its+ # activity legs book it (they link as a transfer) and the statement rows of+ # the same move book nothing; likewise a move into a jar.+ test "books a conversion once on each balance when statements report it too" do+ jar = { "id" => "32000009", "type" => "SAVINGS", "name" => "Holiday", "amount" => { "value" => 500, "currency" => "EUR" },+ "totalWorth" => { "value" => 500, "currency" => "EUR" } }+ conversion = build_interbalance("To <strong>EUR</strong>", resource_id: "4001", primary: "117.50 EUR", secondary: "100 GBP")+ .merge("createdOn" => 3.days.ago.utc.iso8601)+ deposit = build_interbalance("To <strong>Holiday</strong>", resource_id: "6000", primary: "500 EUR")+ .merge("createdOn" => 2.days.ago.utc.iso8601)+ statements = {+ "32000001" => [ statement_row("BALANCE-4001", "-100", "GBP", date: 3.days.ago.utc.iso8601, details_type: "CONVERSION") ],+ "32000002" => [ statement_row("BALANCE-4001", "117.50", "EUR", date: 3.days.ago.utc.iso8601, details_type: "CONVERSION"),+ statement_row("BALANCE-6000", "-500", "EUR", date: 2.days.ago.utc.iso8601, details_type: "OUTGOING_CROSS_BALANCE") ]}- interbalance = build_interbalance("To <strong>Jar</strong>", resource_id: "5001")- provider = FakeWiseProvider.new(savings_balances: [ savings ], activities: [ interbalance ])+ provider = FakeWiseProvider.new(balances: [ standard_balance("32000001", "GBP", 0), standard_balance("32000002", "EUR", 117.5) ],+ savings_balances: [ jar ], borderless_accounts: [], activities: [ conversion, deposit ],+ statements_by_balance: statements)WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ booked = @wise_item.wise_accounts.reload.to_h do |wise_account|+ wise_account = link_account(wise_account)+ WiseAccount::Transactions::Processor.new(wise_account).process+ [ wise_account.name, wise_account.current_account.entries.order(:external_id).pluck(:external_id, :amount) ]+ end- jar = @wise_item.wise_accounts.find_by(balance_id: "10000002")+ assert_equal({ "Wise GBP" => [ [ "wise_interbalance_4001_outflow", BigDecimal("100") ] ],+ "Wise EUR" => [ [ "wise_interbalance_4001_inflow", BigDecimal("-117.5") ], [ "wise_interbalance_6000_outflow", BigDecimal("500") ] ],+ "Holiday" => [ [ "wise_interbalance_6000_inflow", BigDecimal("-500") ] ] }, booked)+ assert_equal({ "BALANCE-4001" => "wise_interbalance_4001_inflow", "BALANCE-6000" => "wise_interbalance_6000_outflow" },+ @wise_item.wise_accounts.find_by!(currency: "EUR", balance_id: "32000002").raw_transactions_payload+ .select { |row| row["wise_statement"] }.to_h { |row| [ row["referenceNumber"], row["wise_superseded_by"] ] })+ end++ # Wise reuses a transfer's reference on its refund. Both rows are kept. The+ # first sync with statement coverage fetches the whole window again, so a+ # debit the old [ref] key had let its refund overwrite comes back; the+ # refund keeps the id it booked under, and the debit gets one of its own.+ test "keeps a refund that shares its transfer's reference next to the debit" do+ debit = statement_row("TRANSFER-555", "-100", "EUR", date: "2026-03-01T10:00:00Z", details_type: "TRANSFER")+ refund = statement_row("TRANSFER-555", "100", "EUR", date: "2026-03-03T10:00:00Z", details_type: "TRANSFER")+ eur = link_account(@wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ refund.merge("wise_statement" => true) ]))+ eur.current_account.entries.create!(external_id: "wise_statement_TRANSFER-555", source: "wise", amount: -100, currency: "EUR",+ date: Date.new(2026, 3, 3), name: "Refund", entryable: Transaction.new)++ travel_to Time.utc(2026, 3, 20, 12) do+ 2.times do+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: FakeWiseProvider.new(statements: [ debit, refund ])).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ end+ end++ assert_equal [ "TRANSFER-555_DEBIT_20260301", "TRANSFER-555" ],+ eur.reload.raw_transactions_payload.sort_by { |row| row["date"] }.map { |row| row["wise_statement_id"] }+ assert_equal({ "wise_statement_TRANSFER-555" => BigDecimal("-100"), "wise_statement_TRANSFER-555_DEBIT_20260301" => BigDecimal("100") },+ eur.current_account.entries.where(source: "wise").pluck(:external_id, :amount).to_h)+ end++ # Upgraded from a build that keyed statement rows by reference, so the+ # refund overwrote the payout's row and the payout's own entry stands next+ # to the refund's, which a person categorized. The debit's statement row+ # comes back with an id of its own and takes the payout's entry over; the+ # refund keeps its entry. Nothing is deleted or booked twice.+ test "a payout's statement row takes its transfer's entry over next to a refund a person edited" do+ payout = build_transfer(id: 777, target_account: 4444).merge("status" => "funds_refunded", "created" => "2026-03-01 10:00:00")+ activities = [+ build_transfer_activity(777, primary: "100 EUR", created_on: "2026-03-01T10:00:01.000Z"),+ build_transfer_activity(777, id: "refund-777", primary: "<positive>+ 100 EUR</positive>", created_on: "2026-03-03T10:00:00.000Z")+ ]+ debit = statement_row("TRANSFER-777", "-100", "EUR", date: "2026-03-01T10:00:05Z", details_type: "TRANSFER")+ refund = statement_row("TRANSFER-777", "100", "EUR", date: "2026-03-03T10:00:00Z", details_type: "TRANSFER")+ eur = link_account(@wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [ payout, refund.merge("wise_statement" => true) ]))+ account = eur.current_account+ payout_entry = account.entries.create!(external_id: "wise_transfer_777", source: "wise", amount: 100, currency: "EUR",+ date: Date.new(2026, 3, 1), name: "Payout", entryable: Transaction.new)+ refund_entry = account.entries.create!(external_id: "wise_statement_TRANSFER-777", source: "wise", amount: -100, currency: "EUR",+ date: Date.new(2026, 3, 3), name: "Refund", user_modified: true, entryable: Transaction.new)++ travel_to Time.utc(2026, 3, 20, 12) do+ 2.times do+ provider = FakeWiseProvider.new(transfers: [ payout ], activities: activities, statements: [ debit, refund ])+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ end+ end++ assert_equal({ payout_entry.id => [ "wise_statement_TRANSFER-777_DEBIT_20260301", BigDecimal("100") ],+ refund_entry.id => [ "wise_statement_TRANSFER-777", BigDecimal("-100") ] },+ account.entries.where(source: "wise").to_h { |entry| [ entry.id, [ entry.external_id, entry.amount ] ] })+ end++ # The window grew back (the sync start date moved earlier) past the debit+ # of a refund booked, and edited, under the plain reference: the refund+ # keeps its entry and the debit books on its own.+ test "books the debit an earlier window start brings back next to the refund that kept its reference" do+ debit = statement_row("TRANSFER-555", "-100", "EUR", date: "2026-03-01T10:00:00Z", details_type: "TRANSFER")+ refund = statement_row("TRANSFER-555", "100", "EUR", date: "2026-03-03T10:00:00Z", details_type: "TRANSFER")+ @wise_item.update!(sync_start_date: Date.new(2026, 3, 2))+ sync = lambda do+ provider = FakeWiseProvider.new(statements: [ debit, refund ], windowed_statements: true)+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ wise_account = WiseItem.find(@wise_item.id).wise_accounts.sole+ link_account(wise_account) unless wise_account.current_account+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ wise_account.reload.current_account+ end++ account = travel_to(Time.utc(2026, 3, 20, 12)) { sync.call }+ account.entries.find_by!(external_id: "wise_statement_TRANSFER-555").update!(user_modified: true, notes: "Cancelled order")+ @wise_item.update!(sync_start_date: Date.new(2026, 2, 1))+ travel_to(Time.utc(2026, 3, 21, 12)) { sync.call }++ assert_equal({ "wise_statement_TRANSFER-555" => BigDecimal("-100"), "wise_statement_TRANSFER-555_DEBIT_20260301" => BigDecimal("100") },+ account.entries.where(source: "wise").pluck(:external_id, :amount).to_h)+ end++ # Once Wise refuses a balance's statements (an SCA key removed or no+ # longer registered), its statement rows carry what happened until they+ # last reached, and its transfers and activities what happened after; when+ # they work again, their rows take those over.+ test "a balance whose statements Wise refuses takes what happened after them from transfers and activities" do+ travel_to Time.utc(2026, 10, 17, 12) do+ reached = { "from" => "2025-10-17T12:00:00Z", "through" => "2026-10-01T12:00:00Z" }+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "statements_coverage" => reached },+ raw_transactions_payload: [ statement_row("CARD-1", "-5", "EUR", date: "2026-09-20T10:00:00Z")+ .merge("wise_statement" => true) ])+ before = build_transfer(id: 500).merge("created" => "2026-09-25 10:00:00")+ after = build_transfer(id: 501).merge("created" => "2026-10-10 10:00:00")+ cards = [ build_card_activity("card_before", "7 EUR", created_on: "2026-09-26T10:00:00.000Z"),+ build_card_activity("card_after", "12 EUR", created_on: "2026-10-11T10:00:00.000Z") ]+ provider = FakeWiseProvider.new(transfers: [ before, after ], activities: cards, raise_on: { get_balance_statements: statements_forbidden })++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert result[:complete]+ assert_includes provider.calls, :get_transfers+ rows = eur.reload.raw_transactions_payload+ assert_equal [ "CARD-1" ], rows.filter_map { |row| row["referenceNumber"] }+ assert_equal [ "501", "card_after" ], rows.filter_map { |row| row["id"]&.to_s }.sort+ end+ end++ # The statements' window opened after a refunded payout was made, so only+ # its refund credit is in it. That credit took the payout over, rewriting+ # its entry as the refund and deleting its fee and refund entries (net -50+ # instead of 52.50). The payout's row keeps booking all three, the credit+ # books nothing, and the later payout is taken over by its own statement+ # row.+ test "keeps a refunded payout booked when only its refund is inside the statements' window" do+ payout = build_transfer(id: 501, target_account: 4444).merge("status" => "funds_refunded", "created" => "2025-10-02 10:00:00")+ later = build_transfer(id: 502, target_account: 4445).merge("sourceValue" => 50.0, "targetValue" => 50.0, "created" => "2026-09-01 10:00:00")+ activities = [+ build_transfer_activity(501, primary: "100 EUR", secondary: "102.50 EUR", created_on: "2025-10-02T10:00:01.000Z"),+ build_transfer_activity(501, id: "refund-501", primary: "<positive>+ 100 EUR</positive>", created_on: "2025-10-20T10:00:00.000Z"),+ build_transfer_activity(502, primary: "50 EUR", created_on: "2026-09-01T10:00:01.000Z")+ ]+ statements = [+ statement_row("TRANSFER-501", "-102.50", "EUR", date: "2025-10-02T10:00:05Z", details_type: "TRANSFER",+ "totalFees" => { "value" => "2.50", "currency" => "EUR" }),+ statement_row("TRANSFER-501", "100", "EUR", date: "2025-10-20T10:00:00Z", details_type: "TRANSFER"),+ statement_row("TRANSFER-502", "-50", "EUR", date: "2026-09-01T10:00:05Z", details_type: "TRANSFER")+ ]+ booked = -> { @wise_item.wise_accounts.sole.current_account.entries.where(source: "wise").order(:external_id).pluck(:external_id, :amount) }++ travel_to Time.utc(2026, 10, 1, 12) do+ provider = FakeWiseProvider.new(transfers: [ payout, later ], activities: activities, raise_on: { get_balance_statements: statements_forbidden })+ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ link_account(@wise_item.wise_accounts.sole)+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ end+ assert_equal [ [ "wise_fee_501", BigDecimal("2.5") ], [ "wise_refund_501", BigDecimal("-100") ], [ "wise_transfer_501", BigDecimal("100") ],+ [ "wise_transfer_502", BigDecimal("50") ] ], booked.call++ # Statements now work; their window starts a year back, after the payout.+ travel_to Time.utc(2026, 10, 11, 12) do+ provider = FakeWiseProvider.new(transfers: [ payout, later ], activities: activities, statements: statements, windowed_statements: true)+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ assert_equal Time.utc(2025, 10, 11, 12), provider.statement_requests.sole[:interval_start]+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ end++ assert_equal [ [ "wise_fee_501", BigDecimal("2.5") ], [ "wise_refund_501", BigDecimal("-100") ],+ [ "wise_statement_TRANSFER-502", BigDecimal("50") ], [ "wise_transfer_501", BigDecimal("100") ] ], booked.call+ end++ # A balance's statements resume a week before the end of its last successful+ # statement fetch, so an outage longer than that overlap leaves no gap; the+ # outage counts as a failed fetch for a balance that holds statement rows.+ test "resumes a balance's statements from its own coverage after an outage" do+ rows = [ statement_row("CARD-1", "-10", "EUR", date: "2026-09-20T10:00:00Z"),+ statement_row("CARD-2", "-90", "EUR", date: "2026-09-25T10:00:00Z"),+ statement_row("CARD-3", "-5", "EUR", date: "2026-10-05T10:00:00Z") ]+ import = lambda do |**options|+ provider = FakeWiseProvider.new(statements: rows, windowed_statements: true, **options)+ [ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import, provider ]+ end++ travel_to(Time.utc(2026, 9, 21, 12)) { import.call }+ outage, = travel_to(Time.utc(2026, 10, 6, 12)) { import.call(raise_on: { get_balance_statements: "Unexpected response 503" }) }+ _, recovery = travel_to(Time.utc(2026, 10, 7, 12)) { import.call }++ assert_equal [ false, false, 1 ], outage.values_at(:success, :complete, :fetch_failures)+ assert_equal Time.utc(2026, 9, 14, 12), recovery.statement_requests.first[:interval_start]+ eur = @wise_item.wise_accounts.find_by!(currency: "EUR")+ assert_equal %w[CARD-1 CARD-2 CARD-3], eur.raw_transactions_payload.map { |row| row["referenceNumber"] }+ assert_equal({ from: Time.utc(2025, 9, 21, 12), through: Time.utc(2026, 10, 7, 12) }, eur.statements_coverage)+ end++ test "counts a statement failure on a balance with statement rows even when transfers stand in" do+ @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ statement_row("CARD-1", "-5", "EUR").merge("wise_statement" => true) ])+ provider = FakeWiseProvider.new(balances: [ standard_balance("10000001", "EUR", 0), standard_balance("10000002", "USD", 0) ],+ borderless_accounts: [], raise_on: { get_balance_statements: "Unexpected response 502" })++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_includes provider.calls, :get_transfers+ assert_equal [ false, 1 ], result.values_at(:complete, :fetch_failures)+ end++ # Consecutive statement rows chain through their runningBalance. A break+ # (CARD-2, which its fee would explain) tells support Sure may read the+ # amounts wrongly; the credit's amount, already net of its fee, chains, and+ # so do two rows of the same second whatever their order.+ test "tells support when statement rows do not follow on from the running balance" do+ running = ->(value) { { "runningBalance" => { "value" => value, "currency" => "EUR" } } }+ rows = [+ statement_row("DEPOSIT-1", "95.86", "EUR", date: "2026-10-01T10:00:00Z", details_type: "DEPOSIT",+ "totalFees" => { "value" => 4.14, "currency" => "EUR" }, **running.call(95.86)),+ statement_row("CARD-1", "-10", "EUR", date: "2026-10-02T10:00:00Z", **running.call(85.86)),+ statement_row("CARD-2", "-5", "EUR", date: "2026-10-03T10:00:00Z", "totalFees" => { "value" => 2, "currency" => "EUR" },+ **running.call(78.86)),+ statement_row("CARD-4", "-2", "EUR", date: "2026-10-04T10:00:00Z", **running.call(75.86)),+ statement_row("CARD-3", "-1", "EUR", date: "2026-10-04T10:00:00Z", **running.call(77.86))+ ]++ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(statements: rows.reverse)).import++ note = DebugLogEntry.where(provider_key: "wise", category: "provider_sync").where("metadata ->> 'operation' = ?", "running_balance").sole+ assert_equal "warn", note.level+ assert_equal [ 5, 1, 1 ], note.metadata.values_at("row_count", "break_count", "fee_explained_count")+ end++ # Until statements work, an SCA profile books its card payments from the+ # activity feed. Each statement row then takes its card payment's entry over+ # (by CARD-<resource id>, else by sign, amount and day), keeping the+ # person's category; an activity no statement row carries is dropped and its+ # entry cleaned up, and the activity rows leave once their entries are+ # renamed.+ test "hands card payments booked from activities over to the statement rows" do+ eur = link_account(@wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD" }))+ account = eur.current_account+ cards = [ build_card_activity("card_1", "12.50 EUR", created_on: 4.days.ago.utc.iso8601(3)),+ build_card_activity("card_2", "8 EUR", created_on: 3.days.ago.utc.iso8601(3)),+ build_card_activity("card_3", "5 EUR", created_on: 2.days.ago.utc.iso8601(3)) ]+ sync = lambda do |**options|+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: FakeWiseProvider.new(activities: cards, **options)).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ end+ statements = [ statement_row("CARD-resource_card_1", "-12.50", "EUR", date: 4.days.ago.utc.iso8601),+ statement_row("CARD-80002", "-8", "EUR", date: 3.days.ago.utc.iso8601) ]++ sync.call(raise_on: { get_balance_statements: statements_forbidden })+ booked = account.entries.where(source: "wise").pluck(:external_id, :id).to_h+ account.entries.find(booked["wise_activity_card_1"]).entryable.update!(locked_attributes: { "category_id" => Time.current.iso8601 })++ sync.call(statements: statements)++ assert_equal({ "wise_statement_CARD-resource_card_1" => booked["wise_activity_card_1"], "wise_statement_CARD-80002" => booked["wise_activity_card_2"] },+ account.entries.where(source: "wise").pluck(:external_id, :id).to_h)+ assert account.entries.find(booked["wise_activity_card_1"]).entryable.locked_attributes.key?("category_id")+ note = statement_migration_notes.sole+ assert_equal [ 2, 1 ], note.metadata.values_at("activities_matched", "activities_unmatched")++ sync.call(statements: statements)+ assert_equal [ "CARD-resource_card_1", "CARD-80002" ], eur.reload.raw_transactions_payload.map { |row| row["referenceNumber"] }+ end++ # A balance's first statement coverage rebuilds its stored rows from a+ # whole window, like a source's first coverage (#coverage_upgraded?).+ test "a balance's first statement coverage counts as a coverage upgrade once" do+ covered = { "from" => "2020-01-01T00:00:00Z", "through" => 1.day.ago.utc.iso8601, "version" => WiseItem::COVERAGE_VERSION }+ @wise_item.update!(raw_payload: { "coverage" => { "transfers" => covered, "activities" => covered } })+ @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ statement_row("CARD-1", "-5", "EUR").merge("wise_statement" => true) ])+ import = -> { WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: FakeWiseProvider.new(statements: [])).import }++ assert import.call[:coverage_upgraded]+ assert_not import.call[:coverage_upgraded]+ end++ # A balance's first statement sync may delete beyond the clean-up's cap the+ # statement entries an old install booked next to a conversion's own legs.+ # That sync being incomplete ran no clean-up, and the later complete ones+ # were capped for good, so each conversion stayed booked twice. The balance+ # now keeps the bypass for those entries until a clean-up after a complete+ # import used it.+ test "removes the conversions an old install booked twice even when its first statement sync was incomplete" do+ travel_to Time.utc(2026, 10, 1, 12) do+ covered = { "from" => "2020-01-01T00:00:00Z", "through" => 1.day.ago.utc.iso8601, "version" => WiseItem::COVERAGE_VERSION }+ @wise_item.update!(raw_payload: { "coverage" => { "transfers" => covered, "activities" => covered } })+ conversions = %w[117.50 230 45.10 80 64.25 99].each_with_index.map do |amount, i|+ build_interbalance("To <strong>EUR</strong>", resource_id: (800 + i).to_s, primary: "#{amount} EUR",+ secondary: "#{(amount.to_d * 0.85).round(2)} GBP")+ .merge("createdOn" => (60 - i * 5).days.ago.utc.iso8601(3))+ end+ statements = conversions.map do |conversion|+ statement_row("BALANCE-#{conversion.dig('resource', 'id')}", conversion["primaryAmount"].to_d.to_s("F"), "EUR",+ date: conversion["createdOn"], details_type: "CONVERSION")+ end+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: conversions + statements.map { |row| row.merge("wise_statement" => true) })+ account = link_account(eur).current_account+ # What older code booked: each conversion's leg and its statement+ # credit.+ conversions.zip(statements) do |conversion, statement|+ date = Time.zone.parse(conversion["createdOn"]).to_date+ amount = -conversion["primaryAmount"].to_d+ account.entries.create!(external_id: "wise_interbalance_#{conversion.dig('resource', 'id')}_inflow", source: "wise", amount: amount,+ currency: "EUR", date: date, name: "From GBP", entryable: Transaction.new)+ account.entries.create!(external_id: "wise_statement_#{statement['referenceNumber']}", source: "wise", amount: amount,+ currency: "EUR", date: date, name: "Converted", entryable: Transaction.new)+ end+ sync = lambda do |**options|+ provider = FakeWiseProvider.new(balances: [ eur_balance("10000001", 0) ], borderless_accounts: [], activities: conversions,+ statements: statements, windowed_statements: true, **options)+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ result+ end++ assert_not sync.call(raise_on: { get_activities: "Unexpected response 502" })[:complete]+ assert_equal 12, account.entries.where(source: "wise").count+ assert_equal account.entries.where(source: "wise").pluck(:external_id).sort, eur.reload.prune_cap_bypass_ids.sort++ assert sync.call[:complete]+ assert_equal conversions.map { |conversion| "wise_interbalance_#{conversion.dig('resource', 'id')}_inflow" },+ account.entries.where(source: "wise").order(:external_id).pluck(:external_id)+ assert_equal [ true, 6 ], prune_notes.order(:created_at).last.metadata.values_at("cap_bypassed", "destroyed_count")+ assert_empty eur.reload.prune_cap_bypass_ids+ end+ end++ # A sync that fetched the whole history again lifts the clean-up's cap only+ # for the entries a row Sure holds can have booked, never for every stale+ # entry: here Wise entries no row of the item explains.+ test "lifts the clean-up's cap only for the entries a row Sure holds explains" do+ usd = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise USD", currency: "USD", raw_payload: { "type" => "STANDARD" })+ account = link_account(usd).current_account+ history = (1..12).map do |i|+ account.entries.create!(external_id: "wise_transfer_150000#{i.to_s.rjust(2, '0')}", source: "wise", amount: i.odd? ? -50 : 50,+ currency: "USD", date: i.days.ago.to_date, name: "Wise", entryable: Transaction.new)+ end+ WiseItem.any_instance.stubs(:wise_provider).returns(+ FakeWiseProvider.new(balances: [ standard_balance("10000001", "USD", 0) ], borderless_accounts: [],+ raise_on: { get_balance_statements: statements_forbidden })+ )++ # The item's first sync: the whole default history is fetched and covered.+ Sync.create!(syncable: @wise_item).perform++ assert @wise_item.reload.fetch_coverage(:transfers)+ assert history.all? { |entry| Entry.exists?(entry.id) }+ assert_equal [ 12, 0 ], prune_notes.sole.metadata.values_at("capped_count", "destroyed_count")+ end++ # An account can keep the history an earlier connection booked (the person+ # removed that connection, which keeps its accounts, and linked the balance+ # of a new one to the account). Those entries predate the new connection's+ # fetched history, so no row will ever book them; the clean-up deleted them,+ # up to its cap, from the balance's empty payload.+ test "keeps the history an earlier connection left on an account a balance is linked to" do+ travel_to Time.utc(2026, 10, 17, 12) do+ account = Account.create!(family: @family, name: "Wise USD", balance: 0, currency: "USD", accountable: Depository.new(subtype: "checking"))+ history = [ [ "wise_transfer_1500000001", -400, Date.new(2024, 3, 1) ], [ "wise_transfer_1500000002", 150, Date.new(2024, 3, 9) ],+ [ "wise_fee_1500000002", 1.2, Date.new(2024, 3, 9) ], [ "wise_interbalance_3000000001_outflow", 100, Date.new(2024, 4, 2) ],+ [ "wise_transfer_1500000003", 148.8, Date.new(2024, 5, 20) ] ].map do |external_id, amount, date|+ account.entries.create!(external_id: external_id, source: "wise", amount: amount, currency: "USD", date: date, name: "Wise",+ entryable: Transaction.new)+ end+ balance = standard_balance("10000001", "USD", 0).merge("recipientId" => 70000000, "creationTime" => "2023-01-10T10:00:00Z")+ WiseItem.any_instance.stubs(:wise_provider).returns(+ FakeWiseProvider.new(balances: [ balance ], borderless_accounts: [], raise_on: { get_balance_statements: statements_forbidden })+ )++ Sync.create!(syncable: @wise_item).perform+ AccountProvider.create!(account: account, provider: @wise_item.wise_accounts.reload.sole)+ Sync.create!(syncable: @wise_item.reload).perform++ assert history.all? { |entry| Entry.exists?(entry.id) }+ assert_empty prune_notes+ end+ end++ # The incremental window follows the transfers coverage marker (the last+ # successful fetch), not the last completed sync, so a failed fetch can no+ # longer move it. It re-lists 14 days before the marker and always the last+ # 60 days, where a sent payout can still bounce.+ test "keeps the transfer window incremental after a full-history fetch" do+ travel_to Time.utc(2026, 10, 21, 12) do+ @wise_item.update!(import_all_history: true, raw_payload: {+ "coverage" => { "transfers" => { "from" => "2015-01-01T00:00:00Z", "through" => "2026-04-20T00:00:00Z", "version" => WiseItem::COVERAGE_VERSION } }+ })+ provider = FakeWiseProvider.new(raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ starts = provider.transfer_requests.map { |request| request[:created_date_start] }.uniq+ assert_equal [ Time.utc(2026, 4, 6), Time.utc(2026, 8, 22, 12) ], starts+ assert_equal({ "from" => "2015-01-01T00:00:00Z", "through" => "2026-10-21T12:00:00Z", "version" => WiseItem::COVERAGE_VERSION },+ @wise_item.reload.raw_payload.dig("coverage", "transfers"))+ end+ end++ test "fetches the full history when nothing is covered yet, even with stored rows" do+ travel_to Time.utc(2026, 10, 17, 12) do+ @wise_item.update!(import_all_history: true)+ @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ build_transfer(id: 1) ])+ provider = FakeWiseProvider.new(+ multi_currency_account: { "id" => 77001, "recipientId" => 99999001, "creationTime" => "2024-09-25T10:00:00Z" },+ raise_on: { get_balance_statements: statements_forbidden }+ )++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert result[:complete]+ # A day before Wise opened the account, which predates every balance.+ full_start = Time.utc(2024, 9, 24, 10)+ assert_equal [ full_start ], provider.transfer_requests.map { |request| request[:created_date_start] }.uniq+ assert_equal [ full_start ], provider.activity_requests.map { |request| request[:since] }+ covered = { "from" => "2024-09-24T10:00:00Z", "through" => "2026-10-17T12:00:00Z", "version" => WiseItem::COVERAGE_VERSION }+ assert_equal({ "transfers" => covered, "activities" => covered }, @wise_item.reload.raw_payload["coverage"])+ assert_equal "2024-09-25T10:00:00Z", @wise_item.raw_payload.dig("multi_currency_account", "creationTime")+ end+ end++ # Coverage that starts after the full history (the item synced the default+ # year first) is widened once import_all_history is switched on.+ test "fetches the full history once import_all_history is enabled after setup" do+ travel_to Time.utc(2026, 10, 17, 12) do+ provider = FakeWiseProvider.new(raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ assert_equal "2025-10-17T12:00:00Z", @wise_item.reload.raw_payload.dig("coverage", "transfers", "from")++ @wise_item.update!(import_all_history: true)+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ full_start = Time.utc(2020, 5, 19, 14, 43, 16.658r)+ assert_equal full_start, provider.transfer_requests.last[:created_date_start]+ assert_equal full_start, provider.activity_requests.last[:since]+ assert_equal "2020-05-19T14:43:16Z", @wise_item.reload.raw_payload.dig("coverage", "activities", "from")+ end+ end++ # A sync start date is where the history starts, not where every sync+ # starts, so one inside the covered window leaves the window incremental (it+ # used to fetch from the date on every sync, and a date past the coverage+ # restarted it).+ test "a sync start date inside the covered window leaves the window incremental" do+ travel_to Time.utc(2026, 10, 17, 12) do+ @wise_item.update!(raw_payload: {+ "coverage" => { "activities" => { "from" => "2015-01-01T00:00:00Z", "through" => "2026-10-06T12:00:00Z",+ "version" => WiseItem::COVERAGE_VERSION } }+ })+ provider = FakeWiseProvider.new++ WiseItem::Importer.new(@wise_item, wise_provider: provider, sync_start_date: Date.new(2026, 6, 1)).import++ assert_equal Time.utc(2026, 9, 6, 12), provider.activity_requests.first[:since]+ assert_equal "2015-01-01T00:00:00Z", @wise_item.reload.raw_payload.dig("coverage", "activities", "from")+ end+ end++ # The edit form saves a sync start date (prefilled a year back) that used to+ # restart every sync's window there, so each sync paged the whole window+ # again, and with import_all_history the history before it was never+ # fetched. It is where the history starts: fetched once in full (with the+ # full history, from the earlier of it and the account's creation),+ # incrementally afterwards, and once more if moved back.+ test "starts the history at the sync start date and fetches incrementally once it is covered" do+ travel_to Time.utc(2026, 10, 17, 12) do+ @wise_item.update!(sync_start_date: Date.new(2025, 10, 17))+ provider = FakeWiseProvider.new(raise_on: { get_balance_statements: statements_forbidden })+ import = -> { WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import }++ 2.times { import.call }++ assert_equal [ Time.utc(2025, 10, 17), 60.days.ago ], provider.transfer_requests.map { |request| request[:created_date_start] }+ assert_equal [ Time.utc(2025, 10, 17), 30.days.ago ], provider.activity_requests.map { |request| request[:since] }+ assert_equal "2025-10-17T00:00:00Z", @wise_item.reload.raw_payload.dig("coverage", "activities", "from")++ @wise_item.update!(sync_start_date: Date.new(2025, 6, 1))+ import.call+ assert_equal Time.utc(2025, 6, 1), provider.activity_requests.last[:since]++ @wise_item.update!(import_all_history: true)+ import.call+ assert_equal Time.utc(2020, 5, 19, 14, 43, 16.658r), provider.activity_requests.last[:since]+ import.call+ assert_equal 30.days.ago, provider.activity_requests.last[:since]+ end+ end++ # Coverage says which build recorded it (WiseItem::COVERAGE_VERSION). An+ # older build may have dropped rows the current one stores, or put them on+ # other balances, so its coverage counts as none: the whole history is+ # fetched once again, then incrementally.+ test "fetches the whole history once again when an older build recorded the coverage" do+ travel_to Time.utc(2026, 10, 17, 12) do+ older = { "from" => "2025-10-17T12:00:00Z", "through" => "2026-09-29T12:00:00Z" }+ @wise_item.update!(raw_payload: { "coverage" => { "transfers" => older, "activities" => older } })+ card = build_card_activity("card_1", "10 EUR", created_on: "2026-03-01T10:00:00.000Z")+ provider = FakeWiseProvider.new(activities: [ card ], windowed_activities: true, raise_on: { get_balance_statements: statements_forbidden })+ import = -> { WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import }++ assert import.call[:coverage_upgraded]++ assert_equal [ 365.days.ago ], provider.transfer_requests.map { |request| request[:created_date_start] }+ assert_equal [ 365.days.ago ], provider.activity_requests.map { |request| request[:since] }+ assert_equal [ "card_1" ], @wise_item.wise_accounts.sole.raw_transactions_payload.map { |row| row["id"] }+ covered = { "from" => "2025-10-17T12:00:00Z", "through" => "2026-10-17T12:00:00Z", "version" => WiseItem::COVERAGE_VERSION }+ assert_equal({ "transfers" => covered, "activities" => covered }, @wise_item.reload.raw_payload["coverage"])++ assert_not import.call[:coverage_upgraded]+ assert_equal 30.days.ago, provider.activity_requests.last[:since]+ end+ end++ test "re-reads activities back to the oldest stored one that can still change, at most 180 days" do+ travel_to Time.utc(2026, 10, 17, 12) do+ @wise_item.update!(raw_payload: {+ "coverage" => { "activities" => { "from" => "2015-01-01T00:00:00Z", "through" => "2026-10-02T12:00:00Z", "version" => WiseItem::COVERAGE_VERSION } }+ })+ pending = build_interbalance("To <strong>EUR</strong>", resource_id: "8001", primary: "117.50 EUR", secondary: "100 GBP")+ .merge("status" => "IN_PROGRESS", "createdOn" => "2026-06-17T09:00:00Z")+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ pending ])+ provider = FakeWiseProvider.new++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ assert_equal Time.utc(2026, 6, 16, 9), provider.activity_requests.last[:since]++ eur.update!(raw_transactions_payload: [ pending.merge("createdOn" => "2025-12-02T09:00:00Z") ])+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync", level: "info").count }, 1 do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end+ assert_equal Time.utc(2026, 4, 20, 12), provider.activity_requests.last[:since]+ end+ end++ # Activity routing++ test "routes INTERBALANCE activities to both JAR and STANDARD accounts" do+ savings = {+ "id" => "10000002",+ "amount" => { "value" => 1000.0, "currency" => "EUR" },+ "totalWorth" => { "value" => 1000.0, "currency" => "EUR" },+ "reservedAmount" => { "value" => 0.0, "currency" => "EUR" },+ "type" => "SAVINGS",+ "name" => "Jar"+ }+ interbalance = build_interbalance("To <strong>Jar</strong>", resource_id: "5001")+ provider = FakeWiseProvider.new(savings_balances: [ savings ], activities: [ interbalance ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ jar = @wise_item.wise_accounts.find_by(balance_id: "10000002")standard = @wise_item.wise_accounts.find_by(balance_id: "10000001")- assert_equal 1, jar.raw_transactions_payload.size- assert jar.raw_transactions_payload.any? { |a| a["type"] == "INTERBALANCE" }- assert standard.raw_transactions_payload.any? { |a| a["type"] == "INTERBALANCE" }+ assert_equal 1, jar.raw_transactions_payload.size+ assert jar.raw_transactions_payload.any? { |a| a["type"] == "INTERBALANCE" }+ assert standard.raw_transactions_payload.any? { |a| a["type"] == "INTERBALANCE" }+ end++ test "routes currency conversions only to the source and target STANDARD balances" do+ balances = %w[GBP EUR CHF USD].each_with_index.map do |currency, i|+ {+ "id" => "2000000#{i}",+ "amount" => { "value" => 100.0, "currency" => currency },+ "reservedAmount" => { "value" => 0.0, "currency" => currency },+ "type" => "STANDARD"+ }+ end+ gbp_to_eur = build_interbalance("To <strong>EUR</strong>", resource_id: "7001",+ primary: "117.50 EUR", secondary: "100 GBP")+ usd_to_chf = build_interbalance("To <strong>CHF</strong>", resource_id: "7002",+ primary: "1,345.20 CHF", secondary: "1,500 USD")+ provider = FakeWiseProvider.new(balances: balances, activities: [ gbp_to_eur, usd_to_chf ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ routed = @wise_item.wise_accounts.to_h do |wise_account|+ [ wise_account.currency, wise_account.raw_transactions_payload.map { |a| a["id"] } ]+ end++ assert_equal [ "interbalance_7001" ], routed["GBP"]+ assert_equal [ "interbalance_7001" ], routed["EUR"]+ assert_equal [ "interbalance_7002" ], routed["CHF"]+ assert_equal [ "interbalance_7002" ], routed["USD"]+ end++ test "drops previously stored conversions that do not involve the STANDARD balance" do+ balances = [+ { "id" => "20000001", "amount" => { "value" => 100.0, "currency" => "GBP" }, "type" => "STANDARD" }+ ]+ own = build_interbalance("To <strong>EUR</strong>", resource_id: "7005", primary: "117.50 EUR", secondary: "100 GBP")+ other = build_interbalance("To <strong>CHF</strong>", resource_id: "7006", primary: "1,345.20 CHF", secondary: "1,500 USD")+ transfer = build_transfer(id: 4242, source_currency: "GBP", target_currency: "GBP")+ gbp = @wise_item.wise_accounts.create!(balance_id: "20000001", currency: "GBP", name: "Wise GBP",+ raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ transfer, own, other ])+ provider = FakeWiseProvider.new(balances: balances, transfers: [ transfer ], activities: [])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ 4242, "interbalance_7005" ], gbp.reload.raw_transactions_payload.map { |t| t["id"] }+ end++ test "routes a cross-currency JAR move to the source STANDARD balance but not the jar-currency one" do+ balances = [+ { "id" => "20000001", "amount" => { "value" => 100.0, "currency" => "GBP" }, "type" => "STANDARD" },+ { "id" => "20000002", "amount" => { "value" => 100.0, "currency" => "EUR" }, "type" => "STANDARD" }+ ]+ savings = {+ "id" => "20000003",+ "amount" => { "value" => 0.0, "currency" => "EUR" },+ "totalWorth" => { "value" => 0.0, "currency" => "EUR" },+ "type" => "SAVINGS",+ "name" => "Holiday"+ }+ move = build_interbalance("To <strong>Holiday</strong>", resource_id: "7003",+ primary: "117.50 EUR", secondary: "100 GBP")+ provider = FakeWiseProvider.new(balances: balances, savings_balances: [ savings ], activities: [ move ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal 1, @wise_item.wise_accounts.find_by(balance_id: "20000001").raw_transactions_payload.size+ assert_empty Array(@wise_item.wise_accounts.find_by(balance_id: "20000002").raw_transactions_payload)+ assert_equal 1, @wise_item.wise_accounts.find_by(balance_id: "20000003").raw_transactions_payload.size+ end++ # A jar takes moves in its own currency only, and the balance in the move's+ # currency books its side, an outflow into the unknown jar, which support is+ # told about.+ test "does not route a same-currency JAR move to a STANDARD balance or a jar in another currency" do+ balances = [+ { "id" => "20000001", "amount" => { "value" => 100.0, "currency" => "GBP" }, "type" => "STANDARD" },+ { "id" => "20000002", "amount" => { "value" => 100.0, "currency" => "EUR" }, "type" => "STANDARD" }+ ]+ move = build_interbalance("To <strong>Jar</strong>", resource_id: "7004", primary: "1,250 EUR")+ provider = FakeWiseProvider.new(balances: balances, savings_balances: [ jar_balance("20000003", "GBP", "Jar") ], activities: [ move ])++ assert_difference -> { activity_notes.count }, 1 do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end++ assert_equal({ "20000001" => [], "20000002" => [ "interbalance_7004" ], "20000003" => [] }, payload_ids)+ assert_equal 1, activity_notes.sole.metadata["unidentified_jar_move_count"]+ eur = link_account(@wise_item.wise_accounts.find_by!(balance_id: "20000002"))+ WiseAccount::Transactions::Processor.new(eur).process+ assert_equal [ [ "wise_interbalance_7004_outflow", BigDecimal("1250") ] ], eur.current_account.entries.pluck(:external_id, :amount)+ end++ # Cashback goes to the jar in its currency only (it used to go to every jar+ # whatever its currency).+ test "routes BALANCE_CASHBACK to the jar in its currency only" do+ savings = {+ "id" => "10000002",+ "amount" => { "value" => 1000.0, "currency" => "EUR" },+ "totalWorth" => { "value" => 1000.0, "currency" => "EUR" },+ "reservedAmount" => { "value" => 0.0, "currency" => "EUR" },+ "type" => "SAVINGS",+ "name" => "Jar"+ }+ cashback = build_cashback("57001")+ provider = FakeWiseProvider.new(savings_balances: [ savings, jar_balance("10000003", "GBP", "Rainy day", 500) ], activities: [ cashback ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal({ "10000001" => [], "10000002" => [ "cashback_57001" ], "10000003" => [] }, payload_ids)+ assert_equal "10000002", @wise_item.wise_accounts.find_by!(balance_id: "10000002").raw_transactions_payload.sole["wise_jar_balance_id"]+ end++ # Jars++ # Wise names where money went, as in "To <strong>EUR</strong>" on every+ # conversion, so a move naming the balance's currency or coming "From" the+ # jar is a withdrawal: an outflow on the jar, an inflow on the balance,+ # linked as a transfer.+ test "books jar deposits and withdrawals on both sides and links them, however Wise titles them" do+ moves = [+ build_interbalance("To <strong>Holiday</strong>", resource_id: "6000", primary: "500 EUR"),+ build_interbalance("To <strong>EUR</strong>", resource_id: "6001", primary: "200 EUR"),+ build_interbalance("From <strong>EUR</strong>", resource_id: "6002", primary: "50 EUR"),+ build_interbalance("From <strong>Holiday</strong>", resource_id: "6003", primary: "30 EUR")+ ]+ provider = FakeWiseProvider.new(savings_balances: [ jar_balance("10000002", "EUR", "Holiday", 220) ], activities: moves)++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ booked = book_every_balance++ assert_equal [ [ "wise_interbalance_6000_inflow", BigDecimal("-500"), "EUR" ], [ "wise_interbalance_6001_outflow", BigDecimal("200"), "EUR" ],+ [ "wise_interbalance_6002_outflow", BigDecimal("50"), "EUR" ], [ "wise_interbalance_6003_outflow", BigDecimal("30"), "EUR" ] ],+ booked["Holiday"]+ assert_equal [ [ "wise_interbalance_6000_outflow", BigDecimal("500"), "EUR" ], [ "wise_interbalance_6001_inflow", BigDecimal("-200"), "EUR" ],+ [ "wise_interbalance_6002_inflow", BigDecimal("-50"), "EUR" ], [ "wise_interbalance_6003_inflow", BigDecimal("-30"), "EUR" ] ],+ booked["Wise EUR"]+ assert_equal 4, Transfer.where(status: "confirmed").count+ # Every copy says which jar the move was routed to.+ assert_equal [ "10000002" ], @wise_item.wise_accounts.flat_map { |wa| wa.raw_transactions_payload.map { |row| row["wise_jar_balance_id"] } }.uniq+ end++ # A move out of a jar into a balance in another currency debits the jar, not+ # the balance in the jar's currency. (The same move titled "To+ # <strong>EUR</strong>" stays a conversion between the two balances: nothing+ # in it names the jar, and Wise documents jar withdrawals in one currency+ # only.)+ test "books a move out of a jar into another currency on the jar and the receiving balance only" do+ balances = [ standard_balance("20000001", "GBP", 0), standard_balance("20000002", "EUR", 117.5) ]+ move = build_interbalance("From <strong>Holiday</strong>", resource_id: "6800", primary: "117.50 EUR", secondary: "100 GBP")+ provider = FakeWiseProvider.new(balances: balances, savings_balances: [ jar_balance("20000003", "GBP", "Holiday") ],+ borderless_accounts: [], activities: [ move ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal({ "Wise GBP" => [], "Wise EUR" => [ [ "wise_interbalance_6800_inflow", BigDecimal("-117.5"), "EUR" ] ],+ "Holiday" => [ [ "wise_interbalance_6800_outflow", BigDecimal("100"), "GBP" ] ] }, book_every_balance)+ assert_equal 1, Transfer.where(status: "confirmed").count+ end++ # Titles name a jar as it was called then. After a rename in Wise its new+ # and earlier names both route to it, and its moves from another currency+ # stay off the balance in its currency.+ test "keeps routing moves to a jar Wise renamed" do+ balances = [ standard_balance("20000001", "GBP", 0), standard_balance("20000002", "EUR", 0) ]+ old_deposit = build_interbalance("To <strong>Holiday</strong>", resource_id: "7001", primary: "100 EUR")+ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(+ balances: balances, savings_balances: [ jar_balance("20000003", "EUR", "Holiday") ], borderless_accounts: [], activities: [ old_deposit ]+ )).import++ moves = [+ old_deposit,+ build_interbalance("To <strong>Trip</strong>", resource_id: "7002", primary: "50 EUR"),+ build_interbalance("To <strong>Trip</strong>", resource_id: "7003", primary: "117.50 EUR", secondary: "100 GBP"),+ build_interbalance("To <strong>Holiday</strong>", resource_id: "7004", primary: "20 EUR")+ ]+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: FakeWiseProvider.new(+ balances: balances, savings_balances: [ jar_balance("20000003", "EUR", "Trip") ], borderless_accounts: [], activities: moves+ )).import++ assert_equal [ "Trip", [ "Holiday" ] ], @wise_item.wise_accounts.find_by!(balance_id: "20000003").raw_payload.values_at("name", "name_history")+ assert_equal({ "20000001" => %w[interbalance_7003], "20000002" => %w[interbalance_7001 interbalance_7002 interbalance_7004],+ "20000003" => %w[interbalance_7001 interbalance_7002 interbalance_7003 interbalance_7004] }, payload_ids)+ end++ # A jar Wise calls by a name now takes the moves naming it before a jar that+ # had the name earlier (renamed since), which still takes those from before+ # the new jar opened. Only jars alike in that, both called so now or both+ # before, leave a move unclear.+ test "routes a move to the jar called by its name now before a jar called so earlier" do+ { "30000001" => "Holiday", "30000003" => "Trip", "30000004" => "Trip" }.each do |balance_id, name|+ @wise_item.wise_accounts.create!(balance_id: balance_id, name: name, currency: "EUR", raw_payload: { "type" => "SAVINGS", "name" => name })+ end+ jars = [ jar_balance("30000001", "EUR", "Holiday 2025").merge("creationTime" => 400.days.ago.utc.iso8601),+ jar_balance("30000002", "EUR", "Holiday").merge("creationTime" => 2.days.ago.utc.iso8601),+ jar_balance("30000003", "EUR", "Trip to Rome"), jar_balance("30000004", "EUR", "Trip to Oslo") ]+ moves = [+ build_interbalance("To <strong>Holiday</strong>", resource_id: "9100", primary: "100 EUR").merge("createdOn" => 1.hour.ago.utc.iso8601),+ build_interbalance("To <strong>Holiday</strong>", resource_id: "9101", primary: "40 EUR").merge("createdOn" => 300.days.ago.utc.iso8601),+ build_interbalance("To <strong>Trip</strong>", resource_id: "9102", primary: "20 EUR")+ ]+ provider = FakeWiseProvider.new(balances: [ standard_balance("20000001", "EUR", 0) ], savings_balances: jars, borderless_accounts: [],+ activities: moves)++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ "Holiday 2025", [ "Holiday" ] ], @wise_item.wise_accounts.find_by!(balance_id: "30000001").raw_payload.values_at("name", "name_history")+ assert_equal({ "20000001" => %w[interbalance_9100 interbalance_9101 interbalance_9102], "30000001" => %w[interbalance_9101],+ "30000002" => %w[interbalance_9100], "30000003" => [], "30000004" => [] }, payload_ids)+ assert_equal 1, activity_notes.sole.metadata["ambiguous_jar_move_count"]+ end++ # A jar takes a move in its own currency only, and a title that is a bare+ # currency code names that currency's balance, not a jar called like it.+ test "routes a move to the jar of that name in its currency, and never to a jar named like a currency" do+ balances = [ standard_balance("20000001", "GBP", 0), standard_balance("20000002", "EUR", 117.5) ]+ jars = [ jar_balance("30000001", "GBP", "Savings", 100), jar_balance("30000002", "EUR", "Savings"), jar_balance("30000003", "GBP", "EUR") ]+ deposit = build_interbalance("To <strong>Savings</strong>", resource_id: "9003", primary: "100 GBP")+ conversion = build_interbalance("To <strong>EUR</strong>", resource_id: "7001", primary: "117.50 EUR", secondary: "100 GBP")+ provider = FakeWiseProvider.new(balances: balances, savings_balances: jars, borderless_accounts: [], activities: [ deposit, conversion ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal({ "20000001" => %w[interbalance_7001 interbalance_9003], "20000002" => %w[interbalance_7001],+ "30000001" => %w[interbalance_9003], "30000002" => [], "30000003" => [] }, payload_ids)+ end++ # Several jars fit the title, or none: a move in one currency still books on+ # the balance in that currency (its side is certain) but on no jar. A move+ # between two currencies has its jar in the currency the title points at, so+ # the balance in the other one books its side also while several jars fit.+ # Support is told once per sync. So 8103 is booked on the GBP balance and+ # the EUR jar Twin (the GBP jar also called Twin does not make the deposit+ # credited in EUR ambiguous), and 8104, between two currencies with two EUR+ # jars called Holiday, books the GBP balance's side.+ test "books no jar side of a move whose title does not tell the jar, and tells support" do+ balances = [ standard_balance("20000001", "EUR", 0), standard_balance("20000002", "GBP", 0) ]+ jars = [ jar_balance("30000001", "EUR", "Holiday"), jar_balance("30000002", "EUR", "Twin"), jar_balance("30000003", "GBP", "Twin"),+ jar_balance("30000004", "EUR", "Holiday") ]+ moves = [+ build_interbalance("To <strong>EUR</strong>", resource_id: "8101", primary: "200 EUR"),+ build_interbalance("To <strong>Savings</strong>", resource_id: "8102", primary: "100 EUR"),+ build_interbalance("To <strong>Twin</strong>", resource_id: "8103", primary: "117.50 EUR", secondary: "100 GBP"),+ build_interbalance("To <strong>Holiday</strong>", resource_id: "8104", primary: "58.75 EUR", secondary: "50 GBP")+ ]+ provider = FakeWiseProvider.new(balances: balances, savings_balances: jars, borderless_accounts: [], activities: moves)++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal({ "20000001" => %w[interbalance_8101 interbalance_8102], "20000002" => %w[interbalance_8103 interbalance_8104],+ "30000001" => [], "30000002" => %w[interbalance_8103], "30000003" => [], "30000004" => [] }, payload_ids)+ note = activity_notes.sole+ assert_equal [ "warn", 2, 1 ], [ note.level, *note.metadata.values_at("ambiguous_jar_move_count", "unidentified_jar_move_count") ]+ eur = link_account(@wise_item.wise_accounts.find_by!(balance_id: "20000001"))+ gbp = link_account(@wise_item.wise_accounts.find_by!(balance_id: "20000002"))+ [ eur, gbp ].each { |wise_account| WiseAccount::Transactions::Processor.new(wise_account).process }+ assert_equal [ [ "wise_interbalance_8101_inflow", BigDecimal("-200") ], [ "wise_interbalance_8102_outflow", BigDecimal("100") ] ],+ eur.current_account.entries.order(:external_id).pluck(:external_id, :amount)+ assert_equal [ [ "wise_interbalance_8103_outflow", BigDecimal("100") ], [ "wise_interbalance_8104_outflow", BigDecimal("50") ] ],+ gbp.current_account.entries.order(:external_id).pluck(:external_id, :amount)+ end++ # Between two currencies the title points at the jar's side. A deposit+ # ("To") credits the jar the primary amount; money taken "From" a jar is+ # debited from it, the secondary. A jar of the same name in the other+ # currency is not it, and both sides book and link.+ test "books a move between two currencies on the jar in the currency its title points at" do+ balances = [ standard_balance("20000001", "GBP", 0), standard_balance("20000002", "EUR", 0) ]+ jars = [ jar_balance("30000001", "GBP", "Savings", 50), jar_balance("30000002", "EUR", "Savings", 117.5) ]+ moves = [+ build_interbalance("To <strong>Savings</strong>", resource_id: "8301", primary: "117.50 EUR", secondary: "100 GBP"),+ build_interbalance("From <strong>Savings</strong>", resource_id: "8302", primary: "58.75 EUR", secondary: "50 GBP")+ ]+ provider = FakeWiseProvider.new(balances: balances, savings_balances: jars, borderless_accounts: [], activities: moves)++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal({ "20000001" => [ [ "wise_interbalance_8301_outflow", BigDecimal("100"), "GBP" ] ],+ "20000002" => [ [ "wise_interbalance_8302_inflow", BigDecimal("-58.75"), "EUR" ] ],+ "30000001" => [ [ "wise_interbalance_8302_outflow", BigDecimal("50"), "GBP" ] ],+ "30000002" => [ [ "wise_interbalance_8301_inflow", BigDecimal("-117.5"), "EUR" ] ] }, book_every_balance(key: :balance_id))+ assert_equal 2, Transfer.where(status: "confirmed").count+ end++ # With only the GBP jar of that name known (the EUR one closed before Sure+ # saw it), a deposit credited in EUR is not taken out of the GBP jar, also+ # where a stored copy says it went there (as an earlier build decided), and+ # the GBP balance books its debit.+ test "never books a deposit as a withdrawal from a jar of its name in the other currency" do+ move = build_interbalance("To <strong>Savings</strong>", resource_id: "8105", primary: "117.50 EUR", secondary: "100 GBP")+ @wise_item.wise_accounts.create!(balance_id: "30000001", name: "Savings", currency: "GBP", raw_payload: { "type" => "SAVINGS", "name" => "Savings" },+ raw_transactions_payload: [ move.merge("wise_jar_balance_id" => "30000001") ])+ balances = [ standard_balance("20000001", "GBP", 0), standard_balance("20000002", "EUR", 0) ]+ provider = FakeWiseProvider.new(balances: balances, savings_balances: [ jar_balance("30000001", "GBP", "Savings", 100) ],+ borderless_accounts: [], activities: [ move ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_empty payload_ids["30000001"]+ gbp = link_account(@wise_item.wise_accounts.find_by!(balance_id: "20000001"))+ WiseAccount::Transactions::Processor.new(gbp).process+ assert_equal [ [ "wise_interbalance_8105_outflow", BigDecimal("100"), "GBP" ] ], gbp.current_account.entries.pluck(:external_id, :amount, :currency)+ end++ # An older build booked the debit of a deposit into the EUR jar Savings on+ # the GBP balance, and both jars called Savings booked its credit. The first+ # sync after keeps the debit and the EUR jar's credit; only the GBP jar's+ # copy goes.+ test "keeps what an older build booked right for a move between two currencies" do+ move = build_interbalance("To <strong>Savings</strong>", resource_id: "8103", primary: "117.50 EUR", secondary: "100 GBP")+ stored = { [ "20000001", "Wise GBP", "GBP", "STANDARD" ] => [ move ], [ "20000002", "Wise EUR", "EUR", "STANDARD" ] => [],+ [ "30000001", "Savings", "GBP", "SAVINGS" ] => [ move ], [ "30000002", "Savings", "EUR", "SAVINGS" ] => [ move ] }+ accounts = stored.to_h do |(balance_id, name, currency, type), rows|+ wise_account = @wise_item.wise_accounts.create!(balance_id: balance_id, name: name, currency: currency, raw_transactions_payload: rows,+ raw_payload: { "type" => type, "name" => (name if type == "SAVINGS") }.compact)+ [ balance_id, link_account(wise_account).current_account ]+ end+ book = ->(balance_id, external_id, amount, currency) {+ accounts[balance_id].entries.create!(external_id: external_id, source: "wise", amount: amount, currency: currency,+ date: 7.days.ago.to_date, name: "Jar move", entryable: Transaction.new)+ }+ debit = book.call("20000001", "wise_interbalance_8103_outflow", 100, "GBP")+ credit = book.call("30000002", "wise_interbalance_8103_inflow", -117.5, "EUR")+ copy = book.call("30000001", "wise_interbalance_8103_inflow", -117.5, "EUR")+ balances = [ standard_balance("20000001", "GBP", 0), standard_balance("20000002", "EUR", 0) ]+ jars = [ jar_balance("30000001", "GBP", "Savings", 100), jar_balance("30000002", "EUR", "Savings", 117.5) ]+ provider = FakeWiseProvider.new(balances: balances, savings_balances: jars, borderless_accounts: [], activities: [ move ],+ raise_on: { get_balance_statements: statements_forbidden })++ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])++ assert result[:complete]+ assert_equal [ [ debit.id, BigDecimal("100") ], [ credit.id, BigDecimal("-117.5") ] ],+ Entry.where(account_id: accounts.values.map(&:id), source: "wise").order(amount: :desc).pluck(:id, :amount)+ assert_not Entry.exists?(copy.id)+ end++ # While several jars fit a move (two EUR jars called Twin), a copy an+ # earlier sync stored stays: on the one of them that holds it, which keeps+ # the move from then on, or on each that holds it, so the clean-up deletes+ # none of their entries. A move no sync stored books only on the balance on+ # its other side.+ test "keeps a move that several jars fit on the jars an earlier sync stored it on" do+ held_by_both = build_interbalance("To <strong>Twin</strong>", resource_id: "8201", primary: "117.50 EUR", secondary: "100 GBP")+ held_by_one = build_interbalance("To <strong>Twin</strong>", resource_id: "8202", primary: "58.75 EUR", secondary: "50 GBP")+ in_one_currency = build_interbalance("To <strong>Twin</strong>", resource_id: "8203", primary: "30 EUR")+ unseen = build_interbalance("To <strong>Twin</strong>", resource_id: "8204", primary: "23.50 EUR", secondary: "20 GBP")+ stored = { [ "20000001", "Wise GBP", "GBP", "STANDARD" ] => [ held_by_both, held_by_one ],+ [ "20000002", "Wise EUR", "EUR", "STANDARD" ] => [ in_one_currency ],+ [ "30000001", "Twin", "EUR", "SAVINGS" ] => [ held_by_both, held_by_one, in_one_currency ],+ [ "30000002", "Twin", "EUR", "SAVINGS" ] => [ held_by_both, in_one_currency ] }+ stored.each do |(balance_id, name, currency, type), rows|+ @wise_item.wise_accounts.create!(balance_id: balance_id, name: name, currency: currency, raw_transactions_payload: rows,+ raw_payload: { "type" => type, "name" => (name if type == "SAVINGS") }.compact)+ end+ balances = [ standard_balance("20000001", "GBP", 0), standard_balance("20000002", "EUR", 0) ]+ jars = [ jar_balance("30000001", "EUR", "Twin"), jar_balance("30000002", "EUR", "Twin") ]+ provider = FakeWiseProvider.new(balances: balances, savings_balances: jars, borderless_accounts: [],+ activities: [ held_by_both, held_by_one, in_one_currency, unseen ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal({ "20000001" => %w[interbalance_8201 interbalance_8202 interbalance_8204], "20000002" => %w[interbalance_8203],+ "30000001" => %w[interbalance_8201 interbalance_8202 interbalance_8203], "30000002" => %w[interbalance_8201 interbalance_8203] },+ payload_ids)+ decided = @wise_item.wise_accounts.flat_map { |wise_account| wise_account.raw_transactions_payload.map { |row| row.values_at("id", "wise_jar_balance_id") } }+ assert_equal({ "interbalance_8201" => [ nil ], "interbalance_8202" => [ "30000001" ], "interbalance_8203" => [ nil ], "interbalance_8204" => [ nil ] },+ decided.group_by(&:first).transform_values { |pairs| pairs.map(&:last).uniq })+ assert_equal 3, activity_notes.sole.metadata["ambiguous_jar_move_count"]+ end++ # Interest, cashback and fees on holdings go to the jar or invested balance+ # in their currency (the one the title names when there are several), else+ # to the balance in their currency; when it stays unclear, nowhere, and+ # support is told.+ test "routes interest and fees to the jar or invested balance in their currency" do+ balances = [ standard_balance("20000001", "EUR", 0), standard_balance("20000002", "USD", 0).merge("investmentState" => "INVESTED"),+ standard_balance("20000003", "GBP", 0) ]+ jars = [ jar_balance("30000001", "EUR", "Holiday"), jar_balance("30000002", "CHF", "Rainy day"), jar_balance("30000003", "CHF", "House") ]+ activities = [+ holding_activity("cashback_eur", "BALANCE_CASHBACK", "<positive>+ 1.12 EUR</positive>", title: "<strong>Cashback</strong>"),+ holding_activity("interest_usd", "BALANCE_INTEREST", "<positive>+ 0.42 USD</positive>"),+ holding_activity("asset_fee_usd", "BALANCE_ASSET_FEE", "0.06 USD", title: "<strong>Wise Assets fee</strong>"),+ holding_activity("interest_gbp", "BALANCE_INTEREST", "<positive>+ 0.10 GBP</positive>"),+ holding_activity("cashback_chf", "BALANCE_CASHBACK", "<positive>+ 0.50 CHF</positive>", title: "<strong>Cashback</strong>"),+ holding_activity("interest_chf", "BALANCE_INTEREST", "<positive>+ 0.20 CHF</positive>", title: "Interest on <strong>House</strong>")+ ]+ provider = FakeWiseProvider.new(balances: balances, savings_balances: jars, borderless_accounts: [], activities: activities,+ raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal({ "20000001" => [], "20000002" => %w[asset_fee_usd interest_usd], "20000003" => %w[interest_gbp],+ "30000001" => %w[cashback_eur], "30000002" => [], "30000003" => %w[interest_chf] }, payload_ids)+ note = activity_notes.sole+ assert_equal [ "warn", 1 ], [ note.level, note.metadata["ambiguous_holding_count"] ]+ end++ # Where a jar move or holding row first went is kept on every stored copy+ # ("wise_jar_balance_id") and honoured, so a second jar in the currency or a+ # jar opened later takes no row booked elsewhere; only new rows follow the+ # new jars.+ test "keeps each jar move and interest row on the balance it was first routed to" do+ balances = [ standard_balance("20000001", "EUR", 0), standard_balance("20000002", "GBP", 0) ]+ withdrawal = build_interbalance("To <strong>EUR</strong>", resource_id: "8001", primary: "200 EUR")+ interest_eur = holding_activity("interest_eur", "BALANCE_INTEREST", "<positive>+ 0.42 EUR</positive>")+ interest_gbp = holding_activity("interest_gbp", "BALANCE_INTEREST", "<positive>+ 0.10 GBP</positive>")+ sync = lambda do |jars, activities|+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: FakeWiseProvider.new(+ balances: balances, savings_balances: jars, borderless_accounts: [], activities: activities+ )).import+ end++ sync.call([ jar_balance("30000001", "EUR", "Holiday") ], [ withdrawal, interest_eur, interest_gbp ])+ assert_equal({ "20000001" => %w[interbalance_8001], "20000002" => %w[interest_gbp], "30000001" => %w[interbalance_8001 interest_eur] },+ payload_ids)++ later_jars = [ jar_balance("30000001", "EUR", "Holiday"), jar_balance("30000002", "EUR", "House"), jar_balance("30000003", "GBP", "Trip") ]+ interest_trip = holding_activity("interest_trip", "BALANCE_INTEREST", "<positive>+ 0.05 GBP</positive>", created_on: 1.hour.ago.utc.iso8601(3))+ assert_no_difference -> { activity_notes.count } do+ sync.call(later_jars, [ withdrawal, interest_eur, interest_gbp, interest_trip ])+ end+ expected = { "20000001" => %w[interbalance_8001], "20000002" => %w[interest_gbp], "30000001" => %w[interbalance_8001 interest_eur],+ "30000002" => [], "30000003" => %w[interest_trip] }+ assert_equal expected, payload_ids++ # Rows the window no longer reaches stay where they went.+ sync.call(later_jars, [])+ assert_equal expected, payload_ids+ end++ # A jar takes no row from before Wise opened it, such as interest stored+ # on the balance that earned it before Sure kept where rows went.+ test "leaves interest from before a jar was opened on the balance that earned it" do+ interest = holding_activity("interest_gbp", "BALANCE_INTEREST", "<positive>+ 0.10 GBP</positive>", created_on: 10.days.ago.utc.iso8601(3))+ @wise_item.wise_accounts.create!(balance_id: "20000002", currency: "GBP", name: "Wise GBP", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ interest ])+ jar = jar_balance("30000003", "GBP", "Trip").merge("creationTime" => 2.days.ago.utc.iso8601)+ provider = FakeWiseProvider.new(balances: [ standard_balance("20000002", "GBP", 0) ], savings_balances: [ jar ], borderless_accounts: [],+ activities: [ interest ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal({ "20000002" => %w[interest_gbp], "30000003" => [] }, payload_ids)+ assert_equal "20000002", @wise_item.wise_accounts.find_by!(balance_id: "20000002").raw_transactions_payload.sole["wise_jar_balance_id"]+ end++ # The interest a jar earned is booked once, on the jar, also while syncs+ # after the jar closed still fetch it.+ test "books the interest a jar earned once, also after the jar closed" do+ interest = holding_activity("interest_1", "BALANCE_INTEREST", "<positive>+ 0.42 EUR</positive>", created_on: 5.days.ago.utc.iso8601(3))+ sync = lambda do |jars|+ provider = FakeWiseProvider.new(balances: [ standard_balance("10000001", "EUR", 100) ], savings_balances: jars, borderless_accounts: [],+ activities: [ interest ], raise_on: { get_balance_statements: statements_forbidden })+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ end+ jar = jar_balance("10000002", "EUR", "Holiday")++ sync.call([ jar ])+ @wise_item.wise_accounts.reload.each { |wise_account| link_account(wise_account) }+ sync.call([ jar ])+ 2.times { sync.call([]) }++ assert @wise_item.wise_accounts.reload.find(&:jar?).closed?+ assert_equal [ "Holiday" ], Entry.where(source: "wise", external_id: "wise_activity_interest_1").map { |entry| entry.account.name }+ end++ # A jar linked after the first sync books the moves that sync stored, and+ # the leg of a withdrawal Sure had booked on the wrong side is renamed in+ # place, so both link.+ test "a jar linked after the first sync books its stored moves and renames a leg booked on the wrong side" do+ jar = jar_balance("10000002", "EUR", "Holiday", 250)+ deposit = build_interbalance("To <strong>Holiday</strong>", resource_id: "9001", primary: "300 EUR").merge("createdOn" => 30.days.ago.utc.iso8601)+ withdrawal = build_interbalance("From <strong>Holiday</strong>", resource_id: "9002", primary: "50 EUR").merge("createdOn" => 20.days.ago.utc.iso8601)+ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(savings_balances: [ jar ], activities: [ deposit, withdrawal ])).import+ eur = link_account(@wise_item.wise_accounts.find_by!(balance_id: "10000001"))+ holiday = link_account(@wise_item.wise_accounts.find_by!(balance_id: "10000002"))+ old_leg = eur.current_account.entries.create!(external_id: "wise_interbalance_9002_outflow", source: "wise", amount: -50, currency: "EUR",+ date: 20.days.ago.to_date, name: "Transfer from Holiday", entryable: Transaction.new)++ # The sync that linking starts reaches back only weeks.+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: FakeWiseProvider.new(savings_balances: [ jar ])).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ @wise_item.link_jar_transfers!++ assert_equal [ [ "wise_interbalance_9001_inflow", BigDecimal("-300") ], [ "wise_interbalance_9002_outflow", BigDecimal("50") ] ],+ holiday.current_account.entries.order(:external_id).pluck(:external_id, :amount)+ assert_equal [ [ "wise_interbalance_9001_outflow", BigDecimal("300") ], [ "wise_interbalance_9002_inflow", BigDecimal("-50") ] ],+ eur.current_account.entries.order(:external_id).pluck(:external_id, :amount)+ assert_equal "wise_interbalance_9002_inflow", old_leg.reload.external_id+ assert_equal 2, Transfer.where(status: "confirmed").count+ end++ # Single-leg activities on balances without statements: the feed is the only+ # source of card payments, refunds, cash and direct debits, here in each+ # shape Wise reports them.+ test "books each card, cash and direct debit shape on the balance it moved money on" do+ @family.update!(timezone: "Europe/Dublin")+ activities = [+ build_card_activity("same_currency", "37.65 CHF", created_on: "2026-09-08T14:26:51.473Z"),+ build_card_activity("late_evening", "15 CHF", created_on: "2026-06-24T23:18:42.519Z"),+ build_card_activity("auto_converted", "7.40 CHF", "6.42 GBP", created_on: "2026-04-09T13:07:36.928Z"),+ build_card_activity("paid_from_chf", "2.84 GBP", "3.29 CHF", created_on: "2026-03-17T17:52:04.211Z"),+ build_card_activity("refund", "<positive>+ 0.64 CHF</positive>", created_on: "2026-08-04T00:26:13.684Z"),+ build_card_activity("split_card", "17.60 CHF", "AUD, CHF", created_on: "2026-03-25T10:41:58.032Z"),+ build_card_activity("atm", "120 CHF", "GBP, CHF", type: "CASH_WITHDRAWAL", created_on: "2026-09-29T15:33:21.137Z"),+ build_card_activity("declined_atm", "120 CHF", "122.70 CHF", type: "CASH_WITHDRAWAL", status: "CANCELLED",+ created_on: "2026-04-15T19:08:33.836Z"),+ build_card_activity("card_check", "0 CHF", type: "CARD_CHECK", status: "CANCELLED", created_on: "2026-07-08T08:14:55.817Z"),+ build_card_activity("direct_debit", "83.10 CAD", type: "DIRECT_DEBIT_TRANSACTION", resource_type: "DIRECT_DEBIT_TRANSACTION",+ created_on: "2026-06-15T05:46:29.302Z")+ ]+ provider = FakeWiseProvider.new(balances: balances_in(%w[GBP CHF AUD CAD]), borderless_accounts: [],+ activities: activities, raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ stored = @wise_item.wise_accounts.to_h { |wa| [ wa.currency, Array(wa.raw_transactions_payload).map { |row| row["id"] }.sort ] }+ assert_equal({ "GBP" => %w[atm auto_converted],+ "CHF" => %w[atm declined_atm late_evening paid_from_chf refund same_currency split_card],+ "AUD" => %w[split_card], "CAD" => %w[direct_debit] }, stored)++ booked = @wise_item.wise_accounts.to_h do |wise_account|+ wise_account = link_account(wise_account)+ assert WiseAccount::Transactions::Processor.new(wise_account).process[:success]+ [ wise_account.currency, wise_account.current_account.entries.order(:external_id).pluck(:external_id, :amount, :date) ]+ end+ # Without a balance replay a split payment books in full on the+ # merchant-currency balance (CHF); 23:18Z on 24 June is 25 June in Dublin.+ assert_equal({+ "GBP" => [ [ "wise_activity_auto_converted", BigDecimal("6.42"), Date.new(2026, 4, 9) ] ],+ "CHF" => [ [ "wise_activity_atm", BigDecimal("120"), Date.new(2026, 9, 29) ],+ [ "wise_activity_late_evening", BigDecimal("15"), Date.new(2026, 6, 25) ],+ [ "wise_activity_paid_from_chf", BigDecimal("3.29"), Date.new(2026, 3, 17) ],+ [ "wise_activity_refund", BigDecimal("-0.64"), Date.new(2026, 8, 4) ],+ [ "wise_activity_same_currency", BigDecimal("37.65"), Date.new(2026, 9, 8) ],+ [ "wise_activity_split_card", BigDecimal("17.60"), Date.new(2026, 3, 25) ] ],+ "AUD" => [],+ "CAD" => [ [ "wise_activity_direct_debit", BigDecimal("83.10"), Date.new(2026, 6, 15) ] ]+ }, booked)+ end++ # A deposit into the account details from a bank or another Wise profile has+ # no /v1/transfers row, so its activity is booked; the activity of a+ # transfer Sure has only enriches that transfer.+ test "books a deposit for no transfer Sure has, and only attaches one for a transfer it has" do+ top_up = build_transfer(id: 9000000104, target_account: 99999001)+ matched = build_transfer_activity(9000000104, primary: "<positive>+ 100 EUR</positive>").merge("type" => "BALANCE_DEPOSIT")+ deposit = build_transfer_activity(77001, id: "bank_deposit", primary: "<positive>+ 450 EUR</positive>").merge("type" => "BALANCE_DEPOSIT")+ unknown_payout = build_transfer_activity(77002, id: "unknown_payout", primary: "30 EUR")+ provider = FakeWiseProvider.new(transfers: [ top_up ], activities: [ matched, deposit, unknown_payout ],+ raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ eur = link_account(@wise_item.wise_accounts.first)+ assert_equal [ "9000000104", "bank_deposit" ], eur.raw_transactions_payload.map { |row| row["id"].to_s }.sort+ WiseAccount::Transactions::Processor.new(eur).process+ assert_equal({ "wise_transfer_9000000104" => BigDecimal("-100"), "wise_activity_bank_deposit" => BigDecimal("-450") },+ eur.current_account.entries.pluck(:external_id, :amount).to_h)++ # A later sync whose transfer list fails keeps the booked deposit.+ failing = FakeWiseProvider.new(activities: [ matched, deposit, unknown_payout ],+ raise_on: { get_transfers: "Unexpected response 502", get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(@wise_item, wise_provider: failing).import+ assert_equal [ "9000000104", "bank_deposit" ], eur.reload.raw_transactions_payload.map { |row| row["id"].to_s }.sort+ end++ test "waits for a sync whose transfer list arrived before booking a deposit for an unknown transfer" do+ deposit = build_transfer_activity(77001, id: "late_transfer", primary: "<positive>+ 450 EUR</positive>").merge("type" => "BALANCE_DEPOSIT")+ failing = FakeWiseProvider.new(activities: [ deposit ],+ raise_on: { get_transfers: "Unexpected response 502", get_balance_statements: statements_forbidden })++ assert_difference -> { activity_notes.count }, 1 do+ WiseItem::Importer.new(@wise_item, wise_provider: failing).import+ end+ assert_equal 1, activity_notes.recent.first.metadata["deferred_transfer_count"]+ eur = @wise_item.wise_accounts.first+ assert_empty Array(eur.raw_transactions_payload)++ # The transfer was only late: once listed, the activity just enriches it.+ late = build_transfer(id: 77001, target_account: 99999001).merge("sourceValue" => 450.0, "targetValue" => 450.0)+ recovered = FakeWiseProvider.new(transfers: [ late ], activities: [ deposit ],+ raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(@wise_item, wise_provider: recovered).import++ stored = eur.reload.raw_transactions_payload.sole+ assert_equal [ 77001, "late_transfer" ], [ stored["id"], stored.dig("wise_activity", "id") ]+ end++ # The sync that defers a deposit (its transfer list failed) read its+ # activities in full, and covering them ran the next window from 30 days+ # before that sync: a deposit older than that was never fetched again, nor+ # booked. Activity coverage now ends a day before the oldest deferred one.+ test "fetches a deferred deposit again and books it once a transfer list arrives" do+ travel_to Time.utc(2026, 10, 17, 12) do+ salary = build_transfer_activity(77001, id: "salary_july", primary: "<positive>+ 450 EUR</positive>",+ created_on: 90.days.ago.utc.iso8601(3)).merge("type" => "BALANCE_DEPOSIT")+ failing = FakeWiseProvider.new(activities: [ salary ], windowed_activities: true,+ raise_on: { get_transfers: "Unexpected response 502", get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(@wise_item, wise_provider: failing).import+ eur = @wise_item.wise_accounts.sole+ assert_empty Array(eur.raw_transactions_payload)+ assert_equal 91.days.ago.utc.iso8601, @wise_item.reload.raw_payload.dig("coverage", "activities", "through")++ travel 1.day+ recovered = FakeWiseProvider.new(activities: [ salary ], windowed_activities: true, raise_on: { get_balance_statements: statements_forbidden })+ assert WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: recovered).import[:complete]++ assert_equal Time.utc(2026, 6, 18, 12), recovered.activity_requests.sole[:since]+ assert_equal [ "salary_july" ], eur.reload.raw_transactions_payload.map { |row| row["id"] }+ assert_equal "2026-10-18T12:00:00Z", @wise_item.reload.raw_payload.dig("coverage", "activities", "through")+ end+ end++ # Transfers are listed before activities, so a top-up created in between was+ # missing from the list, booked from its activity, then once more from its+ # transfer on the next sync. A credit for a transfer Sure does not have,+ # created after the list was read, now waits for the next sync's list (and+ # no balance is replayed meanwhile).+ test "books a top-up created after the transfer list was read once, from its transfer" do+ travel_to Time.utc(2026, 10, 17, 12) do+ payout = build_transfer(id: 1).merge("created" => 20.days.ago.utc.strftime("%Y-%m-%d %H:%M:%S"))+ eur = link_account(@wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [ payout ]))+ top_up_activity = build_transfer_activity(88001, id: "top_up", primary: "<positive>+ 450 EUR</positive>", title: "To <strong>EUR</strong>",+ created_on: Time.current.utc.iso8601(3)).merge("type" => "BALANCE_DEPOSIT")+ listed_first = FakeWiseProvider.new(transfers: [ payout ], activities: [ top_up_activity ], raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: listed_first).import+ assert_equal [ :get_transfers, :get_activities ], listed_first.calls & [ :get_transfers, :get_activities ]+ assert_equal 1, activity_notes.sole.metadata["deferred_transfer_count"]+ WiseAccount::Transactions::Processor.new(eur.reload).process++ travel 1.day+ top_up = build_transfer(id: 88001, target_account: 99999001).merge("sourceValue" => 450.0, "targetValue" => 450.0,+ "created" => 1.day.ago.utc.strftime("%Y-%m-%d %H:%M:%S"))+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: FakeWiseProvider.new(+ transfers: [ payout, top_up ], activities: [ top_up_activity ], raise_on: { get_balance_statements: statements_forbidden }+ )).import+ WiseAccount::Transactions::Processor.new(eur.reload).process++ assert_equal [ [ "wise_transfer_88001", BigDecimal("-450") ] ], eur.current_account.entries.where("amount < 0").pluck(:external_id, :amount)+ end+ end++ # A credit deferred while this sync asked for no transfer list at all+ # (statements carry the balances' movements) does not hold the activity+ # coverage back: no later sync is sure to list transfers either.+ test "does not hold activity coverage back for a deposit no transfer list was asked for" do+ travel_to Time.utc(2026, 10, 17, 12) do+ deposit = build_transfer_activity(77001, id: "bank_deposit", primary: "<positive>+ 450 EUR</positive>",+ created_on: 90.days.ago.utc.iso8601(3)).merge("type" => "BALANCE_DEPOSIT")+ @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ statement_row("CARD-1", "-5", "EUR").merge("wise_statement" => true) ])+ provider = FakeWiseProvider.new(activities: [ deposit ], statements: [])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_not_includes provider.calls, :get_transfers+ assert_equal 1, activity_notes.sole.metadata["deferred_transfer_count"]+ assert_equal "2026-10-17T12:00:00Z", @wise_item.reload.raw_payload.dig("coverage", "activities", "through")+ end+ end++ test "drops a stored deposit once Sure has the transfer it belongs to" do+ deposit = build_transfer_activity(77001, id: "bank_deposit", primary: "<positive>+ 450 EUR</positive>").merge("type" => "BALANCE_DEPOSIT")+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [ deposit ])+ transfer = build_transfer(id: 77001, target_account: 99999001)+ provider = FakeWiseProvider.new(transfers: [ transfer ], raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ 77001 ], eur.reload.raw_transactions_payload.map { |row| row["id"] }+ end++ # Wrapper types move money as transfers Sure already imports, and the rest+ # have not been seen; none is booked.+ # Booked in full on the first balance the payment lists, which support+ # should know is an estimate.+ test "tells support about a split payment in a currency none of its balances is in" do+ provider = FakeWiseProvider.new(balances: [ eur_balance("10000001", 10.0), standard_balance("10000002", "GBP", 10.0) ],+ borderless_accounts: [], activities: [ build_card_activity("split_usd", "100 USD", "GBP, EUR") ],+ raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ [ "split_usd" ], [ "split_usd" ] ], payload_ids.values_at("10000001", "10000002")+ note = activity_notes.sole+ assert_equal [ "warn", 1 ], [ note.level, note.metadata["foreign_split_count"] ]+ end++ test "stores no activity Sure cannot book and reports them once per sync" do+ activities = [+ build_card_activity("card_check", "0 EUR", type: "CARD_CHECK", status: "CANCELLED"),+ build_card_activity("scheduled_1", "50 EUR", type: "SCHEDULED_SEND_ORDER", resource_type: "SEND_ORDER"),+ build_card_activity("scheduled_2", "60 EUR", type: "SCHEDULED_SEND_ORDER", resource_type: "SEND_ORDER"),+ build_card_activity("fee_refund", "<positive>+ 1 EUR</positive>", type: "FEE_REFUND"),+ build_card_activity("paid_from_chf", "10 EUR", "9.50 CHF")+ ]+ provider = FakeWiseProvider.new(activities: activities, raise_on: { get_balance_statements: statements_forbidden })++ assert_difference -> { activity_notes.count }, 1 do+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end++ assert_empty Array(@wise_item.wise_accounts.first.raw_transactions_payload)+ note = activity_notes.recent.first+ assert_equal "warn", note.level+ assert_equal({ "CARD_CHECK" => 1, "SCHEDULED_SEND_ORDER" => 2, "FEE_REFUND" => 1 }, note.metadata["unbooked_type_counts"])+ assert_equal [ 1, [ "CHF" ] ], note.metadata.values_at("unrouted_count", "unrouted_currencies")+ end++ test "routes an auto-conversion to both balances and links its legs" do+ conversion = build_interbalance("To <strong>EUR</strong>", resource_id: "9001", primary: "117.50 EUR", secondary: "100 GBP")+ .merge("type" => "AUTO_CONVERSION", "id" => "auto_conversion_9001")+ provider = FakeWiseProvider.new(balances: balances_in(%w[GBP EUR]), borderless_accounts: [], activities: [ conversion ],+ raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ legs = @wise_item.wise_accounts.to_h do |wise_account|+ wise_account = link_account(wise_account)+ WiseAccount::Transactions::Processor.new(wise_account).process+ [ wise_account.currency, wise_account.current_account.entries.pluck(:external_id, :amount) ]+ end+ @wise_item.link_jar_transfers!++ assert_equal({ "GBP" => [ [ "wise_interbalance_9001_outflow", BigDecimal("100") ] ],+ "EUR" => [ [ "wise_interbalance_9001_inflow", BigDecimal("-117.50") ] ] }, legs)+ transfer = Transfer.find_by!(inflow_transaction_id: Entry.find_by!(external_id: "wise_interbalance_9001_inflow").entryable_id)+ assert_equal "wise_interbalance_9001_outflow", transfer.outflow_transaction.entry.external_id+ # Linked by WiseItem::InterbalanceLinker like any conversion: confirmed,+ # with transfer kinds on both legs.+ assert transfer.confirmed?+ assert_equal %w[funds_movement funds_movement], [ transfer.inflow_transaction, transfer.outflow_transaction ].map { |txn| txn.reload.kind }+ end++ # A balance's statement rows already carry its card payments, so the+ # activity feed must not book them again, also on the first sync where its+ # statements arrive.+ test "leaves card payments to the statements of the balances they cover" do+ balances = balances_in(%w[EUR USD GBP])+ eur = @wise_item.wise_accounts.create!(+ balance_id: balances[0]["id"], name: "Wise EUR", currency: "EUR", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ statement_row("CARD-1", "-5.00", "EUR").merge("wise_statement" => true) ]+ )+ usd = @wise_item.wise_accounts.create!(+ balance_id: balances[1]["id"], name: "Wise USD", currency: "USD", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ build_card_activity("usd_earlier", "4 USD") ]+ )+ activities = [ build_card_activity("eur_card", "12 EUR"), build_card_activity("usd_card", "3.40 USD"),+ build_card_activity("gbp_card", "7.40 EUR", "6.42 GBP") ]+ provider = FakeWiseProvider.new(balances: balances, borderless_accounts: [], activities: activities)+ statements_by_balance = { balances[1]["id"] => [ statement_row("CARD-2", "-3.40", "USD") ] }+ provider.define_singleton_method(:get_balance_statements) do |_profile_id, balance_id, **|+ statements_by_balance.fetch(balance_id, [])+ end++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ "CARD-1" ], eur.reload.raw_transactions_payload.map { |row| row["referenceNumber"] }+ assert_equal [ [ nil, "CARD-2" ] ], usd.reload.raw_transactions_payload.map { |row| row.values_at("id", "referenceNumber") }+ assert_equal [ "gbp_card" ], @wise_item.wise_accounts.find_by!(currency: "GBP").raw_transactions_payload.map { |row| row["id"] }+ end++ test "books a card payment on the open balance of a reopened currency, not the closed one" do+ closed = @wise_item.wise_accounts.create!(balance_id: "10000009", name: "Wise EUR (closed)", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "closed_at" => 10.days.ago.utc.iso8601 })+ provider = FakeWiseProvider.new(activities: [ build_card_activity("card_1", "12 EUR") ],+ raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ "card_1" ], @wise_item.wise_accounts.find_by!(balance_id: "10000001").raw_transactions_payload.map { |row| row["id"] }+ assert_empty Array(closed.reload.raw_transactions_payload)+ end++ # The row-kind predicate: a stored card payment is not a /v1/transfers row,+ # so it neither asks for the transfer fallback nor starts the legacy window+ # whose outgoing statement rows used to be dropped.+ test "does not treat stored card payments as legacy transfers" do+ @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ build_card_activity("card_1", "12 EUR", created_on: "2024-01-10T10:00:00Z") ])+ provider = FakeWiseProvider.new(statements: [ statement_row("CARD-555", "-12.50", "EUR", date: "2024-01-15T10:00:00Z") ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ refute_includes provider.calls, :get_transfers+ assert_includes @wise_item.wise_accounts.first.raw_transactions_payload.map { |row| row["referenceNumber"] }, "CARD-555"+ end++ # Interest and fees go to the balance in their currency when no jar or+ # invested balance in it takes them; a jar closed before they were paid+ # takes none.+ test "routes balance interest to the balance in its currency while the profile has no open jar" do+ closed_jar = @wise_item.wise_accounts.create!(balance_id: "50000009", name: "Old jar", currency: "EUR",+ raw_payload: { "type" => "SAVINGS", "closed_at" => 10.days.ago.utc.iso8601 })+ interest = build_card_activity("interest_eur", "<positive>+ 0.42 EUR</positive>", type: "BALANCE_INTEREST", resource_type: "BALANCE_INTEREST")+ cashback = build_card_activity("cashback_gbp", "0.10 GBP", type: "BALANCE_CASHBACK", resource_type: "BALANCE_CASHBACK")+ provider = FakeWiseProvider.new(balances: balances_in(%w[GBP EUR]), borderless_accounts: [], activities: [ interest, cashback ],+ raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ routed = @wise_item.wise_accounts.reject(&:jar?).to_h { |wa| [ wa.currency, wa.raw_transactions_payload.map { |row| row["id"] } ] }+ assert_equal({ "GBP" => [ "cashback_gbp" ], "EUR" => [ "interest_eur" ] }, routed)+ assert_empty Array(closed_jar.reload.raw_transactions_payload)+ end++ test "stores an activity in any status and books it once Wise completes it" do+ pending = build_card_activity("card_1", "12 EUR", status: "IN_PROGRESS")+ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(+ activities: [ pending ], raise_on: { get_balance_statements: statements_forbidden }+ )).import+ eur = link_account(@wise_item.wise_accounts.first)++ assert_equal [ "IN_PROGRESS" ], eur.raw_transactions_payload.map { |row| row["status"] }+ assert_equal 1, WiseAccount::Transactions::Processor.new(eur).process[:skipped]+ assert_empty eur.current_account.entries++ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(+ activities: [ pending.merge("status" => "COMPLETED") ], raise_on: { get_balance_statements: statements_forbidden }+ )).import+ WiseAccount::Transactions::Processor.new(eur.reload).process++ assert_equal [ [ "wise_activity_card_1", BigDecimal("12") ] ], eur.current_account.entries.pluck(:external_id, :amount)+ end++ # Balance replay++ # A synthetic multi-currency profile (fixture: every id, name, amount, rate+ # and time made up). Every balance replays from zero to its live amount: the+ # split parts are the ones the profile was built with (the ATM's 7.85 PLN+ # fee is the 1.74 CHF the CHF balance paid of it), and the only payouts a+ # balance cannot have paid are the CHF to CAD transfer a card paid (CHF held+ # at most 182.23 of its 421.86) and a CHF to DKK one a bank transfer paid+ # (CHF held at most 358.21 of its 486.40). That one follows a top-up and a+ # card payment one summer night after 23:00 UTC (the next day in Dublin):+ # only with Wise's times read as UTC do the three replay in order.+ test "replays a synthetic multi-currency profile to its split parts and its card-funded payout" do+ travel_to Time.utc(2026, 10, 17, 12) do+ @family.update!(timezone: "Europe/Dublin")+ @wise_item.update!(import_all_history: true)+ provider = profile_provider++ # Its transfers in pages Wise takes, and its statements unavailable+ # without a warning per balance.+ assert_no_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error").count } do+ assert_difference -> { replay_notes.where(level: "info").count }, 1 do+ assert WiseItem::Importer.new(@wise_item, wise_provider: provider).import[:complete]+ end+ end+ # Read again after the transfers and activities, unchanged.+ assert_equal 2, provider.calls.count(:get_balances)++ atm, sek_card, chf_card = %w[evt-109 evt-120 evt-124]+ assert_equal({+ "PLN" => [ [ atm, { "CHF" => "1.74", "PLN" => "400.00" }, [ "CHF" ] ],+ [ sek_card, { "SEK" => "262.45", "PLN" => "44.65" }, nil ],+ [ chf_card, { "CHF" => "12.95", "PLN" => "93.85" }, [ "CHF" ] ] ],+ "CHF" => [ [ atm, { "CHF" => "1.74", "PLN" => "400.00" }, [ "CHF" ] ],+ [ chf_card, { "CHF" => "12.95", "PLN" => "93.85" }, [ "CHF" ] ] ],+ "SEK" => [ [ sek_card, { "SEK" => "262.45", "PLN" => "44.65" }, nil ] ]+ }, split_marks)+ assert_equal [ [ "CHF", 62000107 ], [ "CHF", 62000113 ] ], funding_marks+ assert_equal [ "62000107", "62000113" ], replay_notes.sole.metadata["external_transfer_ids"]++ booked = process_every_balance+ # From zero, each balance's entries add up to what Wise holds.+ assert_equal({ "CHF" => BigDecimal("343.52"), "SEK" => BigDecimal("147.62"), "PLN" => BigDecimal("26.45"),+ "NOK" => BigDecimal("0") },+ booked.transform_values { |entries| -entries.sum { |entry| entry[2] } })+ assert_equal [ BigDecimal("1.74"), BigDecimal("12.95") ],+ booked["CHF"].select { |entry| [ "wise_activity_#{atm}", "wise_activity_#{chf_card}" ].include?(entry[1]) }.map { |entry| entry[2] }+ assert_empty booked["CHF"].select { |entry| entry[1].end_with?("_62000107") }++ # A second sync with the same data changes nothing.+ payloads = @wise_item.wise_accounts.reload.to_h { |wise_account| [ wise_account.currency, wise_account.raw_transactions_payload ] }+ assert_no_difference -> { replay_notes.count } do+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: profile_provider).import+ end+ assert_equal payloads, @wise_item.wise_accounts.reload.to_h { |wise_account| [ wise_account.currency, wise_account.raw_transactions_payload ] }+ assert_equal booked, process_every_balance+ end+ end++ # The balance moved between the two reads (a card payment settling while+ # the feed was read), so its rows cannot be matched with either amount:+ # the replay waits, and the re-fetched payout keeps its mark.+ test "keeps a balance's marks when Wise holds another amount after the fetch" do+ @wise_item.update!(import_all_history: true)+ WiseItem::Importer.new(@wise_item, wise_provider: card_funded_payout_provider).import+ gbp = @wise_item.wise_accounts.find_by!(currency: "GBP")+ assert_equal [ [ "GBP", 7102 ] ], funding_marks++ moving = card_funded_payout_provider(live: 125.0, later_live: 118.0)+ assert_no_difference -> { replay_notes.count } do+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: moving).import+ end++ assert_equal 2, moving.calls.count(:get_balances)+ assert_equal "external", gbp.reload.raw_transactions_payload.find { |row| row["id"] == 7102 }["wise_funding"]+ end++ # A replay that does not reconcile keeps the last marks instead of booking+ # the payout again.+ test "keeps a balance's marks and tells support when its replay does not reconcile" do+ @wise_item.update!(import_all_history: true)+ WiseItem::Importer.new(@wise_item, wise_provider: card_funded_payout_provider).import++ # 10 GBP left the balance in a way no row shows.+ assert_difference -> { replay_notes.where(level: "warn").count }, 1 do+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: card_funded_payout_provider(live: 90.0)).import+ end++ note = replay_notes.where(level: "warn").sole+ gbp = @wise_item.wise_accounts.find_by!(currency: "GBP")+ assert_equal [ "leftover_unexplained", "GBP", gbp.id ], note.metadata.values_at("reason", "currency", "wise_account_id")+ assert_equal({ "flow_count" => 3, "payout_count" => 1 }, note.metadata.slice("flow_count", "payout_count"))+ assert_equal [ [ "GBP", 7102 ] ], funding_marks+ end++ # GBP got a 90 top-up and a 4 GBP fee refund (a type Sure does not book),+ # paid a 93 GBP payout from the balance, got 12 more and paid 7.42 GBP of a+ # 150 EUR cash withdrawal the euro balance paid the rest of. EUR has a jar,+ # so it is not replayed. GBP reconciled only by giving its leftover to that+ # withdrawal, whose parts are not written: the payout is not marked+ # externally funded, and support is told why (GBP keeps the payout booked,+ # which its replay did not, so it does not reconcile).+ test "marks no payout when the balance's leftover went into a split part that is not written" do+ travel_to Time.utc(2026, 9, 14, 12) do+ @wise_item.update!(import_all_history: true)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "GBP", date: Date.new(2026, 9, 11), rate: 0.86)+ provider = split_withdrawal_provider(eur_top_up: "150", savings_balances: [ jar_balance(60000009, "EUR", "Holiday") ])++ assert WiseItem::Importer.new(@wise_item, wise_provider: provider).import[:complete]++ assert_empty funding_marks+ note = replay_notes.sole+ assert_equal [ "warn", "funding_unconfirmed", "GBP" ], [ note.level, *note.metadata.values_at("reason", "currency") ]+ end+ end++ # As above, but the euro balance is replayed (it paid 145 EUR of the+ # withdrawal) and Sure knows no EUR/GBP rate. GBP reconciled only with the+ # payout taken as externally funded and a 96.42 GBP share no rate bounds; it+ # kept the payout booked and the share was written too, so GBP booked the 93+ # twice (-87.42 for a live 5.58). Now the withdrawal keeps its parts (none):+ # GBP books the payout once and the euro balance the whole withdrawal, as+ # without a replay.+ test "books a payout once when the share of a split payment its replay put the payout's money in is not confirmed" do+ travel_to Time.utc(2026, 9, 14, 12) do+ @wise_item.update!(import_all_history: true)++ assert WiseItem::Importer.new(@wise_item, wise_provider: split_withdrawal_provider(eur_top_up: "145")).import[:complete]++ assert_empty funding_marks+ assert_empty split_marks+ assert_equal [ %w[EUR split_parts_withheld], %w[GBP funding_unconfirmed] ],+ replay_notes.where(level: "warn").map { |note| note.metadata.values_at("currency", "reason") }.sort+ booked = process_every_balance.transform_values { |entries| entries.map { |_id, external_id, amount| [ external_id, amount ] } }+ assert_equal [ [ "wise_transfer_7101", BigDecimal("-90") ], [ "wise_transfer_7102", BigDecimal("93") ],+ [ "wise_transfer_7103", BigDecimal("-12") ] ], booked["GBP"]+ assert_equal [ [ "wise_activity_atm_1", BigDecimal("150") ], [ "wise_transfer_7104", BigDecimal("-145") ] ], booked["EUR"]+ end+ end++ test "replays nothing when the second balance read fails, without failing the import" do+ @wise_item.update!(import_all_history: true)+ provider = card_funded_payout_provider+ first_read = provider.method(:get_balances)+ provider.define_singleton_method(:get_balances) do |profile_id|+ raise Provider::Wise::WiseError.new("Unexpected response 502", :fetch_failed) if calls.include?(:get_balances)++ first_read.call(profile_id)+ end++ result = nil+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error", level: "warn").count }, 1 do+ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end++ assert result[:success]+ assert result[:complete]+ assert_empty funding_marks+ end++ # A balance Wise dates before the fetched history (coverage from later than+ # its creationTime) and one sharing its currency with another open balance+ # (split parts are kept by currency).+ test "replays only balances whose rows can hold everything that moved them" do+ jar = { "id" => 60000009, "type" => "SAVINGS", "currency" => "GBP", "name" => "Holiday",+ "amount" => { "value" => 0.0, "currency" => "GBP" }, "totalWorth" => { "value" => 0.0, "currency" => "GBP" } }+ # A credit for a transfer Sure does not have, after the payout.+ deposit = build_transfer_activity(99001, id: "bank_deposit", primary: "<positive>+ 30 GBP</positive>",+ created_on: "2026-07-16T10:00:00.000Z").merge("type" => "BALANCE_DEPOSIT")+ # Older than the payout balance, which takes every row (a currency Wise+ # opened again under a new balance).+ older_gbp = standard_balance(60000002, "GBP", 0.0).merge("investmentState" => "NOT_INVESTED", "creationTime" => "2026-04-01T08:00:00Z")+ {+ "without the full history" => [ { full_history: false }, 1 ],+ "after a failed fetch" => [ { raise_on: { get_activities: "Unexpected response 502" } }, 1 ],+ "for an invested balance" => [ { balance: { "investmentState" => "INVESTED" } }, 1 ],+ "without the balance's creation time" => [ { balance: { "creationTime" => nil } }, 1 ],+ "with a jar in its currency" => [ { savings_balances: [ jar ] }, 2 ],+ "with a credit for an unknown transfer" => [ { live: 130.0, extra_activities: [ deposit ] }, 2 ],+ "for a balance Wise dates before the account and the fetched history" => [ { balance: { "creationTime" => "2026-04-01T08:00:00Z" } }, 2 ],+ "with another open balance in its currency" => [ { more_balances: [ older_gbp ] }, 2 ]+ }.each do |label, (variant, balance_reads)|+ @wise_item.wise_accounts.destroy_all+ # Reloaded first: the previous import stored coverage the stale copy does not hold.+ @wise_item.reload.update!(import_all_history: variant.fetch(:full_history, true), raw_payload: nil)+ provider = card_funded_payout_provider(**variant.except(:full_history))++ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import++ assert_empty funding_marks, label+ assert_equal balance_reads, provider.calls.count(:get_balances), label+ end+ end++ # Statement rows are not replayed, so a balance with statements is not+ # either, although its transfer rows (kept until its statements take them+ # over) would reconcile here with the payout marked.+ test "replays no balance its statements cover" do+ @wise_item.update!(import_all_history: true)+ @wise_item.wise_accounts.create!(+ balance_id: "60000001", name: "Wise GBP", currency: "GBP",+ raw_payload: { "type" => "STANDARD", "statements_coverage" => { "from" => "2026-07-01T08:00:00Z", "through" => "2026-07-03T08:00:00Z" } },+ raw_transactions_payload: [ statement_row("CARD-9", "-1", "GBP", date: "2026-07-03T07:00:00Z").merge("wise_statement" => true),+ *card_funded_transfers ]+ )+ provider = card_funded_payout_provider(live: 120.0, statements: [], raise_on: { get_balance_statements: nil })++ assert WiseItem::Importer.new(@wise_item, wise_provider: provider).import[:complete]++ assert_includes provider.calls, :get_transfers+ assert_equal 2, provider.calls.count(:get_balances)+ assert_equal [ 7101, 7102 ], @wise_item.wise_accounts.sole.raw_transactions_payload.filter_map { |row| row["id"] }+ assert_empty funding_marks+ end++ # Coverage alone may stem from an earlier sync. In this one the statements+ # of a third balance arrived, so no transfer was listed: the two balances+ # sharing a card payment are not replayed, though their rows would reconcile+ # and write split parts.+ test "replays nothing in a sync that listed no transfers" do+ covered = { "from" => "2020-01-01T00:00:00Z", "through" => 1.day.ago.utc.iso8601, "version" => WiseItem::COVERAGE_VERSION }+ @wise_item.update!(import_all_history: true, raw_payload: { "coverage" => { "transfers" => covered, "activities" => covered } })+ @wise_item.wise_accounts.create!(balance_id: "50000002", name: "Wise USD", currency: "USD", raw_payload: { "type" => "STANDARD" },+ raw_transactions_payload: [ statement_row("CARD-1", "-5", "USD").merge("wise_statement" => true) ])+ replayable = { "investmentState" => "NOT_INVESTED", "creationTime" => "2026-09-30T08:00:00Z" }+ provider = FakeWiseProvider.new(+ balances: [ standard_balance("50000000", "EUR", 0.0).merge(replayable), standard_balance("50000001", "GBP", 0.0).merge(replayable),+ standard_balance("50000002", "USD", 0.0) ],+ borderless_accounts: [], activities: [ build_card_activity("card_1", "25 EUR", "GBP, EUR") ],+ statements_by_balance: { "50000002" => [ statement_row("CARD-1", "-5", "USD") ] }+ )++ assert WiseItem::Importer.new(@wise_item, wise_provider: provider).import[:complete]++ assert_not_includes provider.calls, :get_transfers+ assert_equal 2, provider.calls.count(:get_balances)+ assert_equal [ "card_1" ], @wise_item.wise_accounts.find_by!(balance_id: "50000001").raw_transactions_payload.map { |row| row["id"] }+ assert_empty split_marks+ end++ # Payloads are stored in one transaction with a savepoint per balance, so+ # the database refusing one balance's rows (PostgreSQL takes no NUL in+ # jsonb) keeps the others'.+ test "stores the other balances' rows when the database refuses one balance's" do+ provider = FakeWiseProvider.new(+ balances: [ eur_balance("10000001", 0.0), standard_balance("10000002", "USD", 0.0) ], borderless_accounts: [],+ transfers: [ build_transfer(id: 1), build_transfer(id: 2, source_currency: "USD", target_currency: "USD").merge("reference" => "a\u0000b") ],+ raise_on: { get_balance_statements: statements_forbidden }+ )++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_not result[:success]+ assert_equal 1, result[:transactions_failed]+ assert_equal [ 1 ], @wise_item.wise_accounts.find_by!(currency: "EUR").raw_transactions_payload.map { |row| row["id"] }+ assert_nil @wise_item.wise_accounts.find_by!(currency: "USD").raw_transactions_payload+ end++ # GBP got 50, converted 11.31 GBP into 13 EUR, and paid 10.44 GBP of a 25+ # EUR card payment the euro balance paid 13 EUR of. The copies of a split+ # payment carry the same parts, so when the database refuses the euro+ # balance's payload (a NUL in a held card payment), GBP's new parts are+ # not stored either, and the next sync stores both.+ test "stores a split payment's new parts on every balance holding it or on none" do+ travel_to Time.utc(2026, 3, 5, 12) do+ @wise_item.update!(import_all_history: true)+ replayable = { "investmentState" => "NOT_INVESTED", "creationTime" => "2026-03-01T08:00:00Z" }+ balances = [ standard_balance(60000001, "GBP", 28.25).merge(replayable, "recipientId" => 90000101),+ standard_balance(60000002, "EUR", 0.0).merge(replayable, "recipientId" => 90000102) ]+ top_up = build_transfer(id: 7101, source_currency: "GBP", target_currency: "GBP", target_account: 90000101)+ .merge("sourceValue" => 50.0, "targetValue" => 50.0, "created" => "2026-03-01 09:00:00")+ activities = [ build_interbalance("To <strong>EUR</strong>", resource_id: "8001", primary: "13 EUR", secondary: "11.31 GBP")+ .merge("createdOn" => "2026-03-01T10:00:00Z"),+ build_card_activity("split_card", "25 EUR", "GBP, EUR", created_on: "2026-03-01T12:00:00.000Z") ]+ held = build_card_activity("held_card", "4 EUR", status: "IN_PROGRESS", created_on: "2026-03-02T12:00:00.000Z")+ import = lambda do |extra_activities|+ provider = FakeWiseProvider.new(balances: balances, borderless_accounts: [],+ multi_currency_account: { "id" => 40000001, "recipientId" => 90000001, "creationTime" => "2026-03-01T07:59:00Z" },+ transfers: [ top_up ], activities: activities + extra_activities,+ raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ end++ refused = import.call([ held.merge("title" => "<strong>Caf\u0000e</strong>") ])+ assert_equal 2, refused[:transactions_failed]+ assert_empty split_marks++ assert_equal 0, import.call([ held ])[:transactions_failed]+ parts = { "EUR" => "13.00", "GBP" => "10.44" }+ assert_equal({ "EUR" => [ [ "split_card", parts, nil ] ], "GBP" => [ [ "split_card", parts, nil ] ] }, split_marks)+ endend- test "routes BALANCE_CASHBACK only to JAR account" do- savings = {- "id" => "10000002",- "amount" => { "value" => 1000.0, "currency" => "EUR" },- "totalWorth" => { "value" => 1000.0, "currency" => "EUR" },- "reservedAmount" => { "value" => 0.0, "currency" => "EUR" },- "type" => "SAVINGS",- "name" => "Jar"- }- cashback = build_cashback("57001")- provider = FakeWiseProvider.new(savings_balances: [ savings ], activities: [ cashback ])+ # The replay runs in a savepoint, so a database error in its exchange rate+ # lookup changes no mark and loses no payload; support is told.+ test "stores the payloads unmarked when the replay's rate lookup fails in the database" do+ @wise_item.update!(import_all_history: true)+ broken_lookup = ExchangeRate.where("wise_no_such_column = 1")+ ExchangeRate.stubs(:where).returns(broken_lookup)+ atm = build_card_activity("atm_1", "150 EUR", "GBP, EUR", type: "CASH_WITHDRAWAL", created_on: "2026-07-17T10:00:00.000Z")- WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ result = nil+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error", level: "error").count }, 1 do+ result = WiseItem::Importer.new(@wise_item, wise_provider: card_funded_payout_provider(extra_activities: [ atm ])).import+ end- jar = @wise_item.wise_accounts.find_by(balance_id: "10000002")- standard = @wise_item.wise_accounts.find_by(balance_id: "10000001")+ assert result[:success]+ assert_equal %w[7101 7102 atm_1 card_1], @wise_item.wise_accounts.sole.raw_transactions_payload.map { |row| row["id"].to_s }.sort+ assert_empty funding_marks+ assert_equal "balance_replay", DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error").sole.metadata["operation"]+ end- assert_equal 1, jar.raw_transactions_payload.size- assert_empty standard.raw_transactions_payload.select { |a| a["type"] == "BALANCE_CASHBACK" }+ # A card payment Wise has not completed is not booked and its hold is out of+ # the balance's amount, so the live amount the replay ends at counts the+ # hold back in (amount 90 + 10 reserved): the card-funded payout is still+ # found.+ test "replays a balance with a pending card hold to its amount plus what the hold reserves" do+ @wise_item.update!(import_all_history: true)+ hold = build_card_activity("hold_1", "10 GBP", status: "IN_PROGRESS", created_on: "2026-07-15T10:00:00.000Z")+ provider = card_funded_payout_provider(live: 90.0, balance: { "reservedAmount" => { "value" => 10.0, "currency" => "GBP" } },+ extra_activities: [ hold ])++ assert WiseItem::Importer.new(@wise_item, wise_provider: provider).import[:complete]++ assert_equal [ [ "GBP", 7102 ] ], funding_marksend- test "stops activity pagination when Wise repeats a cursor" do+ # A repeated cursor means Wise ignored it and the feed was not read to the+ # end, so the fetch now fails the import and its pages are dropped instead+ # of passing for the complete history.+ test "stops activity pagination and fails the fetch when Wise repeats a cursor" doactivity = build_interbalance("To <strong>Jar</strong>", resource_id: "5001")- repeated_cursor = "repeated-cursor"provider = FakeWiseProvider.new- provider.define_singleton_method(:get_activities) do |_profile_id, cursor: nil, size: 100|+ provider.define_singleton_method(:get_activities) do |_profile_id, size: 100, **|calls << :get_activities- { "activities" => Array.new(size, activity), "cursor" => repeated_cursor }+ { "activities" => Array.new(size, activity), "cursor" => "repeated-cursor" }end- WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).importassert_equal 2, provider.calls.count(:get_activities)+ assert_not result[:success]+ assert_not result[:complete]+ assert_equal 1, result[:fetch_failures]+ assert_empty Array(@wise_item.wise_accounts.first.raw_transactions_payload)+ assert_nil @wise_item.reload.raw_payload.dig("coverage", "activities")+ end++ test "follows nextCursor until Wise returns no cursor" do+ to_eur = build_interbalance("To <strong>EUR</strong>", resource_id: "7001", primary: "117.50 EUR", secondary: "100 GBP")+ from_eur = build_interbalance("To <strong>GBP</strong>", resource_id: "7002", primary: "86.10 GBP", secondary: "100 EUR")+ pages = { nil => { "activities" => [ to_eur ], "cursor" => "page-2" },+ "page-2" => { "activities" => [ from_eur ], "cursor" => nil } }+ provider = FakeWiseProvider.new(activity_pages: pages)++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert result[:complete]+ assert_equal [ nil, "page-2" ], provider.activity_requests.map { |request| request[:cursor] }+ assert_equal %w[interbalance_7001 interbalance_7002],+ @wise_item.wise_accounts.first.raw_transactions_payload.map { |a| a["id"] }.sort+ end++ # One 5xx answer on a later page no longer drops the pages already read.+ test "asks again for a page Wise answered with a server error" do+ to_eur = build_interbalance("To <strong>EUR</strong>", resource_id: "7001", primary: "117.50 EUR", secondary: "100 GBP")+ from_eur = build_interbalance("To <strong>GBP</strong>", resource_id: "7002", primary: "86.10 GBP", secondary: "100 EUR")+ pages = { nil => { "activities" => [ to_eur ], "cursor" => "page-2" },+ "page-2" => { "activities" => [ from_eur ], "cursor" => nil } }+ provider = FakeWiseProvider.new(activity_pages: pages, raise_on: { get_balance_statements: statements_forbidden })+ failed_once = false+ provider.define_singleton_method(:get_activities) do |*args, cursor: nil, **options|+ if cursor == "page-2" && !failed_once+ failed_once = true+ raise Provider::Wise::WiseError.new("Unexpected response 502: Bad Gateway", :server_error)+ end+ super(*args, cursor: cursor, **options)+ end+ Provider::Wise.expects(:sleep).once++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert result[:complete]+ assert failed_once+ assert_equal [ nil, "page-2" ], provider.activity_requests.map { |request| request[:cursor] }+ assert_equal %w[interbalance_7001 interbalance_7002], payload_ids["10000001"]+ end++ # Wise lists transfers oldest first, so stopping at the first old one never+ # reached newer pages. The third page starts at 200, not after the 101 rows+ # received (Wise refuses offset 101, see below).+ test "fetches every page of Wise's oldest-first transfer list" do+ old = (1..100).map do |i|+ build_transfer(id: i).merge("created" => (400.days.ago + i.minutes).utc.strftime("%Y-%m-%d %H:%M:%S"))+ end+ recent = build_transfer(id: 101).merge("created" => 1.day.ago.utc.strftime("%Y-%m-%d %H:%M:%S"))+ provider = FakeWiseProvider.new(transfers: old + [ recent ], raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider, sync_start_date: 30.days.ago.to_date).import++ assert_equal [ 0, 100, 200 ], provider.transfer_requests.map { |request| request[:offset] }+ assert_includes @wise_item.wise_accounts.first.raw_transactions_payload.map { |t| t["id"] }, 101+ end++ # Wise takes an offset only as a multiple of the limit: any other offset+ # gets HTTP 422 inconsistent.pagination, and one past the last row an empty+ # page. Paging on by the rows received failed the transfer list every sync,+ # so no import was complete and no transfers coverage was ever written.+ test "asks for each transfer page at a multiple of the page size" do+ provider = FakeWiseProvider.new(transfers: (1..47).map { |id| build_transfer(id: id) },+ raise_on: { get_balance_statements: statements_forbidden })++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ [ 0, 100 ], [ 100, 100 ] ], provider.transfer_requests.map { |request| request.values_at(:offset, :limit) }+ assert result[:complete]+ assert_equal 0, result[:fetch_failures]+ assert_equal (1..47).to_a, payload_ids["10000001"]+ assert_not_nil @wise_item.reload.fetch_coverage(:transfers)+ end++ test "reads a transfer list of several pages up to the empty page after the last" do+ provider = FakeWiseProvider.new(transfers: (1..230).map { |id| build_transfer(id: id) },+ raise_on: { get_balance_statements: statements_forbidden })++ assert WiseItem::Importer.new(@wise_item, wise_provider: provider).import[:complete]++ assert_equal [ 0, 100, 200, 300 ], provider.transfer_requests.map { |request| request[:offset] }+ assert_equal (1..230).to_a, payload_ids["10000001"]+ end++ # A page may hold fewer transfers than the limit without being the last+ # (a server cap or filter): only an empty page ends the list, and the next+ # page still starts a page size on, the only offset Wise takes.+ test "follows a transfer page shorter than the limit with the next page" do+ pages = { 0 => (1..60).map { |id| build_transfer(id: id) }, 100 => (61..100).map { |id| build_transfer(id: id) } }+ provider = FakeWiseProvider.new(transfer_pages: pages, raise_on: { get_balance_statements: statements_forbidden })++ assert WiseItem::Importer.new(@wise_item, wise_provider: provider).import[:complete]++ assert_equal [ 0, 100, 200 ], provider.transfer_requests.map { |request| request[:offset] }+ assert_equal (1..100).to_a, payload_ids["10000001"]+ end++ test "waits for Wise's Retry-After before retrying a rate-limited transfers page" do+ provider = FakeWiseProvider.new(transfers: [ build_transfer(id: 1) ],+ raise_on: { get_balance_statements: statements_forbidden })+ limited = true+ provider.define_singleton_method(:get_transfers) do |*args, **options|+ if limited+ limited = false+ raise Provider::Wise::WiseError.new("Rate limit exceeded", :rate_limited, retry_after: 7)+ end+ super(*args, **options)+ end+ Provider::Wise.expects(:sleep).with { |seconds| seconds >= 7 && seconds < 8 }.once++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert result[:success]+ assert_equal [ 1 ], @wise_item.wise_accounts.first.raw_transactions_payload.map { |t| t["id"] }+ end++ test "a failed activities fetch keeps payloads and coverage, and the next sync resumes from them" do+ travel_to Time.utc(2026, 10, 17, 12) do+ coverage = { "activities" => { "from" => "2015-01-01T00:00:00Z", "through" => "2026-10-01T00:00:00Z", "version" => WiseItem::COVERAGE_VERSION } }+ @wise_item.update!(raw_payload: { "coverage" => coverage })+ stored = build_interbalance("To <strong>EUR</strong>", resource_id: "7001", primary: "117.50 EUR", secondary: "100 GBP")+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD" }, raw_transactions_payload: [ stored ])+ failing = FakeWiseProvider.new(raise_on: { get_activities: "Unexpected response 502" })++ result = nil+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error").count }, 1 do+ result = WiseItem::Importer.new(@wise_item, wise_provider: failing).import+ end++ assert_not result[:success]+ assert_not result[:complete]+ assert_equal 1, result[:fetch_failures]+ assert_equal [ stored ], eur.reload.raw_transactions_payload+ assert_equal coverage, @wise_item.reload.raw_payload["coverage"]++ later = build_interbalance("To <strong>GBP</strong>", resource_id: "7002", primary: "86.10 GBP", secondary: "100 EUR")+ recovered = FakeWiseProvider.new(activities: [ later ])+ assert WiseItem::Importer.new(@wise_item, wise_provider: recovered).import[:complete]++ assert_equal Time.utc(2026, 9, 1), recovered.activity_requests.first[:since]+ assert_equal %w[interbalance_7001 interbalance_7002], eur.reload.raw_transactions_payload.map { |a| a["id"] }+ end+ end++ # A failed first-sync transfer list used to report success and move the+ # window past the transfers it never fetched.+ test "a failed transfers fetch is retried from the full window on the next sync" do+ travel_to Time.utc(2026, 10, 17, 12) do+ failing = FakeWiseProvider.new(raise_on: { get_transfers: "Connection failed: Net::ReadTimeout",+ get_balance_statements: statements_forbidden })+ result = WiseItem::Importer.new(@wise_item, wise_provider: failing).import++ assert_not result[:success]+ assert_equal 1, result[:fetch_failures]+ assert_nil @wise_item.reload.raw_payload.dig("coverage", "transfers")++ history = build_transfer(id: 5).merge("created" => 90.days.ago.utc.strftime("%Y-%m-%d %H:%M:%S"))+ recovered = FakeWiseProvider.new(transfers: [ history ], raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(@wise_item, wise_provider: recovered).import++ assert_equal 365.days.ago, recovered.transfer_requests.first[:created_date_start]+ assert_equal [ 5 ], @wise_item.wise_accounts.first.raw_transactions_payload.map { |t| t["id"] }+ end+ end++ test "re-reads stored transfers that can still change, newest first" do+ older = build_transfer(id: 21).merge("status" => "processing", "created" => "2025-08-26 10:00:00")+ newer = build_transfer(id: 22).merge("status" => "incoming_payment_waiting", "created" => "2025-11-18 10:00:00")+ sent = build_transfer(id: 23)+ cancelled = build_transfer(id: 24).merge("status" => "cancelled")+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [ older, newer, sent, cancelled ])+ provider = FakeWiseProvider.new(+ transfer_details: { "21" => older.merge("status" => "funds_refunded"), "22" => newer.merge("status" => "cancelled") },+ raise_on: { get_balance_statements: statements_forbidden }+ )++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert result[:complete]+ assert_equal [ 22, 21 ], provider.transfer_reads+ statuses = eur.reload.raw_transactions_payload.to_h { |t| [ t["id"], t["status"] ] }+ assert_equal({ 21 => "funds_refunded", 22 => "cancelled", 23 => "outgoing_payment_sent", 24 => "cancelled" }, statuses)+ end++ test "re-reads at most 50 transfers per sync" do+ rows = (1..51).map { |i| build_transfer(id: i).merge("status" => "processing", "created" => "2025-07-22 10:#{format('%02d', i)}:00") }+ @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: rows)+ provider = FakeWiseProvider.new(transfer_details: rows.index_by { |row| row["id"].to_s },+ raise_on: { get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal (2..51).to_a.reverse, provider.transfer_reads+ end++ # Re-reads refresh stored rows, not the listed window, so the window still+ # counts as covered.+ test "a failed transfer re-read fails the import and keeps the stored copy" do+ travel_to Time.utc(2026, 10, 17, 12) do+ processing = build_transfer(id: 31).merge("status" => "processing")+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [ processing ])+ provider = FakeWiseProvider.new(raise_on: { get_transfer: "Unexpected response 503",+ get_balance_statements: statements_forbidden })++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_not result[:complete]+ assert_equal 1, result[:fetch_failures]+ assert_equal [ processing ], eur.reload.raw_transactions_payload+ assert_equal "2026-10-17T12:00:00Z", @wise_item.reload.raw_payload.dig("coverage", "transfers", "through")+ end+ end++ # A transfer Wise no longer finds is no failed fetch (one vanished transfer+ # would keep every import incomplete); its stored copy stays, and support is+ # told how many once. It is read again on three syncs, then no more, unless+ # Wise lists it again.+ test "a transfer Wise no longer finds keeps its stored copy and fails nothing" do+ processing = build_transfer(id: 41).merge("status" => "processing")+ eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },+ raw_transactions_payload: [ processing ])+ import = lambda do |**options|+ provider = FakeWiseProvider.new(raise_on: { get_balance_statements: statements_forbidden }, **options)+ [ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import, provider ]+ end++ result, provider = nil+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error", level: "warn").count }, 1 do+ result, provider = import.call+ end++ assert result[:success]+ assert result[:complete]+ assert_equal [ 41 ], provider.transfer_reads+ assert_equal [ processing.merge("wise_missing_count" => 1) ], eur.reload.raw_transactions_payload+ note = DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error").sole+ assert_equal [ "transfer", 1 ], note.metadata.values_at("operation", "missing_transfer_count")+ assert @wise_item.reload.raw_payload.dig("coverage", "transfers")++ reads = 3.times.map { import.call.last.transfer_reads }+ assert_equal [ [ 41 ], [ 41 ], [] ], reads+ assert_equal 1, DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error").count+ assert_equal 3, eur.reload.raw_transactions_payload.sole["wise_missing_count"]++ import.call(transfers: [ processing.merge("status" => "outgoing_payment_sent") ])+ assert_equal [ processing.merge("status" => "outgoing_payment_sent") ], eur.reload.raw_transactions_payload+ end++ # A jar is linked after the first sync, so its payload must keep what+ # earlier syncs fetched.+ test "keeps a jar's stored moves when a later fetch returns fewer rows or fails" do+ savings = {+ "id" => "10000002", "type" => "SAVINGS", "name" => "Holiday",+ "amount" => { "value" => 1200.0, "currency" => "EUR" }, "totalWorth" => { "value" => 1200.0, "currency" => "EUR" }+ }+ deposit = build_interbalance("To <strong>Holiday</strong>", resource_id: "5001")++ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(savings_balances: [ savings ], activities: [ deposit ])).import+ jar = @wise_item.wise_accounts.find_by!(balance_id: "10000002")+ assert_equal [ "interbalance_5001" ], jar.raw_transactions_payload.map { |a| a["id"] }++ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(savings_balances: [ savings ])).import+ assert_equal [ "interbalance_5001" ], jar.reload.raw_transactions_payload.map { |a| a["id"] }++ failing = FakeWiseProvider.new(savings_balances: [ savings ], raise_on: { get_activities: "Unexpected response 503" })+ WiseItem::Importer.new(@wise_item, wise_provider: failing).import+ assert_equal [ "interbalance_5001" ], jar.reload.raw_transactions_payload.map { |a| a["id"] }+ end++ test "takes the account recipient from the multi-currency account" do+ provider = FakeWiseProvider.new(borderless_accounts: [],+ multi_currency_account: { "id" => 5, "recipientId" => 12345678, "creationTime" => "2025-06-11T10:00:00Z" })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal 12345678, @wise_item.wise_accounts.first.raw_payload["recipient_id"]+ assert_equal({ "id" => 5, "recipientId" => 12345678, "creationTime" => "2025-06-11T10:00:00Z" },+ @wise_item.reload.raw_payload["multi_currency_account"])+ end++ # A failed lookup of the multi-currency account must not move the full+ # history to FULL_HISTORY_START_DATE: the creationTime the item keeps from+ # an earlier lookup still dates it.+ test "starts the full history from the stored account creation when the lookup fails" do+ travel_to Time.utc(2026, 10, 17, 12) do+ @wise_item.update!(import_all_history: true,+ raw_payload: { "multi_currency_account" => { "creationTime" => "2024-11-27T10:00:00Z" } })+ provider = FakeWiseProvider.new(raise_on: { get_multi_currency_account: "Unexpected response 502",+ get_balance_statements: statements_forbidden })++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal [ Time.utc(2024, 11, 26, 10) ], provider.transfer_requests.map { |request| request[:created_date_start] }.uniq+ assert_equal [ Time.utc(2024, 11, 26, 10) ], provider.activity_requests.map { |request| request[:since] }+ assert_equal "2024-11-27T10:00:00Z", @wise_item.reload.raw_payload.dig("multi_currency_account", "creationTime")+ end+ end++ test "keeps stored recipient ids when the account lookups fail" do+ eur = @wise_item.wise_accounts.create!(+ balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "borderless_account_id" => 88888001, "recipientId" => 77777001 }+ )+ provider = FakeWiseProvider.new(raise_on: { get_multi_currency_account: "Unexpected response 502",+ get_borderless_accounts: "Unexpected response 502" })++ result = nil+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error", level: "warn").count }, 2 do+ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ end++ assert result[:success]+ assert result[:complete]+ assert_equal [ 99999001, 88888001, 77777001 ], eur.reload.raw_payload.values_at("recipient_id", "borderless_account_id", "recipientId")+ end++ test "tracks whether both balance lists arrived in full" do+ complete = WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new)+ complete.import+ assert complete.send(:balance_lists_complete?)++ [ { get_savings_balances: "Unexpected response 500" },+ { get_savings_balances: Provider::Wise::WiseError.new("Resource not found", :not_found) },+ { get_balances: Provider::Wise::WiseError.new("Resource not found", :not_found) } ].each do |raise_on|+ importer = WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(raise_on: raise_on))+ found_nothing = raise_on.values.first.is_a?(Provider::Wise::WiseError)+ assert_equal found_nothing, importer.import[:complete], "only a list Wise says is empty completes (#{raise_on.inspect})"+ assert_not importer.send(:balance_lists_complete?), raise_on.keys.first+ end+ end++ # Closed balances++ test "marks a balance closed only after two complete balance lists in a row without it" do+ old_eur = @wise_item.wise_accounts.create!(balance_id: "10000009", name: "Wise EUR (old)", currency: "EUR", current_balance: 50,+ raw_payload: { "type" => "STANDARD" })+ listed = FakeWiseProvider.new(raise_on: { get_balance_statements: statements_forbidden })++ # A list that failed or answered not_found proves nothing.+ [ { get_savings_balances: "Unexpected response 500" },+ { get_savings_balances: Provider::Wise::WiseError.new("Resource not found", :not_found) },+ { get_balances: Provider::Wise::WiseError.new("Resource not found", :not_found) } ].each do |raise_on|+ partial = FakeWiseProvider.new(raise_on: raise_on.merge(get_balance_statements: statements_forbidden))+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: partial).import+ assert_nil old_eur.reload.raw_payload["absent_count"], raise_on.keys.first+ end++ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: listed).import+ assert_equal 1, old_eur.reload.raw_payload["absent_count"]+ assert_not old_eur.closed?+ assert_equal BigDecimal("50"), old_eur.current_balance++ assert_difference -> { balance_notes.count }, 1 do+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: listed).import+ end+ assert old_eur.reload.closed?+ assert_equal [ 2, BigDecimal("0") ], [ old_eur.raw_payload["absent_count"], old_eur.current_balance ]+ assert_equal old_eur.id, balance_notes.sole.metadata["wise_account_id"]++ # Listed again: open again, at the amount Wise reports.+ reopened = FakeWiseProvider.new(balances: [ eur_balance("10000001", 1964.88), eur_balance("10000009", 12.0) ],+ raise_on: { get_balance_statements: statements_forbidden })+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: reopened).import+ assert_not old_eur.reload.closed?+ assert_not old_eur.raw_payload.key?("absent_count")+ assert_equal BigDecimal("12"), old_eur.current_balance+ end++ # Wise closes only empty balances, and the conversion that emptied one+ # usually comes in the first sync whose lists miss it.+ test "a closed balance keeps the conversion that emptied it and drops to zero" do+ WiseItem::Importer.new(@wise_item, wise_provider: FakeWiseProvider.new(+ balances: [ standard_balance("20000001", "GBP", 100), standard_balance("20000002", "EUR", 50) ], borderless_accounts: [],+ raise_on: { get_balance_statements: statements_forbidden }+ )).import+ eur = link_account(@wise_item.wise_accounts.find_by!(currency: "EUR"))+ convert_out = build_interbalance("To <strong>GBP</strong>", resource_id: "9100", primary: "43.10 GBP", secondary: "50 EUR")+ emptied = FakeWiseProvider.new(balances: [ standard_balance("20000001", "GBP", 143.10) ], borderless_accounts: [],+ activities: [ convert_out ], raise_on: { get_balance_statements: statements_forbidden })++ 2.times do+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: emptied).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ end++ assert eur.reload.closed?+ assert_equal [ [ "wise_interbalance_9100_outflow", BigDecimal("50") ] ], eur.current_account.entries.pluck(:external_id, :amount)+ assert_equal BigDecimal("0"), eur.current_account.reload.balance+ end++ # Wise opened a closed currency again under a new balance id.+ test "books each movement of a reopened currency on the balance of its time" do+ old_eur = @wise_item.wise_accounts.create!(balance_id: "10000009", currency: "EUR", name: "Wise EUR (old)", current_balance: 111,+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "recipientId" => 1111,+ "creationTime" => "2025-01-10T09:00:00Z" })+ link_account(old_eur)+ new_eur = eur_balance("10000001", 960.0).merge("creationTime" => 10.days.ago.utc.iso8601)+ before_reopening = build_transfer(id: 76, target_account: 5555).merge("created" => 20.days.ago.utc.strftime("%Y-%m-%d %H:%M:%S"))+ after_reopening = build_transfer(id: 77, target_account: 5555).merge("created" => 2.days.ago.utc.strftime("%Y-%m-%d %H:%M:%S"))+ provider = FakeWiseProvider.new(balances: [ new_eur ], transfers: [ before_reopening, after_reopening ],+ raise_on: { get_balance_statements: statements_forbidden })++ 2.times { WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import }++ holders = [ 76, 77 ].index_with do |id|+ @wise_item.wise_accounts.reload.select { |wa| Array(wa.raw_transactions_payload).any? { |row| row["id"] == id } }.map(&:balance_id)+ end+ assert_equal({ 76 => [ "10000009" ], 77 => [ "10000001" ] }, holders)+ assert old_eur.reload.closed?+ WiseAccount::Processor.new(old_eur).process+ assert_equal BigDecimal("0"), old_eur.current_account.reload.balance+ end++ # Wise opened the new euro balance at 15:00, six hours after a conversion+ # emptied the old one. In the day before the opening, money that left the+ # currency left the old balance (the new one held nothing yet), and money+ # that came in reached the new one (a pay-in can be dated before the+ # balance it reached existed).+ test "books what left a currency reopened within a day on the old balance and what came in on the new one" do+ @wise_item.wise_accounts.create!(balance_id: "10000009", currency: "EUR", name: "Wise EUR (old)", current_balance: 50,+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "creationTime" => "2025-01-10T09:00:00Z" })+ reopened_at = 10.days.ago.utc.change(hour: 15)+ emptied = build_interbalance("To <strong>GBP</strong>", resource_id: "9100", primary: "43.10 GBP", secondary: "50 EUR")+ .merge("createdOn" => reopened_at.change(hour: 9).iso8601)+ pay_in = build_transfer(id: 9200, target_account: 99999001).merge("created" => (reopened_at - 2.hours).strftime("%Y-%m-%d %H:%M:%S"))+ provider = FakeWiseProvider.new(balances: [ eur_balance("10000001", 100.0).merge("creationTime" => reopened_at.iso8601),+ standard_balance("20000001", "GBP", 43.10) ],+ borderless_accounts: [], transfers: [ pay_in ], activities: [ emptied ],+ raise_on: { get_balance_statements: statements_forbidden })++ 2.times { WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import }++ assert_equal({ "10000009" => [ "interbalance_9100" ], "10000001" => [ 9200 ], "20000001" => [ "interbalance_9100" ] }, payload_ids)+ end++ test "keeps a closed balance's rows as they are, adds only older ones and asks it for no statements" do+ misrouted = build_interbalance("To <strong>CHF</strong>", resource_id: "7006", primary: "1,345.20 CHF", secondary: "1,500 USD")+ closed = @wise_item.wise_accounts.create!(balance_id: "10000009", currency: "EUR", name: "Wise EUR (closed)",+ raw_payload: { "type" => "STANDARD", "closed_at" => 5.days.ago.utc.iso8601 },+ raw_transactions_payload: [ misrouted ])+ provider = FakeWiseProvider.new(activities: [ build_card_activity("card_old", "8 EUR", created_on: 6.days.ago.utc.iso8601(3)),+ build_card_activity("card_new", "12 EUR", created_on: 1.day.ago.utc.iso8601(3)) ],+ statements: [ statement_row("CARD-1", "-3", "EUR") ])++ WiseItem::Importer.new(@wise_item, wise_provider: provider).import++ assert_equal %w[interbalance_7006 card_old], closed.reload.raw_transactions_payload.map { |row| row["id"] }+ assert_equal [ "10000001" ], provider.statement_requests.map { |request| request[:balance_id] }+ end++ # An install that booked each conversion leg on every balance before routing+ # was fixed. The first sync of the fixed code re-fetches the whole history,+ # so processing removes the legs no balance's rows book any more, on the+ # emptied USD balance too.+ test "the first full sync removes conversion legs an older routing booked on every balance" do+ conversion = build_interbalance("To <strong>AUD</strong>", resource_id: "9000000106", primary: "3,710.65 AUD", secondary: "1,875 GBP")+ .merge("createdOn" => 20.days.ago.utc.iso8601)+ balance_ids = { "GBP" => "20000001", "AUD" => "20000003", "USD" => "20000004" }+ accounts = balance_ids.to_h do |currency, balance_id|+ wise_account = @wise_item.wise_accounts.create!(balance_id: balance_id, currency: currency, name: "Wise #{currency}",+ raw_payload: { "type" => "STANDARD" }, raw_transactions_payload: [ conversion ])+ account = link_account(wise_account).current_account+ # What older routing booked on every STANDARD balance.+ account.entries.create!(external_id: "wise_interbalance_9000000106_outflow", source: "wise", amount: 3710.65, currency: "AUD",+ date: 20.days.ago.to_date, name: "Transfer to AUD", entryable: Transaction.new)+ [ currency, account ]+ end+ provider = FakeWiseProvider.new(balances: balance_ids.map { |currency, id| standard_balance(id, currency, 0) }, borderless_accounts: [],+ activities: [ conversion ], raise_on: { get_balance_statements: statements_forbidden })++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ assert result[:coverage_upgraded]+ # The conversion's row explains each balance's copy, so each may go+ # beyond the cap if stale: on USD, which the row left, and on AUD, where+ # the conversion's leg is its inflow.+ assert_equal({ "GBP" => %w[wise_interbalance_9000000106_outflow], "AUD" => %w[wise_interbalance_9000000106_outflow],+ "USD" => %w[wise_interbalance_9000000106_outflow] },+ @wise_item.wise_accounts.reload.to_h { |wise_account| [ wise_account.currency, wise_account.prune_cap_bypass_ids ] })+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])++ assert_empty @wise_item.wise_accounts.find_by!(currency: "USD").raw_transactions_payload+ assert_empty @wise_item.wise_accounts.find_by!(currency: "USD").prune_cap_bypass_ids+ assert_not accounts["USD"].entries.exists?+ assert_equal [ [ "wise_interbalance_9000000106_outflow", BigDecimal("1875"), "GBP" ] ],+ accounts["GBP"].entries.pluck(:external_id, :amount, :currency)+ assert_equal BigDecimal("-3710.65"), accounts["AUD"].entries.sum(:amount)+ assert_equal 1, Entry.where(source: "wise", external_id: "wise_interbalance_9000000106_outflow").count+ end++ # An older build booked each conversion as an outflow on every balance, on+ # its target too, which then counted what it received as spent. Ten such+ # copies are more than a clean-up may delete at once (the cap), but the+ # conversions' rows explain them, so the sync that re-fetched the whole+ # history removes them all.+ test "the first full sync removes the conversion copies an older routing booked on their target balance, beyond the cap" do+ conversions = (1..10).map do |i|+ build_interbalance("To <strong>USD</strong>", resource_id: "77#{i}", primary: "120 USD", secondary: "100 GBP")+ .merge("id" => "conv_#{i}", "createdOn" => (40 - i).days.ago.utc.iso8601(3))+ end+ balances = [ standard_balance("32000001", "GBP", 0.0), standard_balance("32000002", "USD", 1200.0) ]+ gbp, usd = balances.map do |balance|+ wise_account = @wise_item.wise_accounts.create!(balance_id: balance["id"], name: "Wise #{balance.dig('amount', 'currency')}",+ currency: balance.dig("amount", "currency"), raw_payload: balance,+ raw_transactions_payload: conversions)+ link_account(wise_account).current_account+ end+ conversions.each do |activity|+ [ gbp, usd ].each do |account|+ account.entries.create!(external_id: "wise_interbalance_#{activity.dig('resource', 'id')}_outflow", source: "wise", amount: 120,+ currency: "USD", date: Time.zone.parse(activity["createdOn"]).to_date, name: "To USD", entryable: Transaction.new)+ end+ end+ provider = FakeWiseProvider.new(balances: balances, borderless_accounts: [], activities: conversions,+ raise_on: { get_balance_statements: statements_forbidden })++ 2.times do+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ end++ assert_equal [ 10, BigDecimal("-1200") ], [ usd.entries.where(source: "wise").count, usd.entries.where(source: "wise").sum(:amount) ]+ assert_equal({ [ BigDecimal("100"), "GBP" ] => 10 }, gbp.entries.where(source: "wise").group(:amount, :currency).count)+ end++ # The older build's copy on the target balance was an outflow of what it+ # received, which a person categorized: it is renamed to the inflow in+ # place, keeps the category and gets the conversion's amount.+ test "renames a conversion's outflow copy on its target balance to its inflow, keeping what a person did" do+ conversion = build_interbalance("To <strong>USD</strong>", resource_id: "771", primary: "120 USD", secondary: "100 GBP")+ .merge("createdOn" => 10.days.ago.utc.iso8601(3))+ usd = link_account(@wise_item.wise_accounts.create!(balance_id: "32000002", name: "Wise USD", currency: "USD",+ raw_payload: standard_balance("32000002", "USD", 120.0)))+ category = @family.categories.create!(name: "Savings", color: "#000000")+ copy = usd.current_account.entries.create!(external_id: "wise_interbalance_771_outflow", source: "wise", amount: 120, currency: "USD",+ date: 10.days.ago.to_date, name: "To USD", user_modified: true,+ entryable: Transaction.new(category: category))+ provider = FakeWiseProvider.new(balances: [ standard_balance("32000001", "GBP", 0.0), standard_balance("32000002", "USD", 120.0) ],+ borderless_accounts: [], activities: [ conversion ], raise_on: { get_balance_statements: statements_forbidden })++ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])++ assert_equal [ [ copy.id, "wise_interbalance_771_inflow", BigDecimal("-120") ] ],+ usd.current_account.entries.where(source: "wise").pluck(:id, :external_id, :amount)+ assert_equal category, copy.reload.entryable.category+ end++ # An older build booked every jar's interest and cashback on every jar,+ # and kept a jar's payload to the last sync's activities, so most copies+ # have no stored row. The balance in the interest's currency books it now,+ # which explains the copies on the jar, so they go beyond the cap.+ test "the first full sync removes the interest copies an older build booked on a jar in another currency" do+ cashbacks = (1..30).map do |i|+ holding_activity("cb_gbp_#{i}", "BALANCE_CASHBACK", "<positive>+ 0.10 GBP</positive>", title: "<strong>Cashback</strong>",+ created_on: (40 - i).days.ago.utc.iso8601(3))+ end+ gbp = link_account(@wise_item.wise_accounts.create!(balance_id: "32000001", name: "Wise GBP", currency: "GBP",+ raw_payload: standard_balance("32000001", "GBP", 3.0)))+ jar = link_account(@wise_item.wise_accounts.create!(balance_id: "32000009", name: "Holiday", currency: "EUR",+ raw_payload: jar_balance("32000009", "EUR", "Holiday", 0.0),+ raw_transactions_payload: cashbacks.last(2)))+ cashbacks.each do |activity|+ jar.current_account.entries.create!(external_id: "wise_activity_#{activity['id']}", source: "wise", amount: -0.10, currency: "GBP",+ date: Time.zone.parse(activity["createdOn"]).to_date, name: "Interest", entryable: Transaction.new)+ end+ provider = FakeWiseProvider.new(balances: [ standard_balance("32000001", "GBP", 3.0) ], savings_balances: [ jar_balance("32000009", "EUR", "Holiday", 0.0) ],+ borderless_accounts: [], activities: cashbacks, raise_on: { get_balance_statements: statements_forbidden })++ 2.times do+ result = WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ WiseItem.find(@wise_item.id).process_accounts(import_complete: result[:complete])+ end++ assert_equal 0, jar.current_account.entries.where(source: "wise").count+ assert_equal 30, gbp.current_account.entries.where(source: "wise").count+ end++ # Interest the failed jar list made fall back to the balance in its+ # currency is not pinned there, so the jar takes it once listed.+ test "interest a failed jar list left on the balance moves to the jar once the list arrives" do+ jar = jar_balance("10000002", "EUR", "Holiday", 1000.0).merge("creationTime" => 200.days.ago.utc.iso8601)+ interest = holding_activity("interest_1", "BALANCE_INTEREST", "<positive>+ 1.12 EUR</positive>")+ [ { get_savings_balances: "Unexpected response 503" }, {} ].each do |failures|+ provider = FakeWiseProvider.new(savings_balances: [ jar ], activities: [ interest ],+ raise_on: { get_balance_statements: statements_forbidden }.merge(failures))+ WiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).import+ end++ assert_equal({ "10000001" => [], "10000002" => [ "interest_1" ] }, payload_ids)+ end++ test "says when the import covered a source for the first time or re-fetched the whole history" do+ provider = FakeWiseProvider.new(raise_on: { get_balance_statements: statements_forbidden })+ import = ->(**options) { WiseItem::Importer.new(WiseItem.find(@wise_item.id), **options).import[:coverage_upgraded] }++ assert import.call(wise_provider: provider)+ assert_not import.call(wise_provider: provider)++ # A sync start date inside the covered window changes nothing; one before+ # anything is covered starts the first coverage.+ assert_not import.call(wise_provider: provider, sync_start_date: 30.days.ago.to_date)+ @wise_item.reload.update!(raw_payload: nil)+ assert import.call(wise_provider: provider, sync_start_date: 30.days.ago.to_date)++ # Coverage that does not reach the full history is fetched again from its start.+ @wise_item.reload.update!(import_all_history: true)+ assert import.call(wise_provider: provider)++ # Fetches that failed upgrade nothing.+ @wise_item.reload.update!(raw_payload: nil)+ failing = FakeWiseProvider.new(raise_on: { get_activities: "Unexpected response 502", get_transfers: "Unexpected response 502",+ get_balance_statements: statements_forbidden })+ assert_not import.call(wise_provider: failing)end# Returns failed result when balances fetch fails@@ -537,6 +3565,32 @@ class WiseItem::ImporterTest < ActiveSupport::TestCaseprivate+ # A statement 403 without an SCA challenge: the token may not read+ # statements at all.+ def statements_forbidden+ Provider::Wise::WiseError.new("Access forbidden — check token permissions", :access_forbidden)+ end++ # What a token Wise asks for SCA gets for every statement without an SCA+ # key: 403 with Wise's SCA challenge, which Sure cannot sign. With a key,+ # what Wise answers to the signed retry.+ def statements_challenged+ Provider::Wise::WiseError.new("Access forbidden — check token permissions", :access_forbidden, sca_challenged: true)+ end++ # EUR and USD balances without statement rows (and more_balances), whose+ # statement requests all raise statement_error, and one EUR payout.+ def two_balances_provider(statement_error, more_balances: [])+ balances = %w[EUR USD].each_with_index.map do |currency, i|+ { "id" => (10000001 + i).to_s, "amount" => { "value" => 10.0, "currency" => currency }, "type" => "STANDARD" }+ end+ borderless = [ { "id" => 88888001, "recipientId" => 99999001,+ "balances" => [ { "id" => 10000001 }, { "id" => 10000002 } ] } ]+ transfers = [ build_transfer(id: 1, source_currency: "EUR", target_currency: "EUR", target_account: 9999) ]+ FakeWiseProvider.new(balances: balances + more_balances, borderless_accounts: borderless, transfers: transfers,+ raise_on: { get_balance_statements: statement_error })+ end+def build_transfer(id:, source_currency: "EUR", target_currency: "EUR", target_account: 9999){"id" => id,@@ -550,16 +3604,244 @@ class WiseItem::ImporterTest < ActiveSupport::TestCase}end- def build_interbalance(title, resource_id:)+ # The activity Wise lists for a transfer (resource TRANSFER, same id).+ # What the importer reports about transfers it cannot book in full.+ def transfer_notes+ DebugLogEntry.where(provider_key: "wise", category: "provider_sync").where("metadata ->> 'operation' = ?", "transfers")+ end++ def build_transfer_activity(transfer_id, primary:, secondary: nil, id: "transfer-activity-#{transfer_id}",+ status: "COMPLETED", title: "<strong>Recipient</strong>",+ created_on: 7.days.ago.utc.iso8601(3))+ {+ "id" => id,+ "type" => "TRANSFER",+ "resource" => { "type" => "TRANSFER", "id" => transfer_id.to_s },+ "title" => title,+ "description" => "Sent",+ "primaryAmount" => primary,+ "secondaryAmount" => secondary,+ "status" => status,+ "createdOn" => created_on,+ "updatedOn" => created_on+ }.compact+ end++ def link_account(wise_account)+ account = Account.create!(family: @family, name: wise_account.name, balance: 0, currency: wise_account.currency,+ accountable: Depository.new(subtype: "checking"))+ AccountProvider.create!(account: account, provider: wise_account)+ wise_account.reload+ end++ def build_interbalance(title, resource_id:, primary: "1,000 EUR", secondary: nil){"id" => "interbalance_#{resource_id}","type" => "INTERBALANCE","resource" => { "type" => "BALANCE_TRANSACTION", "id" => resource_id },"title" => title,- "primaryAmount" => "1,000 EUR",+ "primaryAmount" => primary,+ "secondaryAmount" => secondary,"status" => "COMPLETED","createdOn" => 7.days.ago.iso8601+ }.compact+ end++ # STANDARD balances with their own account details, in the given order.+ def balances_in(currencies)+ currencies.each_with_index.map do |currency, i|+ { "id" => "5000000#{i}", "type" => "STANDARD", "recipientId" => 70000000 + i,+ "amount" => { "value" => 0.0, "currency" => currency }, "reservedAmount" => { "value" => 0.0, "currency" => currency } }+ end+ end++ # A single-leg activity as Wise lists it (card payment unless told+ # otherwise); the secondary is empty when no conversion or fee applied.+ def build_card_activity(id, primary, secondary = "", type: "CARD_PAYMENT", status: "COMPLETED",+ resource_type: "CARD_TRANSACTION", created_on: 3.days.ago.utc.iso8601(3))+ {+ "id" => id,+ "type" => type,+ "resource" => { "type" => resource_type, "id" => "resource_#{id}" },+ "title" => "<strong>Merchant</strong>",+ "description" => "",+ "primaryAmount" => primary,+ "secondaryAmount" => secondary,+ "status" => status,+ "createdOn" => created_on,+ "updatedOn" => created_on+ }+ end++ # extra: more of Wise's keys (totalFees, runningBalance).+ def statement_row(reference, value, currency, date: 2.days.ago.utc.iso8601, details_type: "CARD", **extra)+ { "type" => value.to_d.negative? ? "DEBIT" : "CREDIT", "date" => date,+ "amount" => { "value" => value, "currency" => currency }, "details" => { "type" => details_type },+ "referenceNumber" => reference }.merge(extra)+ end++ # What the importer reports about rows waiting for a statement row.+ def statement_migration_notes+ DebugLogEntry.where(provider_key: "wise", category: "provider_sync").where("metadata ->> 'operation' = ?", "statement_migration")+ end++ # What the importer reports about activities it books on no balance.+ def activity_notes+ DebugLogEntry.where(provider_key: "wise", category: "provider_sync").where("metadata ->> 'operation' = ?", "activity_routing")+ end++ # What processing reports about the stale entries it deleted or kept.+ def prune_notes+ DebugLogEntry.where(provider_key: "wise", category: "provider_sync").where("metadata ->> 'operation' = ?", "prune")+ end++ # What the importer reports about the balance replay.+ def replay_notes+ DebugLogEntry.where(provider_key: "wise", category: "provider_sync").where("metadata ->> 'operation' = ?", "balance_replay")+ end++ # What the importer reports about balances it marks closed or open.+ def balance_notes+ DebugLogEntry.where(provider_key: "wise", category: "provider_sync").where("metadata ->> 'operation' = ?", "balances")+ end++ def standard_balance(id, currency, value)+ { "id" => id, "type" => "STANDARD", "amount" => { "value" => value, "currency" => currency },+ "reservedAmount" => { "value" => 0.0, "currency" => currency } }+ end++ def eur_balance(id, value)+ standard_balance(id, "EUR", value)+ end++ # Statements answered with Wise's SCA challenge, as without an SCA key.+ def profile_provider+ profile = JSON.parse(file_fixture("wise/multi_currency_profile.json").read)+ FakeWiseProvider.new(balances: profile["balances"], borderless_accounts: [],+ multi_currency_account: profile["multi_currency_account"], transfers: profile["transfers"],+ activities: profile["activities"], raise_on: { get_balance_statements: statements_challenged })+ end++ # A GBP balance that held 120 when a card paid its GBP to USD payout+ # (160.25 GBP gross), then paid 20 GBP by card, so Wise holds 100+ # (later_live: what the balance read after the transfers and activities+ # returns instead; more_balances: other balances Wise lists).+ def card_funded_payout_provider(live: 100.0, later_live: nil, balance: {}, more_balances: [], extra_activities: [], raise_on: {}, **options)+ gbp = { "id" => 60000001, "currency" => "GBP", "type" => "STANDARD", "investmentState" => "NOT_INVESTED",+ "creationTime" => "2026-07-01T08:00:00Z", "recipientId" => 90000101,+ "amount" => { "value" => live, "currency" => "GBP" },+ "reservedAmount" => { "value" => 0.0, "currency" => "GBP" } }.merge(balance)+ activities = [+ build_transfer_activity(7101, primary: "<positive>+ 120 GBP</positive>", created_on: "2026-07-07T11:38:24.906Z"),+ build_transfer_activity(7102, primary: "213 USD", secondary: "160.25 GBP", created_on: "2026-07-09T15:21:08.517Z"),+ build_card_activity("card_1", "20 GBP", created_on: "2026-07-13T10:00:00.000Z")+ ]+ FakeWiseProvider.new(+ balances: [ gbp ] + more_balances,+ later_balances: later_live && [ gbp.merge("amount" => { "value" => later_live, "currency" => "GBP" }) ] + more_balances,+ borderless_accounts: [],+ multi_currency_account: { "id" => 40000001, "recipientId" => 90000001, "creationTime" => "2026-07-01T07:59:00Z" },+ transfers: card_funded_transfers, activities: activities + extra_activities,+ raise_on: { get_balance_statements: statements_forbidden }.merge(raise_on), **options+ )+ end++ # The split withdrawal scenario: GBP got a 90 top-up and a 4 GBP fee+ # refund (a type Sure does not book), paid a 93 GBP payout from the+ # balance, got 12 more, and paid what the euro balance did not of a+ # 150 EUR cash withdrawal; the euro balance got eur_top_up just before.+ # Wise holds GBP 5.58 and EUR 0.+ def split_withdrawal_provider(eur_top_up:, savings_balances: [])+ replayable = { "investmentState" => "NOT_INVESTED", "creationTime" => "2026-08-26T13:00:00Z" }+ balances = [ standard_balance(60000001, "GBP", 5.58).merge(replayable, "recipientId" => 90000101),+ standard_balance(60000002, "EUR", 0.0).merge(replayable, "recipientId" => 90000102) ]+ transfer = ->(id, currency, value, target_account, created) {+ build_transfer(id: id, source_currency: currency, target_currency: currency, target_account: target_account)+ .merge("sourceValue" => value.to_f, "targetValue" => value.to_f, "created" => created)}+ # Top-ups into the balances' own account details, and a payout.+ transfers = [ transfer.call(7101, "GBP", "90", 90000101, "2026-09-01 09:20:00"), transfer.call(7102, "GBP", "93", 55555555, "2026-09-05 11:12:00"),+ transfer.call(7103, "GBP", "12", 90000101, "2026-09-08 15:35:00"), transfer.call(7104, "EUR", eur_top_up, 90000102, "2026-09-11 07:50:00") ]+ activities = [+ build_transfer_activity(7101, primary: "<positive>+ 90 GBP</positive>", created_on: "2026-09-01T09:20:00.500Z"),+ build_card_activity("fee_refund_1", "<positive>+ 4 GBP</positive>", type: "FEE_REFUND", resource_type: "BALANCE_TRANSACTION",+ created_on: "2026-09-01T13:45:00.000Z"),+ build_transfer_activity(7102, primary: "93 GBP", created_on: "2026-09-05T11:12:00.500Z"),+ build_transfer_activity(7103, primary: "<positive>+ 12 GBP</positive>", created_on: "2026-09-08T15:35:00.500Z"),+ build_transfer_activity(7104, primary: "<positive>+ #{eur_top_up} EUR</positive>", created_on: "2026-09-11T07:50:00.500Z"),+ build_card_activity("atm_1", "150 EUR", "GBP, EUR", type: "CASH_WITHDRAWAL", created_on: "2026-09-11T10:41:00.000Z")+ ]+ FakeWiseProvider.new(+ balances: balances, savings_balances: savings_balances, borderless_accounts: [],+ multi_currency_account: { "id" => 40000001, "recipientId" => 90000001, "creationTime" => "2026-08-26T12:59:00Z" },+ transfers: transfers, activities: activities, raise_on: { get_balance_statements: statements_forbidden }+ )+ end++ # The card-funded payout scenario's top-up into the GBP balance's own+ # account details and the 158.40 (gross 160.25) GBP to USD payout.+ def card_funded_transfers+ [ build_transfer(id: 7101, source_currency: "GBP", target_currency: "GBP", target_account: 90000101)+ .merge("created" => "2026-07-07 11:38:24", "sourceValue" => 120.0, "targetValue" => 120.0),+ build_transfer(id: 7102, source_currency: "GBP", target_currency: "USD", target_account: 55555555)+ .merge("created" => "2026-07-09 15:21:07", "sourceValue" => 158.4, "targetValue" => 213.0) ]+ end++ # { currency => [[activity id, split parts, estimated currencies], ...] }+ # for the stored rows that carry split parts.+ def split_marks+ @wise_item.wise_accounts.reload.to_h do |wise_account|+ marked = Array(wise_account.raw_transactions_payload).select { |row| row.key?("wise_split_parts") }+ [ wise_account.currency, marked.map { |row| row.values_at("id", "wise_split_parts", "wise_split_estimated") }.sort_by(&:first) ]+ end.reject { |_currency, rows| rows.empty? }+ end++ # [currency, transfer id] of each stored transfer marked externally funded.+ def funding_marks+ @wise_item.wise_accounts.reload.flat_map do |wise_account|+ Array(wise_account.raw_transactions_payload).select { |row| row["wise_funding"] == "external" }+ .map { |row| [ wise_account.currency, row["id"] ] }+ end+ end++ # Links (once) and processes every balance:+ # { currency => [[entry id, external id, amount], ...] }.+ def process_every_balance+ @wise_item.wise_accounts.reload.to_h do |wise_account|+ wise_account = link_account(wise_account) unless wise_account.current_account+ assert WiseAccount::Transactions::Processor.new(wise_account).process[:success]+ [ wise_account.currency, wise_account.current_account.entries.order(:external_id).pluck(:id, :external_id, :amount) ]+ end+ end++ def jar_balance(id, currency, name, value = 0.0)+ { "id" => id, "type" => "SAVINGS", "name" => name, "amount" => { "value" => value, "currency" => currency },+ "totalWorth" => { "value" => value, "currency" => currency }, "reservedAmount" => { "value" => 0.0, "currency" => currency } }+ end++ # Interest, cashback or a fee on what a balance holds.+ def holding_activity(id, type, primary, title: "<strong>Interest</strong>", created_on: 3.days.ago.utc.iso8601(3))+ build_card_activity(id, primary, type: type, resource_type: type, created_on: created_on).merge("title" => title)+ end++ # { balance id => sorted ids of the rows stored on it }.+ def payload_ids+ @wise_item.wise_accounts.reload.to_h do |wise_account|+ [ wise_account.balance_id, Array(wise_account.raw_transactions_payload).map { |row| row["id"] }.sort ]+ end+ end++ # Links (once) and processes every balance, then links the conversion+ # legs: { balance name => [[external id, amount, currency], ...] }+ # (key: :balance_id where jars share a name).+ def book_every_balance(key: :name)+ booked = @wise_item.wise_accounts.reload.to_h do |wise_account|+ wise_account = link_account(wise_account) unless wise_account.current_account+ assert WiseAccount::Transactions::Processor.new(wise_account).process[:success]+ [ wise_account.public_send(key), wise_account.current_account.entries.where(source: "wise").order(:external_id).pluck(:external_id, :amount, :currency) ]+ end+ @wise_item.link_jar_transfers!+ bookedenddef build_cashback(resource_id)diff --git a/test/models/wise_item/statement_migration_test.rb b/test/models/wise_item/statement_migration_test.rbnew file mode 100644index 0000000000..634082faf7--- /dev/null+++ b/test/models/wise_item/statement_migration_test.rb@@ -0,0 +1,278 @@+require "test_helper"++# The rows a balance booked before it had statements hand their movements over+# to the statement rows carrying them.+class WiseItem::StatementMigrationTest < ActiveSupport::TestCase+ OWN_RECIPIENT = 70000001++ setup do+ @family = families(:empty)+ @wise_item = WiseItem.create!(family: @family, name: "Test Wise", token: "test_token", profile_id: "123", profile_type: :business)+ @eur = @wise_item.wise_accounts.create!(balance_id: "10000001", name: "Wise EUR", currency: "EUR",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "recipientId" => OWN_RECIPIENT })+ end++ test "a statement row takes over the transfer its reference names, and a refund credit its refund" do+ payout = transfer(101, 100, created: "2026-03-01 10:00:00", gross: "102.50 EUR")+ top_up = transfer(102, 500, created: "2026-03-02 10:00:00", target: OWN_RECIPIENT)+ refunded = transfer(103, 40, created: "2026-03-10 10:00:00", status: "funds_refunded",+ refund: "<positive>+ 40 EUR</positive>")+ rows = [ payout, top_up, refunded,+ statement("TRANSFER-101", "-102.50", "2026-03-01T10:05:00Z", fee: "2.50"),+ statement("TRANSFER-102", "500", "2026-03-02T10:01:00Z", type: "DEPOSIT"),+ statement("TRANSFER-103", "-40", "2026-03-10T10:01:00Z"),+ statement("TRANSFER-103", "40", "2026-03-12T09:00:00Z") ]++ result = migrate(rows)++ assert_equal "wise_statement_TRANSFER-101", row(result, 101)["wise_superseded_by"]+ assert_equal({ "main" => "wise_transfer_101", "fee" => "wise_fee_101" }, statement_row(result, "TRANSFER-101")["wise_supersedes"])+ assert_equal({ "main" => "wise_transfer_102", "fee" => "wise_fee_102" }, statement_row(result, "TRANSFER-102")["wise_supersedes"])+ debit, credit = statement_rows(result, "TRANSFER-103")+ assert_equal({ "main" => "wise_transfer_103", "fee" => "wise_fee_103" }, debit["wise_supersedes"])+ assert_equal({ "main" => "wise_refund_103" }, credit["wise_supersedes"])+ assert_equal "TRANSFER-103_CREDIT_20260312", credit["wise_statement_id"]+ assert_equal "wise_statement_TRANSFER-103", row(result, 103)["wise_superseded_by"]+ assert_equal 3, result.counts[:transfers_matched]+ assert_equal 0, result.counts[:transfers_unmatched]+ end++ # A refunded payout created before the statements' window has only its+ # refund credit inside it, and that credit, the only row with the reference,+ # took the payout over as its main row (the payout's entry became the+ # refund, its fee and refund entries went). A row takes a transfer over only+ # with the sign of the transfer's own movement. The refund credit books+ # nothing here: the transfer's row keeps booking the payout, its fee and the+ # refund. A credit for a payout that was not refunded (bounced back, say)+ # books on its own.+ test "takes a transfer over only by a row of its own sign, and lets a refunded payout from before the window keep its refund" do+ refunded = transfer(601, 100, created: "2025-12-02 10:00:00", status: "funds_refunded", gross: "102.50 EUR",+ refund: "<positive>+ 100 EUR</positive>")+ sent = transfer(602, 30, created: "2025-12-03 10:00:00")+ rows = [ refunded, sent,+ statement("TRANSFER-601", "100", "2025-12-17T10:00:00Z"),+ statement("TRANSFER-602", "30", "2025-12-18T10:00:00Z") ]++ result = migrate(rows)++ assert_nil row(result, 601)["wise_superseded_by"]+ assert_nil row(result, 602)["wise_superseded_by"]+ assert_equal [ "wise_refund_601", nil ], statement_row(result, "TRANSFER-601").values_at("wise_superseded_by", "wise_supersedes")+ assert_equal [ nil, nil ], statement_row(result, "TRANSFER-602").values_at("wise_superseded_by", "wise_supersedes")+ assert_equal [ 0, 0 ], result.counts.values_at(:transfers_matched, :transfers_unmatched)+ end++ # Wise documents no reference format, so a TRANSFER row of the transfer's+ # amount (a payout's gross, what a pay-in credited) within a day stands in.+ test "matches a transfer without its reference by a TRANSFER row of its amount within a day" do+ payout = transfer(201, 100, created: "2026-03-01 22:00:00", gross: "102.50 EUR")+ top_up = transfer(202, 300, created: "2026-03-03 08:00:00", target: OWN_RECIPIENT)+ rows = [ payout, top_up,+ statement("P-card", "-102.50", "2026-03-01T22:05:00Z", type: "CARD"),+ statement("P-far", "-102.50", "2026-03-04T10:00:00Z"),+ statement("P-later", "-102.50", "2026-03-02T20:00:00Z"),+ statement("P-near", "-102.50", "2026-03-02T01:00:00Z"),+ statement("P-in", "300", "2026-03-03T08:30:00Z") ]++ result = migrate(rows)++ assert_equal "wise_statement_P-near", row(result, 201)["wise_superseded_by"]+ assert_equal "wise_statement_P-in", row(result, 202)["wise_superseded_by"]+ assert_equal %w[P-card P-far P-later], result.rows.select { |r| r["wise_statement"] && r["wise_supersedes"].nil? }.map { |r| r["referenceNumber"] }+ end++ # While a booked transfer inside the statements' window has no statement+ # row, the balance keeps its transfer rows (they keep booking) and none+ # leaves, matched ones included.+ test "keeps every transfer row while one that books inside the window has no statement row" do+ rows = [ transfer(301, 10, created: "2026-03-01 10:00:00"),+ transfer(302, 20, created: "2026-04-01 10:00:00"),+ transfer(303, 30, created: "2025-12-01 10:00:00"),+ transfer(304, 40, created: "2026-04-02 10:00:00", status: "cancelled"),+ statement("TRANSFER-301", "-10", "2026-03-01T10:01:00Z") ]++ result = migrate(rows, entry_ids: ->(_ids) { [] })++ assert_equal [ 301, 302, 303, 304 ], result.rows.filter_map { |r| r["id"] }+ assert_equal [ 1, 1, 0 ], result.counts.values_at(:transfers_matched, :transfers_unmatched, :retired)+ assert_nil row(result, 302)["wise_superseded_by"]+ end++ test "retires the rows a statement row took over once the account has no entry under their ids" do+ rows = [ transfer(401, 10, created: "2026-03-01 10:00:00"), card("a", "12.50 EUR", at: "2026-03-02T10:00:00Z"),+ statement("TRANSFER-401", "-10", "2026-03-01T10:01:00Z"), statement("CARD-rid_a", "-12.50", "2026-03-02T10:00:00Z") ]+ asked = []+ fee_left = lambda do |ids|+ asked << ids.sort+ [ "wise_fee_401" ]+ end++ waiting = migrate(rows, entry_ids: fee_left)+ assert_equal [ [ "wise_activity_a", "wise_fee_401", "wise_refund_401", "wise_transfer_401" ] ], asked+ assert_equal [ 401 ], waiting.rows.filter_map { |r| r["id"] }+ assert_equal 1, waiting.counts[:retired]++ renamed = migrate(rows, entry_ids: ->(_ids) { [] })+ assert_empty renamed.rows.filter_map { |r| r["id"] }+ assert_equal [ "TRANSFER-401", "CARD-rid_a" ], renamed.rows.map { |r| r["referenceNumber"] }+ assert_equal 2, renamed.counts[:retired]++ unlinked = migrate(rows, entry_ids: nil)+ assert_equal [ 401, "a" ], unlinked.rows.filter_map { |r| r["id"] }+ end++ # Card payments booked from the activity feed before statements worked are+ # taken over by CARD-<resource id> (a refund credit sharing the reference is+ # not the payment), else by sign, amount and day. Inside the window the rest+ # is dropped, as some statement row carries it; before it, they stay.+ test "hands activities over by their reference, else by amount and day, and drops the rest of the window" do+ rows = [ card("a", "12.50 EUR", at: "2026-03-02T10:00:00Z"),+ card("b", "8 EUR", at: "2026-03-05T23:30:00Z"),+ card("c", "5 EUR", at: "2026-03-07T10:00:00Z"),+ card("d", "6 EUR", at: "2026-03-08T10:00:00Z", status: "IN_PROGRESS"),+ card("e", "7 EUR", at: "2025-11-01T10:00:00Z"),+ statement("CARD-rid_a", "12.50", "2026-03-01T10:00:00Z", type: "CARD"),+ statement("CARD-rid_a", "-12.50", "2026-03-02T10:00:00Z", type: "CARD"),+ statement("CARD-999", "-8", "2026-03-06T10:00:00Z", type: "CARD") ]++ result = migrate(rows)++ assert_equal %w[a b e], result.rows.filter_map { |r| r["id"] }+ credit, debit = statement_rows(result, "CARD-rid_a")+ assert_nil credit["wise_supersedes"]+ assert_equal({ "main" => "wise_activity_a" }, debit["wise_supersedes"])+ assert_equal "wise_statement_#{debit['wise_statement_id']}", row(result, "a")["wise_superseded_by"]+ assert_equal({ "main" => "wise_activity_b" }, statement_row(result, "CARD-999")["wise_supersedes"])+ assert_nil row(result, "e")["wise_superseded_by"]+ assert_equal [ 2, 1 ], result.counts.values_at(:activities_matched, :activities_unmatched)+ end++ # Wise's conversion rows stay (verified, they link as transfers); a+ # statement row of the same move books nothing.+ test "lets a conversion's own row book it instead of the statement row of the same move" do+ rows = [ conversion("4001", "To <strong>EUR</strong>", "117.50 EUR", "100 GBP", at: "2026-03-03T10:00:00Z"),+ conversion("6000", "To <strong>Holiday</strong>", "500 EUR", nil, at: "2026-03-04T10:00:00Z"),+ statement("BALANCE-4001", "117.50", "2026-03-03T10:00:00Z", type: "CONVERSION"),+ statement("BALANCE-4002", "50", "2026-03-03T11:00:00Z", type: "CONVERSION"),+ statement("CARD-1", "117.50", "2026-03-03T12:00:00Z", type: "CARD"),+ statement("BALANCE-6000", "-500", "2026-03-04T10:00:00Z", type: "OUTGOING_CROSS_BALANCE") ]++ result = migrate(rows)++ marks = result.rows.select { |r| r["wise_statement"] }.to_h { |r| [ r["referenceNumber"], r["wise_superseded_by"] ] }+ assert_equal({ "BALANCE-4001" => "wise_interbalance_4001_inflow", "BALANCE-4002" => nil, "CARD-1" => nil,+ "BALANCE-6000" => "wise_interbalance_6000_outflow" }, marks)+ assert_equal 2, result.counts[:conversions_matched]+ assert_equal 2, result.rows.count { |r| r["type"] == "INTERBALANCE" }+ end++ # Wise reuses a transfer's reference on its refund: the earliest row keeps+ # it as its id.+ test "gives statement rows sharing a reference their own ids" do+ rows = [ statement("TRANSFER-555", "60", "2026-03-03T10:00:00Z"),+ statement("TRANSFER-555", "-100", "2026-03-01T10:00:00Z"),+ statement("TRANSFER-555", "40", "2026-03-03T15:00:00Z"),+ statement("CARD-1", "-5", "2026-03-03T15:00:00Z", type: "CARD") ]++ result = migrate(rows)++ assert_equal [ "TRANSFER-555_CREDIT_20260303", nil, "TRANSFER-555_CREDIT_20260303_40.0", nil ],+ result.rows.map { |r| r["wise_statement_id"] }+ end++ test "works the marks out again from the rows, but a statement row keeps its id" do+ rows = [ transfer(501, 10, created: "2026-03-01 10:00:00").merge("wise_superseded_by" => "wise_statement_TRANSFER-501"),+ statement("CARD-1", "-5", "2026-03-03T15:00:00Z", type: "CARD")+ .merge("wise_supersedes" => { "main" => "wise_activity_x" }, "wise_statement_id" => "CARD-1_DEBIT_20260303") ]++ result = migrate(rows)++ assert result.rows.none? { |r| r.keys.intersect?(WiseItem::StatementMigration::WORKED_OUT_KEYS) }+ assert_equal "CARD-1_DEBIT_20260303", statement_row(result, "CARD-1")["wise_statement_id"]+ assert_equal 1, result.counts[:transfers_unmatched]+ end++ # The window grew back (the full history switched on), so the debit of a+ # refund booked under the plain reference turns up after it: the refund+ # keeps its id and the debit gets its own, rather than the debit taking+ # over the refund's entry.+ test "keeps a statement row's id when an earlier row with its reference turns up" do+ refund = statement("TRANSFER-9", "100", "2026-03-10T10:00:00Z")+ stored = WiseItem::StatementMigration.with_booked_ids([ refund ])+ rows = stored + [ statement("TRANSFER-9", "-100", "2026-03-01T10:00:00Z") ]++ result = migrate(rows)++ assert_equal [ "TRANSFER-9_DEBIT_20260301", "TRANSFER-9" ], statement_rows(result, "TRANSFER-9").map { |r| r["wise_statement_id"] }+ end++ # Wise refused the balance's statements after October 1: a card payment+ # after that has no statement row to hand over to, so it stays.+ test "drops no activity after the end of the statements' window" do+ card = card("after", "12 EUR", at: "2026-10-05T10:00:00Z")++ result = migrate([ card ], window: { from: Time.utc(2025, 12, 10), through: Time.utc(2026, 10, 1) })++ assert_equal [ "after" ], result.rows.map { |r| r["id"] }+ assert_equal 0, result.counts[:activities_unmatched]+ end++ # Only one stored row without an id booked under the plain reference: the+ # earliest, as Sure gave it that id.+ test "with_booked_ids gives the plain reference to the stored row that booked under it" do+ rows = [ statement("TRANSFER-7", "40", "2026-03-03T10:00:00Z"), statement("TRANSFER-7", "-100", "2026-03-01T10:00:00Z"),+ statement("TRANSFER-8", "-5", "2026-03-01T10:00:00Z").merge("wise_statement_id" => "TRANSFER-8"),+ statement("TRANSFER-8", "5", "2026-03-02T10:00:00Z") ]++ assert_equal [ nil, "TRANSFER-7", "TRANSFER-8", nil ], WiseItem::StatementMigration.with_booked_ids(rows).map { |r| r["wise_statement_id"] }+ end++ private++ # entry_ids: nil (the default) as for a balance not linked, so no row leaves.+ def migrate(rows, window: { from: Time.utc(2025, 12, 10), through: Time.utc(2026, 10, 17) }, entry_ids: nil)+ WiseItem::StatementMigration.new(@eur, rows, own_recipient_ids: @wise_item.own_recipient_ids, window: window,+ entry_ids: entry_ids).call+ end++ # A same-currency transfer as /v1/transfers lists it: a payout unless it+ # targets the balance's own recipient; gross: the activity's gross debit+ # (sourceValue excludes the fee); refund: a refund credit's amount.+ def transfer(id, value, created:, target: 4242, status: "outgoing_payment_sent", gross: nil, refund: nil)+ row = { "id" => id, "targetAccount" => target, "sourceCurrency" => "EUR", "targetCurrency" => "EUR",+ "sourceValue" => value, "targetValue" => value, "status" => status, "created" => created }+ row["wise_activity"] = { "id" => "act-#{id}", "type" => "TRANSFER", "status" => "COMPLETED", "primaryAmount" => "#{value} EUR",+ "secondaryAmount" => gross, "createdOn" => "#{created.sub(' ', 'T')}Z" } if gross+ row["wise_refund_activity"] = { "id" => "refund-#{id}", "type" => "TRANSFER", "status" => "COMPLETED", "primaryAmount" => refund } if refund+ row+ end++ def statement(reference, value, date, type: "TRANSFER", fee: nil)+ { "type" => value.to_d.negative? ? "DEBIT" : "CREDIT", "date" => date, "amount" => { "value" => value, "currency" => "EUR" },+ "totalFees" => ({ "value" => fee, "currency" => "EUR" } if fee), "details" => { "type" => type },+ "referenceNumber" => reference, "wise_statement" => true }.compact+ end++ def card(id, primary, at:, status: "COMPLETED")+ { "id" => id, "type" => "CARD_PAYMENT", "resource" => { "type" => "CARD_TRANSACTION", "id" => "rid_#{id}" },+ "title" => "<strong>Merchant</strong>", "primaryAmount" => primary, "secondaryAmount" => "", "status" => status,+ "createdOn" => at, "updatedOn" => at }+ end++ def conversion(resource_id, title, primary, secondary, at:)+ { "id" => "interbalance_#{resource_id}", "type" => "INTERBALANCE", "resource" => { "type" => "BALANCE_TRANSACTION", "id" => resource_id },+ "title" => title, "primaryAmount" => primary, "secondaryAmount" => secondary, "status" => "COMPLETED", "createdOn" => at }.compact+ end++ def row(result, id)+ result.rows.find { |r| r["id"] == id }+ end++ def statement_rows(result, reference)+ result.rows.select { |r| r["referenceNumber"] == reference }.sort_by { |r| r["date"] }+ end++ def statement_row(result, reference)+ statement_rows(result, reference).sole+ end+enddiff --git a/test/models/wise_item/syncer_test.rb b/test/models/wise_item/syncer_test.rbindex ce65ad95f5..2e192fe490 100644--- a/test/models/wise_item/syncer_test.rb+++ b/test/models/wise_item/syncer_test.rb@@ -15,4 +15,67 @@ class WiseItem::SyncerTest < ActiveSupport::TestCaseassert_equal I18n.t("wise_items.syncer.credentials_invalid"), sync.errorassert wise_item.reload.requires_update?end++ # A failed fetch completed the sync with no error anywhere. It still+ # completes, but the error is in the sync stats the Wise card shows, and+ # processing is told the import was incomplete.+ test "reports failed fetches and withholds the complete flag from processing" do+ wise_item = linked_wise_item+ WiseItem.any_instance.stubs(:import_latest_wise_data)+ .returns(success: false, complete: false, fetch_failures: 2, accounts_failed: 0, transactions_failed: 0)+ WiseItem.any_instance.expects(:process_accounts).with(import_complete: false).returns([])+ WiseItem.any_instance.stubs(:schedule_account_syncs).returns([])+ sync = Sync.create!(syncable: wise_item)++ sync.perform++ assert sync.reload.completed?, "expected the sync to complete, was #{sync.status}"+ assert_equal 1, sync.sync_stats["total_errors"]+ assert_equal [ I18n.t("wise_items.syncer.fetch_failed", count: 2) ], sync.sync_stats["errors"].map { |error| error["message"] }+ end++ test "tells processing the import was complete when every fetch succeeded" do+ wise_item = linked_wise_item+ WiseItem.any_instance.stubs(:import_latest_wise_data)+ .returns(success: true, complete: true, fetch_failures: 0, accounts_failed: 0, transactions_failed: 0)+ WiseItem.any_instance.expects(:process_accounts).with(import_complete: true).returns([])+ WiseItem.any_instance.stubs(:schedule_account_syncs).returns([])+ sync = Sync.create!(syncable: wise_item)++ sync.perform++ assert_equal 0, sync.reload.sync_stats["total_errors"]+ end++ # A full re-fetch (coverage_upgraded) is no longer passed on; the balances+ # it rebuilt keep their cap bypass themselves+ # (WiseAccount#prune_cap_bypass_ids).+ test "records the stale entries processing deleted" do+ wise_item = linked_wise_item+ WiseItem.any_instance.stubs(:import_latest_wise_data)+ .returns(success: true, complete: true, coverage_upgraded: true, fetch_failures: 0, accounts_failed: 0, transactions_failed: 0)+ WiseItem.any_instance.expects(:process_accounts).with(import_complete: true).returns([+ { wise_account_id: 1, success: true, result: { imported: 3, skipped: 0, failed: 0, pruned: 2 } },+ { wise_account_id: 2, success: true, result: { imported: 1, skipped: 0, failed: 0, pruned: 1 } },+ { wise_account_id: 3, success: true, result: nil }+ ])+ WiseItem.any_instance.stubs(:schedule_account_syncs).returns([])+ sync = Sync.create!(syncable: wise_item)++ sync.perform++ assert_equal 3, sync.reload.sync_stats["wise_pruned_entries"]+ summary = DebugLogEntry.where(provider_key: "wise", source: "WiseItem::Syncer").order(:created_at).last+ assert_equal 3, summary.metadata["pruned_entry_count"]+ end++ private++ def linked_wise_item+ wise_item = wise_items(:one)+ account = Account.create!(family: wise_item.family, name: "Wise EUR", balance: 0, currency: "EUR",+ accountable: Depository.new(subtype: "checking"))+ AccountProvider.create!(account: account, provider: wise_accounts(:checking))+ wise_item+ endenddiff --git a/test/models/wise_item_test.rb b/test/models/wise_item_test.rbindex fdbd44d68b..65eb78e3e6 100644--- a/test/models/wise_item_test.rb+++ b/test/models/wise_item_test.rb@@ -137,25 +137,127 @@ class WiseItemTest < ActiveSupport::TestCaseassert_not_equal first_public_key, second_public_keyend+ # Sync metadata (raw_payload)++ test "sync metadata reads a blank raw_payload and merges writes" do+ assert_equal({}, @wise_item.sync_metadata)+ assert_nil @wise_item.fetch_coverage(:transfers)++ @wise_item.merge_sync_metadata!(coverage: { "transfers" => { "from" => "2025-04-02T16:00:00Z", "through" => "2026-10-17T12:00:00Z",+ "version" => WiseItem::COVERAGE_VERSION } })+ @wise_item.merge_sync_metadata!("multi_currency_account" => { "recipientId" => 99999001 })++ assert_equal %w[coverage multi_currency_account], @wise_item.reload.raw_payload.keys.sort+ assert_equal({ from: Time.utc(2025, 4, 2, 16), through: Time.utc(2026, 10, 17, 12) }, @wise_item.fetch_coverage("transfers"))+ assert_nil @wise_item.fetch_coverage(:activities)+ end++ # Coverage an older build recorded claims rows that build did not keep, so+ # it counts as none.+ test "fetch coverage ignores coverage recorded under an older coverage version" do+ window = { "from" => "2025-08-27T03:00:00Z", "through" => "2026-10-17T12:00:00Z" }+ @wise_item.merge_sync_metadata!(coverage: { "transfers" => window, "activities" => window.merge("version" => WiseItem::COVERAGE_VERSION - 1) })+ assert_nil @wise_item.fetch_coverage(:transfers)+ assert_nil @wise_item.fetch_coverage(:activities)++ @wise_item.merge_sync_metadata!(coverage: { "transfers" => window.merge("version" => WiseItem::COVERAGE_VERSION + 1) })+ assert_equal({ from: Time.utc(2025, 8, 27, 3), through: Time.utc(2026, 10, 17, 12) }, @wise_item.fetch_coverage(:transfers))+ end++ # Family checks its zone only when it changes, so a zone stored before that+ # check (or one tzdata dropped later) can stay. Every Wise row then failed+ # on it; now Wise dates fall back to UTC, reported once a day rather than on+ # every sync of every balance.+ test "time zone falls back to UTC for a family zone tzdata does not know, reported once a day" do+ original_cache = Rails.cache+ # The test store (:null_store) keeps nothing, so the once-a-day lease+ # needs a real one.+ Rails.cache = ActiveSupport::Cache::MemoryStore.new+ @family.update_column(:timezone, "Invalid/Timezone")+ notes = -> { DebugLogEntry.where(provider_key: "wise").where("metadata ->> 'operation' = ?", "time_zone") }++ assert_difference -> { notes.call.count }, 1 do+ 2.times { assert_equal ActiveSupport::TimeZone["UTC"], WiseItem.find(@wise_item.id).time_zone }+ end+ assert_equal [ "warn", @family ], notes.call.sole.then { |note| [ note.level, note.family ] }++ @family.update_column(:timezone, "Europe/Dublin")+ assert_equal ActiveSupport::TimeZone["Europe/Dublin"], WiseItem.find(@wise_item.id).time_zone+ @family.update_column(:timezone, nil)+ assert_equal ActiveSupport::TimeZone["UTC"], WiseItem.find(@wise_item.id).time_zone+ ensure+ Rails.cache = original_cache+ end++ test "own_recipient_ids holds the account recipient and every balance's own recipient" do+ @wise_item.merge_sync_metadata!("multi_currency_account" => { "recipientId" => 99999009 })+ @standard_account.update!(raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "recipientId" => 77777001 })+ WiseAccount.create!(wise_item: @wise_item, balance_id: "10000003", name: "Wise USD", currency: "USD",+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001, "recipientId" => 77777003,+ "closed_at" => "2026-09-01T00:00:00Z" })++ assert_equal %w[99999009 99999001 77777001 77777003].sort, @wise_item.own_recipient_ids.sort+ end++ # Each balance's processing asks for the recipients, so reading every+ # balance's stored rows (the whole history) for them would grow with the+ # square of the balances.+ test "reads the recipients without loading any balance's stored rows" do+ @standard_account.update!(raw_payload: { "type" => "STANDARD", "recipientId" => 77777001 },+ raw_transactions_payload: [ { "id" => 1 } ])+ queries = []+ callback = ->(*, payload) { queries << payload[:sql] if payload[:sql].include?("wise_accounts") }++ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do+ assert_includes WiseItem.find(@wise_item.id).own_recipient_ids, "77777001"+ assert_equal({ "77777001" => [ @standard_account.id ] }, WiseItem.find(@wise_item.id).balance_recipient_owners)+ end++ assert_equal 2, queries.size+ queries.each { |sql| assert_no_match(/raw_transactions_payload|wise_accounts"\.\*/, sql) }+ end++ # Whether the import re-fetched the whole history no longer travels with it:+ # the balances whose rows that moved keep it themselves+ # (WiseAccount#prune_cap_bypass_ids).+ test "process_accounts tells each account processor whether the import was complete" do+ WiseAccount::Processor.expects(:new).with(@standard_account, import_complete: true).returns(stub(process: { imported: 0 }))+ WiseAccount::Processor.expects(:new).with(@jar_account, import_complete: true).returns(stub(process: { imported: 0 }))++ results = @wise_item.process_accounts(import_complete: true)++ assert_equal [ true, true ], results.map { |result| result[:success] }+ end++ test "process_accounts assumes an incomplete import unless told otherwise" do+ WiseAccount::Processor.expects(:new).twice+ .with { |_wise_account, options| options == { import_complete: false } }+ .returns(stub(process: nil))++ @wise_item.process_accounts+ end+# link_jar_transfers!+ #+ # Legs are booked through WiseActivity::Processor, as a sync books them, so+ # they start out as standard transactions. These tests used to build the legs+ # by hand as funds_movement, which hid that linking never set any kinds.test "links matching interbalance inflow and outflow entries as a Transfer" do- inflow_entry = create_interbalance_entry(@jar_sure_account, "5001", side: :inflow, amount: -1000.0)- outflow_entry = create_interbalance_entry(@standard_sure_account, "5001", side: :outflow, amount: 1000.0)+ inflow, outflow = book(jar_deposit("5001", "1,000 EUR"), @jar_account, @standard_account)assert_difference "Transfer.count", 1 do@wise_item.link_jar_transfers!end- transfer = Transfer.find_by(inflow_transaction_id: inflow_entry.entryable_id)- assert_not_nil transfer- assert_equal outflow_entry.entryable_id, transfer.outflow_transaction_id- assert_equal "confirmed", transfer.status+ transfer = Transfer.find_by!(inflow_transaction_id: inflow.entryable_id)+ assert_equal outflow.entryable_id, transfer.outflow_transaction_id+ assert transfer.confirmed?+ assert_equal %w[funds_movement funds_movement], leg_kinds(inflow, outflow)endtest "does not create duplicate Transfer for already-linked pair" do- inflow_entry = create_interbalance_entry(@jar_sure_account, "5002", side: :inflow, amount: -2000.0)- outflow_entry = create_interbalance_entry(@standard_sure_account, "5002", side: :outflow, amount: 2000.0)+ book(jar_deposit("5002", "2,000 EUR"), @jar_account, @standard_account)@wise_item.link_jar_transfers!@@ -165,7 +267,7 @@ class WiseItemTest < ActiveSupport::TestCaseendtest "skips unmatched inflow entries with no corresponding outflow" do- create_interbalance_entry(@jar_sure_account, "5003", side: :inflow, amount: -500.0)+ book(jar_deposit("5003", "500 EUR"), @jar_account)assert_no_difference "Transfer.count" do@wise_item.link_jar_transfers!@@ -173,10 +275,8 @@ class WiseItemTest < ActiveSupport::TestCaseendtest "links multiple interbalance pairs in one call" do- create_interbalance_entry(@jar_sure_account, "6001", side: :inflow, amount: -1000.0)- create_interbalance_entry(@standard_sure_account, "6001", side: :outflow, amount: 1000.0)- create_interbalance_entry(@jar_sure_account, "6002", side: :inflow, amount: -3000.0)- create_interbalance_entry(@standard_sure_account, "6002", side: :outflow, amount: 3000.0)+ book(jar_deposit("6001", "1,000 EUR"), @jar_account, @standard_account)+ book(jar_deposit("6002", "3,000 EUR"), @jar_account, @standard_account)assert_difference "Transfer.count", 2 do@wise_item.link_jar_transfers!@@ -189,6 +289,296 @@ class WiseItemTest < ActiveSupport::TestCaseendend+ # Without transfer kinds, reports counted every conversion as income on one+ # balance and spending on the other.+ test "a linked conversion counts as neither income nor spending" do+ inflow, outflow = book(gbp_to_eur("9000000106"), @standard_account, create_balance("GBP", "10000003"))++ @wise_item.link_jar_transfers!++ assert Transfer.find_by!(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: outflow.entryable_id).confirmed?+ assert_equal %w[funds_movement funds_movement], leg_kinds(inflow, outflow)+ end++ test "repairs a conversion linked before its legs got transfer kinds" do+ inflow, outflow = book(gbp_to_eur("9000000106"), @standard_account, create_balance("GBP", "10000003"))+ # What earlier versions saved: a confirmed transfer with both legs standard.+ transfer = Transfer.create!(inflow_transaction: inflow.entryable, outflow_transaction: outflow.entryable, status: "confirmed")++ assert_no_difference "Transfer.count" do+ @wise_item.link_jar_transfers!+ end++ assert transfer.reload.confirmed?+ assert_equal %w[funds_movement funds_movement], leg_kinds(inflow, outflow)+ end++ # An older build read this withdrawal from a jar Wise named like its+ # currency as a deposit, booked its legs on the wrong sides and linked them+ # that way round. The legs are renamed to their sides (and re-signed), and+ # the reversed link is replaced, so the withdrawal is no income and no+ # spending.+ test "replaces a link an older build made the wrong way round" do+ @jar_account.update!(name: "EUR", raw_payload: { "type" => "SAVINGS", "name" => "EUR" })+ withdrawal = interbalance("5501", title: "To <strong>EUR</strong>", primary: "500 EUR")+ jar_leg = leg(@jar_account, "5501_inflow", -500)+ balance_leg = leg(@standard_account, "5501_outflow", 500)+ Transfer.create!(inflow_transaction: jar_leg.entryable, outflow_transaction: balance_leg.entryable, status: "confirmed")+ [ @jar_account, @standard_account ].each do |wise_account|+ wise_account.update!(raw_transactions_payload: [ withdrawal ])+ WiseAccount::Transactions::Processor.new(wise_account.reload, import_complete: true).process+ end++ stats = @wise_item.link_jar_transfers!++ transfer = Transfer.where(inflow_transaction_id: [ balance_leg.entryable_id, jar_leg.entryable_id ]).sole+ assert_equal [ balance_leg.entryable_id, jar_leg.entryable_id ], [ transfer.inflow_transaction_id, transfer.outflow_transaction_id ]+ assert_equal [ "wise_interbalance_5501_inflow", BigDecimal("-500") ], balance_leg.reload.values_at(:external_id, :amount)+ assert transfer.confirmed? && transfer.valid?+ assert_equal %w[funds_movement funds_movement], leg_kinds(balance_leg, jar_leg)+ assert_equal 1, stats[:replaced_stale_links]+ end++ # Removing a link the linker made (the transfer drawer's Delete) records a+ # rejection, so the next sync does not link the legs again.+ test "a link the linker makes again on its own is told apart from a person's transfer" do+ inflow, outflow = book(gbp_to_eur("9000000106"), @standard_account, create_balance("GBP", "10000003"))+ @wise_item.link_jar_transfers!+ linked = Transfer.find_by!(inflow_transaction_id: inflow.entryable_id)+ bank = bank_entry(amount: 50, date: Date.current)+ person = Transfer.create!(inflow_transaction: @standard_sure_account.entries.create!(amount: -50, currency: "EUR", date: Date.current,+ name: "From bank", entryable: Transaction.new).entryable,+ outflow_transaction: bank.entryable, status: "confirmed")++ assert WiseItem::InterbalanceLinker.relinks?(linked)+ assert_not WiseItem::InterbalanceLinker.relinks?(person)+ linked.update!(notes: "Moved my savings")+ assert_not WiseItem::InterbalanceLinker.relinks?(linked)+ end++ # A transfer from the GBP balance into the euro balance's own account+ # details is in both statements under its reference: a debit on GBP and a+ # credit on EUR, linked as a transfer like a conversion. A refund credit+ # shares the reference on the paying balance and is left alone.+ test "links the two statement rows of a send from one balance to another's account details" do+ gbp = create_balance("GBP", "10000003")+ debit = statement_entry(gbp, "wise_statement_TRANSFER-4242", 100)+ statement_entry(gbp, "wise_statement_TRANSFER-4242_fee", 0.5)+ credit = statement_entry(@standard_account, "wise_statement_TRANSFER-4242", -115)+ refunded = statement_entry(gbp, "wise_statement_TRANSFER-4343", 40)+ statement_entry(gbp, "wise_statement_TRANSFER-4343_CREDIT_20260303", -40)++ @wise_item.link_jar_transfers!++ transfer = Transfer.where(outflow_transaction_id: gbp.current_account.transactions.select(:id)).sole+ assert_equal [ credit.entryable_id, debit.entryable_id ], [ transfer.inflow_transaction_id, transfer.outflow_transaction_id ]+ assert transfer.confirmed?+ assert WiseItem::InterbalanceLinker.relinks?(transfer)+ assert_equal "standard", refunded.entryable.reload.kind+ end++ test "does not relink a conversion the user rejected" do+ inflow, outflow = book(gbp_to_eur("9000000106"), @standard_account, create_balance("GBP", "10000003"))+ @wise_item.link_jar_transfers!+ Transfer.find_by!(inflow_transaction_id: inflow.entryable_id).reject!++ assert_no_difference "Transfer.count" do+ @wise_item.link_jar_transfers!+ end++ assert RejectedTransfer.exists?(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: outflow.entryable_id)+ assert_equal %w[standard standard], leg_kinds(inflow, outflow)+ end++ test "replaces a pending suggestion that holds one conversion leg" do+ inflow, outflow = book(gbp_to_eur("9000000106"), @standard_account, create_balance("GBP", "10000003"))+ bank_credit = bank_entry(amount: -1180, date: outflow.date)+ suggestion = Transfer.create!(inflow_transaction: bank_credit.entryable, outflow_transaction: outflow.entryable, status: "pending")++ @wise_item.link_jar_transfers!++ assert_not Transfer.exists?(suggestion.id)+ assert Transfer.find_by!(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: outflow.entryable_id).confirmed?+ assert_equal "standard", bank_credit.entryable.reload.kind+ end++ test "confirms a pending suggestion that already pairs the two legs" do+ inflow, outflow = book(jar_deposit("5004", "250 EUR"), @jar_account, @standard_account)+ suggestion = Transfer.create!(inflow_transaction: inflow.entryable, outflow_transaction: outflow.entryable, status: "pending")++ assert_no_difference "Transfer.count" do+ @wise_item.link_jar_transfers!+ end++ assert suggestion.reload.confirmed?+ assert_equal %w[funds_movement funds_movement], leg_kinds(inflow, outflow)+ end++ test "keeps the suggestion when the conversion cannot be linked" do+ inflow, outflow = book(gbp_to_eur("9000000106"), @standard_account, create_balance("GBP", "10000003"))+ # A confirmed transfer allows at most 30 days between its legs.+ outflow.update_columns(date: inflow.date - 31.days)+ bank_debit = bank_entry(amount: 1234.56, date: inflow.date)+ suggestion = Transfer.create!(inflow_transaction: inflow.entryable, outflow_transaction: bank_debit.entryable, status: "pending")++ assert_difference "DebugLogEntry.count", 1 do+ @wise_item.link_jar_transfers!+ end++ assert Transfer.find(suggestion.id).pending?, "a refused link must not take the suggestion with it"+ assert_not Transfer.exists?(outflow_transaction_id: outflow.entryable_id)+ end++ test "leaves a conversion leg the user confirmed against another transaction" do+ inflow, outflow = book(gbp_to_eur("9000000106"), @standard_account, create_balance("GBP", "10000003"))+ bank_debit = bank_entry(amount: 1234.56, date: inflow.date)+ users_link = Transfer.create!(inflow_transaction: inflow.entryable, outflow_transaction: bank_debit.entryable, status: "confirmed")++ assert_no_difference "Transfer.count" do+ @wise_item.link_jar_transfers!+ end++ assert Transfer.exists?(users_link.id)+ assert_not Transfer.exists?(outflow_transaction_id: outflow.entryable_id)+ end++ # Before conversions were routed by currency, every STANDARD balance booked+ # an _outflow copy of each one in the target currency, the target balance+ # included, and upgraded installs still hold those entries.+ test "links the leg on the conversion's source balance when earlier routing left copies" do+ usd = create_balance("USD", "10000004")+ inflow, outflow = book(gbp_to_eur("9000000106"), @standard_account, create_balance("GBP", "10000003"))+ [ @standard_account, usd ].each { |wise_account| book_pre_routing_copy(wise_account, "9000000106", inflow.date) }++ @wise_item.link_jar_transfers!++ assert_equal outflow.entryable_id, Transfer.find_by!(inflow_transaction_id: inflow.entryable_id).outflow_transaction_id+ end++ test "does not link a copy on a balance in another currency than the conversion's source" do+ inflow, = book(gbp_to_eur("9000000106"), @standard_account) # Wise GBP is not linked in Sure+ book_pre_routing_copy(create_balance("USD", "10000004"), "9000000106", inflow.date)++ assert_difference "DebugLogEntry.count", 1 do+ @wise_item.link_jar_transfers!+ end++ assert_not Transfer.exists?(inflow_transaction_id: inflow.entryable_id)+ end++ # Wise's automatic conversions (e.g. for a card payment in a currency the+ # balance lacks) are booked through the conversion path, and their stored+ # rows name the source balance just as INTERBALANCE rows do.+ test "links an auto-conversion on its source balance like a conversion" do+ auto_conversion = gbp_to_eur("9000000107").merge("type" => "AUTO_CONVERSION", "id" => "auto_conversion_9000000107")+ inflow, outflow = book(auto_conversion, @standard_account, create_balance("GBP", "10000003"))+ book_pre_routing_copy(create_balance("USD", "10000004"), "9000000107", inflow.date)++ @wise_item.link_jar_transfers!++ transfer = Transfer.find_by!(inflow_transaction_id: inflow.entryable_id)+ assert_equal outflow.entryable_id, transfer.outflow_transaction_id+ assert transfer.confirmed?+ assert_equal %w[funds_movement funds_movement], leg_kinds(inflow, outflow)+ end++ # The linker before routing by currency confirmed a jar move's leg against+ # whichever _outflow copy it found first, usually one routing had booked on+ # another balance in the move's currency. That link is the linker's own, not+ # a person's, so the move's real legs replace it.+ test "replaces a link the old linker made to a copy earlier routing left on another balance" do+ jar_leg, eur_leg = book(jar_deposit("5005", "100 EUR"), @jar_account, @standard_account)+ copy = book_pre_routing_copy(create_balance("GBP", "10000003"), "5005", jar_leg.date, amount: 100)+ old_link = Transfer.create!(inflow_transaction: jar_leg.entryable, outflow_transaction: copy.entryable, status: "confirmed")++ stats = nil+ assert_difference -> { DebugLogEntry.where(category: "provider_sync", level: "info").count }, 1 do+ stats = @wise_item.link_jar_transfers!+ end++ assert_equal [ 1, 1 ], stats.values_at(:linked, :replaced_stale_links)+ assert_not Transfer.exists?(old_link.id)+ assert_equal eur_leg.entryable_id, Transfer.find_by!(inflow_transaction_id: jar_leg.entryable_id).outflow_transaction_id+ assert_equal %w[funds_movement funds_movement standard], leg_kinds(jar_leg, eur_leg, copy)+ end++ test "keeps a link to such a copy that a person added notes to, and reports it" do+ jar_leg, eur_leg = book(jar_deposit("5006", "100 EUR"), @jar_account, @standard_account)+ copy = book_pre_routing_copy(create_balance("GBP", "10000003"), "5006", jar_leg.date, amount: 100)+ noted = Transfer.create!(inflow_transaction: jar_leg.entryable, outflow_transaction: copy.entryable, status: "confirmed",+ notes: "Moved to the holiday jar")++ assert_difference -> { DebugLogEntry.where(category: "provider_sync_error").count }, 1 do+ assert_equal 1, @wise_item.link_jar_transfers![:kept_link_to_copy]+ end++ assert Transfer.exists?(noted.id)+ assert_not Transfer.exists?(outflow_transaction_id: eur_leg.entryable_id)+ assert_equal [ "kept_link_to_copy" ], DebugLogEntry.order(:created_at).last.metadata["problems"].map { |problem| problem["reason"] }+ end++ # Without the move's stored row (an older payload that lost it, a source+ # balance not linked) a single leg is linked and several are left alone, and+ # a copy earlier routing booked in the move's currency on a balance in+ # another currency never counts.+ test "without a stored row links the one leg that is not a copy and leaves two alone" do+ gbp = create_balance("GBP", "10000003")+ jar_leg = leg(@jar_account, "6006_inflow", -50)+ eur_leg = leg(@standard_account, "6006_outflow", 50)+ book_pre_routing_copy(gbp, "6006", jar_leg.date, amount: 50)++ @wise_item.link_jar_transfers!++ assert_equal eur_leg.entryable_id, Transfer.find_by(inflow_transaction_id: jar_leg.entryable_id)&.outflow_transaction_id++ two_legs = leg(@jar_account, "6007_inflow", -70)+ leg(@standard_account, "6007_outflow", 70)+ leg(create_balance("EUR", "10000005", type: "SAVINGS"), "6007_outflow", 70)+ lone_inflow = leg(@jar_account, "6008_inflow", -30)+ book_pre_routing_copy(gbp, "6008", lone_inflow.date, amount: 30)++ assert_difference -> { DebugLogEntry.where(category: "provider_sync_error").count }, 1 do+ @wise_item.link_jar_transfers!+ end++ assert_not Transfer.exists?(inflow_transaction_id: two_legs.entryable_id)+ assert_not Transfer.exists?(inflow_transaction_id: lone_inflow.entryable_id)+ assert_equal [ 2, 1 ], DebugLogEntry.order(:created_at).last.metadata["problems"].map { |problem| problem["candidate_count"] }+ end++ test "leaves a conversion unlinked when two legs sit on balances in its source currency" do+ gbp_jar = create_balance("GBP", "10000005", type: "SAVINGS")+ inflow, = book(gbp_to_eur("9000000106"), @standard_account, create_balance("GBP", "10000003"))+ gbp_jar.current_account.entries.create!(external_id: "wise_interbalance_9000000106_outflow", source: "wise", amount: 1150,+ currency: "GBP", date: inflow.date, name: "Transfer to EUR", entryable: Transaction.new)++ assert_difference "DebugLogEntry.count", 1 do+ @wise_item.link_jar_transfers!+ end++ assert_not Transfer.exists?(inflow_transaction_id: inflow.entryable_id)+ end++ # Auto-matching no longer pairs two balances of one item, so a suggestion it+ # made before (a top-up "matching" a payout) would otherwise stay forever.+ test "discards pending suggestions between two balances of the connection" do+ usd = create_balance("USD", "10000004")+ top_up = @standard_sure_account.entries.create!(external_id: "wise_transfer_9000000104", source: "wise", amount: -2465,+ currency: "EUR", date: Date.current, name: "Top-up", entryable: Transaction.new)+ payout = usd.current_account.entries.create!(external_id: "wise_transfer_9000000105", source: "wise", amount: 1618.42,+ currency: "USD", date: Date.current, name: "Payout", entryable: Transaction.new)+ within_item = Transfer.create!(inflow_transaction: top_up.entryable, outflow_transaction: payout.entryable, status: "pending")+ other_payout = usd.current_account.entries.create!(external_id: "wise_transfer_9000000103", source: "wise", amount: 5482.37,+ currency: "USD", date: Date.current, name: "Payout", entryable: Transaction.new)+ bank_credit = bank_entry(amount: -5482.37, date: Date.current, currency: "USD")+ with_bank = Transfer.create!(inflow_transaction: bank_credit.entryable, outflow_transaction: other_payout.entryable, status: "pending")++ @wise_item.link_jar_transfers!++ assert_not Transfer.exists?(within_item.id)+ assert Transfer.exists?(with_bank.id)+ end+privatedef stub_sca_encryption_available@@ -196,18 +586,75 @@ class WiseItemTest < ActiveSupport::TestCaseWiseItem.stubs(:encrypted_attributes).returns([ "sca_private_key" ])end- def create_interbalance_entry(account, resource_id, side:, amount:)- external_id = "wise_interbalance_#{resource_id}_#{side}"- transaction = Transaction.create!(kind: "funds_movement")- entry = account.entries.create!(- external_id: external_id,- source: "wise",- amount: amount,- currency: "EUR",- date: Date.today,- name: "Transfer to Jar",- entryable: transaction+ def create_balance(currency, balance_id, type: "STANDARD")+ wise_account = WiseAccount.create!(wise_item: @wise_item, balance_id: balance_id, name: "Wise #{currency}",+ currency: currency, raw_payload: { "type" => type })+ AccountProvider.create!(+ account: Account.create!(family: @family, name: "Wise #{currency}", accountable: Depository.new(subtype: "checking"),+ balance: 0, currency: currency),+ provider: wise_account)- entry+ wise_account+ end++ # Stores the activity on each balance and books it there, as a sync does.+ def book(activity, *wise_accounts)+ wise_accounts.map do |wise_account|+ wise_account.update!(raw_transactions_payload: Array(wise_account.raw_transactions_payload) + [ activity ])+ WiseActivity::Processor.new(activity, wise_account: wise_account).process+ end+ end++ # The +primaryAmount _outflow leg the routing before currency-aware+ # conversions booked on every STANDARD balance.+ def book_pre_routing_copy(wise_account, resource_id, date, amount: 1234.56)+ wise_account.current_account.entries.create!(external_id: "wise_interbalance_#{resource_id}_outflow", source: "wise",+ amount: amount, currency: "EUR", date: date, name: "Transfer to EUR",+ entryable: Transaction.new)+ end++ # A leg booked before the payload kept the move's row (side: e.g.+ # "6006_inflow"), in its balance's currency.+ def leg(wise_account, side, amount)+ wise_account.current_account.entries.create!(external_id: "wise_interbalance_#{side}", source: "wise", amount: amount,+ currency: wise_account.currency, date: Date.current, name: "Jar move",+ entryable: Transaction.new)+ end++ def interbalance(resource_id, title:, primary:, secondary: nil)+ {+ "id" => "interbalance_activity_#{resource_id}",+ "type" => "INTERBALANCE",+ "resource" => { "type" => "BALANCE_TRANSACTION", "id" => resource_id },+ "title" => title,+ "primaryAmount" => primary,+ "secondaryAmount" => secondary,+ "status" => "COMPLETED",+ "createdOn" => "2026-03-18T09:41:27.109Z"+ }.compact+ end++ def jar_deposit(resource_id, amount)+ interbalance(resource_id, title: "To <strong>Jar</strong>", primary: amount)+ end++ def gbp_to_eur(resource_id)+ interbalance(resource_id, title: "To <strong>EUR</strong>", primary: "1,234.56 EUR", secondary: "1,000 GBP")+ end++ # A transaction on a bank account outside the Wise connection.+ def bank_entry(amount:, date:, currency: "EUR")+ bank = Account.create!(family: @family, name: "Bank #{currency}", accountable: Depository.new(subtype: "checking"),+ balance: 0, currency: currency)+ bank.entries.create!(amount: amount, currency: currency, date: date, name: "Bank transfer", entryable: Transaction.new)+ end++ def statement_entry(wise_account, external_id, amount)+ wise_account.current_account.entries.create!(external_id: external_id, source: "wise", amount: amount, currency: wise_account.currency,+ date: Date.current, name: "Wise statement", entryable: Transaction.new)+ end++ def leg_kinds(*entries)+ entries.map { |entry| entry.entryable.reload.kind }endenddiff --git a/test/models/wise_statement/processor_test.rb b/test/models/wise_statement/processor_test.rbindex 67150047ee..7aa97800d0 100644--- a/test/models/wise_statement/processor_test.rb+++ b/test/models/wise_statement/processor_test.rb@@ -70,6 +70,94 @@ class WiseStatement::ProcessorTest < ActiveSupport::TestCaseassert_equal I18n.t("wise_items.entries.fee_name"), fee_entry.nameend+ test "re-importing a statement row drops wise metadata Wise no longer reports" do+ statement = {+ "type" => "DEBIT",+ "date" => "2026-01-15T10:00:00Z",+ "amount" => { "value" => "-7.76", "currency" => "EUR" },+ "details" => { "description" => "Card payment", "paymentReference" => "INV-1234" },+ "referenceNumber" => "statement-457"+ }+ WiseStatement::Processor.new(statement, wise_account: @wise_account).process++ entry = WiseStatement::Processor.new(statement.merge("details" => { "description" => "Card payment" }),+ wise_account: @wise_account).process++ assert_nil entry.entryable.reload.extra.dig("wise", "payment_reference")+ end++ # The fee entry's wise namespace is replaced as well.+ test "re-importing a statement row drops wise metadata its fee no longer carries" do+ statement = { "type" => "DEBIT", "date" => "2026-01-15T10:00:00Z", "amount" => { "value" => "-7.76", "currency" => "EUR" },+ "totalFees" => { "value" => "0.04", "currency" => "EUR" }, "referenceNumber" => "statement-458" }+ WiseStatement::Processor.new(statement, wise_account: @wise_account).process+ fee = @account.entries.find_by!(external_id: "wise_statement_statement-458_fee").entryable+ fee.update_column(:extra, fee.extra.deep_merge("wise" => { "payment_reference" => "INV-1234" }))++ WiseStatement::Processor.new(statement, wise_account: @wise_account).process++ assert_equal({ "statement_id" => "statement-458", "type" => "FEE", "fee" => "0.04" }, fee.reload.extra["wise"])+ end++ # A COMPACT credit's amount is what reached the balance, already net of its+ # fee (runningBalance rises by it), so it books in full and the fee is only+ # kept in extra.+ test "books a credit at its full amount and keeps its fee in extra" do+ statement = { "type" => "CREDIT", "date" => "2026-03-01T10:00:00Z",+ "amount" => { "value" => 95.86, "currency" => "EUR" },+ "totalFees" => { "value" => 4.14, "currency" => "EUR" },+ "details" => { "type" => "DEPOSIT", "description" => "Received money" },+ "runningBalance" => { "value" => 95.86, "currency" => "EUR" },+ "referenceNumber" => "DEPOSIT-1" }+ processor = WiseStatement::Processor.new(statement, wise_account: @wise_account)++ entry = processor.process++ assert_equal [ [ "wise_statement_DEPOSIT-1", BigDecimal("-95.86") ] ], @account.entries.where(source: "wise").pluck(:external_id, :amount)+ assert_equal "4.14", entry.entryable.extra.dig("wise", "fee")+ assert_equal [ "wise_statement_DEPOSIT-1" ], processor.expected_external_ids+ end++ # Wise reuses a transfer's reference on its refund; the importer gives the+ # later row its own id (WiseItem::StatementMigration).+ test "books a row under the id the importer gave it" do+ statement = { "type" => "CREDIT", "date" => "2026-03-03T10:00:00Z", "amount" => { "value" => 100, "currency" => "EUR" },+ "referenceNumber" => "TRANSFER-555", "wise_statement_id" => "TRANSFER-555_CREDIT_20260303" }++ entry = WiseStatement::Processor.new(statement, wise_account: @wise_account).process++ assert_equal "wise_statement_TRANSFER-555_CREDIT_20260303", entry.external_id+ assert_equal "TRANSFER-555_CREDIT_20260303", entry.entryable.extra.dig("wise", "statement_id")+ end++ test "books nothing for a conversion the conversion's own row books" do+ statement = { "type" => "DEBIT", "date" => "2026-03-03T10:00:00Z", "amount" => { "value" => -100, "currency" => "EUR" },+ "details" => { "type" => "CONVERSION" }, "referenceNumber" => "BALANCE-4001",+ "wise_superseded_by" => "wise_interbalance_4001_outflow", "wise_supersedes" => { "main" => "wise_transfer_1" } }+ processor = WiseStatement::Processor.new(statement, wise_account: @wise_account)++ assert_equal :skipped, processor.process+ assert_empty processor.expected_external_ids+ assert_empty processor.superseded_external_ids+ assert_empty @account.entries+ end++ # The entries the importer matched to the row (wise_supersedes) move to its+ # ids before it books (WiseAccount::Transactions::Processor).+ test "names the entries it takes over, the fee only when it books one" do+ debit = { "type" => "DEBIT", "date" => "2026-03-01T10:00:00Z", "amount" => { "value" => -102.5, "currency" => "EUR" },+ "totalFees" => { "value" => 2.5, "currency" => "EUR" }, "referenceNumber" => "TRANSFER-101",+ "wise_supersedes" => { "main" => "wise_transfer_101", "fee" => "wise_fee_101" } }+ credit = { "type" => "CREDIT", "date" => "2026-03-01T10:00:00Z", "amount" => { "value" => 500, "currency" => "EUR" },+ "totalFees" => { "value" => 1, "currency" => "EUR" }, "referenceNumber" => "TRANSFER-102",+ "wise_supersedes" => { "main" => "wise_transfer_102", "fee" => "wise_fee_102" } }++ assert_equal({ "wise_transfer_101" => "wise_statement_TRANSFER-101", "wise_fee_101" => "wise_statement_TRANSFER-101_fee" },+ WiseStatement::Processor.new(debit, wise_account: @wise_account).superseded_external_ids)+ assert_equal({ "wise_transfer_102" => "wise_statement_TRANSFER-102" },+ WiseStatement::Processor.new(credit, wise_account: @wise_account).superseded_external_ids)+ end+test "ignores fees denominated in a different currency" dostatement = {"type" => "DEBIT",