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 locality = details[:rate_center]
53 params = [tel, region, locality, CONFIG[:creds][:account]]
54 DB.exec(STASH_QUERY, params)
55 end
56
57 def disconnect(tel, order_name)
58 tn = tel.sub(/\A\+1/, "")
59 btn = BandwidthIris::Tn.new({ telephone_number: tn }, @move_client)
60 if CONFIG[:keep_area_codes].find { |area| tn.start_with?(area) }
61 stash_for_later(tel, btn)
62 else
63 BandwidthIris::Disconnect.create(order_name, tn)
64 end
65 end
66
67 def move(tel, order_name, source_account_id)
68 tn = tel.sub(/\A\+1/, "")
69 BandwidthIris::Tn.new({ telephone_number: tn }, @move_client).move(
70 customer_order_id: order_name,
71 source_account_id: source_account_id,
72 site_id: CONFIG[:bandwidth_site],
73 sip_peer_id: CONFIG[:bandwidth_peer]
74 )
75 end
76end