Only bill customer if they for sure have balance and are expired

Stephen Paul Weber created

Change summary

lib/bill_plan_command.rb | 25 ++++++++++++++++++++++---
1 file changed, 22 insertions(+), 3 deletions(-)

Detailed changes

lib/bill_plan_command.rb 🔗

@@ -3,6 +3,7 @@
 class BillPlanCommand
 	def self.for(customer)
 		return ForUnregistered.new(customer) unless customer.registered?
+		return ForNotExpired.new(customer) unless customer.expires_at <= Time.now
 
 		unless customer.balance > customer.monthly_price
 			return ForLowBalance.new(customer)
@@ -16,10 +17,15 @@ class BillPlanCommand
 	end
 
 	def call
-		@customer.bill_plan(note: "Renew account plan")
+		billed = @customer.bill_plan(note: "Renew account plan") { |db|
+			@customer = Command.execution.customer_repo.with(db: db)
+				.find(@customer.customer_id).sync
+			@customer.balance > @customer.monthly_price &&
+				@customer.expires_at <= Time.now
+		}
 		Command.reply do |reply|
-			reply.note_type = :info
-			reply.note_text = "#{@customer.customer_id} billed"
+			reply.note_type = billed ? :info : :error
+			reply.note_text = "#{@customer.customer_id}#{billed ? '' : ' not'} billed"
 		end
 	end
 
@@ -70,4 +76,17 @@ class BillPlanCommand
 			end
 		end
 	end
+
+	class ForNotExpired
+		def initialize(customer)
+			@customer = customer
+		end
+
+		def call
+			Command.reply do |reply|
+				reply.note_type = :error
+				reply.note_text = "#{@customer.customer_id} is not expired"
+			end
+		end
+	end
 end