feat(ntfy): dispatch sms_delivered and sms_failed from SmsMessage

This commit is contained in:
Min Zeya Phyo
2026-07-28 02:17:51 +08:00
parent 36a3f6daad
commit a93c39726a
2 changed files with 62 additions and 9 deletions

View File

@@ -1,4 +1,6 @@
class SmsMessage < ApplicationRecord
include NtfyDispatchable
# Normalize metadata to always be a Hash
attribute :metadata, :jsonb, default: {}
@@ -52,19 +54,24 @@ class SmsMessage < ApplicationRecord
# Mark message as delivered
def mark_delivered!
update!(
status: "delivered",
delivered_at: Time.current
)
update!(status: "delivered", delivered_at: Time.current)
self.class.dispatch_ntfy("sms_delivered",
title: "SMS delivered",
message: "Message to #{phone_number} (#{message_id}) was delivered",
priority: 2,
tags: ["white_check_mark"])
end
# Mark message as failed
def mark_failed!(error_msg = nil)
update!(
status: "failed",
failed_at: Time.current,
error_message: error_msg
)
update!(status: "failed", failed_at: Time.current, error_message: error_msg)
self.class.dispatch_ntfy("sms_failed",
title: "SMS failed",
message: "Message to #{phone_number} (#{message_id}) failed#{error_msg ? ": #{error_msg}" : ''}",
priority: 5,
tags: ["x", "rotating_light"])
end
# Increment retry counter

View File

@@ -0,0 +1,46 @@
require "test_helper"
class SmsMessageTest < ActiveSupport::TestCase
include ActiveJob::TestHelper
setup do
ActiveJob::Base.queue_adapter = :test
@admin = AdminUser.create!(
name: "SMS Admin", email: "sms@example.com",
password: "password123",
ntfy_topic: "sms-topic", ntfy_token: "tk_sms",
ntfy_enabled: true, ntfy_server_url: "https://ntfy.example.com"
)
stub_request(:post, "https://ntfy.example.com/sms-topic").to_return(status: 200)
@gateway = Gateway.create!(
device_id: "sms-gw", name: "SMS GW",
api_key_digest: "d" * 64, status: "online",
last_heartbeat_at: 1.second.ago
)
end
test "mark_delivered! dispatches sms_delivered notification" do
sms = SmsMessage.create!(
direction: "outbound", phone_number: "+14152345678",
message_body: "Hello", status: "sent",
gateway: @gateway, sent_at: 1.minute.ago
)
assert_enqueued_jobs 1 do
sms.mark_delivered!
end
end
test "mark_failed! dispatches sms_failed notification with urgent priority" do
sms = SmsMessage.create!(
direction: "outbound", phone_number: "+14152345678",
message_body: "Hello", status: "sent",
gateway: @gateway, sent_at: 1.minute.ago
)
assert_enqueued_jobs 1 do
sms.mark_failed!("Network timeout")
end
end
end