Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(lunchflow): refresh stored transaction on pending to posted (#2778)

pro3958b0ecb919b000
diff --git a/app/models/lunchflow_item/importer.rb b/app/models/lunchflow_item/importer.rb
index 0a60039470..516b1ca2a2 100644
--- a/app/models/lunchflow_item/importer.rb
+++ b/app/models/lunchflow_item/importer.rb
@@ -275,51 +275,72 @@ class LunchflowItem::Importer
transactions_count = transactions_data[:transactions]&.count || 0
Rails.logger.info "LunchflowItem::Importer - Fetched #{transactions_count} transactions for account #{lunchflow_account.account_id}"
- # Store transactions in the account
+ # Store transactions in the account.
+ #
+ # Transactions are keyed by their Lunchflow ID, or by a content hash when
+ # Lunchflow returns a blank ID (as it does for some pending transactions).
+ # Stored transactions were previously treated as immutable, so a
+ # transaction that Lunchflow later flipped from pending to posted was
+ # skipped as a duplicate and its stale pending snapshot was kept forever —
+ # 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?
begin
existing_transactions = lunchflow_account.raw_transactions_payload.to_a
- # Build set of existing transaction IDs for efficient lookup
- # For transactions with IDs: use the ID directly
- # For transactions without IDs (blank/nil): use content hash to prevent duplicate storage
- existing_ids = existing_transactions.map do |tx|
+ # Stable key for a transaction: its real ID, or a content hash for the
+ # blank IDs Lunchflow returns for some pending transactions.
+ transaction_key = lambda do |tx|
tx_with_access = tx.with_indifferent_access
- tx_id = tx_with_access[:id]
-
- if tx_id.blank?
- # Generate content hash for blank-ID transactions to detect duplicates
- content_hash_for_transaction(tx_with_access)
- else
- tx_id
- end
- end.compact.to_set
-
- # Filter to ONLY truly new transactions (skip duplicates)
- # For transactions WITH IDs: skip if ID already exists (true duplicates)
- # For transactions WITHOUT IDs: skip if content hash exists (prevents unbounded growth)
- # Note: Pending transactions may update from pending→posted, but we treat them as immutable snapshots
- new_transactions = transactions_data[:transactions].select do |tx|
- next false unless tx.is_a?(Hash)
+ tx_with_access[:id].presence || content_hash_for_transaction(tx_with_access)
+ end
- tx_with_access = tx.with_indifferent_access
- tx_id = tx_with_access[:id]
+ # Pool the existing snapshot into one bucket per key. Two genuinely
+ # distinct purchases can share a content hash (Lunchflow returns blank IDs
+ # for some pending transactions), so match incoming rows to stored rows
+ # one-for-one rather than collapsing every same-key row into a single
+ # entry. Collapsing regressed identical same-response purchases, dropping
+ # one before LunchflowEntry::Processor could suffix the collision.
+ existing_pool = Hash.new { |pool, key| pool[key] = [] }
+ existing_transactions.each do |tx|
+ next unless tx.is_a?(Hash)
+
+ existing_pool[transaction_key.call(tx)] << tx
+ end
- if tx_id.blank?
- # Use content hash to detect if we've already stored this exact transaction
- content_hash = content_hash_for_transaction(tx_with_access)
- !existing_ids.include?(content_hash)
+ new_count = 0
+ updated_count = 0
+ merged = []
+ transactions_data[:transactions].each do |tx|
+ next unless tx.is_a?(Hash)
+
+ stored = existing_pool[transaction_key.call(tx)].shift
+ if stored.nil?
+ # New to the snapshot. A second same-response row that collides with
+ # the first on content hash lands here too, so both are preserved.
+ merged << tx
+ new_count += 1
+ elsif stored.with_indifferent_access == tx.with_indifferent_access
+ # Unchanged since last sync; keep the stored copy as-is.
+ merged << stored
else
- # If has ID, only include if not already stored
- !existing_ids.include?(tx_id)
+ # Upstream data changed (e.g. pending → posted); refresh the stored
+ # snapshot so the status transition propagates to the processor.
+ merged << tx
+ updated_count += 1
end
end
- if new_transactions.any?
- Rails.logger.info "LunchflowItem::Importer - Storing #{new_transactions.count} new transactions (#{existing_transactions.count} existing, #{transactions_data[:transactions].count - new_transactions.count} duplicates skipped) for account #{lunchflow_account.account_id}"
- lunchflow_account.upsert_lunchflow_transactions_snapshot!(existing_transactions + new_transactions)
+ # 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)
+
+ if new_count > 0 || updated_count > 0
+ 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)
else
- Rails.logger.info "LunchflowItem::Importer - No new transactions to store (all #{transactions_data[:transactions].count} were duplicates) for account #{lunchflow_account.account_id}"
+ Rails.logger.info "LunchflowItem::Importer - No new or updated transactions to store (all #{transactions_data[: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/test/models/lunchflow_item/importer_blank_id_test.rb b/test/models/lunchflow_item/importer_blank_id_test.rb
index bbfd7b6009..059684aef2 100644
--- a/test/models/lunchflow_item/importer_blank_id_test.rb
+++ b/test/models/lunchflow_item/importer_blank_id_test.rb
@@ -178,6 +178,49 @@ class LunchflowItem::ImporterBlankIdTest < ActiveSupport::TestCase
assert_equal content_hash, external_id_hash, "Importer content hash should match processor's MD5 hash"
end
+ test "refreshes a stored transaction when it flips from pending to posted" do
+ # Same Lunchflow transaction ID, first returned as pending then as posted.
+ pending_version = {
+ "id" => "txn_456",
+ "accountId" => @lunchflow_account.account_id,
+ "amount" => -42.00,
+ "currency" => "GBP",
+ "date" => Date.today.to_s,
+ "merchant" => "AMAZON",
+ "description" => "Order",
+ "isPending" => true
+ }
+ posted_version = pending_version.merge("isPending" => false)
+
+ mock_provider = mock()
+ 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)
+
+ # First sync stores the pending version
+ mock_provider.stubs(:get_account_transactions)
+ .with(@lunchflow_account.account_id, anything)
+ .returns({ transactions: [ pending_version ], count: 1 })
+
+ importer.send(:fetch_and_store_transactions, @lunchflow_account)
+ payload = @lunchflow_account.reload.raw_transactions_payload
+ assert_equal 1, payload.size
+ assert_equal true, payload.first.with_indifferent_access[:isPending]
+
+ # Second sync returns the same transaction, now posted
+ mock_provider.stubs(:get_account_transactions)
+ .with(@lunchflow_account.account_id, anything)
+ .returns({ transactions: [ posted_version ], count: 1 })
+
+ importer.send(:fetch_and_store_transactions, @lunchflow_account)
+ payload = @lunchflow_account.reload.raw_transactions_payload
+ assert_equal 1, payload.size, "must not duplicate the transaction on status change"
+ assert_equal false, payload.first.with_indifferent_access[:isPending],
+ "stored snapshot must refresh so the pending→posted transition reaches the processor"
+ end
+
test "transactions with IDs are not affected by content hash logic" do
# Transaction with a proper ID
transaction_with_id = {
@@ -215,4 +258,42 @@ class LunchflowItem::ImporterBlankIdTest < ActiveSupport::TestCase
assert result[:success]
assert_equal 1, @lunchflow_account.reload.raw_transactions_payload.size
end
+
+ test "preserves identical blank-ID transactions that arrive in the same response" do
+ # Two legitimately distinct but identical purchases (e.g. the same coffee bought
+ # twice). Lunchflow returns blank IDs, so they share a content hash — but both are
+ # real and must survive so LunchflowEntry::Processor can suffix the collision.
+ # Regression: the previous key-Hash merge collapsed the pair into one, dropping a
+ # real transaction before processing.
+ duplicate = {
+ "id" => "",
+ "accountId" => @lunchflow_account.account_id,
+ "amount" => -3.50,
+ "currency" => "GBP",
+ "date" => Date.today.to_s,
+ "merchant" => "CAFE",
+ "description" => "Flat white",
+ "isPending" => true
+ }
+
+ mock_provider = mock()
+ mock_provider.stubs(:get_account_transactions)
+ .with(@lunchflow_account.account_id, anything)
+ .returns({ transactions: [ duplicate.dup, duplicate.dup ], 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)
+
+ # First sync: both identical rows must be stored, not collapsed into one.
+ importer.send(:fetch_and_store_transactions, @lunchflow_account)
+ assert_equal 2, @lunchflow_account.reload.raw_transactions_payload.size,
+ "both same-response blank-ID collisions must be preserved"
+
+ # Second sync returns the same pair: matched one-for-one, so still two, not four.
+ importer.send(:fetch_and_store_transactions, @lunchflow_account)
+ assert_equal 2, @lunchflow_account.reload.raw_transactions_payload.size,
+ "re-syncing the same pair must not accumulate duplicates"
+ end
end