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 source,
12 available_after,
13 premium_price
14 ) VALUES (
15 $1,
16 $2,
17 $3,
18 $4,
19 LOCALTIMESTAMP + '1 MONTH',
20 $5
21 )
22 SQL
23
24 def initialize
25 @move_client =
26 BandwidthIris::Client.new(
27 account_id: CONFIG[:keep_area_codes_in][:account],
28 username: CONFIG[:creds][:username],
29 password: CONFIG[:creds][:password]
30 )
31 end
32
33 def find(tel)
34 BandwidthIris::Tn.new(telephone_number: tel).get_details
35 rescue StandardError
36 {}
37 end
38
39 def put_lidb_name(tel, lidb_name)
40 BandwidthIris::Lidb.create(
41 lidb_tn_groups: { lidb_tn_group: {
42 telephone_numbers: { telephone_number: tel.sub(/\A\+1/, "") },
43 subscriber_information: lidb_name,
44 use_type: "RESIDENTIAL", visibility: "PUBLIC"
45 } }
46 )
47 rescue BandwidthIris::Errors::GenericError
48 raise "Could not set CNAM, please contact support"
49 end
50
51 # @param [String] tel
52 # @param [BandwidthIris::Tn] btn
53 # @param [Numeric] premium_price
54 def stash_for_later(tel, btn, premium_price)
55 LOG.info "stash_for_later #{tel}\n#{caller}"
56 details = btn.get_details
57 region = details[:state]
58 locality = details[:city]
59 params = [tel, region, locality, CONFIG[:creds][:account], premium_price]
60 DB.exec(STASH_QUERY, params)
61 end
62
63 def disconnect(tel, order_name)
64 tn = tel.sub(/\A\+1/, "")
65 btn = BandwidthIris::Tn.new({ telephone_number: tn }, @move_client)
66 code_and_price = CONFIG[:keep_area_codes].find { |keep|
67 tn.start_with?(keep[:area_code])
68 }
69 if code_and_price
70 stash_for_later(tel, btn, code_and_price[:premium_price] || 0)
71 else
72 BandwidthIris::Disconnect.create(order_name, tn)
73 end
74 end
75
76 def move(tel, order_name, source_account_id)
77 tn = tel.sub(/\A\+1/, "")
78 BandwidthIris::Tn.new({ telephone_number: tn }, @move_client).move(
79 customer_order_id: order_name,
80 source_account_id: source_account_id,
81 site_id: CONFIG[:bandwidth_site],
82 sip_peer_id: CONFIG[:bandwidth_peer]
83 )
84 end
85end