Skip to content

Commit

Permalink
Automate AlphaSms balance check (#5365)
Browse files Browse the repository at this point in the history
**Story card:**
[sc-11640](https://app.shortcut.com/simpledotorg/story/11640/automate-alphasms-balance-check)

We want to automate balance check in Bangladesh and alert on low
balance.

The reason the error message is being logged and not raised as an
exception is so we can add a Datadog alert on the log. The corresponding
BSNL task relies on Sentry to alert on an uncaught exception for low
balance, but we have to manually resolve the alert each time for it to
show up again next time. This is not an issue on Datadog.
  • Loading branch information
qptr authored Jan 1, 2024
1 parent 5e7bc9a commit c7ad1a7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
6 changes: 6 additions & 0 deletions config/schedule.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ def local(time)
end
end

every :day, at: local("02:00 pm"), roles: [:cron] do
if CountryConfig.current_country?("Bangladesh") && SimpleServer.env.production?
rake "alpha_sms:check_balance"
end
end

every :day, at: local("05:30 pm"), roles: [:cron] do
runner "Messaging::Bsnl::Sms.get_message_statuses"
end
Expand Down
20 changes: 20 additions & 0 deletions lib/tasks/alpha_sms.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace :alpha_sms do
desc "Fetch account balance and log if we're running low or close to expiry"
task check_balance: :environment do
max_cost_per_day = 5000
alert_in_days = 5

response = Messaging::AlphaSms::Api.new
.get_account_balance
.with_indifferent_access
expiry_date = response.dig(:data, :validity)&.to_date
balance_amount = response.dig(:data, :balance)&.to_f

if expiry_date < alert_in_days.days.from_now
Rails.logger.error("Account balance expires in less than #{alert_in_days}. Please recharge before #{expiry_date}.")
elsif balance_amount < (alert_in_days * max_cost_per_day)
Rails.logger.error("Remaining account balance is #{balance_amount} BDT. May expire in less than #{alert_in_days} days.")
end
print("Balance: #{balance_amount} BDT\nExpiry: #{expiry_date}")
end
end

0 comments on commit c7ad1a7

Please sign in to comment.