~singpolyma/sgx-jmp

ref: 9300f0d14c86a191fbf94b2536a5c3fb31ca4a7f sgx-jmp/lib/bandwidth_tn_order.rb -rw-r--r-- 1.6 KiB
9300f0d1Stephen Paul Weber Helper to allow ordering phone number from Bandwidth v2 1 year, 1 month 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
# frozen_string_literal: true

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

class BandwidthTNOrder
	def self.get(id)
		EM.promise_fiber 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}")
		bw_tel = tel.sub(/^\+?1?/, "")
		EM.promise_fiber do
			Received.new(BandwidthIris::Order.create(
				name: name,
				site_id: CONFIG[:bandwidth_site],
				existing_telephone_number_order_type: {
					telephone_number_list: { telephone_number: [bw_tel] }
				}
			))
		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]&.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 poll
			EMPromise.resolve(self)
		end
	end

	class Failed < BandwidthTNOrder
		def status
			:failed
		end

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