Import hotfixes

Stephen Paul Weber created

Change summary

bin/sim_job | 20 ++++++++++++--------
1 file changed, 12 insertions(+), 8 deletions(-)

Detailed changes

bin/sim_job 🔗

@@ -83,8 +83,9 @@ end
 module SimAction
 	attr_accessor :customer
 
-	def initialize(sim)
+	def initialize(sim, customer: nil)
 		@sim = sim
+		@customer = customer
 	end
 
 	def iccid
@@ -101,7 +102,7 @@ module SimAction
 
 	def refill_and_bill(data, price, note)
 		SIM_REPO.refill(@sim, amount_mb: data).then { |keepgo_tx|
-			raise "SIM refill failed" unless keepgo_tx["ack"] == "success"
+			raise "SIM refill failed: #{iccid}" unless keepgo_tx["ack"] == "success"
 
 			Transaction.new(
 				customer_id: customer_id,
@@ -127,7 +128,7 @@ module SimAction
 			customer_id=$1 AND transaction_id LIKE 'AB_59576_%' AND
 			created_at >= DATE_TRUNC('month', LOCALTIMESTAMP)
 		SQL
-		promise.then { |rows| rows.first["a"] }
+		promise.then { |rows| -rows.first["a"] }
 	end
 end
 
@@ -136,6 +137,7 @@ class SimTopUp
 
 	def low_balance
 		LowBalance.for(customer, refill_price).then(&:notify!).then do |result|
+			@customer = customer.with_balance(customer.balance + result)
 			next call if result.positive?
 
 			LOG.info "Low balance #{customer.customer_id} #{iccid}"
@@ -149,7 +151,7 @@ class SimTopUp
 
 				refill_and_bill(5120, refill_price, "5GB Data Topup for #{iccid}")
 			else
-				SimWarn.new(@sim).call
+				SimWarn.new(@sim, customer: customer).call
 			end
 		end
 	end
@@ -214,7 +216,9 @@ def fetch_customers(cids)
 	# We expect the set to be very small for the forseeable future,
 	# hundreds at most
 	EMPromise.all(
-		Set.new(cids).to_a.compact.map { |id| CUSTOMER_REPO.find(id) }
+		Set.new(cids).to_a.compact.map { |id|
+			CUSTOMER_REPO.find(id).catch_only(CustomerRepo::NotFound) { nil }
+		}
 	).then do |customers|
 		Hash[customers.map { |c| [c.customer_id, JobCustomer.new(c)] }]
 	end
@@ -235,12 +239,12 @@ end
 
 def decide_sim_actions(sims)
 	sims.each_with_object({}) { |sim, h|
-		if sim.remaining_usage_kb < 100000
+		if sim.remaining_days < 31
+			h[sim.iccid] = SimAnnual.new(sim)
+		elsif sim.remaining_usage_kb < 100000
 			h[sim.iccid] = SimTopUp.new(sim)
 		elsif sim.remaining_usage_kb < 250000
 			h[sim.iccid] = SimWarn.new(sim)
-		elsif sim.remaining_days < 30
-			h[sim.iccid] = SimAnnual.new(sim)
 		end
 	}.compact
 end