Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix Lunch Flow sync downloading full transaction history (#4565)

N1KHL68e9462385f0
diff --git a/app/models/lunchflow_item/importer.rb b/app/models/lunchflow_item/importer.rb
index 5374357524..2efa0dcd51 100644
--- a/app/models/lunchflow_item/importer.rb
+++ b/app/models/lunchflow_item/importer.rb
@@ -255,9 +255,10 @@ class LunchflowItem::Importer
def fetch_and_store_transactions(lunchflow_account)
start_date = determine_sync_start_date(lunchflow_account)
+ fetch_started_at = Time.current
include_pending = Rails.configuration.x.lunchflow.include_pending
- Rails.logger.info "LunchflowItem::Importer - Fetching transactions for account #{lunchflow_account.account_id} from #{start_date} (include_pending=#{include_pending})"
+ Rails.logger.info "LunchflowItem::Importer - Fetching transactions for account #{lunchflow_account.account_id} from #{start_date || "the beginning"} (include_pending=#{include_pending})"
begin
# Fetch transactions
@@ -273,7 +274,7 @@ class LunchflowItem::Importer
end
# Validate response structure
- unless transactions_data.is_a?(Hash)
+ unless transactions_data.is_a?(Hash) && transactions_data[:transactions].is_a?(Array)
Rails.logger.error "LunchflowItem::Importer - Invalid transactions_data format for account #{lunchflow_account.account_id}"
return { success: false, transactions_count: 0, error: "Invalid response format" }
end
@@ -389,6 +390,8 @@ class LunchflowItem::Importer
Rails.logger.warn "LunchflowItem::Importer - Failed to fetch holdings for account #{lunchflow_account.account_id}: #{e.message}"
end
+ lunchflow_account.update!(transactions_synced_through: fetch_started_at)
+
{ success: true, transactions_count: transactions_count }
rescue Provider::Lunchflow::LunchflowError => e
Rails.logger.error "LunchflowItem::Importer - Lunchflow API error for account #{lunchflow_account.id}: #{e.message}"
@@ -498,30 +501,14 @@ class LunchflowItem::Importer
end
end
+ # Returns nil until the account has a successful fetch on record, which
+ # fetches its full history. Later syncs resume from that fetch, so one that
+ # keeps failing doesn't leave a gap once the item sync completes.
def determine_sync_start_date(lunchflow_account)
- # Check if this account has any stored transactions
- # If not, treat it as a first sync for this account even if the item has been synced before
- has_stored_transactions = lunchflow_account.raw_transactions_payload.to_a.any?
-
- if has_stored_transactions
- # Account has been synced before, use item-level logic with buffer
- # For subsequent syncs, fetch from last sync date with a buffer
- if lunchflow_item.last_synced_at
- lunchflow_item.last_synced_at - 7.days
- else
- # Fallback if item hasn't been synced but account has transactions
- 90.days.ago
- end
- else
- # Account has no stored transactions - this is a first sync for this account
- # Use account creation date or a generous historical window
- account_baseline = lunchflow_account.created_at || Time.current
- first_sync_window = [ account_baseline - 7.days, 90.days.ago ].max
-
- # Use the more recent of: (account created - 7 days) or (90 days ago)
- # This caps old accounts at 90 days while respecting recent account creation dates
- first_sync_window
- end
+ synced_through = lunchflow_account.transactions_synced_through
+ return if lunchflow_account.raw_transactions_payload.to_a.empty? || synced_through.nil?
+
+ synced_through - 7.days
end
def handle_error(error_message)
diff --git a/app/models/provider/lunchflow.rb b/app/models/provider/lunchflow.rb
index 1c4d2a973c..0eff2eeca8 100644
--- a/app/models/provider/lunchflow.rb
+++ b/app/models/provider/lunchflow.rb
@@ -32,11 +32,11 @@ class Provider::Lunchflow
query_params = {}
if start_date
- query_params[:start_date] = start_date.to_date.to_s
+ query_params[:from] = start_date.to_date.to_s
end
if end_date
- query_params[:end_date] = end_date.to_date.to_s
+ query_params[:to] = end_date.to_date.to_s
end
if include_pending
diff --git a/db/migrate/20261028200000_add_transactions_synced_through_to_lunchflow_accounts.rb b/db/migrate/20261028200000_add_transactions_synced_through_to_lunchflow_accounts.rb
new file mode 100644
index 0000000000..ee424d4374
--- /dev/null
+++ b/db/migrate/20261028200000_add_transactions_synced_through_to_lunchflow_accounts.rb
@@ -0,0 +1,5 @@
+class AddTransactionsSyncedThroughToLunchflowAccounts < ActiveRecord::Migration[8.1]
+ def change
+ add_column :lunchflow_accounts, :transactions_synced_through, :datetime
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index ef3d06a738..1a76581701 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_10_20_090001) do
+ActiveRecord::Schema[8.1].define(version: 2026_10_28_200000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -1625,6 +1625,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_20_090001) do
t.jsonb "raw_holdings_payload"
t.jsonb "raw_payload"
t.jsonb "raw_transactions_payload"
+ t.datetime "transactions_synced_through"
t.boolean "treat_balance_as_available_credit", default: false, null: false
t.datetime "updated_at", null: false
t.index ["account_id"], name: "index_lunchflow_accounts_on_account_id"
diff --git a/test/models/lunchflow_item/importer_start_date_test.rb b/test/models/lunchflow_item/importer_start_date_test.rb
new file mode 100644
index 0000000000..cf217823cc
--- /dev/null
+++ b/test/models/lunchflow_item/importer_start_date_test.rb
@@ -0,0 +1,93 @@
+require "test_helper"
+
+class LunchflowItem::ImporterStartDateTest < ActiveSupport::TestCase
+ setup do
+ @item = LunchflowItem.create!(
+ family: families(:dylan_family),
+ name: "Test Lunchflow",
+ api_key: "test_key_123"
+ )
+ @lunchflow_account = @item.lunchflow_accounts.create!(
+ account_id: "acct-1",
+ name: "Test Account",
+ currency: "EUR"
+ )
+ @provider = mock()
+ end
+
+ test "first sync fetches the full history" do
+ expect_fetch_from(nil)
+
+ import_transactions
+ end
+
+ test "later syncs resume a week before the account's last successful fetch" do
+ synced_through = Time.zone.parse("2026-10-10 06:00")
+ store_previous_transaction
+ @lunchflow_account.update!(transactions_synced_through: synced_through)
+ @item.stubs(:last_synced_at).returns(Time.zone.parse("2026-10-20 06:00"))
+ expect_fetch_from(synced_through - 7.days)
+
+ import_transactions
+ end
+
+ test "accounts without a fetch marker refetch the full history" do
+ store_previous_transaction
+ @item.stubs(:last_synced_at).returns(Time.zone.parse("2026-10-20 06:00"))
+ expect_fetch_from(nil)
+
+ import_transactions
+ end
+
+ test "a successful fetch records when it ran" do
+ expect_fetch_from(nil)
+
+ travel_to Time.zone.parse("2026-10-28 06:00") do
+ import_transactions
+ end
+
+ assert_equal Time.zone.parse("2026-10-28 06:00"), @lunchflow_account.reload.transactions_synced_through
+ end
+
+ test "a failed fetch keeps the previous marker" do
+ synced_through = Time.zone.parse("2026-10-10 06:00")
+ @lunchflow_account.update!(transactions_synced_through: synced_through)
+ @provider.expects(:get_account_transactions)
+ .raises(Provider::Lunchflow::LunchflowError.new("Rate limited", :rate_limited))
+
+ result = import_transactions
+
+ assert_not result[:success]
+ assert_equal synced_through, @lunchflow_account.reload.transactions_synced_through
+ end
+
+ test "a response without a transaction list keeps the previous marker" do
+ synced_through = Time.zone.parse("2026-10-10 06:00")
+ @lunchflow_account.update!(transactions_synced_through: synced_through)
+ @provider.expects(:get_account_transactions).returns({})
+
+ result = import_transactions
+
+ assert_not result[:success]
+ assert_equal synced_through, @lunchflow_account.reload.transactions_synced_through
+ end
+
+ private
+
+ def expect_fetch_from(start_date)
+ @provider.expects(:get_account_transactions)
+ .with("acct-1", has_entries(start_date: start_date))
+ .returns({ transactions: [] })
+ end
+
+ def import_transactions
+ LunchflowItem::Importer.new(@item, lunchflow_provider: @provider)
+ .send(:fetch_and_store_transactions, @lunchflow_account)
+ end
+
+ def store_previous_transaction
+ @lunchflow_account.upsert_lunchflow_transactions_snapshot!([
+ { "id" => "tx-1", "amount" => -10, "currency" => "EUR", "date" => "2026-10-19", "merchant" => "Rewe" }
+ ])
+ end
+end
diff --git a/test/models/provider/lunchflow_test.rb b/test/models/provider/lunchflow_test.rb
index a1edb76a88..972fd3b18d 100644
--- a/test/models/provider/lunchflow_test.rb
+++ b/test/models/provider/lunchflow_test.rb
@@ -5,6 +5,28 @@ class Provider::LunchflowTest < ActiveSupport::TestCase
@provider = Provider::Lunchflow.new("test_key", base_url: "https://www.lunchflow.app/api/v1")
end
+ test "sends the date window as from/to query params" do
+ success = response(200, { transactions: [] }.to_json, "OK")
+
+ Provider::Lunchflow.expects(:get).with(
+ "https://www.lunchflow.app/api/v1/accounts/acct-1/transactions?from=2026-07-30&to=2026-08-31",
+ anything
+ ).returns(success)
+
+ @provider.get_account_transactions("acct-1", start_date: Date.new(2026, 7, 30), end_date: Date.new(2026, 8, 31))
+ end
+
+ test "omits the date filter when no start date is given" do
+ success = response(200, { transactions: [] }.to_json, "OK")
+
+ Provider::Lunchflow.expects(:get).with(
+ "https://www.lunchflow.app/api/v1/accounts/acct-1/transactions",
+ anything
+ ).returns(success)
+
+ @provider.get_account_transactions("acct-1")
+ end
+
test "retries a wrapped GoCardless rate limit and preserves its type" do
rate_limited = response(
503,