diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb index e3bf49850..dd4024d7b 100644 --- a/app/controllers/settings/hostings_controller.rb +++ b/app/controllers/settings/hostings_controller.rb @@ -62,14 +62,27 @@ class Settings::HostingsController < ApplicationController Setting.syncs_include_pending = hosting_params[:syncs_include_pending] == "1" end + sync_settings_changed = false + if hosting_params.key?(:auto_sync_enabled) Setting.auto_sync_enabled = hosting_params[:auto_sync_enabled] == "1" - AutoSyncScheduler.sync! + sync_settings_changed = true end if hosting_params.key?(:auto_sync_time) - Setting.auto_sync_time = hosting_params[:auto_sync_time] - AutoSyncScheduler.sync! + time_value = hosting_params[:auto_sync_time] + unless Setting.valid_auto_sync_time?(time_value) + flash[:alert] = t(".invalid_sync_time") + return redirect_to settings_hosting_path + end + + Setting.auto_sync_time = time_value + Setting.auto_sync_timezone = current_user_timezone + sync_settings_changed = true + end + + if sync_settings_changed + sync_auto_sync_scheduler! end if hosting_params.key?(:openai_access_token) @@ -119,4 +132,16 @@ class Settings::HostingsController < ApplicationController def ensure_admin redirect_to settings_hosting_path, alert: t(".not_authorized") unless Current.user.admin? end + + def sync_auto_sync_scheduler! + AutoSyncScheduler.sync! + rescue StandardError => error + Rails.logger.error("[AutoSyncScheduler] Failed to sync scheduler: #{error.message}") + Rails.logger.error(error.backtrace.join("\n")) + flash[:alert] = t(".scheduler_sync_failed") + end + + def current_user_timezone + Current.family&.timezone.presence || "UTC" + end end diff --git a/app/models/setting.rb b/app/models/setting.rb index c28c611f3..4407d7293 100644 --- a/app/models/setting.rb +++ b/app/models/setting.rb @@ -26,6 +26,19 @@ class Setting < RailsSettings::Base field :syncs_include_pending, type: :boolean, default: SYNCS_INCLUDE_PENDING_DEFAULT field :auto_sync_enabled, type: :boolean, default: ENV.fetch("AUTO_SYNC_ENABLED", "1") == "1" field :auto_sync_time, type: :string, default: ENV.fetch("AUTO_SYNC_TIME", "02:22") + field :auto_sync_timezone, type: :string, default: ENV.fetch("AUTO_SYNC_TIMEZONE", "UTC") + + AUTO_SYNC_TIME_FORMAT = /\A([01]?\d|2[0-3]):([0-5]\d)\z/ + + def self.valid_auto_sync_time?(time_str) + return false if time_str.blank? + AUTO_SYNC_TIME_FORMAT.match?(time_str.to_s.strip) + end + + def self.valid_auto_sync_timezone?(timezone_str) + return false if timezone_str.blank? + ActiveSupport::TimeZone[timezone_str].present? + end # Dynamic fields are now stored as individual entries with "dynamic:" prefix # This prevents race conditions and ensures each field is independently managed diff --git a/app/services/auto_sync_scheduler.rb b/app/services/auto_sync_scheduler.rb index a6bbbdd74..44adea3b0 100644 --- a/app/services/auto_sync_scheduler.rb +++ b/app/services/auto_sync_scheduler.rb @@ -12,20 +12,36 @@ class AutoSyncScheduler def self.upsert_job time_str = Setting.auto_sync_time || "02:22" - hour, minute = time_str.split(":").map(&:to_i) + timezone_str = Setting.auto_sync_timezone || "UTC" - local_time = Time.zone.now.change(hour: hour, min: minute, sec: 0) + unless Setting.valid_auto_sync_time?(time_str) + Rails.logger.error("[AutoSyncScheduler] Invalid time format: #{time_str}, using default 02:22") + time_str = "02:22" + end + + hour, minute = time_str.split(":").map(&:to_i) + timezone = ActiveSupport::TimeZone[timezone_str] || ActiveSupport::TimeZone["UTC"] + local_time = timezone.now.change(hour: hour, min: minute, sec: 0) utc_time = local_time.utc cron = "#{utc_time.min} #{utc_time.hour} * * *" - Sidekiq::Cron::Job.create( + job = Sidekiq::Cron::Job.create( name: JOB_NAME, cron: cron, class: "SyncAllJob", queue: "scheduled", description: "Syncs all accounts for all families" ) + + if job.nil? || (job.respond_to?(:valid?) && !job.valid?) + error_msg = job.respond_to?(:errors) ? job.errors.to_a.join(", ") : "unknown error" + Rails.logger.error("[AutoSyncScheduler] Failed to create cron job: #{error_msg}") + raise StandardError, "Failed to create sync schedule: #{error_msg}" + end + + Rails.logger.info("[AutoSyncScheduler] Created cron job with schedule: #{cron} (#{time_str} #{timezone_str})") + job end def self.remove_job diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml index aaa7246d6..4742bc809 100644 --- a/config/locales/views/settings/hostings/en.yml +++ b/config/locales/views/settings/hostings/en.yml @@ -75,6 +75,8 @@ en: failure: Invalid setting value success: Settings updated invalid_onboarding_state: Invalid onboarding state + invalid_sync_time: Invalid sync time format. Please use HH:MM format (e.g., 02:30). + scheduler_sync_failed: Settings saved, but failed to update the sync schedule. Please try again or check the server logs. clear_cache: cache_cleared: Data cache has been cleared. This may take a few moments to complete. not_authorized: You are not authorized to perform this action