Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

2883: Fix unidentified card holds (#4162)

Ottera3bb5d991f9b
diff --git a/app/models/concerns/card_authorization_hold.rb b/app/models/concerns/card_authorization_hold.rb
new file mode 100644
index 0000000000..8c8527821c
--- /dev/null
+++ b/app/models/concerns/card_authorization_hold.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+# Shared logic for detecting and handling unidentified card authorization holds.
+# Certain ASPSPs return unfinalized card authorization holds with blank provider IDs,
+# masked card PAN descriptors instead of merchant/payee names, and sometimes with
+# inverted credit/debit signs.
+#
+# Including classes must define a class-level unidentified_hold?(raw_transaction_data)
+# predicate and a private instance-level data reader returning the raw payload.
+module CardAuthorizationHold
+ extend ActiveSupport::Concern
+
+ # Pattern matching masked card authorization descriptors (e.g. "474836xxxxxx6879 003015315475")
+ # commonly returned by certain ASPSPs for unfinalized card holds.
+ MASKED_CARD_DESCRIPTOR = /\A\d{4,6}[xX*]{4,8}\d{4}(?:\s+\d+)?\z/
+
+ HOLD_TRANSACTION_NAME = "Card Authorization Hold"
+
+ # Message for the DebugLogEntry recorded the first time a hold is imported.
+ # Kept constant so operators can filter on it in /settings/debug; whether the
+ # sign was inverted is recorded in metadata[:sign_inverted].
+ HOLD_DIAGNOSTIC_MESSAGE = "Unidentified card authorization hold imported as a pending expense"
+
+ class_methods do
+ # True when a single text value is exactly a masked card descriptor.
+ #
+ # @return [Boolean]
+ def masked_card_text?(value)
+ value.to_s.strip.match?(MASKED_CARD_DESCRIPTOR)
+ end
+ end
+
+ private
+
+ def masked_card_text?(value)
+ self.class.masked_card_text?(value)
+ end
+
+ def unidentified_hold?
+ return @unidentified_hold if defined?(@unidentified_hold)
+
+ @unidentified_hold = self.class.unidentified_hold?(data)
+ end
+end
diff --git a/app/models/enable_banking_entry/processor.rb b/app/models/enable_banking_entry/processor.rb
index 7484c509ee..07025f267a 100644
--- a/app/models/enable_banking_entry/processor.rb
+++ b/app/models/enable_banking_entry/processor.rb
@@ -2,6 +2,7 @@ require "digest/md5"
class EnableBankingEntry::Processor
include CurrencyNormalizable
+ include CardAuthorizationHold
# Small-merchant card terminal providers that prefix the payee with "KEYWORD *"
PAYMENT_PROCESSOR_PREFIX = /\A(SUMUP|SQ|IZETTLE|ZETTLE|PAYPAL)\s*\*\s*/i
@@ -82,7 +83,77 @@ class EnableBankingEntry::Processor
data[:transaction_id].blank? && data[:entry_reference].blank?
end
- # True when the ASPSP has flagged this raw payload as not yet settled.
+ def self.party_name(data, key)
+ value = data[key]
+ nested = value.is_a?(Hash) ? value[:name] : (value if value.is_a?(String))
+ nested.presence || data[:"#{key}_name"].presence
+ end
+
+ # True when a single remittance line is a technical terminal/POS booking line
+ # rather than a merchant or transaction descriptor.
+ #
+ # Terminal booking line, e.g. "POS 45,13 AT D6 31.07. 10:27": require the
+ # keyword+amount prefix AND the trailing date+time stamp TOGETHER, not either
+ # alone. Either signal in isolation false-positives on legitimate descriptors:
+ # a line like "POS 45,13 BILLA DANKT ..." (merchant appended after the amount,
+ # no separate technical-only element) would wrongly match on the prefix alone,
+ # and a line like "Invoice paid 31.07. 10:27" would wrongly match on the date
+ # suffix alone. Requiring both matches every real technical line observed in
+ # production while leaving both of those legitimate shapes untouched. Day/month
+ # accept 1-2 digits (not just 2) so an un-padded ASPSP date ("1.07." instead of
+ # "01.07.") is still recognized as technical.
+ def self.technical_remittance_line?(value)
+ line = value.to_s.strip
+ line.match?(/\A(POS|ATM)\s+\d+[.,]\d{2}\b.*\d{1,2}[.\/]\d{1,2}\.?\s+\d{2}:\d{2}\z/i)
+ end
+
+ # True when the transaction represents an unfinalized card authorization hold
+ # (missing provider identifiers, no legitimate counterparty name, and a masked
+ # card descriptor in remittance or transaction code).
+ # Certain institutions expose un-finalized card holds this way even under a "BOOK" status payload.
+ #
+ # @return [Boolean]
+ def self.unidentified_hold?(raw_transaction_data)
+ data = raw_transaction_data.with_indifferent_access
+ return false unless identifierless?(data)
+ return false if party_name(data, :creditor).present?
+
+ if data[:credit_debit_indicator] == "CRDT"
+ return false if party_name(data, :debtor).present?
+ end
+
+ masked_card_descriptor?(data)
+ end
+
+ # True when the transaction's remittance information or bank transaction code
+ # consists of a masked card descriptor.
+ #
+ # When remittance information is present, requires any descriptive (non-technical)
+ # lines to match MASKED_CARD_DESCRIPTOR and prevents firing if a legitimate
+ # payee or merchant descriptor is present alongside a masked card PAN.
+ #
+ # @return [Boolean]
+ def self.masked_card_descriptor?(raw_transaction_data)
+ data = raw_transaction_data.with_indifferent_access
+ remittance = data[:remittance_information]
+
+ if remittance.present?
+ lines = Array.wrap(remittance)
+ .map { |line| line.to_s.strip.sub(WALLET_PREFIX, "").strip }
+ .reject(&:blank?)
+
+ descriptive_lines = lines.reject { |line| technical_remittance_line?(line) }
+
+ if descriptive_lines.any?
+ return descriptive_lines.all? { |line| masked_card_text?(line) }
+ end
+ end
+
+ masked_card_text?(data.dig(:bank_transaction_code, :description))
+ end
+
+ # True when the ASPSP has flagged this raw payload as not yet settled, or when
+ # the payload represents an unidentified card hold.
#
# Named pending_payload? rather than the bare pending? that Transaction#pending?
# already uses, on purpose: this checks the incoming provider hash, not a
@@ -90,7 +161,8 @@ class EnableBankingEntry::Processor
#
# @return [Boolean]
def self.pending_payload?(raw_transaction_data)
- raw_transaction_data.with_indifferent_access[:_pending] == true
+ data = raw_transaction_data.with_indifferent_access
+ data[:_pending] == true || unidentified_hold?(data)
end
# External ids of the rows stored under a synthesised content hash, which are
@@ -153,7 +225,15 @@ class EnableBankingEntry::Processor
claim_identifierless_predecessor!
- begin
+ # EnableBankingAccount::Transactions::Processor re-processes the whole stored
+ # payload on every sync, so a live hold passes through here once per sync until
+ # it settles. Only the first import is worth a diagnostic. Evaluated before the
+ # import, which is what creates the row. A hold is always identifierless with a
+ # masked descriptor, so safe_id is its real content-hash id, never "unknown".
+ first_hold_import = unidentified_hold? &&
+ !account.entries.exists?(source: "enable_banking", external_id: safe_id)
+
+ entry = begin
import_adapter.import_transaction(
external_id: external_id,
amount: amount,
@@ -176,6 +256,10 @@ class EnableBankingEntry::Processor
Rails.logger.error e.backtrace.join("\n")
raise StandardError.new("Unexpected error importing transaction: #{e.message}")
end
+
+ capture_unidentified_hold_diagnostic(entry, external_id: safe_id) if first_hold_import && entry
+
+ entry
end
private
@@ -201,6 +285,8 @@ class EnableBankingEntry::Processor
end
def name
+ return HOLD_TRANSACTION_NAME if unidentified_hold?
+
# Build name from available Enable Banking transaction fields
# Priority: counterparty name > bank_transaction_code description > remittance_information
@@ -227,6 +313,8 @@ class EnableBankingEntry::Processor
end
def merchant
+ return nil if unidentified_hold?
+
# Use the counterparty when it is human readable; otherwise fall back to remittance
# for CARD-* transactions where the remittance often contains the actual merchant
merchant_name = merchant_name_candidate
@@ -271,7 +359,7 @@ class EnableBankingEntry::Processor
end
eb[:merchant_category_code] = data[:merchant_category_code] if data[:merchant_category_code].present?
- eb[:pending] = true if data[:_pending] == true
+ eb[:pending] = true if pending_payload?
eb.compact!
eb.empty? ? nil : { enable_banking: eb }
@@ -294,7 +382,18 @@ class EnableBankingEntry::Processor
# Sure convention: positive = outflow (expense/debit from account), negative = inflow (income/credit)
# Enable Banking: DBIT = debit from account (outflow), CRDT = credit to account (inflow)
# Therefore: DBIT → +absolute_amount, CRDT → -absolute_amount
- credit_debit_indicator == "CRDT" ? -absolute_amount : absolute_amount
+ #
+ # For unidentified card authorization holds, the ASPSP
+ # erroneously returns credit_debit_indicator: "CRDT" for an authorization hold on an outflow.
+ # Force these holds to positive (outflow/expense in Sure) so they appear as pending expenses
+ # and match the settled expense when it arrives.
+ if unidentified_hold?
+ absolute_amount
+ elsif credit_debit_indicator == "CRDT"
+ -absolute_amount
+ else
+ absolute_amount
+ end
rescue ArgumentError => e
Rails.logger.error "Failed to parse Enable Banking transaction amount: #{raw_amount.inspect} - #{e.message}"
raise
@@ -347,18 +446,7 @@ class EnableBankingEntry::Processor
end
def technical_remittance_line?(value)
- line = value.to_s.strip
- # Terminal booking line, e.g. "POS 45,13 AT D6 31.07. 10:27": require the
- # keyword+amount prefix AND the trailing date+time stamp TOGETHER, not either
- # alone. Either signal in isolation false-positives on legitimate descriptors:
- # a line like "POS 45,13 BILLA DANKT ..." (merchant appended after the amount,
- # no separate technical-only element) would wrongly match on the prefix alone,
- # and a line like "Invoice paid 31.07. 10:27" would wrongly match on the date
- # suffix alone. Requiring both matches every real technical line observed in
- # production while leaving both of those legitimate shapes untouched. Day/month
- # accept 1-2 digits (not just 2) so an un-padded ASPSP date ("1.07." instead of
- # "01.07.") is still recognized as technical.
- line.match?(/\A(POS|ATM)\s+\d+[.,]\d{2}\b.*\d{1,2}[.\/]\d{1,2}\.?\s+\d{2}:\d{2}\z/i)
+ self.class.technical_remittance_line?(value)
end
def strip_payment_processor_prefix(value)
@@ -421,7 +509,7 @@ class EnableBankingEntry::Processor
# Account::ProviderImportAdapter already matches and protects that
# transition more conservatively. Keeping this claim scoped to BOOK on both
# sides avoids the two mechanisms fighting over the same row.
- return if self.class.pending_payload?(data)
+ return if pending_payload?
incoming = self.class.compute_external_id(data)
return if incoming.blank?
@@ -544,4 +632,38 @@ class EnableBankingEntry::Processor
Rails.logger.error("Failed to parse Enable Banking transaction date '#{date_value}': #{e.message}")
raise ArgumentError, "Unable to parse transaction date: #{date_value.inspect}"
end
+
+ def pending_payload?
+ data[:_pending] == true || unidentified_hold?
+ end
+
+ # Called only after a successful first import of a hold. Every argument was
+ # already evaluated by that import, so nothing here can raise before
+ # DebugLogEntry.capture's own rescue takes over.
+ #
+ # Enable Banking amounts are absolute and the direction is carried by
+ # credit_debit_indicator, so the sign was inverted exactly when the hold
+ # arrived as CRDT. A DBIT hold is still normalized (name, merchant, pending)
+ # but keeps its sign.
+ def capture_unidentified_hold_diagnostic(entry, external_id:)
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "warn",
+ message: HOLD_DIAGNOSTIC_MESSAGE,
+ source: self.class.name,
+ provider_key: "enable_banking",
+ family: account.family,
+ account: account,
+ account_provider: enable_banking_account.account_provider,
+ metadata: {
+ external_id: external_id,
+ entry_id: entry.id,
+ raw_amount: (data.dig(:transaction_amount, :amount) || data[:amount]).to_s,
+ credit_debit_indicator: credit_debit_indicator,
+ sign_inverted: credit_debit_indicator == "CRDT",
+ amount: amount.to_s,
+ currency: currency
+ }
+ )
+ end
end
diff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rb
index 32aca4b16f..d4927e9313 100644
--- a/app/models/enable_banking_item/importer.rb
+++ b/app/models/enable_banking_item/importer.rb
@@ -528,16 +528,18 @@ class EnableBankingItem::Importer
)
if include_pending
- # Tag any transaction in all_transactions (fetched as BOOK but actually PDNG) with _pending: true
+ # Tag any transaction in all_transactions (fetched as BOOK but actually PDNG or an unidentified hold) with _pending: true
all_transactions = all_transactions.map do |tx|
tx_ia = tx.with_indifferent_access
- tx_ia[:status] == "PDNG" ? tx_ia.merge(_pending: true) : tx_ia
+ is_pending = tx_ia[:status] == "PDNG" || EnableBankingEntry::Processor.unidentified_hold?(tx_ia)
+ is_pending ? tx_ia.merge(_pending: true) : tx_ia
end
else
# If include_pending is false, we must filter out any pending transactions
- # that were returned (e.g. if the bank ignores transaction_status="BOOK").
+ # that were returned (e.g. if the bank ignores transaction_status="BOOK" or returns unfinalized holds).
all_transactions = all_transactions.reject do |tx|
- tx.with_indifferent_access[:status] == "PDNG"
+ tx_ia = tx.with_indifferent_access
+ tx_ia[:status] == "PDNG" || EnableBankingEntry::Processor.unidentified_hold?(tx_ia)
end
end
@@ -606,7 +608,7 @@ class EnableBankingItem::Importer
unless include_pending
removed_pending = existing_transactions.reject! do |tx|
tx = tx.with_indifferent_access
- tx.dig(:extra, :enable_banking, :pending) || tx[:_pending]
+ tx.dig(:extra, :enable_banking, :pending) || tx[:_pending] || EnableBankingEntry::Processor.unidentified_hold?(tx)
end
end
@@ -632,7 +634,7 @@ class EnableBankingItem::Importer
if include_pending
removed_pending ||= existing_transactions.reject! do |tx|
tx = tx.with_indifferent_access
- pending_flag = tx.dig(:extra, :enable_banking, :pending) || tx[:_pending]
+ pending_flag = tx.dig(:extra, :enable_banking, :pending) || tx[:_pending] || EnableBankingEntry::Processor.unidentified_hold?(tx)
next false unless pending_flag
fp = EnableBankingEntry::Processor.compute_external_id(tx)
diff --git a/app/models/lunchflow_entry/processor.rb b/app/models/lunchflow_entry/processor.rb
index f9d43df8ff..cb1165dca9 100644
--- a/app/models/lunchflow_entry/processor.rb
+++ b/app/models/lunchflow_entry/processor.rb
@@ -3,6 +3,26 @@ require "digest/md5"
class LunchflowEntry::Processor
include CurrencyNormalizable
include LunchflowTransactionHash
+ include CardAuthorizationHold
+
+ # True when the transaction lacks a provider ID and its merchant or description
+ # matches a masked card authorization descriptor without identifying a real payee.
+ # Certain institutions expose unfinalized card holds with blank IDs, masked card
+ # numbers instead of merchant names, and sometimes with inverted signs.
+ #
+ # @return [Boolean]
+ def self.unidentified_hold?(raw_transaction_data)
+ data = raw_transaction_data.with_indifferent_access
+ return false if data[:id].present?
+
+ merchant_name = data[:merchant].to_s.strip
+ description = data[:description].to_s.strip
+
+ fields = [ merchant_name, description ].reject(&:blank?)
+ return false if fields.empty?
+
+ fields.all? { |field| masked_card_text?(field) }
+ end
# lunchflow_transaction is the raw hash fetched from Lunchflow API and converted to JSONB
# Transaction structure: { id, accountId, amount, currency, date, merchant, description, isPending }
@@ -18,8 +38,9 @@ class LunchflowEntry::Processor
return nil
end
- # If this is a pending transaction with a temporary ID, check if a posted version already exists
- # This prevents duplicate entries when posted transactions arrive before pending ones
+ # If this is a pending transaction with a temporary ID, check if a posted version already exists.
+ # This prevents duplicate entries when posted transactions arrive before pending ones, or when
+ # a stored hold snapshot is re-processed after a posted transaction has claimed it.
if is_pending? && external_id.start_with?("lunchflow_pending_")
existing_posted = find_existing_posted_version
if existing_posted
@@ -28,8 +49,11 @@ class LunchflowEntry::Processor
end
end
+ first_hold_import = unidentified_hold? &&
+ !account.entries.exists?(source: "lunchflow", external_id: external_id)
+
# Wrap import in error handling to catch validation and save errors
- begin
+ entry = begin
import_adapter.import_transaction(
external_id: external_id,
amount: amount,
@@ -55,6 +79,10 @@ class LunchflowEntry::Processor
Rails.logger.error e.backtrace.join("\n")
raise StandardError.new("Unexpected error importing transaction: #{e.message}")
end
+
+ capture_unidentified_hold_diagnostic(entry) if first_hold_import && entry
+
+ entry
end
private
@@ -129,14 +157,26 @@ class LunchflowEntry::Processor
end
def name
- data[:merchant].presence || "Unknown transaction"
+ if unidentified_hold?
+ HOLD_TRANSACTION_NAME
+ elsif masked_card_text?(data[:merchant]) && data[:description].present?
+ data[:description].to_s.strip
+ else
+ data[:merchant].presence || "Unknown transaction"
+ end
end
def notes
- data[:description].presence
+ if masked_card_text?(data[:merchant]) && data[:description].present?
+ data[:merchant].presence
+ else
+ data[:description].presence || (data[:merchant].presence if unidentified_hold?)
+ end
end
def merchant
+ return nil if unidentified_hold?
+ return nil if masked_card_text?(data[:merchant])
return nil unless data[:merchant].present?
# Create a stable merchant ID from the merchant name
@@ -169,9 +209,18 @@ class LunchflowEntry::Processor
end
# Lunchflow likely uses standard convention where negative is expense, positive is income
- # Maybe expects opposite convention (expenses positive, income negative)
- # So we negate the amount to convert from Lunchflow to Maybe format
- -parsed_amount
+ # Sure expects opposite convention (expenses positive, income negative)
+ # So we negate the amount to convert from Lunchflow to Sure format.
+ #
+ # For unidentified card authorization holds, the ASPSP
+ # erroneously reports the authorization hold as positive credit (inflow).
+ # Force these holds to positive (outflow/expense in Sure) so they appear as pending expenses
+ # and match the settled expense when it arrives.
+ if unidentified_hold?
+ parsed_amount.abs
+ else
+ -parsed_amount
+ end
rescue ArgumentError => e
Rails.logger.error "Failed to parse Lunchflow transaction amount: #{data[:amount].inspect} - #{e.message}"
raise
@@ -213,9 +262,9 @@ class LunchflowEntry::Processor
def extra_metadata
metadata = {}
- # Store pending status from Lunchflow API when present
- if data.key?(:isPending)
- metadata[:lunchflow] = { pending: ActiveModel::Type::Boolean.new.cast(data[:isPending]) }
+ # Store pending status from Lunchflow API when present or when an unidentified hold
+ if data.key?(:isPending) || unidentified_hold?
+ metadata[:lunchflow] = { pending: is_pending? }
end
metadata
@@ -223,32 +272,77 @@ class LunchflowEntry::Processor
# Check if this transaction is marked as pending
def is_pending?
- ActiveModel::Type::Boolean.new.cast(data[:isPending])
+ unidentified_hold? || ActiveModel::Type::Boolean.new.cast(data[:isPending])
end
# Find an existing posted version of this pending transaction
# Matches by: exact amount, currency, merchant name (if present), and date window
# Uses same 8-day window as Account::ProviderImportAdapter reconciliation logic
- # Note: Lunchflow never provides real IDs for pending transactions (they're always blank),
- # so filtering by external_id NOT LIKE 'lunchflow_pending_%' is sufficient to exclude pending entries
def find_existing_posted_version
return nil unless account.present?
query = account.entries
+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")
.where(source: "lunchflow")
.where(amount: amount)
.where(currency: currency)
- .where("date BETWEEN ? AND ?", date, date + 8)
- .where("external_id NOT LIKE 'lunchflow_pending_%'")
- .where("external_id IS NOT NULL")
- .order(date: :asc) # Closest date first (prefer same-day posted, then next day, etc.)
-
- # Add merchant name matching for better precision
- # Only if merchant name is present in the transaction data
- if data[:merchant].present?
+ .where("entries.date BETWEEN ? AND ?", date, date + 8)
+ .where("entries.external_id NOT LIKE 'lunchflow_pending_%'")
+ .where("entries.external_id IS NOT NULL")
+ .where.not(external_id: external_id)
+ .where(Transaction.not_pending_sql("transactions", providers: "lunchflow"))
+ .order("entries.date ASC") # Closest date first (prefer same-day posted, then next day, etc.)
+
+ if unidentified_hold?
+ # An unidentified hold has a masked-card descriptor instead of the real merchant name.
+ # Only match a posted entry if it explicitly claimed this hold's external_id during
+ # pending→posted reconciliation, preventing unrelated same-amount purchases from
+ # suppressing an active hold.
+ query = query.where(
+ "transactions.extra -> 'auto_claimed_pending_ids' @> ?",
+ [ external_id ].to_json
+ )
+ elsif data[:merchant].present?
+ # Add merchant name matching for better precision when merchant name is present
query = query.where(name: name)
end
query.first
end
+
+ # Called only after a successful first import of a hold.
+ def capture_unidentified_hold_diagnostic(entry)
+ raw_amount = begin
+ BigDecimal(data[:amount].to_s)
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ # In Lunchflow convention, negative = expense, positive = income.
+ # Unidentified holds on expenses often arrive erroneously as positive credit (inflow),
+ # which LunchflowEntry::Processor normalizes to positive outflow in Sure (via parsed_amount.abs).
+ # If raw amount was positive, the sign was inverted upstream.
+ sign_inverted = raw_amount ? raw_amount > 0 : false
+
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "warn",
+ message: HOLD_DIAGNOSTIC_MESSAGE,
+ source: self.class.name,
+ provider_key: "lunchflow",
+ family: account.family,
+ account: account,
+ account_provider: lunchflow_account.account_provider,
+ metadata: {
+ external_id: external_id,
+ entry_id: entry.id,
+ raw_amount: data[:amount].to_s,
+ sign_inverted: sign_inverted,
+ amount: amount.to_s,
+ currency: currency,
+ merchant: data[:merchant],
+ description: data[:description]
+ }
+ )
+ end
end
diff --git a/app/models/lunchflow_item/importer.rb b/app/models/lunchflow_item/importer.rb
index 10de598f42..5374357524 100644
--- a/app/models/lunchflow_item/importer.rb
+++ b/app/models/lunchflow_item/importer.rb
@@ -291,7 +291,7 @@ class LunchflowItem::Importer
# leaving the entry stuck with a "Pending" badge (#2735). We now refresh
# the stored snapshot in place when the upstream payload changes, while
# still deduplicating by key to prevent unbounded growth.
- if transactions_data[:transactions].present?
+ if transactions_data[:transactions].present? || !include_pending
begin
existing_transactions = lunchflow_account.raw_transactions_payload.to_a
@@ -318,7 +318,30 @@ class LunchflowItem::Importer
new_count = 0
updated_count = 0
merged = []
- transactions_data[:transactions].each do |tx|
+
+ pending_or_hold = lambda do |tx|
+ next false unless tx.is_a?(Hash)
+ tx_ia = tx.with_indifferent_access
+ ActiveModel::Type::Boolean.new.cast(tx_ia[:isPending]) || LunchflowEntry::Processor.unidentified_hold?(tx_ia)
+ end
+
+ incoming_transactions = transactions_data[:transactions] || []
+ if include_pending
+ # Tag unidentified card holds as isPending: true
+ incoming_transactions = incoming_transactions.map do |tx|
+ next tx unless tx.is_a?(Hash)
+ if LunchflowEntry::Processor.unidentified_hold?(tx) && !ActiveModel::Type::Boolean.new.cast(tx.with_indifferent_access[:isPending])
+ tx.merge("isPending" => true)
+ else
+ tx
+ end
+ end
+ else
+ # If include_pending is disabled, filter out pending transactions and unidentified holds
+ incoming_transactions = incoming_transactions.reject(&pending_or_hold)
+ end
+
+ incoming_transactions.each do |tx|
next unless tx.is_a?(Hash)
stored = existing_pool[transaction_key.call(tx)].shift
@@ -341,12 +364,14 @@ class LunchflowItem::Importer
# Keep any stored rows the current response no longer returned — a normal
# sync never prunes the snapshot (unchanged prior behaviour).
leftover = existing_pool.values.flatten(1)
+ leftover = leftover.reject(&pending_or_hold) unless include_pending
+ merged_snapshot = merged + leftover
- if new_count > 0 || updated_count > 0
+ if new_count > 0 || updated_count > 0 || merged_snapshot.size != existing_transactions.size
Rails.logger.info "LunchflowItem::Importer - Storing #{new_count} new and #{updated_count} updated transactions (#{existing_transactions.count} existing) for account #{lunchflow_account.account_id}"
- lunchflow_account.upsert_lunchflow_transactions_snapshot!(merged + leftover)
+ lunchflow_account.upsert_lunchflow_transactions_snapshot!(merged_snapshot)
else
- Rails.logger.info "LunchflowItem::Importer - No new or updated transactions to store (all #{transactions_data[:transactions].count} unchanged) for account #{lunchflow_account.account_id}"
+ Rails.logger.info "LunchflowItem::Importer - No new or updated transactions to store (all #{incoming_transactions.count} unchanged) for account #{lunchflow_account.account_id}"
end
rescue => e
Rails.logger.error "LunchflowItem::Importer - Failed to store transactions for account #{lunchflow_account.account_id}: #{e.message}"
diff --git a/docs/llm-guides/providers.md b/docs/llm-guides/providers.md
index 02e57d83ab..b58b61f3ee 100644
--- a/docs/llm-guides/providers.md
+++ b/docs/llm-guides/providers.md
@@ -53,7 +53,7 @@ metadata produces no badge; manual/CSV imports have no pending concept.
| --- | --- |
| SimpleFIN | [`SimplefinEntry::Processor.pending?`](../../app/models/simplefin_entry/processor.rb) accepts an explicitly truthy `pending` flag, or `posted` equal to numeric `0` or string `"0"` with a present, positive `transacted_at` timestamp. A blank/missing `posted` value does **not** imply pending. Writes `extra["simplefin"]["pending"]` as true or false so a posted update clears stale pending metadata. |
| Plaid | [`PlaidEntry::Processor`](../../app/models/plaid_entry/processor.rb) stores bank/credit transaction `pending` and `pending_transaction_id` under `extra["plaid"]`; the linking ID supports pending-to-posted reconciliation. It also stores `original_description`, `payment_channel`, `transaction_code`, `payment_meta` and `counterparties`, and passes `replace_extra_namespaces: ["plaid"]` so the namespace is a snapshot of what Plaid currently reports. The investment transaction processor does not store pending metadata. |
-| Lunchflow | [`LunchflowEntry::Processor`](../../app/models/lunchflow_entry/processor.rb) stores the boolean-cast `isPending` value under `extra["lunchflow"]["pending"]` when the upstream key is present. |
+| Lunchflow | [`LunchflowEntry::Processor`](../../app/models/lunchflow_entry/processor.rb) stores the boolean-cast `isPending` value under `extra["lunchflow"]["pending"]` when the upstream key is present, or `true` when an unidentified card authorization hold is detected. |
| Monobank | [`MonobankEntry::Processor`](../../app/models/monobank_entry/processor.rb) treats a `hold: true` statement item as pending and writes `extra["monobank"]["pending"]`. Monobank may settle a hold under a *different* id, so the settled record reconciles onto the pending entry through [`Account::ProviderImportAdapter`](../../app/models/account/provider_import_adapter.rb)'s amount/date lookup. A hold that simply disappears is pruned, but only when the statement request actually covered its date range, and never when the entry is `protected_from_sync?` — those only lose the pending flag. `currencyCode` on a statement item is the **operation** currency, not the account's — it varies between items on one account — so entries take their currency from `MonobankAccount#currency` and `currencyCode`/`operationAmount` populate `fx_from`/`fx_amount`. Those two are emitted only for a recognized foreign operation — a known `currencyCode` differing from the account currency, and for `fx_amount` a parseable `operationAmount`, whose failure is captured as a `provider_sync_error`. Independently of that, `operation_amount` keeps the raw minor-unit figure whenever it differs from `amount`. |
SimpleFIN additionally stores `extra["simplefin"]["fx_from"]` when transaction and
diff --git a/test/models/enable_banking_entry/processor_test.rb b/test/models/enable_banking_entry/processor_test.rb
index bfb01593e4..0a0073a3e2 100644
--- a/test/models/enable_banking_entry/processor_test.rb
+++ b/test/models/enable_banking_entry/processor_test.rb
@@ -624,6 +624,382 @@ class EnableBankingEntry::ProcessorTest < ActiveSupport::TestCase
assert_equal true, eb_extra["pending"]
end
+ # --- unidentified_hold? unit tests ---
+
+ test "unidentified_hold? returns true when counterparty is absent and remittance has masked card descriptor" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: "2026-08-01",
+ transaction_amount: { amount: "26.57", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "474836xxxxxx6879 003015315475" ],
+ status: "BOOK"
+ }
+ assert_equal true, EnableBankingEntry::Processor.unidentified_hold?(tx)
+ end
+
+ test "unidentified_hold? returns false when remittance lacks masked card descriptor" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: "2026-08-01",
+ transaction_amount: { amount: "26.57", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "Arbitrary transfer" ],
+ status: "BOOK"
+ }
+ assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
+ end
+
+ test "unidentified_hold? returns true when creditor has empty or blank name and remittance has masked card descriptor" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ credit_debit_indicator: "DBIT",
+ creditor: { name: "" },
+ remittance_information: [ "474836xxxxxx6879" ]
+ }
+ assert_equal true, EnableBankingEntry::Processor.unidentified_hold?(tx)
+
+ tx2 = {
+ entry_reference: nil,
+ transaction_id: nil,
+ credit_debit_indicator: "DBIT",
+ creditor: { name: nil },
+ remittance_information: [ "474836xxxxxx6879" ]
+ }
+ assert_equal true, EnableBankingEntry::Processor.unidentified_hold?(tx2)
+ end
+
+ test "unidentified_hold? returns false when transaction_id is present" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: "txn_123",
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "474836xxxxxx6879" ]
+ }
+ assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
+ end
+
+ test "unidentified_hold? returns false when entry_reference is present" do
+ tx = {
+ entry_reference: "ref_123",
+ transaction_id: nil,
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "474836xxxxxx6879" ]
+ }
+ assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
+ end
+
+ test "unidentified_hold? returns false when creditor name is present" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ credit_debit_indicator: "DBIT",
+ creditor: { name: "Kaufland" },
+ remittance_information: [ "474836xxxxxx6879" ]
+ }
+ assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
+ end
+
+ test "unidentified_hold? returns false when creditor_name string is present" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ credit_debit_indicator: "DBIT",
+ creditor_name: "Kaufland",
+ remittance_information: [ "474836xxxxxx6879" ]
+ }
+ assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
+ end
+
+ test "unidentified_hold? returns false for incoming CRDT when debtor is present" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ credit_debit_indicator: "CRDT",
+ creditor: nil,
+ debtor: { name: "Alice" },
+ remittance_information: [ "474836xxxxxx6879" ]
+ }
+ assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
+ end
+
+ test "unidentified_hold? returns true for incoming CRDT when debtor is absent and remittance has masked card descriptor" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ credit_debit_indicator: "CRDT",
+ creditor: nil,
+ debtor: nil,
+ remittance_information: [ "474836xxxxxx6879" ]
+ }
+ assert_equal true, EnableBankingEntry::Processor.unidentified_hold?(tx)
+ end
+
+ test "pending_payload? returns true for an unidentified hold" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "474836xxxxxx6879" ]
+ }
+ assert_equal true, EnableBankingEntry::Processor.pending_payload?(tx)
+ end
+
+ test "stores pending true in extra for unidentified holds" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "26.57", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "5168XXXXXXXX1234" ],
+ status: "BOOK"
+ }
+
+ assert_difference "@account.entries.count", 1 do
+ EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
+ end
+
+ content_id = EnableBankingEntry::Processor.compute_external_id(tx)
+ entry = @account.entries.find_by!(external_id: content_id)
+ eb_extra = entry.transaction&.extra&.dig("enable_banking")
+ assert_equal true, eb_extra["pending"]
+ assert entry.transaction.pending?
+ end
+
+ test "normalizes CRDT amount to positive (outflow) and name to Card Authorization Hold for masked card holds" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "14.97", currency: "EUR" },
+ credit_debit_indicator: "CRDT",
+ creditor: nil,
+ remittance_information: [ "474836xxxxxx6879 003015315475" ],
+ status: "BOOK"
+ }
+
+ processor = EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account)
+ entry = processor.process
+
+ assert_not_nil entry
+ assert_equal BigDecimal("14.97"), entry.amount, "Must be positive outflow in Sure convention"
+ assert_equal "Card Authorization Hold", entry.name
+ assert_nil entry.transaction.merchant
+ assert_equal "474836xxxxxx6879 003015315475", entry.notes
+ assert entry.transaction.pending?
+ end
+
+ test "does not invert CRDT amount for legitimate incoming transfer without card descriptor" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "50.00", currency: "EUR" },
+ credit_debit_indicator: "CRDT",
+ creditor: nil,
+ debtor: nil,
+ remittance_information: [ "Gift from grandma" ],
+ status: "BOOK"
+ }
+
+ processor = EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account)
+ entry = processor.process
+
+ assert_not_nil entry
+ assert_equal BigDecimal("-50.00"), entry.amount, "Must remain negative inflow in Sure convention"
+ assert_not_equal "Card Authorization Hold", entry.name
+ end
+
+ test "masked_card_descriptor? detects masked card numbers in remittance or bank transaction code" do
+ assert EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: [ "474836xxxxxx6879 003015315475" ])
+ assert EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: "474836XXXXXX6879")
+ assert EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: [ "474836******6879" ])
+ assert EnableBankingEntry::Processor.masked_card_descriptor?(bank_transaction_code: { description: "474836xxxxxx6879" })
+
+ assert_not EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: [ "Supermarket" ])
+ assert_not EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: [ "Salary" ])
+ assert_not EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: nil)
+ assert_not EnableBankingEntry::Processor.masked_card_descriptor?(
+ remittance_information: [ "Amazon.com", "474836xxxxxx6879 003015315475" ]
+ )
+ assert_not EnableBankingEntry::Processor.masked_card_descriptor?(
+ remittance_information: [ "474836xxxxxx6879 003015315475", "Amazon.com" ]
+ )
+ # Technical terminal lines are ignored when finding descriptive remittance lines
+ assert EnableBankingEntry::Processor.masked_card_descriptor?(
+ remittance_information: [ "474836xxxxxx6879 003015315475", "POS 45,13 AT D6 31.07. 10:27" ]
+ )
+ # Masked bank transaction code does not override legitimate remittance merchant
+ assert_not EnableBankingEntry::Processor.masked_card_descriptor?(
+ remittance_information: [ "Amazon.com" ],
+ bank_transaction_code: { description: "474836xxxxxx6879" }
+ )
+ end
+
+ test "does not treat multi-line remittance with legitimate payee and card PAN as unidentified hold" do
+ # When payee matches a known merchant, preserves payee name and associates known merchant
+ tx_known = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "29.99", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "Amazon.com", "474836xxxxxx6879 003015315475" ],
+ status: "BOOK"
+ }
+
+ entry_known = EnableBankingEntry::Processor.new(tx_known, enable_banking_account: @enable_banking_account).process
+
+ assert_not_nil entry_known
+ assert_equal BigDecimal("29.99"), entry_known.amount
+ assert_equal "Amazon", entry_known.name
+ assert_equal "Amazon", entry_known.transaction.merchant&.name
+ assert_not entry_known.transaction.pending?
+
+ # When payee is not an existing known merchant, preserves remittance text as entry name
+ tx_unknown = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "15.50", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "Acme Store", "474836xxxxxx6879 003015315475" ],
+ status: "BOOK"
+ }
+
+ entry_unknown = EnableBankingEntry::Processor.new(tx_unknown, enable_banking_account: @enable_banking_account).process
+
+ assert_not_nil entry_unknown
+ assert_equal BigDecimal("15.50"), entry_unknown.amount
+ assert_equal "Acme Store", entry_unknown.name
+ assert_not entry_unknown.transaction.pending?
+ end
+
+ test "captures warning DebugLogEntry when processing unidentified card hold on first import only" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "14.97", currency: "EUR" },
+ credit_debit_indicator: "CRDT",
+ creditor: nil,
+ remittance_information: [ "474836xxxxxx6879 003015315475" ],
+ status: "BOOK"
+ }
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
+ end
+
+ log_entry = DebugLogEntry.last
+ assert_equal "provider_sync", log_entry.category
+ assert_equal "warn", log_entry.level
+ assert_equal "enable_banking", log_entry.provider_key
+ assert_equal @account, log_entry.account
+ assert_equal @account.family, log_entry.family
+ assert_equal @enable_banking_account.account_provider, log_entry.account_provider
+ assert_equal CardAuthorizationHold::HOLD_DIAGNOSTIC_MESSAGE, log_entry.message
+ assert_equal true, log_entry.metadata["sign_inverted"]
+ assert_equal "14.97", log_entry.metadata["raw_amount"]
+ assert_equal "CRDT", log_entry.metadata["credit_debit_indicator"]
+
+ # Re-processing the same hold on subsequent sync does not write duplicate DebugLogEntry
+ assert_no_difference -> { DebugLogEntry.count } do
+ EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
+ end
+ end
+
+ test "captures warning DebugLogEntry with sign_inverted false for DBIT unidentified hold" do
+ tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "20.00", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "474836xxxxxx6879 003015315475" ],
+ status: "BOOK"
+ }
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
+ end
+
+ log_entry = DebugLogEntry.last
+ assert_equal false, log_entry.metadata["sign_inverted"]
+ assert_equal "DBIT", log_entry.metadata["credit_debit_indicator"]
+ assert_equal "20.00", log_entry.metadata["raw_amount"]
+ end
+
+ test "does not capture DebugLogEntry for regular transactions" do
+ tx = {
+ entry_reference: "ref_regular",
+ transaction_id: "tx_regular",
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "14.97", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: { name: "Regular Store" },
+ status: "BOOK"
+ }
+
+ assert_no_difference -> { DebugLogEntry.count } do
+ EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
+ end
+ end
+
+ test "reconciles and claims unfinalized card hold when settled booked transaction arrives" do
+ # 1. First sync: unfinalized card hold arrives with status BOOK, CRDT, no counterparty, masked remittance
+ hold_tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "14.97", currency: "EUR" },
+ credit_debit_indicator: "CRDT",
+ creditor: nil,
+ remittance_information: [ "474836xxxxxx6879 003015315475" ],
+ status: "BOOK"
+ }
+
+ hold_entry = EnableBankingEntry::Processor.new(hold_tx, enable_banking_account: @enable_banking_account).process
+ assert_not_nil hold_entry
+ assert_equal BigDecimal("14.97"), hold_entry.amount
+ assert_equal "Card Authorization Hold", hold_entry.name
+ assert hold_entry.transaction.pending?
+
+ # 2. Later sync: settled booked transaction arrives with real creditor, DBIT, and identifiers
+ settled_tx = {
+ entry_reference: "ref_settled_999",
+ transaction_id: "txn_settled_999",
+ booking_date: Date.current.to_s,
+ transaction_amount: { amount: "14.97", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: { name: "Billa" },
+ remittance_information: [ "BILLA DANKT 0007114" ],
+ status: "BOOK"
+ }
+
+ settled_entry = EnableBankingEntry::Processor.new(settled_tx, enable_banking_account: @enable_banking_account).process
+ assert_not_nil settled_entry
+
+ # Should have claimed the pending hold entry instead of creating a duplicate
+ assert_equal hold_entry.id, settled_entry.id, "Settled transaction must claim the pending hold row"
+ assert_equal "enable_banking_txn_settled_999", settled_entry.external_id
+ assert_not settled_entry.transaction.pending?, "Pending flag must be cleared upon settlement"
+ assert_equal 1, @account.entries.where(source: "enable_banking").count
+ end
+
test "does not add enable_banking extra key when no extra data present" do
tx = {
entry_reference: "ref_noextra",
diff --git a/test/models/enable_banking_item/importer_pdng_test.rb b/test/models/enable_banking_item/importer_pdng_test.rb
index 3fd1d18afd..c70f444d3a 100644
--- a/test/models/enable_banking_item/importer_pdng_test.rb
+++ b/test/models/enable_banking_item/importer_pdng_test.rb
@@ -188,4 +188,85 @@ class EnableBankingItem::ImporterPdngTest < ActiveSupport::TestCase
assert result[:success]
assert_nil @enable_banking_account.raw_transactions_payload
end
+
+ test "fetch_and_store_transactions tags unidentified hold with BOOK status as pending when include_pending is true" do
+ @importer.stubs(:include_pending?).returns(true)
+
+ hold_tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: "2026-08-01",
+ transaction_amount: { amount: "26.57", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "5168XXXXXXXX1234" ],
+ status: "BOOK"
+ }
+
+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ hold_tx ])
+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG")).returns([])
+
+ result = @importer.send(:fetch_and_store_transactions, @enable_banking_account)
+
+ assert result[:success]
+ stored = @enable_banking_account.raw_transactions_payload
+ assert_equal 1, stored.size
+ assert_equal true, stored.first.with_indifferent_access[:_pending]
+ end
+
+ test "fetch_and_store_transactions filters out unidentified hold with BOOK status when include_pending is false" do
+ @importer.stubs(:include_pending?).returns(false)
+
+ hold_tx = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: "2026-08-01",
+ transaction_amount: { amount: "26.57", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "5168XXXXXXXX1234" ],
+ status: "BOOK"
+ }
+
+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ hold_tx ])
+
+ result = @importer.send(:fetch_and_store_transactions, @enable_banking_account)
+
+ assert result[:success]
+ assert_nil @enable_banking_account.raw_transactions_payload
+ end
+
+ test "fetch_and_store_transactions prunes cached unidentified holds from existing transactions when include_pending is false" do
+ @importer.stubs(:include_pending?).returns(false)
+
+ cached_hold = {
+ entry_reference: nil,
+ transaction_id: nil,
+ booking_date: "2026-08-01",
+ transaction_amount: { amount: "26.57", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ creditor: nil,
+ remittance_information: [ "5168XXXXXXXX1234" ],
+ status: "BOOK"
+ }
+ cached_settled = {
+ entry_reference: "settled_ref",
+ transaction_id: "tx_123",
+ booking_date: "2026-08-01",
+ transaction_amount: { amount: "50.00", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ status: "BOOK"
+ }
+
+ @enable_banking_account.upsert_enable_banking_transactions_snapshot!([ cached_hold, cached_settled ])
+
+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([])
+
+ result = @importer.send(:fetch_and_store_transactions, @enable_banking_account)
+
+ assert result[:success]
+ stored = @enable_banking_account.raw_transactions_payload
+ assert_equal 1, stored.size
+ assert_equal "settled_ref", stored.first.with_indifferent_access[:entry_reference]
+ end
end
diff --git a/test/models/lunchflow_entry/processor_test.rb b/test/models/lunchflow_entry/processor_test.rb
index 0f51c29801..6bbfd44653 100644
--- a/test/models/lunchflow_entry/processor_test.rb
+++ b/test/models/lunchflow_entry/processor_test.rb
@@ -403,4 +403,279 @@ class LunchflowEntry::ProcessorTest < ActiveSupport::TestCase
assert_equal Date.new(2025, 7, 14), result.date,
"Transaction at 21:20 EDT should land on July 14, not July 15"
end
+
+ # --- unidentified card hold tests ---
+
+ test "unidentified_hold? detects masked card descriptors in merchant or description only when id is blank" do
+ assert LunchflowEntry::Processor.unidentified_hold?(id: nil, merchant: "474836xxxxxx6879 003015315475")
+ assert LunchflowEntry::Processor.unidentified_hold?(id: "", merchant: "474836XXXXXX6879")
+ assert LunchflowEntry::Processor.unidentified_hold?(merchant: "474836******6879")
+ assert LunchflowEntry::Processor.unidentified_hold?(merchant: nil, description: "474836xxxxxx6879 003015315475")
+ assert LunchflowEntry::Processor.unidentified_hold?(merchant: "", description: "474836xxxxxx6879")
+
+ assert_not LunchflowEntry::Processor.unidentified_hold?(id: "lf_123", merchant: "474836xxxxxx6879 003015315475")
+ assert_not LunchflowEntry::Processor.unidentified_hold?(merchant: "Uber", description: "474836xxxxxx6879")
+ assert_not LunchflowEntry::Processor.unidentified_hold?(merchant: "474836xxxxxx6879", description: "Uber")
+ assert_not LunchflowEntry::Processor.unidentified_hold?(merchant: "Amazon", description: "Order 123")
+ assert_not LunchflowEntry::Processor.unidentified_hold?(merchant: "Card 123", description: nil)
+ end
+
+ test "does not treat masked merchant with legitimate description as unidentified hold" do
+ data = {
+ id: "",
+ accountId: 456,
+ amount: -25.00,
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "474836xxxxxx6879 003015315475",
+ description: "Uber Trip",
+ isPending: false
+ }
+
+ result = LunchflowEntry::Processor.new(data, lunchflow_account: @lunchflow_account).process
+
+ assert_not_nil result
+ assert_equal BigDecimal("25.00"), result.amount
+ assert_equal "Uber Trip", result.name
+ assert_nil result.entryable.merchant, "Must not create a ProviderMerchant for a masked PAN"
+ assert_equal "474836xxxxxx6879 003015315475", result.notes
+ assert_not result.entryable.pending?
+ end
+
+ test "normalizes inverted positive hold amount to positive expense, suppresses merchant, and sets name" do
+ # Unidentified hold returned via Lunchflow with positive amount (credit), masked card PAN
+ hold_data = {
+ id: "",
+ accountId: 456,
+ amount: 14.97, # Erroneously positive credit in Lunchflow
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "474836xxxxxx6879 003015315475",
+ description: "474836xxxxxx6879 003015315475",
+ isPending: false # Even if API returned false/missing
+ }
+
+ result = LunchflowEntry::Processor.new(
+ hold_data,
+ lunchflow_account: @lunchflow_account
+ ).process
+
+ assert_not_nil result
+ assert_equal BigDecimal("14.97"), result.amount, "Must be positive outflow in Sure convention"
+ assert_equal "Card Authorization Hold", result.name
+ assert_nil result.entryable.merchant
+ assert_equal "474836xxxxxx6879 003015315475", result.notes
+ assert result.entryable.pending?
+ assert_equal true, result.entryable.extra.dig("lunchflow", "pending")
+ end
+
+ test "claims pending hold when settled transaction arrives and skips re-importing the claimed hold on next sync" do
+ # 1. Pending card hold arrives first with masked card number and inverted positive amount
+ hold_data = {
+ id: "",
+ accountId: 456,
+ amount: 14.97,
+ currency: "EUR",
+ date: "2025-01-19",
+ merchant: "474836xxxxxx6879 003015315475",
+ description: "474836xxxxxx6879 003015315475"
+ }
+
+ hold_entry = LunchflowEntry::Processor.new(
+ hold_data,
+ lunchflow_account: @lunchflow_account
+ ).process
+
+ assert_not_nil hold_entry
+ assert hold_entry.entryable.pending?
+
+ # 2. Settled transaction arrives with real merchant name "BILLA" and amount -14.97 (negative = expense in Lunchflow)
+ posted_data = {
+ id: "lf_txn_posted_billa",
+ accountId: 456,
+ amount: -14.97,
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "BILLA",
+ description: "Supermarket purchase",
+ isPending: false
+ }
+
+ posted_entry = LunchflowEntry::Processor.new(
+ posted_data,
+ lunchflow_account: @lunchflow_account
+ ).process
+
+ assert_equal hold_entry.id, posted_entry.id, "Posted transaction must claim the pending hold"
+ assert_equal "lunchflow_lf_txn_posted_billa", posted_entry.external_id
+ assert_not posted_entry.entryable.reload.pending?
+
+ # 3. Cached hold in raw_transactions_payload is re-processed on subsequent sync
+ reprocessed_hold = LunchflowEntry::Processor.new(
+ hold_data,
+ lunchflow_account: @lunchflow_account
+ ).process
+
+ assert_equal posted_entry.id, reprocessed_hold.id, "Claimed hold must match the posted entry that claimed it"
+ assert_equal 1, @account.entries.where(source: "lunchflow").count
+ end
+
+ test "does not skip unidentified hold when an unrelated posted purchase has the same amount and date" do
+ # Unrelated posted purchase arrived first without claiming any hold
+ unrelated_posted = {
+ id: "lf_txn_unrelated",
+ accountId: 456,
+ amount: -14.97,
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "BILLA",
+ description: "Earlier purchase",
+ isPending: false
+ }
+
+ posted_entry = LunchflowEntry::Processor.new(
+ unrelated_posted,
+ lunchflow_account: @lunchflow_account
+ ).process
+
+ # New unidentified hold for the same amount arrives
+ hold_data = {
+ id: "",
+ accountId: 456,
+ amount: 14.97,
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "474836xxxxxx6879 003015315475",
+ description: "474836xxxxxx6879 003015315475"
+ }
+
+ hold_entry = LunchflowEntry::Processor.new(
+ hold_data,
+ lunchflow_account: @lunchflow_account
+ ).process
+
+ assert_not_equal posted_entry.id, hold_entry.id, "Unrelated posted purchase must not suppress a new hold"
+ assert hold_entry.entryable.pending?
+ assert_equal 2, @account.entries.where(source: "lunchflow").count
+ end
+
+ test "find_existing_posted_version excludes pending entries that have a real provider ID" do
+ # Pending entry that happened to have a real provider ID
+ pending_with_id = {
+ id: "lf_pending_real_id",
+ accountId: 456,
+ amount: -25.00,
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "Coffee Shop",
+ description: "Coffee",
+ isPending: true
+ }
+
+ first_entry = LunchflowEntry::Processor.new(
+ pending_with_id,
+ lunchflow_account: @lunchflow_account
+ ).process
+ assert first_entry.entryable.pending?
+
+ # Second pending entry without ID for the same merchant and amount
+ pending_without_id = {
+ id: "",
+ accountId: 456,
+ amount: -25.00,
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "Coffee Shop",
+ description: "Coffee",
+ isPending: true
+ }
+
+ second_entry = LunchflowEntry::Processor.new(
+ pending_without_id,
+ lunchflow_account: @lunchflow_account
+ ).process
+
+ assert_not_equal first_entry.id, second_entry.id, "Pending entry with real ID must not be treated as a posted version"
+ assert_equal 2, @account.entries.where(source: "lunchflow").count
+ end
+
+ test "captures warning DebugLogEntry when processing unidentified card hold on first import only" do
+ hold_data = {
+ id: "",
+ accountId: 456,
+ amount: 14.97,
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "474836xxxxxx6879 003015315475",
+ description: "474836xxxxxx6879 003015315475"
+ }
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ LunchflowEntry::Processor.new(
+ hold_data,
+ lunchflow_account: @lunchflow_account
+ ).process
+ end
+
+ log_entry = DebugLogEntry.last
+ assert_equal "provider_sync", log_entry.category
+ assert_equal "warn", log_entry.level
+ assert_equal "lunchflow", log_entry.provider_key
+ assert_equal @lunchflow_account.current_account, log_entry.account
+ assert_equal @lunchflow_account.current_account.family, log_entry.family
+ assert_equal @lunchflow_account.account_provider, log_entry.account_provider
+ assert_equal CardAuthorizationHold::HOLD_DIAGNOSTIC_MESSAGE, log_entry.message
+ assert_equal true, log_entry.metadata["sign_inverted"]
+ assert_equal "14.97", log_entry.metadata["raw_amount"]
+
+ # Re-processing the same hold on subsequent sync does not write duplicate DebugLogEntry
+ assert_no_difference -> { DebugLogEntry.count } do
+ LunchflowEntry::Processor.new(
+ hold_data,
+ lunchflow_account: @lunchflow_account
+ ).process
+ end
+ end
+
+ test "captures warning DebugLogEntry with sign_inverted false for negative amount hold" do
+ hold_data = {
+ id: "",
+ accountId: 456,
+ amount: -14.97,
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "474836xxxxxx6879 003015315475",
+ description: "474836xxxxxx6879 003015315475"
+ }
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ LunchflowEntry::Processor.new(
+ hold_data,
+ lunchflow_account: @lunchflow_account
+ ).process
+ end
+
+ log_entry = DebugLogEntry.last
+ assert_equal false, log_entry.metadata["sign_inverted"]
+ assert_equal "-14.97", log_entry.metadata["raw_amount"]
+ end
+
+ test "does not capture DebugLogEntry for regular transactions" do
+ data = {
+ id: "tx_regular",
+ accountId: 456,
+ amount: -14.97,
+ currency: "EUR",
+ date: "2025-01-20",
+ merchant: "Uber",
+ description: "Uber ride"
+ }
+
+ assert_no_difference -> { DebugLogEntry.count } do
+ LunchflowEntry::Processor.new(
+ data,
+ lunchflow_account: @lunchflow_account
+ ).process
+ end
+ end
end
diff --git a/test/models/lunchflow_item/importer_blank_id_test.rb b/test/models/lunchflow_item/importer_blank_id_test.rb
index 059684aef2..5e58d8f7a1 100644
--- a/test/models/lunchflow_item/importer_blank_id_test.rb
+++ b/test/models/lunchflow_item/importer_blank_id_test.rb
@@ -2,6 +2,8 @@ require "test_helper"
class LunchflowItem::ImporterBlankIdTest < ActiveSupport::TestCase
setup do
+ Rails.configuration.x.lunchflow.stubs(:include_pending).returns(true)
+
@family = families(:dylan_family)
@item = LunchflowItem.create!(
family: @family,
@@ -296,4 +298,119 @@ class LunchflowItem::ImporterBlankIdTest < ActiveSupport::TestCase
assert_equal 2, @lunchflow_account.reload.raw_transactions_payload.size,
"re-syncing the same pair must not accumulate duplicates"
end
+
+ test "tags unidentified card holds as isPending when include_pending is enabled" do
+ Rails.configuration.x.lunchflow.stubs(:include_pending).returns(true)
+
+ hold_transaction = {
+ "id" => "",
+ "accountId" => @lunchflow_account.account_id,
+ "amount" => 15.50,
+ "currency" => "GBP",
+ "date" => Date.today.to_s,
+ "merchant" => "474836xxxxxx6879 003015315475",
+ "description" => "474836xxxxxx6879 003015315475"
+ }
+
+ mock_provider = mock()
+ mock_provider.stubs(:get_account_transactions)
+ .with(@lunchflow_account.account_id, anything)
+ .returns({ transactions: [ hold_transaction ], count: 1 })
+ mock_provider.stubs(:get_account_balance)
+ .with(@lunchflow_account.account_id)
+ .returns({ balance: 100.0, currency: "GBP" })
+
+ importer = LunchflowItem::Importer.new(@item, lunchflow_provider: mock_provider)
+ result = importer.send(:fetch_and_store_transactions, @lunchflow_account)
+
+ assert result[:success]
+ payload = @lunchflow_account.reload.raw_transactions_payload
+ assert_equal 1, payload.size
+ assert_equal true, payload.first.with_indifferent_access[:isPending],
+ "unidentified hold must be tagged as isPending when include_pending is enabled"
+ end
+
+ test "filters out unidentified card holds when include_pending is disabled" do
+ Rails.configuration.x.lunchflow.stubs(:include_pending).returns(false)
+
+ hold_transaction = {
+ "id" => "",
+ "accountId" => @lunchflow_account.account_id,
+ "amount" => 15.50,
+ "currency" => "GBP",
+ "date" => Date.today.to_s,
+ "merchant" => "474836xxxxxx6879 003015315475",
+ "description" => "474836xxxxxx6879 003015315475"
+ }
+ regular_transaction = {
+ "id" => "lf_posted_1",
+ "accountId" => @lunchflow_account.account_id,
+ "amount" => -20.00,
+ "currency" => "GBP",
+ "date" => Date.today.to_s,
+ "merchant" => "Tesco",
+ "description" => "Groceries",
+ "isPending" => false
+ }
+
+ mock_provider = mock()
+ mock_provider.stubs(:get_account_transactions)
+ .with(@lunchflow_account.account_id, anything)
+ .returns({ transactions: [ hold_transaction, regular_transaction ], count: 2 })
+ mock_provider.stubs(:get_account_balance)
+ .with(@lunchflow_account.account_id)
+ .returns({ balance: 100.0, currency: "GBP" })
+
+ importer = LunchflowItem::Importer.new(@item, lunchflow_provider: mock_provider)
+ result = importer.send(:fetch_and_store_transactions, @lunchflow_account)
+
+ assert result[:success]
+ payload = @lunchflow_account.reload.raw_transactions_payload
+ assert_equal 1, payload.size, "hold must be excluded when include_pending is disabled"
+ assert_equal "lf_posted_1", payload.first.with_indifferent_access[:id]
+ end
+
+ test "prunes cached holds and pending rows from snapshot leftovers when include_pending is disabled" do
+ Rails.configuration.x.lunchflow.stubs(:include_pending).returns(false)
+
+ hold_transaction = {
+ "id" => "",
+ "accountId" => @lunchflow_account.account_id,
+ "amount" => 15.50,
+ "currency" => "GBP",
+ "date" => Date.today.to_s,
+ "merchant" => "474836xxxxxx6879 003015315475",
+ "description" => "474836xxxxxx6879 003015315475"
+ }
+ regular_transaction = {
+ "id" => "lf_posted_1",
+ "accountId" => @lunchflow_account.account_id,
+ "amount" => -20.00,
+ "currency" => "GBP",
+ "date" => Date.today.to_s,
+ "merchant" => "Tesco",
+ "description" => "Groceries",
+ "isPending" => false
+ }
+
+ # Pre-populate raw_transactions_payload with cached hold and regular transaction
+ @lunchflow_account.upsert_lunchflow_transactions_snapshot!([ hold_transaction, regular_transaction ])
+
+ # Sync response returns no transactions (e.g. empty API response)
+ mock_provider = mock()
+ mock_provider.stubs(:get_account_transactions)
+ .with(@lunchflow_account.account_id, anything)
+ .returns({ transactions: [], count: 0 })
+ mock_provider.stubs(:get_account_balance)
+ .with(@lunchflow_account.account_id)
+ .returns({ balance: 100.0, currency: "GBP" })
+
+ importer = LunchflowItem::Importer.new(@item, lunchflow_provider: mock_provider)
+ result = importer.send(:fetch_and_store_transactions, @lunchflow_account)
+
+ assert result[:success]
+ payload = @lunchflow_account.reload.raw_transactions_payload
+ assert_equal 1, payload.size, "cached hold must be pruned from leftover snapshot"
+ assert_equal "lf_posted_1", payload.first.with_indifferent_access[:id]
+ end
end