bandwidth_tn_repo.rb

 1# frozen_string_literal: true
 2
 3require "ruby-bandwidth-iris"
 4
 5class BandwidthTnRepo
 6	STASH_QUERY = <<~SQL
 7		INSERT INTO tel_inventory (
 8			tel,
 9			region,
10			locality,
11			bandwidth_account_id,
12			available_after
13		) VALUES (
14			$1,
15			$2,
16			$3,
17			$4,
18			LOCALTIMESTAMP + '1 MONTH'
19		)
20	SQL
21
22	def initialize
23		@move_client =
24			BandwidthIris::Client.new(
25				account_id: CONFIG[:keep_area_codes_in][:account],
26				username: CONFIG[:creds][:username],
27				password: CONFIG[:creds][:password]
28			)
29	end
30
31	def find(tel)
32		BandwidthIris::Tn.new(telephone_number: tel).get_details
33	rescue StandardError
34		{}
35	end
36
37	def put_lidb_name(tel, lidb_name)
38		BandwidthIris::Lidb.create(
39			lidb_tn_groups: { lidb_tn_group: {
40				telephone_numbers: { telephone_number: tel.sub(/\A\+1/, "") },
41				subscriber_information: lidb_name,
42				use_type: "RESIDENTIAL", visibility: "PUBLIC"
43			} }
44		)
45	rescue BandwidthIris::Errors::GenericError
46		raise "Could not set CNAM, please contact support"
47	end
48
49	def stash_for_later(tel, btn)
50		details = btn.get_rate_center
51		region = details[:state]
52		raise "No city in: #{details.inspect}" unless details[:city]
53
54		locality = details[:city]
55		params = [tel, region, locality, CONFIG[:creds][:account]]
56		DB.exec(STASH_QUERY, params)
57	end
58
59	def disconnect(tel, order_name)
60		tn = tel.sub(/\A\+1/, "")
61		btn = BandwidthIris::Tn.new({ telephone_number: tn }, @move_client)
62		if CONFIG[:keep_area_codes].find { |area| tn.start_with?(area) }
63			stash_for_later(tel, btn)
64		else
65			BandwidthIris::Disconnect.create(order_name, tn)
66		end
67	end
68
69	def move(tel, order_name, source_account_id)
70		tn = tel.sub(/\A\+1/, "")
71		BandwidthIris::Tn.new({ telephone_number: tn }, @move_client).move(
72			customer_order_id: order_name,
73			source_account_id: source_account_id,
74			site_id: CONFIG[:bandwidth_site],
75			sip_peer_id: CONFIG[:bandwidth_peer]
76		)
77	end
78end