If expired with auto top up, NOTIFY for a week before sending expiry notice

Stephen Paul Weber created

Change summary

bin/billing_monthly_cronjob | 23 +++++++++++++++--------
1 file changed, 15 insertions(+), 8 deletions(-)

Detailed changes

bin/billing_monthly_cronjob 🔗

@@ -114,18 +114,19 @@ class Plan
 end
 
 class ExpiredCustomer
-	def self.for(row)
+	def self.for(row, db)
 		plan = Plan.from_name(row["plan_name"])
 		if row["balance"] < plan.price
-			WithLowBalance.new(row, plan)
+			WithLowBalance.new(row, plan, db)
 		else
-			new(row, plan)
+			new(row, plan, db)
 		end
 	end
 
-	def initialize(row, plan)
+	def initialize(row, plan, db)
 		@row = row
 		@plan = plan
+		@db = db
 	end
 
 	def customer_id
@@ -145,12 +146,18 @@ class ExpiredCustomer
 
 	class WithLowBalance < ExpiredCustomer
 		ONE_WEEK = 60 * 60 * 24 * 7
+		LAST_WEEK = Time.now - ONE_WEEK
 
 		def try_renew(_, stats)
 			stats.add(:not_renewed, 1)
-			return if REDIS.exists?("jmp_customer_low_balance-#{customer_id}")
-			REDIS.set("jmp_customer_low_balance-#{customer_id}", Time.now, ex: ONE_WEEK)
-			send_notification
+			if REDIS.exists?("jmp_customer_auto_top_up_amount-#{customer_id}") && \
+			   @row["expires_at"] > LAST_WEEK
+				@db.exec_params("SELECT pg_notify('low_balance', $1)", [customer_id])
+			else
+				return if REDIS.exists?("jmp_customer_low_balance-#{customer_id}")
+				REDIS.set("jmp_customer_low_balance-#{customer_id}", Time.now, ex: ONE_WEEK)
+				send_notification
+			end
 		end
 
 	protected
@@ -201,7 +208,7 @@ db.transaction do
 		WHERE expires_at <= NOW()
 		SQL
 	).each do |row|
-		ExpiredCustomer.for(row).try_renew(db, stats)
+		ExpiredCustomer.for(row, db).try_renew(db, stats)
 	end
 end