1# frozen_string_literal: true
2
3require "lazy_object"
4require "value_semantics/monkey_patched"
5
6require_relative "bandwidth_tn_repo"
7require_relative "customer"
8require_relative "polyfill"
9
10class CustomerRepo
11 class NotFound < RuntimeError; end
12
13 value_semantics do
14 set_user Proc, default: ->(**) {}, coerce: :to_proc.to_proc
15 redis Anything(), default: LazyObject.new { REDIS }
16 db Anything(), default: LazyObject.new { DB }
17 braintree Anything(), default: LazyObject.new { BRAINTREE }
18 sgx_repo Anything(), default: TrivialBackendSgxRepo.new
19 bandwidth_tn_repo Anything(), default: BandwidthTnRepo.new
20 end
21
22 module QueryKey
23 def self.for(s)
24 case s
25 when Blather::JID, ProxiedJID
26 JID.for(s)
27 when /\Axmpp:(.*)/
28 JID.for($1)
29 when /\A(?:tel:)?(\+\d+)\Z/
30 Tel.new($1)
31 else
32 ID.new(s)
33 end
34 end
35
36 ID = Struct.new(:customer_id) do
37 def keys(redis)
38 redis.get("jmp_customer_jid-#{customer_id}").then do |jid|
39 raise NotFound, "No jid" unless jid
40
41 [customer_id, jid]
42 end
43 end
44 end
45
46 JID = Struct.new(:jid) do
47 def self.for(jid)
48 if jid.to_s =~ /\Acustomer_(.+)@#{CONFIG[:component][:jid]}\Z/
49 ID.new($1)
50 else
51 new(jid)
52 end
53 end
54
55 def keys(redis)
56 redis.get("jmp_customer_id-#{jid}").then do |customer_id|
57 raise NotFound, "No customer" unless customer_id
58
59 [customer_id, jid]
60 end
61 end
62 end
63
64 Tel = Struct.new(:tel) do
65 def keys(redis)
66 redis.get("catapult_jid-#{tel}").then do |jid|
67 raise NotFound, "No jid" unless jid
68
69 JID.for(jid).keys(redis)
70 end
71 end
72 end
73 end
74
75 def find(customer_id)
76 set_user.call(customer_id: customer_id)
77 QueryKey::ID.new(customer_id).keys(redis).then { |k| find_inner(*k) }
78 end
79
80 def find_by_jid(jid)
81 set_user.call(jid: jid)
82 QueryKey::JID.for(jid).keys(redis).then { |k| find_inner(*k) }
83 end
84
85 def find_by_tel(tel)
86 set_user.call(tel: tel)
87 QueryKey::Tel.new(tel).keys(redis).then { |k| find_inner(*k) }
88 end
89
90 def find_by_format(s)
91 set_user.call(q: s)
92 QueryKey.for(s).keys(redis).then { |k| find_inner(*k) }
93 end
94
95 def create(jid)
96 @braintree.customer.create.then do |result|
97 raise "Braintree customer create failed" unless result.success?
98
99 cid = result.customer.id
100 @redis.msetnx(
101 "jmp_customer_id-#{jid}", cid, "jmp_customer_jid-#{cid}", jid
102 ).then do |redis_result|
103 raise "Saving new customer to redis failed" unless redis_result == 1
104
105 Customer.new(cid, Blather::JID.new(jid), sgx: new_sgx(cid))
106 end
107 end
108 end
109
110 def put_lidb_name(customer, lidb_name)
111 @bandwidth_tn_repo.put_lidb_name(customer.registered?.phone, lidb_name)
112 end
113
114 def put_transcription_enabled(customer, enabled)
115 @sgx_repo.put_transcription_enabled(customer.customer_id, enabled)
116 end
117
118 def put_fwd(customer, customer_fwd)
119 tel = customer.registered?.phone
120 @sgx_repo.put_fwd(customer.customer_id, tel, customer_fwd)
121 end
122
123 def put_monthly_overage_limit(customer, limit)
124 k = "jmp_customer_monthly_overage_limit-#{customer.customer_id}"
125 @redis.set(k, limit)
126 end
127
128 def change_jid(customer, new_jid)
129 @redis.set("jmp_customer_id-#{new_jid}", customer.customer_id).then {
130 @redis.set("jmp_customer_jid-#{customer.customer_id}", new_jid)
131 }.then {
132 SwapDefaultFwd.new.do(self, customer, new_jid)
133 }.then do
134 @redis.del("jmp_customer_id-#{customer.jid}")
135 end
136 end
137
138 # I've put this here to hide the lines from rubocop
139 # After we sort out where call routing should live, this whole process will
140 # no longer be necessary
141 class SwapDefaultFwd
142 def do(repo, customer, new_jid)
143 unless customer.fwd.uri == "xmpp:#{customer.jid}"
144 return EMPromise.resolve(nil)
145 end
146
147 repo.put_fwd(customer, customer.fwd.with(uri: "xmpp:#{new_jid}"))
148 end
149 end
150
151protected
152
153 def new_sgx(customer_id)
154 TrivialBackendSgxRepo.new.get(customer_id).with(registered?: false)
155 end
156
157 def mget(*keys)
158 @redis.mget(*keys).then { |values| Hash[keys.zip(values.map(&:to_i))] }
159 end
160
161 def fetch_redis(customer_id)
162 mget(
163 "jmp_customer_auto_top_up_amount-#{customer_id}",
164 "jmp_customer_monthly_overage_limit-#{customer_id}"
165 ).then { |r|
166 r.transform_keys { |k| k.match(/^jmp_customer_([^-]+)/)[1].to_sym }
167 }
168 end
169
170 SQL = <<~SQL
171 SELECT COALESCE(balance,0) AS balance, plan_name, expires_at
172 FROM customer_plans LEFT JOIN balances USING (customer_id)
173 WHERE customer_id=$1 LIMIT 1
174 SQL
175
176 def fetch_all(customer_id)
177 EMPromise.all([
178 @sgx_repo.get(customer_id).then { |sgx| { sgx: sgx } },
179 @db.query_one(SQL, customer_id, default: {}),
180 fetch_redis(customer_id)
181 ]).then { |all| all.reduce(&:merge) }
182 end
183
184 def tndetails(sgx)
185 return {} unless sgx.registered?
186
187 LazyObject.new { @bandwidth_tn_repo.find(sgx.registered?.phone) || {} }
188 end
189
190 def find_inner(customer_id, jid)
191 set_user.call(customer_id: customer_id, jid: jid)
192 fetch_all(customer_id).then do |data|
193 Customer.new(
194 customer_id, Blather::JID.new(jid),
195 tndetails: tndetails(data[:sgx]),
196 plan: CustomerPlan.extract(customer_id, data),
197 **data.slice(:balance, :sgx, :tndetails)
198 )
199 end
200 end
201end