1# frozen_string_literal: true
2
3require "em_promise"
4require "ruby-bandwidth-iris"
5Faraday.default_adapter = :em_synchrony
6
7class BandwidthTNOptions
8 def self.set_port_out_pin(user_id, token, secret, pin, tel)
9 client = BandwidthIris::Client.new(
10 account_id: user_id,
11 username: token,
12 password: secret
13 )
14
15 data = {
16 tn_option_groups: {
17 tn_option_group: [
18 {
19 port_out_passcode: pin,
20 telephone_numbers: {
21 telephone_number: [tel]
22 }
23 }
24 ]
25 }
26 }
27
28 EMPromise.resolve(nil).then do
29 order = BandwidthIris::TnOptions.create_tn_option_order(client, data)
30 order_id = order[:order_id]
31
32 unless order_id
33 raise StandardError.new("Missing OrderId in create response")
34 end
35
36 poll_order(order_id, client)
37 end
38 end
39
40 def self.poll_order(order_id, client, attempt=1, max_attempts=30)
41 if attempt > max_attempts
42 return EMPromise.reject(StandardError.new(
43 "TnOptions polling timeout after #{max_attempts} attempts"
44 ))
45 end
46
47 EMPromise.resolve(nil).then do
48 order = BandwidthIris::TnOptions.get_tn_option_order(client, order_id)
49
50 error_list = order[:error_list]
51 if error_list&.any?
52 errors = [error_list].flatten
53 msgs = errors.map { |e| e.to_s }.reject(&:empty?).join('; ')
54 raise StandardError.new("Dashboard tnOptions errors: #{msgs}")
55 end
56
57 warnings = order[:warnings]
58 if warnings&.any?
59 warns = [warnings].flatten
60 descs = warns.map { |w| w.to_s }.reject(&:empty?).join('; ')
61 raise StandardError.new("Dashboard tnOptions warnings: #{descs}")
62 end
63
64 status = order[:order_status] || order[:processing_status]
65
66 case status&.to_s&.upcase
67 when 'COMPLETE', 'PARTIAL'
68 true
69 when 'FAILED'
70 raise StandardError.new("TnOptions order failed with status: #{status}")
71 when 'RECEIVED', 'PROCESSING'
72 EMPromise.new { |resolve, reject|
73 EM.add_timer(2) do
74 poll_order(order_id, client, attempt + 1, max_attempts)
75 .then { |result| resolve.call(result) }
76 .catch { |error| reject.call(error) }
77 end
78 }
79 else
80 raise StandardError.new("Unexpected poll status: #{status.inspect}")
81 end
82 end
83 end
84end