The personal finance app for everyone (by everyone)
Ruby
Implement start date for Lunch Flow syncs and history management (#4619)
N1KHL5e8060bbb1e3
diff --git a/app/models/lunchflow_item.rb b/app/models/lunchflow_item.rbindex f34eeb4635..373767814f 100644--- a/app/models/lunchflow_item.rb+++ b/app/models/lunchflow_item.rb@@ -14,6 +14,7 @@ class LunchflowItem < ApplicationRecordvalidates :name, presence: truevalidates :api_key, presence: true, on: :create+ validate :sync_start_date_must_be_validbelongs_to :familyhas_one_attached :logo, dependent: :purge_later@@ -169,4 +170,15 @@ class LunchflowItem < ApplicationRecordrescue URI::InvalidURIErrorDEFAULT_BASE_URLend++ private++ def sync_start_date_must_be_valid+ if sync_start_date.nil?+ # A value that isn't a date casts to nil; reject it instead of clearing the saved date.+ errors.add(:sync_start_date, :invalid) if sync_start_date_before_type_cast.present?+ elsif sync_start_date.to_date > Date.current+ errors.add(:sync_start_date, :invalid)+ end+ endenddiff --git a/app/models/lunchflow_item/importer.rb b/app/models/lunchflow_item/importer.rbindex 2efa0dcd51..88e64c5206 100644--- a/app/models/lunchflow_item/importer.rb+++ b/app/models/lunchflow_item/importer.rb@@ -254,6 +254,7 @@ class LunchflowItem::Importerenddef fetch_and_store_transactions(lunchflow_account)+ fetches_history = history_needed?(lunchflow_account)start_date = determine_sync_start_date(lunchflow_account)fetch_started_at = Time.currentinclude_pending = Rails.configuration.x.lunchflow.include_pending@@ -390,7 +391,9 @@ class LunchflowItem::ImporterRails.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)+ sync_markers = { transactions_synced_through: fetch_started_at }+ sync_markers[:history_synced_from] = start_date if fetches_history+ lunchflow_account.update!(sync_markers){ success: true, transactions_count: transactions_count }rescue Provider::Lunchflow::LunchflowError => e@@ -501,14 +504,33 @@ class LunchflowItem::Importerendend- # 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.+ # Starts from the chosen start date (nil fetches the full history) when the+ # account needs history it doesn't have yet. Otherwise resumes from the last+ # successful fetch, so one that keeps failing doesn't leave a gap once the+ # item sync completes, but never goes back before the chosen start date.def determine_sync_start_date(lunchflow_account)- synced_through = lunchflow_account.transactions_synced_through- return if lunchflow_account.raw_transactions_payload.to_a.empty? || synced_through.nil?+ chosen_start = chosen_start_date+ return chosen_start if history_needed?(lunchflow_account)- synced_through - 7.days+ [ (lunchflow_account.transactions_synced_through - 7.days).to_date, chosen_start ].compact.max+ end++ # The chosen start date as a day on the family's calendar. The panel saves it+ # in the family's timezone, but syncs run in the app's zone.+ def chosen_start_date+ start = lunchflow_item.sync_start_date+ start && lunchflow_item.family.local_date(start)+ end++ # True until the account has a successful fetch on record, and again when the+ # chosen start date moves before the history already fetched or is cleared.+ # A blank history_synced_from means the account already has everything.+ def history_needed?(lunchflow_account)+ return true if lunchflow_account.raw_transactions_payload.to_a.empty? || lunchflow_account.transactions_synced_through.nil?++ synced_from = lunchflow_account.history_synced_from+ chosen_start = chosen_start_date+ synced_from.present? && (chosen_start.nil? || chosen_start < synced_from.to_date)enddef handle_error(error_message)diff --git a/app/views/settings/providers/_lunchflow_panel.html.erb b/app/views/settings/providers/_lunchflow_panel.html.erbindex 0df02f4b9a..306a2c16a0 100644--- a/app/views/settings/providers/_lunchflow_panel.html.erb+++ b/app/views/settings/providers/_lunchflow_panel.html.erb@@ -36,6 +36,12 @@placeholder: t("settings.providers.lunchflow_panel.base_url_placeholder"),value: lunchflow_item.base_url %>+ <%= form.date_field :sync_start_date,+ label: t("settings.providers.lunchflow_panel.sync_start_date_label"),+ value: lunchflow_item.sync_start_date&.to_date,+ max: Date.current,+ help_text: t("settings.providers.lunchflow_panel.sync_start_date_help") %>+<div class="flex justify-end"><%= form.submit is_new_record ? t("settings.providers.lunchflow_panel.save_and_connect") : t("settings.providers.lunchflow_panel.update_connection") %></div>diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex e8b722fab4..d1cf7cfb7e 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -647,6 +647,8 @@ en:api_key_placeholder_update: "Enter new API key to update"base_url_label: "Base URL (Optional)"base_url_placeholder: "https://lunchflow.app/api/v1 (default)"+ sync_start_date_label: "Import transactions from"+ sync_start_date_help: "Leave blank to import everything Lunch Flow has. Moving the date earlier imports the missing period on the next sync. Moving it later doesn't affect transactions already imported."save_and_connect: "Save and connect"update_connection: "Update connection"akahu_panel:diff --git a/db/migrate/20261030200000_add_history_synced_from_to_lunchflow_accounts.rb b/db/migrate/20261030200000_add_history_synced_from_to_lunchflow_accounts.rbnew file mode 100644index 0000000000..2dd499802b--- /dev/null+++ b/db/migrate/20261030200000_add_history_synced_from_to_lunchflow_accounts.rb@@ -0,0 +1,5 @@+class AddHistorySyncedFromToLunchflowAccounts < ActiveRecord::Migration[8.1]+ def change+ add_column :lunchflow_accounts, :history_synced_from, :datetime+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 1a76581701..d6553e696b 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_28_200000) do+ActiveRecord::Schema[8.1].define(version: 2026_10_30_200000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -1617,6 +1617,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_28_200000) dot.datetime "created_at", null: falset.string "currency"t.decimal "current_balance", precision: 19, scale: 4+ t.datetime "history_synced_from"t.boolean "holdings_supported", default: true, null: falset.jsonb "institution_metadata"t.uuid "lunchflow_item_id", null: falsediff --git a/test/controllers/lunchflow_items_controller_test.rb b/test/controllers/lunchflow_items_controller_test.rbindex 0b19db8370..0f64e40597 100644--- a/test/controllers/lunchflow_items_controller_test.rb+++ b/test/controllers/lunchflow_items_controller_test.rb@@ -15,6 +15,27 @@ class LunchflowItemsControllerTest < ActionDispatch::IntegrationTestassert_equal "Renamed Lunch Flow", lunchflow_items(:one).reload.nameend+ test "update from the page saves the import start date" do+ patch lunchflow_item_url(lunchflow_items(:one)),+ params: { lunchflow_item: { sync_start_date: "2026-01-15" } },+ as: :turbo_stream++ assert_turbo_stream action: "replace", target: "lunchflow-providers-panel"+ assert_includes response.body, %(value="2026-01-15")+ assert_equal Date.new(2026, 1, 15), lunchflow_items(:one).reload.sync_start_date.to_date+ end++ test "update from the page clears the import start date" do+ lunchflow_items(:one).update!(sync_start_date: Date.new(2026, 1, 15))++ patch lunchflow_item_url(lunchflow_items(:one)),+ params: { lunchflow_item: { sync_start_date: "" } },+ as: :turbo_stream++ assert_turbo_stream action: "replace", target: "lunchflow-providers-panel"+ assert_nil lunchflow_items(:one).reload.sync_start_date+ end+test "invalid create from the page shows the error in the panel" dopost lunchflow_items_url,params: { lunchflow_item: { name: "Second Lunch Flow", api_key: "" } },diff --git a/test/models/lunchflow_item/importer_start_date_test.rb b/test/models/lunchflow_item/importer_start_date_test.rbindex cf217823cc..df903a9b58 100644--- a/test/models/lunchflow_item/importer_start_date_test.rb+++ b/test/models/lunchflow_item/importer_start_date_test.rb@@ -26,7 +26,7 @@ class LunchflowItem::ImporterStartDateTest < ActiveSupport::TestCasestore_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)+ expect_fetch_from((synced_through - 7.days).to_date)import_transactionsend@@ -39,6 +39,114 @@ class LunchflowItem::ImporterStartDateTest < ActiveSupport::TestCaseimport_transactionsend+ test "first sync starts at the chosen start date" do+ @item.update!(sync_start_date: Date.new(2026, 1, 15))+ expect_fetch_from(Date.new(2026, 1, 15))++ import_transactions+ end++ test "the chosen start date is the day picked in the family's timezone" do+ @item.family.update!(timezone: "Europe/Berlin")+ Time.use_zone("Europe/Berlin") { @item.update!(sync_start_date: "2026-01-15") }+ expect_fetch_from(Date.new(2026, 1, 15))++ import_transactions+ end++ test "later syncs never go back before the chosen start date" do+ @item.update!(sync_start_date: Date.new(2026, 10, 8))+ store_previous_transaction+ @lunchflow_account.update!(transactions_synced_through: Time.zone.parse("2026-10-10 06:00"))+ expect_fetch_from(Date.new(2026, 10, 8))++ import_transactions+ end++ test "later syncs resume from the last fetch when the chosen start date is older" do+ synced_through = Time.zone.parse("2026-10-10 06:00")+ @item.update!(sync_start_date: Date.new(2026, 1, 15))+ store_previous_transaction+ @lunchflow_account.update!(transactions_synced_through: synced_through)+ expect_fetch_from((synced_through - 7.days).to_date)++ import_transactions+ end++ test "a first fetch records how far back it reached" do+ @item.update!(sync_start_date: Date.new(2026, 1, 15))+ expect_fetch_from(Date.new(2026, 1, 15))++ import_transactions++ assert_equal Time.zone.parse("2026-01-15"), @lunchflow_account.reload.history_synced_from+ end++ test "moving the start date earlier fetches from the new date" do+ @item.update!(sync_start_date: Date.new(2026, 1, 1))+ mark_previously_synced(history_from: Time.zone.parse("2026-03-01"))+ expect_fetch_from(Date.new(2026, 1, 1))++ import_transactions++ assert_equal Time.zone.parse("2026-01-01"), @lunchflow_account.reload.history_synced_from+ end++ test "clearing the start date fetches the full history" do+ mark_previously_synced(history_from: Time.zone.parse("2026-03-01"))+ expect_fetch_from(nil)++ import_transactions++ assert_nil @lunchflow_account.reload.history_synced_from+ end++ test "a full history fetch marks the account as having everything" do+ @lunchflow_account.update!(history_synced_from: Time.zone.parse("2026-03-01"))+ expect_fetch_from(nil)++ import_transactions++ assert_nil @lunchflow_account.reload.history_synced_from+ end++ test "keeping the same start date doesn't refetch history" do+ @item.update!(sync_start_date: Date.new(2026, 3, 1))+ mark_previously_synced(history_from: Time.zone.parse("2026-03-01"))+ expect_fetch_from(Date.new(2026, 10, 3))++ import_transactions+ end++ test "moving the start date later keeps the history already fetched" do+ @item.update!(sync_start_date: Date.new(2026, 3, 1))+ mark_previously_synced(history_from: Time.zone.parse("2026-01-01"))+ expect_fetch_from(Date.new(2026, 10, 3))++ import_transactions++ assert_equal Time.zone.parse("2026-01-01"), @lunchflow_account.reload.history_synced_from+ end++ test "accounts with the full history don't refetch it when a start date is chosen" do+ @item.update!(sync_start_date: Date.new(2026, 1, 1))+ mark_previously_synced(history_from: nil)+ expect_fetch_from(Date.new(2026, 10, 3))++ import_transactions+ end++ test "a failed history fetch keeps the previous history marker" do+ @item.update!(sync_start_date: Date.new(2026, 1, 1))+ mark_previously_synced(history_from: Time.zone.parse("2026-03-01"))+ @provider.expects(:get_account_transactions)+ .raises(Provider::Lunchflow::LunchflowError.new("Rate limited", :rate_limited))++ import_transactions++ assert_equal Time.zone.parse("2026-03-01"), @lunchflow_account.reload.history_synced_from+ end+test "a successful fetch records when it ran" doexpect_fetch_from(nil)@@ -90,4 +198,13 @@ class LunchflowItem::ImporterStartDateTest < ActiveSupport::TestCase{ "id" => "tx-1", "amount" => -10, "currency" => "EUR", "date" => "2026-10-19", "merchant" => "Rewe" }])end++ # An account whose last successful fetch ran on 2026-10-10 06:00.+ def mark_previously_synced(history_from:)+ store_previous_transaction+ @lunchflow_account.update!(+ transactions_synced_through: Time.zone.parse("2026-10-10 06:00"),+ history_synced_from: history_from+ )+ endenddiff --git a/test/models/lunchflow_item_test.rb b/test/models/lunchflow_item_test.rbindex b2a9adf540..7df7ad8daf 100644--- a/test/models/lunchflow_item_test.rb+++ b/test/models/lunchflow_item_test.rb@@ -45,6 +45,31 @@ class LunchflowItemTest < ActiveSupport::TestCaseassert_sync_status(:en, total: 3, linked: 1, unlinked: 2, expected: "1 synced, 2 need setup")end+ test "rejects a sync start date in the future" do+ @lunchflow_item.sync_start_date = Date.current + 1.day++ assert_not @lunchflow_item.valid?+ assert @lunchflow_item.errors.added?(:sync_start_date, :invalid)+ end++ test "rejects a sync start date that isn't a date" do+ @lunchflow_item.sync_start_date = "not-a-date"++ assert_not @lunchflow_item.valid?+ assert @lunchflow_item.errors.added?(:sync_start_date, :invalid)+ end++ test "accepts today or a blank sync start date" do+ @lunchflow_item.sync_start_date = Date.current+ assert @lunchflow_item.valid?++ @lunchflow_item.sync_start_date = nil+ assert @lunchflow_item.valid?++ @lunchflow_item.sync_start_date = ""+ assert @lunchflow_item.valid?+ end+privatedef assert_sync_status(locale, total:, linked:, unlinked:, expected:)@lunchflow_item.stubs(:total_accounts_count).returns(total)