diff --git a/app/jobs/send_ntfy_notification_job.rb b/app/jobs/send_ntfy_notification_job.rb new file mode 100644 index 0000000..4c68430 --- /dev/null +++ b/app/jobs/send_ntfy_notification_job.rb @@ -0,0 +1,23 @@ +require "my_smsa_pio/notifications/ntfy/publisher" + +class SendNtfyNotificationJob < ApplicationJob + queue_as :notifications + retry_on StandardError, wait: :exponentially_longer, attempts: 3 + + def perform(admin_id, event_type, title:, message:, priority: 3, tags: [], click: nil) + admin = AdminUser.find_by(id: admin_id) + return unless admin + return unless admin.ntfy_configured? + + MySmsaPio::Notifications::Ntfy::Publisher.new(admin).publish( + title: title, + message: message, + priority: priority, + tags: tags, + click: click + ) + rescue StandardError => e + Rails.logger.error("SendNtfyNotificationJob failed for admin #{admin_id}: #{e.message}") + raise + end +end diff --git a/test/jobs/send_ntfy_notification_job_test.rb b/test/jobs/send_ntfy_notification_job_test.rb new file mode 100644 index 0000000..a5eb4e6 --- /dev/null +++ b/test/jobs/send_ntfy_notification_job_test.rb @@ -0,0 +1,49 @@ +require "test_helper" + +class SendNtfyNotificationJobTest < ActiveJob::TestCase + setup do + @admin = AdminUser.create!( + name: "Job Admin", email: "jobadmin@example.com", + password: "password123", + ntfy_topic: "job-topic", ntfy_token: "tk_job", + ntfy_enabled: true, + ntfy_server_url: "https://ntfy.example.com" + ) + + stub_request(:post, "https://ntfy.example.com/job-topic") + .to_return(status: 200, body: "", headers: {}) + end + + test "perform calls Publisher with provided params" do + SendNtfyNotificationJob.perform_now( + @admin.id, + "gateway_offline", + title: "Gateway offline", + message: "gw-001 went offline", + priority: 4, + tags: ["rotating_light"], + click: "https://app.example.com/admin/gateways" + ) + + assert_requested :post, "https://ntfy.example.com/job-topic", + body: hash_including("title" => "Gateway offline", "priority" => 4) + end + + test "perform does nothing if admin not found" do + assert_nothing_raised do + SendNtfyNotificationJob.perform_now(999999, "gateway_offline", + title: "X", message: "Y", priority: 3, tags: []) + end + end + + test "perform does nothing if admin ntfy not configured" do + unconfigured = AdminUser.create!( + name: "UC", email: "uc@example.com", password: "password123" + ) + + SendNtfyNotificationJob.perform_now(unconfigured.id, "gateway_offline", + title: "X", message: "Y", priority: 3, tags: []) + + assert_not_requested :post, "https://ntfy.example.com/job-topic" + end +end