Factor out BuyNumber

Stephen Paul Weber created

Change summary

lib/registration.rb | 65 +++++++++++++++++++++++++---------------------
1 file changed, 35 insertions(+), 30 deletions(-)

Detailed changes

lib/registration.rb 🔗

@@ -580,53 +580,58 @@ class Registration
 		end
 	end
 
-	class Finish
+	class BuyNumber
 		def initialize(customer, tel)
 			@customer = customer
 			@tel = tel
-			@invites = InvitesRepo.new(DB, REDIS)
 		end
 
 		def write
-			if @customer.balance >= @tel.price
-				@tel.order(DB, @customer).then(
-					->(_) { customer_active_tel_purchased },
-					method(:number_purchase_error)
+			Command.reply { |reply|
+				reply.command << FormTemplate.render(
+					"registration/buy_number",
+					tel: @tel
 				)
-			else
-				buy_number.then {
-					try_again
-				}.then(&:write)
-			end
+			}.then(&method(:parse)).then(&:write)
 		end
 
-		def try_again
-			reload_customer(@customer).then do |customer|
-				Finish.new(customer, @tel)
-			end
-		end
+	protected
 
-		def form
-			FormTemplate.render(
-				"registration/buy_number",
-				tel: @tel
+		def parse(iq)
+			Payment.for(
+				iq, @customer, @tel,
+				maybe_bill: ::Registration::Payment::JustCharge,
+				price: @tel.price
 			)
 		end
+	end
 
-		def buy_number
-			Command.reply { |reply|
-				reply.command << form
-			}.then { |iq|
-				Payment.for(
-					iq, @customer, @tel,
-					maybe_bill: ::Registration::Payment::JustCharge,
-					price: @tel.price
-				)
-			}.then(&:write)
+	class Finish
+		def initialize(customer, tel)
+			@customer = customer
+			@tel = tel
+			@invites = InvitesRepo.new(DB, REDIS)
+		end
+
+		def write
+			return buy_number if @customer.balance < @tel.price
+
+			@tel.order(DB, @customer).then(
+				->(_) { customer_active_tel_purchased },
+				method(:number_purchase_error)
+			)
 		end
 
 	protected
 
+		def buy_number
+			BuyNumber.new(@customer, @tel).write.then do
+				reload_customer(@customer).then { |customer|
+					Finish.new(customer, @tel)
+				}.then(&:write)
+			end
+		end
+
 		def number_purchase_error(e)
 			Command.log.error "number_purchase_error", e
 			TEL_SELECTIONS.delete(@customer.jid).then {