1# frozen_string_literal: true
2
3require_relative "customer_repo"
4require_relative "proxied_jid"
5require_relative "legacy_customer"
6
7class CustomerInfoForm
8 def initialize(customer_repo=CustomerRepo.new)
9 @customer_repo = customer_repo
10 end
11
12 def picker_form
13 form = Blather::Stanza::X.new(:form)
14 form.title = "Pick Customer"
15 form.instructions = "Tell us something about the customer and we'll try " \
16 "to get more information for you"
17
18 form.fields = {
19 var: "q", type: "text-single",
20 label: "Something about the customer",
21 description: "Supported things include: customer ID, JID, phone number"
22 }
23
24 form
25 end
26
27 def find_customer(response)
28 parse_something(response.form.field("q").value)
29 end
30
31 class NoCustomer
32 class AdminInfo
33 def fields
34 [{ var: "Account Status", value: "Not Found" }]
35 end
36 end
37
38 def admin_info
39 AdminInfo.new
40 end
41 end
42
43 def parse_something(value)
44 parser = Parser.new(@customer_repo)
45
46 EMPromise.all([
47 parser.as_customer_id(value),
48 parser.as_jid(value),
49 parser.as_phone(value),
50 EMPromise.resolve(NoCustomer.new)
51 ]).then { |approaches| approaches.compact.first }
52 end
53
54 class Parser
55 def initialize(customer_repo)
56 @customer_repo = customer_repo
57 end
58
59 def as_customer_id(value)
60 @customer_repo.find(value).catch { nil }
61 end
62
63 def as_cheo(value)
64 ProxiedJID.proxy(Blather::JID.new(value))
65 end
66
67 def as_jid(value)
68 EMPromise.all([
69 @customer_repo.find_by_jid(value).catch { nil },
70 @customer_repo.find_by_jid(as_cheo(value)).catch { nil }
71 ]).then { |approaches| approaches.compact.first }
72 end
73
74 def as_phone(value)
75 unless value.gsub(/[^0-9]/, "") =~ /^\+?1?(\d{10})$/
76 return EMPromise.resolve(nil)
77 end
78
79 @customer_repo.find_by_tel("+1#{$1}").catch { nil }
80 end
81 end
82end