diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 84f8a8fe..b8d5a836 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,5 +1,5 @@ class ApplicationController < ActionController::Base - include Authentication, Invitable, SelfHostable + include AutoSync, Authentication, Invitable, SelfHostable include Pagy::Backend # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. diff --git a/app/controllers/concerns/auto_sync.rb b/app/controllers/concerns/auto_sync.rb new file mode 100644 index 00000000..122710a6 --- /dev/null +++ b/app/controllers/concerns/auto_sync.rb @@ -0,0 +1,13 @@ +module AutoSync + extend ActiveSupport::Concern + + included do + before_action :sync_family, if: -> { Current.family.present? && Current.family.needs_sync? } + end + + private + + def sync_family + Current.family.sync + end +end diff --git a/app/models/account/sync.rb b/app/models/account/sync.rb index 5db21b89..1442ec0b 100644 --- a/app/models/account/sync.rb +++ b/app/models/account/sync.rb @@ -78,5 +78,6 @@ class Account::Sync < ApplicationRecord partial: "shared/notification", locals: { type: type, message: message } ) + broadcast_refresh_to account end end diff --git a/app/models/account/syncable.rb b/app/models/account/syncable.rb index a0fe78cd..382d401f 100644 --- a/app/models/account/syncable.rb +++ b/app/models/account/syncable.rb @@ -11,6 +11,14 @@ module Account::Syncable syncs.syncing.any? end + def latest_sync_date + syncs.where.not(last_ran_at: nil).pluck(:last_ran_at).max&.to_date + end + + def needs_sync? + latest_sync_date.nil? || latest_sync_date < Date.current + end + def sync_later(start_date: nil) AccountSyncJob.perform_later(self, start_date: start_date) end diff --git a/app/models/demo/generator.rb b/app/models/demo/generator.rb index b897064b..2fb27157 100644 --- a/app/models/demo/generator.rb +++ b/app/models/demo/generator.rb @@ -34,10 +34,6 @@ class Demo::Generator create_car_and_loan! puts "accounts created" - - family.sync - - puts "balances synced" puts "Demo data loaded successfully!" end end diff --git a/app/models/family.rb b/app/models/family.rb index cdcf2e8b..2aaeaf14 100644 --- a/app/models/family.rb +++ b/app/models/family.rb @@ -105,6 +105,16 @@ class Family < ApplicationRecord end def sync(start_date: nil) - accounts.active.sync(start_date: start_date) + accounts.active.each do |account| + if account.needs_sync? + account.sync_later(start_date: start_date || account.last_sync_date) + end + end + + update! last_synced_at: Time.now + end + + def needs_sync? + last_synced_at.nil? || last_synced_at.to_date < Date.current end end diff --git a/app/views/accounts/show.html.erb b/app/views/accounts/show.html.erb index 2459a7eb..b67c5869 100644 --- a/app/views/accounts/show.html.erb +++ b/app/views/accounts/show.html.erb @@ -1,3 +1,5 @@ +<%= turbo_stream_from @account %> +