price functionality on Tns

Phillip Davis created

0 unless LocalInventory, in which case price is fetched from postgres

Change summary

lib/tel_selections.rb | 51 +++++++++++++++++++++++++++++++++++++++-----
1 file changed, 45 insertions(+), 6 deletions(-)

Detailed changes

lib/tel_selections.rb 🔗

@@ -155,7 +155,7 @@ class TelSelections
 							full_number: row["tel"].sub(/\A\+1/, ""),
 							city: row["locality"],
 							state: row["region"]
-						), row["bandwidth_account_id"])
+						), row["bandwidth_account_id"], price: row["premium_price"])
 					}
 				}
 			end
@@ -215,13 +215,49 @@ class TelSelections
 
 			def self.for_pending_value(value)
 				if value.start_with?("LocalInventory/")
-					tel, account = value.sub(/\ALocalInventory\//, "").split("/", 2)
-					LocalInventory.new(Tn.new(tel), account)
+					tel, account, price =
+						value.sub(/\ALocalInventory\//, "").split("/", 3)
+					LocalInventory.new(Tn.new(tel), account, price: price.to_d)
 				else
 					Bandwidth.new(Tn.new(value))
 				end
 			end
 
+			def price
+				0
+			end
+
+			# Creates and inserts transaction charging the customer
+			# for the phone number. If price <= 0 this is a noop.
+			# This method never checks customer balance.
+			#
+			# @param customer [Customer] the customer to charge
+			def charge(customer)
+				return if price <= 0
+
+				transaction(customer).insert
+			end
+
+			# @param customer [Customer] the customer to charge
+			def transaction(customer)
+				Transaction.new(
+					customer_id: customer.customer_id,
+					transaction_id: transaction_id(customer),
+					amount: -price,
+					note: transaction_note,
+					ignore_duplicate: false
+				)
+			end
+
+			# @param customer [Customer] the customer to charge
+			def transaction_id(customer)
+				"#{customer.customer_id}-bill-#{customer.plan}-at-#{Time.now.to_i}"
+			end
+
+			def transaction_note
+				"One-time charge for number: #{formatted_tel}"
+			end
+
 			def initialize(tel)
 				@tel = tel
 			end
@@ -286,6 +322,8 @@ class TelSelections
 			end
 
 			class LocalInventory < SimpleDelegator
+				attr_reader :price
+
 				def self.fetch(tn, db: DB)
 					db.query_defer("SELECT * FROM tel_inventory WHERE tel = $1", [tn])
 						.then { |rows|
@@ -294,18 +332,19 @@ class TelSelections
 								full_number: row["tel"].sub(/\A\+1/, ""),
 								city: row["locality"],
 								state: row["region"]
-							), row["bandwidth_account_id"])
+							), row["bandwidth_account_id"], price: row["premium_price"])
 						}
 					}
 				end
 
-				def initialize(tn, bandwidth_account_id)
+				def initialize(tn, bandwidth_account_id, price: 0)
 					super(tn)
 					@bandwidth_account_id = bandwidth_account_id
+					@price = price
 				end
 
 				def pending_value
-					"LocalInventory/#{tel}/#{@bandwidth_account_id}"
+					"LocalInventory/#{tel}/#{@bandwidth_account_id}/#{price}"
 				end
 
 				def reserve(*)