~singpolyma/sgx-jmp

ref: c7c48663714307e3598dc14848e539fb8672b0b7 sgx-jmp/lib/customer_info_form.rb -rw-r--r-- 1.8 KiB
c7c48663Christopher Vollick Customer Info Forms and More Info 10 months 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
# frozen_string_literal: true

require_relative "bwmsgsv2_repo"
require_relative "customer_repo"
require_relative "proxied_jid"
require_relative "legacy_customer"

class CustomerInfoForm
	def initialize(customer_repo=CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new))
		@customer_repo = customer_repo
	end

	def picker_form
		form = Blather::Stanza::X.new(:form)
		form.title = "Pick Customer"
		form.instructions = "Tell us something about the customer and we'll try " \
			"to get more information for you"

		form.fields = {
			var: "q", type: "text-single",
			label: "Something about the customer",
			description: "Supported things include: customer ID, JID, phone number"
		}

		form
	end

	def find_customer(response)
		parse_something(response.form.field("q").value)
	end

	class NoCustomer
		def form
			FormTemplate.render("no_customer_info")
		end

		def admin_info
			self
		end
	end

	def parse_something(value)
		parser = Parser.new(@customer_repo)

		EMPromise.all([
			parser.as_customer_id(value),
			parser.as_jid(value),
			parser.as_phone(value),
			EMPromise.resolve(NoCustomer.new)
		]).then { |approaches| approaches.compact.first }
	end

	class Parser
		def initialize(customer_repo)
			@customer_repo = customer_repo
		end

		def as_customer_id(value)
			@customer_repo.find(value).catch { nil }
		end

		def as_cheo(value)
			ProxiedJID.proxy(Blather::JID.new(value))
		end

		def as_jid(value)
			EMPromise.all([
				@customer_repo.find_by_jid(value).catch { nil },
				@customer_repo.find_by_jid(as_cheo(value)).catch { nil }
			]).then { |approaches| approaches.compact.first }
		end

		def as_phone(value)
			unless value.gsub(/[^0-9]/, "") =~ /^\+?1?(\d{10})$/
				return EMPromise.resolve(nil)
			end

			@customer_repo.find_by_tel("+1#{$1}").catch { nil }
		end
	end
end