~singpolyma/sgx-jmp

sgx-jmp/lib/bandwidth_tn_order.rb -rw-r--r-- 2.1 KiB
a5c92357Stephen Paul Weber JID cannot contain whitespace 14 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# frozen_string_literal: true

require "forwardable"
require "ruby-bandwidth-iris"
Faraday.default_adapter = :em_synchrony

class BandwidthTNOrder
	ORDER_DEFAULTS = {
		site_id: CONFIG[:bandwidth_site],
		peer_id: CONFIG[:bandwidth_peer]
	}.freeze

	def self.get(id)
		EMPromise.resolve(nil).then do
			self.for(BandwidthIris::Order.get_order_response(
				# https://github.com/Bandwidth/ruby-bandwidth-iris/issues/44
				BandwidthIris::Client.new,
				id
			))
		end
	end

	def self.create(
		tel,
		name: "sgx-jmp order #{tel}",
		reservation_id: nil,
		**kwargs
	)
		EMPromise.resolve(nil).then do
			Received.new(BandwidthIris::Order.create(
				name: name, **ORDER_DEFAULTS, **kwargs,
				existing_telephone_number_order_type: {
					telephone_number_list: { telephone_number: [tel.sub(/^\+?1?/, "")] }
				}.merge(ReservationIdList.new(reservation_id).to_h)
			))
		end
	end

	def self.for(bandwidth_order)
		const_get(bandwidth_order.order_status.capitalize).new(bandwidth_order)
	rescue NameError
		new(bandwidth_order)
	end

	extend Forwardable
	def_delegators :@order, :id

	def initialize(bandwidth_order)
		@order = bandwidth_order
	end

	def status
		@order[:order_status]&.downcase&.to_sym
	end

	def error_description
		[@order[:error_list]].flatten.first&.dig(:error, :description)
	end

	def poll
		raise "Unknown order status: #{status}"
	end

	class Received < BandwidthTNOrder
		def status
			:received
		end

		def poll
			EM.promise_timer(1).then do
				BandwidthTNOrder.get(id).then(&:poll)
			end
		end
	end

	class Complete < BandwidthTNOrder
		def status
			:complete
		end

		def tel
			"+1#{@order.completed_numbers[:telephone_number][:full_number]}"
		end

		def poll
			EMPromise.resolve(self)
		end
	end

	class Failed < BandwidthTNOrder
		def status
			:failed
		end

		def poll
			raise "Order failed: #{id} #{error_description}"
		end
	end

	class ReservationIdList
		def initialize(reservation_id)
			@reservation_id = reservation_id
		end

		def to_h
			return {} unless @reservation_id

			{ reservation_id_list: { reservation_id: @reservation_id } }
		end
	end
end