customer_repo.rb

  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, tel: nil)
 38				redis.get("jmp_customer_jid-#{customer_id}").then do |jid|
 39					raise NotFound, "No jid" unless jid
 40
 41					[customer_id, Blather::JID.new(jid), *tel]
 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, tel: nil)
 56				redis.get("jmp_customer_id-#{jid}").then do |customer_id|
 57					raise NotFound, "No customer" unless customer_id
 58
 59					[customer_id, Blather::JID.new(jid), *tel]
 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, tel: tel)
 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.created(cid, jid, sgx: new_sgx(cid), repo: self)
106			end
107		end
108	end
109
110	def disconnect_tel(customer)
111		tel = customer.registered?.phone
112		@bandwidth_tn_repo.disconnect(tel, customer.customer_id)
113	end
114
115	def put_lidb_name(customer, lidb_name)
116		@bandwidth_tn_repo.put_lidb_name(customer.registered?.phone, lidb_name)
117	end
118
119	def put_transcription_enabled(customer, enabled)
120		@sgx_repo.put_transcription_enabled(customer.customer_id, enabled)
121	end
122
123	def put_fwd(customer, customer_fwd)
124		tel = customer.registered?.phone
125		@sgx_repo.put_fwd(customer.customer_id, tel, customer_fwd)
126	end
127
128	def put_monthly_overage_limit(customer, limit)
129		k = "jmp_customer_monthly_overage_limit-#{customer.customer_id}"
130		@redis.set(k, limit)
131	end
132
133	def change_jid(customer, new_jid)
134		@redis.set("jmp_customer_id-#{new_jid}", customer.customer_id).then {
135			@redis.set("jmp_customer_jid-#{customer.customer_id}", new_jid)
136		}.then {
137			SwapDefaultFwd.new.do(self, customer, new_jid)
138		}.then do
139			@redis.del("jmp_customer_id-#{customer.jid}")
140		end
141	end
142
143	# I've put this here to hide the lines from rubocop
144	# After we sort out where call routing should live, this whole process will
145	# no longer be necessary
146	class SwapDefaultFwd
147		def do(repo, customer, new_jid)
148			unless customer.fwd.uri == "xmpp:#{customer.jid}"
149				return EMPromise.resolve(nil)
150			end
151
152			repo.put_fwd(customer, customer.fwd.with(uri: "xmpp:#{new_jid}"))
153		end
154	end
155
156protected
157
158	def new_sgx(customer_id)
159		TrivialBackendSgxRepo.new.get(customer_id).with(registered?: false)
160	end
161
162	def mget(*keys)
163		@redis.mget(*keys).then { |values| Hash[keys.zip(values.map(&:to_i))] }
164	end
165
166	def fetch_redis(customer_id)
167		EMPromise.all([
168			mget(
169				"jmp_customer_auto_top_up_amount-#{customer_id}",
170				"jmp_customer_monthly_overage_limit-#{customer_id}"
171			),
172			@redis.smembers("jmp_customer_feature_flags-#{customer_id}")
173		]).then { |r, flags|
174			r.transform_keys { |k| k.match(/^jmp_customer_([^-]+)/)[1].to_sym }
175			 .merge(feature_flags: flags.map(&:to_sym))
176		}
177	end
178
179	SQL = <<~SQL
180		SELECT
181			COALESCE(balance,0) AS balance, plan_name, expires_at,
182			parent_customer_id, pending
183		FROM customer_plans LEFT JOIN balances USING (customer_id)
184		WHERE customer_id=$1 LIMIT 1
185	SQL
186
187	def tndetails(sgx)
188		return {} unless sgx.registered?
189
190		LazyObject.new { @bandwidth_tn_repo.find(sgx.registered?.phone) || {} }
191	end
192
193	def find_inner(cid, jid, tel=nil)
194		set_user.call(customer_id: cid, jid: jid)
195		EMPromise.all([
196			@sgx_repo.get(cid, tel: tel).then { |sgx| { sgx: sgx } },
197			@db.query_one(SQL, cid, default: {}),
198			fetch_redis(cid)
199		]).then { |all| all.reduce(&:merge) }.then do |data|
200			Customer.extract(cid, jid, tndetails: tndetails(data[:sgx]), **data)
201		end
202	end
203end