1# frozen_string_literal: true
2
3require "forwardable"
4require "ruby-bandwidth-iris"
5Faraday.default_adapter = :em_synchrony
6
7class BandwidthTNOrder
8 def self.get(id)
9 EM.promise_fiber do
10 self.for(BandwidthIris::Order.get_order_response(
11 # https://github.com/Bandwidth/ruby-bandwidth-iris/issues/44
12 BandwidthIris::Client.new,
13 id
14 ))
15 end
16 end
17
18 def self.create(tel, name: "sgx-jmp order #{tel}")
19 bw_tel = tel.sub(/^\+?1?/, "")
20 EM.promise_fiber do
21 Received.new(BandwidthIris::Order.create(
22 name: name,
23 site_id: CONFIG[:bandwidth_site],
24 existing_telephone_number_order_type: {
25 telephone_number_list: { telephone_number: [bw_tel] }
26 }
27 ))
28 end
29 end
30
31 def self.for(bandwidth_order)
32 const_get(bandwidth_order.order_status.capitalize).new(bandwidth_order)
33 rescue NameError
34 new(bandwidth_order)
35 end
36
37 extend Forwardable
38 def_delegators :@order, :id
39
40 def initialize(bandwidth_order)
41 @order = bandwidth_order
42 end
43
44 def status
45 @order[:order_status]&.downcase&.to_sym
46 end
47
48 def error_description
49 @order[:error_list]&.dig(:error, :description)
50 end
51
52 def poll
53 raise "Unknown order status: #{status}"
54 end
55
56 class Received < BandwidthTNOrder
57 def status
58 :received
59 end
60
61 def poll
62 EM.promise_timer(1).then do
63 BandwidthTNOrder.get(id).then(&:poll)
64 end
65 end
66 end
67
68 class Complete < BandwidthTNOrder
69 def status
70 :complete
71 end
72
73 def tel
74 "+1#{@order.completed_numbers[:telephone_number][:full_number]}"
75 end
76
77 def poll
78 catapult_import.then do |http|
79 raise "Catapult import failed" unless http.response_header.status == 201
80
81 self
82 end
83 end
84
85 protected
86
87 # After buying, import to catapult and set v1 voice app
88 def catapult_import
89 catapult_request.apost(
90 head: catapult_headers,
91 body: {
92 number: tel,
93 applicationId: catapult[:application_id],
94 provider: dashboard_provider
95 }.to_json
96 )
97 end
98
99 def catapult
100 CONFIG[:catapult]
101 end
102
103 def catapult_request
104 EM::HttpRequest.new(
105 "https://api.catapult.inetwork.com/v1/users/" \
106 "#{catapult[:user]}/phoneNumbers",
107 tls: { verify_peer: true }
108 )
109 end
110
111 def catapult_headers
112 {
113 "Authorization" => [catapult[:token], catapult[:secret]],
114 "Content-Type" => "application/json"
115 }
116 end
117
118 def dashboard_provider
119 {
120 providerName: "bandwidth-dashboard",
121 properties: {
122 accountId: CONFIG[:creds][:account],
123 userName: CONFIG[:creds][:username],
124 password: CONFIG[:creds][:password]
125 }
126 }
127 end
128 end
129
130 class Failed < BandwidthTNOrder
131 def status
132 :failed
133 end
134
135 def poll
136 raise "Order failed: #{id} #{error_description}"
137 end
138 end
139end