Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Prevent duplicate Lunch Flow's transactions on sync (#4626)

N1KHLc47ce7e48969
diff --git a/app/models/lunchflow_account/transactions/processor.rb b/app/models/lunchflow_account/transactions/processor.rb
index ca82104129..9745ced5d1 100644
--- a/app/models/lunchflow_account/transactions/processor.rb
+++ b/app/models/lunchflow_account/transactions/processor.rb
@@ -1,4 +1,6 @@
class LunchflowAccount::Transactions::Processor
+ include LunchflowTransactionHash
+
attr_reader :lunchflow_account
def initialize(lunchflow_account)
@@ -20,11 +22,14 @@ class LunchflowAccount::Transactions::Processor
# Each entry is processed inside a transaction, but to avoid locking up the DB when
# there are hundreds or thousands of transactions, we process them individually.
+ seen_content_hashes = Hash.new(0)
+
lunchflow_account.raw_transactions_payload.each_with_index do |transaction_data, index|
begin
result = LunchflowEntry::Processor.new(
transaction_data,
- lunchflow_account: lunchflow_account
+ lunchflow_account: lunchflow_account,
+ occurrence: occurrence_of(transaction_data, seen_content_hashes)
).process
if result.nil?
@@ -68,4 +73,17 @@ class LunchflowAccount::Transactions::Processor
result
end
+
+ private
+
+ # How many earlier rows without an ID share this row's content hash.
+ def occurrence_of(transaction_data, seen_content_hashes)
+ data = transaction_data.with_indifferent_access
+ return 0 if data[:id].present?
+
+ content_hash = content_hash_for_transaction(data)
+ occurrence = seen_content_hashes[content_hash]
+ seen_content_hashes[content_hash] += 1
+ occurrence
+ end
end
diff --git a/app/models/lunchflow_entry/processor.rb b/app/models/lunchflow_entry/processor.rb
index cb1165dca9..b53fc1657a 100644
--- a/app/models/lunchflow_entry/processor.rb
+++ b/app/models/lunchflow_entry/processor.rb
@@ -26,9 +26,10 @@ class LunchflowEntry::Processor
# lunchflow_transaction is the raw hash fetched from Lunchflow API and converted to JSONB
# Transaction structure: { id, accountId, amount, currency, date, merchant, description, isPending }
- def initialize(lunchflow_transaction, lunchflow_account:)
+ def initialize(lunchflow_transaction, lunchflow_account:, occurrence: 0)
@lunchflow_transaction = lunchflow_transaction
@lunchflow_account = lunchflow_account
+ @occurrence = occurrence
end
def process
@@ -86,7 +87,7 @@ class LunchflowEntry::Processor
end
private
- attr_reader :lunchflow_transaction, :lunchflow_account
+ attr_reader :lunchflow_transaction, :lunchflow_account, :occurrence
def import_adapter
@import_adapter ||= Account::ProviderImportAdapter.new(account)
@@ -106,54 +107,12 @@ class LunchflowEntry::Processor
def calculate_external_id
id = data[:id].presence
+ return "lunchflow_#{id}" if id
- # For pending transactions, Lunchflow may return blank/nil IDs
- # Generate a stable temporary ID based on transaction attributes
- if id.blank?
- # Create a deterministic hash from key transaction attributes
- # This ensures the same pending transaction gets the same ID across syncs
- base_temp_id = content_hash_for_transaction(data)
- temp_id_with_prefix = "lunchflow_pending_#{base_temp_id}"
-
- # Check if entry with this external_id already exists
- # If it does AND it's still pending, reuse the same ID for re-sync.
- # The import adapter's skip logic will handle user edits correctly.
- # We DON'T check if attributes match - user edits should not cause duplicates.
- if entry_exists_with_external_id?(temp_id_with_prefix)
- existing_entry = account.entries.find_by(external_id: temp_id_with_prefix, source: "lunchflow")
- if existing_entry && existing_entry.entryable.is_a?(Transaction) && existing_entry.entryable.pending?
- Rails.logger.debug "Lunchflow: Reusing ID #{temp_id_with_prefix} for re-synced pending transaction"
- return temp_id_with_prefix
- end
- end
-
- # Handle true collisions: multiple different transactions with same attributes
- # (e.g., two Uber rides on the same day for the same amount within the same sync)
- final_id = temp_id_with_prefix
- counter = 1
-
- while entry_exists_with_external_id?(final_id)
- final_id = "#{temp_id_with_prefix}_#{counter}"
- counter += 1
- end
-
- if counter > 1
- Rails.logger.debug "Lunchflow: Collision detected, using #{final_id} for pending transaction: #{data[:merchant]} #{data[:amount]} #{data[:currency]}"
- else
- Rails.logger.debug "Lunchflow: Generated temporary ID #{final_id} for pending transaction: #{data[:merchant]} #{data[:amount]} #{data[:currency]}"
- end
-
- final_id
- else
- "lunchflow_#{id}"
- end
- end
-
- def entry_exists_with_external_id?(external_id)
- return false unless account.present?
-
- # Check if an entry with this external_id already exists in the account
- account.entries.exists?(external_id: external_id, source: "lunchflow")
+ # Blank IDs are keyed by content hash. Identical rows are told apart by their
+ # position among them in the stored list: the first gets no suffix, the next _1.
+ temp_id = "lunchflow_pending_#{content_hash_for_transaction(data)}"
+ occurrence.positive? ? "#{temp_id}_#{occurrence}" : temp_id
end
def name
diff --git a/test/models/lunchflow_account/transactions/processor_test.rb b/test/models/lunchflow_account/transactions/processor_test.rb
new file mode 100644
index 0000000000..63622688f9
--- /dev/null
+++ b/test/models/lunchflow_account/transactions/processor_test.rb
@@ -0,0 +1,128 @@
+require "test_helper"
+
+class LunchflowAccount::Transactions::ProcessorTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:empty)
+ @lunchflow_item = LunchflowItem.create!(name: "Test Lunchflow Connection", api_key: "test_key", family: @family)
+ @lunchflow_account = LunchflowAccount.create!(
+ lunchflow_item: @lunchflow_item,
+ name: "Test Account",
+ currency: "EUR",
+ account_id: "lf_acc_123"
+ )
+ @account = Account.create!(
+ family: @family,
+ name: "Test Checking",
+ accountable: Depository.new(subtype: "checking"),
+ balance: 1000,
+ currency: "EUR"
+ )
+ AccountProvider.create!(account: @account, provider: @lunchflow_account)
+ @lunchflow_account.reload
+ end
+
+ test "keeps one entry for a posted transaction without an id across syncs" do
+ store [ coffee("isPending" => false) ]
+
+ 3.times { process }
+
+ assert_equal 1, lunchflow_entries.count
+ assert_match(/\Alunchflow_pending_[a-f0-9]{32}\z/, lunchflow_entries.first.external_id)
+ end
+
+ test "keeps one entry when the isPending field is absent" do
+ store [ coffee ]
+
+ 3.times { process }
+
+ assert_equal 1, lunchflow_entries.count
+ end
+
+ test "keeps identical purchases without an id apart, and stable across syncs" do
+ store [ coffee("isPending" => false), coffee("isPending" => false) ]
+
+ process
+ first_ids = lunchflow_entries.pluck(:external_id).sort
+ 2.times { process }
+
+ assert_equal 2, first_ids.size
+ assert_equal first_ids, lunchflow_entries.pluck(:external_id).sort
+ assert_equal [ first_ids.first, "#{first_ids.first}_1" ], first_ids
+ end
+
+ test "keeps identical pending purchases without an id apart" do
+ store [ coffee("isPending" => true), coffee("isPending" => true) ]
+
+ 2.times { process }
+
+ assert_equal 2, lunchflow_entries.count
+ assert lunchflow_entries.all? { |entry| entry.entryable.pending? }
+ end
+
+ test "settles a pending transaction without an id once and keeps it settled" do
+ store [ coffee("isPending" => true) ]
+ process
+ pending_entry = lunchflow_entries.sole
+ assert pending_entry.entryable.pending?
+
+ # The importer replaces the stored row when it settles; the content hash ignores isPending.
+ store [ coffee("isPending" => false) ]
+ 2.times { process }
+
+ settled_entry = lunchflow_entries.sole
+ assert_equal pending_entry.id, settled_entry.id
+ assert_not settled_entry.entryable.reload.pending?
+ end
+
+ test "adds only the new purchase when an identical one shows up in a later sync" do
+ store [ coffee("isPending" => false) ]
+ process
+ original = lunchflow_entries.sole
+
+ store [ coffee("isPending" => false), coffee("isPending" => false) ]
+ 2.times { process }
+
+ assert_equal 2, lunchflow_entries.count
+ assert_equal [ original.external_id, "#{original.external_id}_1" ], lunchflow_entries.pluck(:external_id).sort
+ end
+
+ test "transactions with an id are unaffected by identical transactions without one" do
+ store [
+ coffee("id" => "tx_1", "isPending" => false),
+ coffee("isPending" => false),
+ coffee("id" => "tx_2", "isPending" => false)
+ ]
+
+ 2.times { process }
+
+ assert_equal 3, lunchflow_entries.count
+ assert_includes lunchflow_entries.pluck(:external_id), "lunchflow_tx_1"
+ assert_includes lunchflow_entries.pluck(:external_id), "lunchflow_tx_2"
+ end
+
+ private
+
+ def coffee(overrides = {})
+ {
+ "id" => "",
+ "accountId" => @lunchflow_account.account_id,
+ "amount" => -4.20,
+ "currency" => "EUR",
+ "date" => "2026-10-19",
+ "merchant" => "Cafe Central",
+ "description" => "Latte"
+ }.merge(overrides)
+ end
+
+ def store(transactions)
+ @lunchflow_account.upsert_lunchflow_transactions_snapshot!(transactions)
+ end
+
+ def process
+ LunchflowAccount::Transactions::Processor.new(@lunchflow_account.reload).process
+ end
+
+ def lunchflow_entries
+ @account.entries.where(source: "lunchflow")
+ end
+end