~singpolyma/sgx-jmp

ref: 4178a87a901cbf00cddbf9671c2f99aa79dfd3a8 sgx-jmp/lib/bandwidth_tn_order.rb -rw-r--r-- 2.2 KiB
4178a87aStephen Paul Weber Factor out Catapult connection 2 years 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
112
113
114
115
116
117
118
# frozen_string_literal: true

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

require_relative "./catapult"

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 tel
			"+1#{@order.completed_numbers[:telephone_number][:full_number]}"
		end

		def poll
			catapult_import.then do |http|
				raise "Catapult import failed" unless http.response_header.status == 201

				self
			end
		end

	protected

		# After buying, import to catapult and set v1 voice app
		def catapult_import
			CATAPULT.import(
				number: tel,
				provider: dashboard_provider
			)
		end

		def dashboard_provider
			{
				providerName: "bandwidth-dashboard",
				properties: {
					accountId: CONFIG[:creds][:account],
					userName: CONFIG[:creds][:username],
					password: CONFIG[:creds][:password]
				}
			}
		end
	end

	class Failed < BandwidthTNOrder
		def status
			:failed
		end

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