From bcb47a9d29a838ff936fccd12f2a1784422075a1 Mon Sep 17 00:00:00 2001 From: Zach Gollwitzer Date: Tue, 13 May 2025 16:14:29 -0400 Subject: [PATCH] Fix auto sync trigger logic and add tests --- app/controllers/concerns/auto_sync.rb | 8 ++-- app/models/concerns/syncable.rb | 4 ++ test/controllers/concerns/auto_sync_test.rb | 41 +++++++++++++++++++++ 3 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 test/controllers/concerns/auto_sync_test.rb diff --git a/app/controllers/concerns/auto_sync.rb b/app/controllers/concerns/auto_sync.rb index 4e375359..e6ced672 100644 --- a/app/controllers/concerns/auto_sync.rb +++ b/app/controllers/concerns/auto_sync.rb @@ -11,9 +11,11 @@ module AutoSync end def family_needs_auto_sync? - return false unless Current.family.present? - return false unless Current.family.accounts.active.any? + return false unless Current.family&.accounts&.active&.any? + return false if (Current.family.last_sync_created_at&.to_date || 1.day.ago) >= Date.current - (Current.family.last_synced_at&.to_date || 1.day.ago) < Date.current + Rails.logger.info "Auto-syncing family #{Current.family.id}, last sync was #{Current.family.last_sync_created_at}" + + true end end diff --git a/app/models/concerns/syncable.rb b/app/models/concerns/syncable.rb index d804b992..ce3c30fd 100644 --- a/app/models/concerns/syncable.rb +++ b/app/models/concerns/syncable.rb @@ -34,6 +34,10 @@ module Syncable latest_sync&.last_ran_at end + def last_sync_created_at + latest_sync&.created_at + end + private def latest_sync syncs.order(created_at: :desc).first diff --git a/test/controllers/concerns/auto_sync_test.rb b/test/controllers/concerns/auto_sync_test.rb new file mode 100644 index 00000000..a388456b --- /dev/null +++ b/test/controllers/concerns/auto_sync_test.rb @@ -0,0 +1,41 @@ +require "test_helper" + +class AutoSyncTest < ActionDispatch::IntegrationTest + setup do + sign_in @user = users(:family_admin) + @family = @user.family + + # Start fresh + Sync.destroy_all + end + + test "auto-syncs family if hasn't synced" do + assert_difference "Sync.count", 1 do + get root_path + end + end + + test "auto-syncs family if hasn't synced in last 24 hours" do + # If request comes in at beginning of day, but last sync was 1 hour ago ("yesterday"), we still sync + travel_to Time.current.beginning_of_day + last_sync_datetime = 1.hour.ago + + Sync.create!(syncable: @family, created_at: last_sync_datetime) + + assert_difference "Sync.count", 1 do + get root_path + end + end + + test "does not auto-sync if family has synced today already" do + travel_to Time.current.end_of_day + + last_created_sync_at = 23.hours.ago + + Sync.create!(syncable: @family, created_at: last_created_sync_at) + + assert_no_difference "Sync.count" do + get root_path + end + end +end