diff --git a/app/jobs/one_time/import_from_sailors_log_job.rb b/app/jobs/one_time/import_from_sailors_log_job.rb index 0701d59..7ad553e 100644 --- a/app/jobs/one_time/import_from_sailors_log_job.rb +++ b/app/jobs/one_time/import_from_sailors_log_job.rb @@ -11,11 +11,34 @@ class OneTime::ImportFromSailorsLogJob < ApplicationJob def perform # Import from SailorsLog + total_count = 0 + found_count = 0 + created_count = 0 + SailorsLog::SlackNotificationPreference.enabled.each do |preference| + puts "Importing preference for #{preference.slack_user_id} in #{preference.slack_channel_id}" + slnp = ::SailorsLogNotificationPreference.find_or_create_by( slack_uid: preference.slack_user_id, slack_channel_id: preference.slack_channel_id - ) + ) do |new_record| + # This block only runs on creation, not when found + created_count += 1 + end + + if slnp.persisted? + found_count += 1 + else + puts "Failed to create/find preference: #{slnp.errors.full_messages.join(', ')}" + end + + total_count += 1 end + + puts "Process complete:" + puts "Total processed: #{total_count}" + puts "Found existing: #{found_count}" + puts "Newly created: #{created_count}" + puts "Total in source: #{SailorsLog::SlackNotificationPreference.enabled.count}" end end diff --git a/app/models/sailors_log.rb b/app/models/sailors_log.rb index ca3e712..9a834e9 100644 --- a/app/models/sailors_log.rb +++ b/app/models/sailors_log.rb @@ -2,7 +2,7 @@ class SailorsLog < ApplicationRecord validates :slack_uid, presence: true, uniqueness: true validates :projects_summary, presence: true - before_create :initialize_projects_summary + before_validation :initialize_projects_summary has_many :notification_preferences, class_name: "SailorsLogNotificationPreference", @@ -18,8 +18,6 @@ class SailorsLog < ApplicationRecord def initialize_projects_summary return unless projects_summary.blank? - Heartbeat.where(user_id: slack_uid).distinct.pluck(:project).each do |project| - self.projects_summary[project] = Heartbeat.where(user_id: slack_uid, project: project).duration_seconds - end + self.projects_summary = Heartbeat.where(user_id: slack_uid).group(:project).duration_seconds end end diff --git a/app/models/sailors_log_notification_preference.rb b/app/models/sailors_log_notification_preference.rb index 815ab98..b1874d7 100644 --- a/app/models/sailors_log_notification_preference.rb +++ b/app/models/sailors_log_notification_preference.rb @@ -16,8 +16,6 @@ class SailorsLogNotificationPreference < ApplicationRecord def ensure_sailors_log_exists return if sailors_log.present? - sailors_log = SailorsLog.find_or_create_by(slack_uid: slack_uid) - self.sailors_log = sailors_log - sailors_log.send(:initialize_projects_summary) + self.sailors_log = SailorsLog.find_or_create_by(slack_uid: slack_uid) end end