From c7ad1a7752b193d2ca6df763b11a5fe0ae9755b6 Mon Sep 17 00:00:00 2001 From: Akshatha <71076330+qptr@users.noreply.github.com> Date: Mon, 1 Jan 2024 16:42:36 +0530 Subject: [PATCH] Automate AlphaSms balance check (#5365) **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. --- config/schedule.rb | 6 ++++++ lib/tasks/alpha_sms.rake | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 lib/tasks/alpha_sms.rake diff --git a/config/schedule.rb b/config/schedule.rb index a482a71489..eb781111c6 100644 --- a/config/schedule.rb +++ b/config/schedule.rb @@ -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 diff --git a/lib/tasks/alpha_sms.rake b/lib/tasks/alpha_sms.rake new file mode 100644 index 0000000000..239c6602a2 --- /dev/null +++ b/lib/tasks/alpha_sms.rake @@ -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