From cc51b1a7c0c5e614607bc74ee73563f5268b229f Mon Sep 17 00:00:00 2001
From: Teal <git@teal.is>
Date: Mon, 27 May 2024 15:41:46 +0200
Subject: [PATCH] add upcoming job notifier

---
 app/jobs/telegram_notify_upcoming_job.rb      | 20 +++++++++++++++++++
 config/cronotab.rb                            |  1 +
 .../jobs/telegram_notify_upcoming_job_test.rb |  7 +++++++
 3 files changed, 28 insertions(+)
 create mode 100644 app/jobs/telegram_notify_upcoming_job.rb
 create mode 100644 test/jobs/telegram_notify_upcoming_job_test.rb

diff --git a/app/jobs/telegram_notify_upcoming_job.rb b/app/jobs/telegram_notify_upcoming_job.rb
new file mode 100644
index 0000000..acd2c67
--- /dev/null
+++ b/app/jobs/telegram_notify_upcoming_job.rb
@@ -0,0 +1,20 @@
+class TelegramNotifyUpcomingJob < ApplicationJob
+  queue_as :default
+
+  def perform(**args)
+    Session.scheduled.includes(:stage, :assignments).where(stage: { name: ["Stage 1", "Stage 2", "Standby"] }).where(starts_at: Time.now..(Time.now + args[:interval])).order(:starts_at).each do |session|
+      assignees = session.assignments.map(&:user)
+      if assignees.length.positive?
+        notify_names = assignees.map { |a| a.telegram_username ? "@#{a.telegram_username}" : a.name }
+
+        message = notify_names.join(' ') + ": Your scheduled session <i>#{session.title}</i> starts at <b>#{session.starts_at.strftime("%H:%M")}</b> on <b>#{session.stage.name}</b>"
+        TelegramGroupChatNotificationJob.perform_later(target: "-316096320", text: message, parse_mode: 'HTML')
+        # TelegramGroupChatNotificationJob.perform_now(target: "2192297", text: message, parse_mode: 'HTML')
+      else
+        message = "<b>⚠️ No assignees</b> for session <i>#{session.title}</i> starting at <b>#{session.starts_at.strftime("%H:%M")}</b> on <b>#{session.stage.name}</b>"
+        TelegramGroupChatNotificationJob.perform_later(target: "-316096320", text: message, parse_mode: 'HTML')
+        # TelegramGroupChatNotificationJob.perform_now(target: "2192297", text: message, parse_mode: 'HTML')
+      end
+    end
+  end
+end
diff --git a/config/cronotab.rb b/config/cronotab.rb
index 976cc97..04bbfe1 100644
--- a/config/cronotab.rb
+++ b/config/cronotab.rb
@@ -15,3 +15,4 @@
 #
 
 Crono.perform(FetchConferenceDataJob, 'rp2024').every 5.minutes
+Crono.perform(TelegramNotifyUpcomingJob, interval: 15.minutes).every 15.minutes
diff --git a/test/jobs/telegram_notify_upcoming_job_test.rb b/test/jobs/telegram_notify_upcoming_job_test.rb
new file mode 100644
index 0000000..811f6e4
--- /dev/null
+++ b/test/jobs/telegram_notify_upcoming_job_test.rb
@@ -0,0 +1,7 @@
+require "test_helper"
+
+class TelegramNotifyUpcomingJobTest < ActiveJob::TestCase
+  # test "the truth" do
+  #   assert true
+  # end
+end
-- 
GitLab