tel_selections.rb

  1# frozen_string_literal: true
  2
  3require "ruby-bandwidth-iris"
  4Faraday.default_adapter = :em_synchrony
  5
  6require "cbor"
  7require "countries"
  8
  9require_relative "area_code_repo"
 10require_relative "form_template"
 11
 12class TelSelections
 13	THIRTY_DAYS = 60 * 60 * 24 * 30
 14
 15	def initialize(redis: REDIS, db: DB, memcache: MEMCACHE)
 16		@redis = redis
 17		@memcache = memcache
 18		@db = db
 19	end
 20
 21	def set(jid, tel)
 22		@redis.setex("pending_tel_for-#{jid}", THIRTY_DAYS, tel.pending_value)
 23	end
 24
 25	def set_tel(jid, tel)
 26		ChooseTel::Tn::LocalInventory.fetch(tel).then do |local_inv|
 27			set(
 28				jid,
 29				local_inv || ChooseTel::Tn::Bandwidth.new(ChooseTel::Tn.new(tel))
 30			)
 31		end
 32	end
 33
 34	def delete(jid)
 35		@redis.del("pending_tel_for-#{jid}")
 36	end
 37
 38	def [](jid)
 39		@redis.get("pending_tel_for-#{jid}").then do |tel|
 40			tel ? HaveTel.new(tel) : ChooseTel.new(db: @db, memcache: @memcache)
 41		end
 42	end
 43
 44	class HaveTel
 45		def initialize(tel)
 46			@tel = ChooseTel::Tn.for_pending_value(tel)
 47		end
 48
 49		def choose_tel
 50			EMPromise.resolve(@tel)
 51		end
 52	end
 53
 54	class ChooseTel
 55		class Fail < RuntimeError; end
 56
 57		def initialize(db: DB, memcache: MEMCACHE)
 58			@db = db
 59			@memcache = memcache
 60		end
 61
 62		def choose_tel(error: nil)
 63			Command.reply { |reply|
 64				reply.allowed_actions = [:next]
 65				reply.command << FormTemplate.render("tn_search", error: error)
 66			}.then do |iq|
 67				available = AvailableNumber.for(iq.form, db: @db, memcache: @memcache)
 68				next available if available.is_a?(Tn::Bandwidth)
 69
 70				choose_from_list(available.tns)
 71			rescue Fail
 72				choose_tel(error: $!.to_s)
 73			end
 74		end
 75
 76		def choose_from_list(tns)
 77			raise Fail, "No numbers found, try another search." if tns.empty?
 78
 79			Command.reply { |reply|
 80				reply.allowed_actions = [:next, :prev]
 81				reply.command << FormTemplate.render("tn_list", tns: tns)
 82			}.then { |iq|
 83				choose_from_list_result(tns, iq)
 84			}
 85		end
 86
 87		def choose_from_list_result(tns, iq)
 88			tel = iq.form.field("tel")&.value
 89			return choose_tel if iq.prev? || !tel
 90
 91			tns.find { |tn| tn.tel == tel } || Tn::Bandwidth.new(Tn.new(tel))
 92		end
 93
 94		class AvailableNumber
 95			def self.for(form, db: DB, memcache: MEMCACHE)
 96				qs = form.field("q")&.value.to_s.strip
 97				return Tn.for_pending_value(qs) if qs =~ /\A\+1\d{10}\Z/
 98
 99				quantity = Quantity.for(form)
100				q = Q.for(feelinglucky(qs, form), db: db, memcache: memcache)
101
102				new(
103					q.iris_query
104					.merge(enableTNDetail: true, LCA: false),
105					q.sql_query, quantity,
106					fallback: q.fallback, memcache: memcache, db: db
107				)
108			end
109
110			ACTION_FIELD = "http://jabber.org/protocol/commands#actions"
111
112			def self.feelinglucky(q, form)
113				return q unless q.empty?
114				return q unless form.field(ACTION_FIELD)&.value == "feelinglucky"
115
116				"810"
117			end
118
119			def initialize(
120				iris_query, sql_query, quantity,
121				fallback: [], memcache: MEMCACHE, db: DB
122			)
123				@iris_query = iris_query.merge(quantity.iris_query)
124				@sql_query = sql_query
125				@quantity = quantity
126				@fallback = fallback
127				@memcache = memcache
128				@db = db
129			end
130
131			def tns
132				Command.log.debug("BandwidthIris::AvailableNumber.list", @iris_query)
133				unless (result = fetch_cache)
134					result = fetch_bandwidth_inventory + fetch_local_inventory.sync
135				end
136				return next_fallback if result.empty? && !@fallback.empty?
137
138				@quantity.limit(result)
139			end
140
141			def fetch_bandwidth_inventory
142				BandwidthIris::AvailableNumber
143					.list(@iris_query)
144					.map { |tn| Tn::Bandwidth.new(Tn::Option.new(**tn)) }
145			rescue BandwidthIris::APIError
146				raise Fail, $!.message
147			end
148
149			def fetch_local_inventory
150				return EMPromise.resolve([]) unless @sql_query
151
152				@db.query_defer(@sql_query[0], @sql_query[1..-1]).then { |rows|
153					rows.map { |row|
154						Tn::LocalInventory.new(Tn::Option.new(
155							full_number: row["tel"].sub(/\A\+1/, ""),
156							city: row["locality"],
157							state: row["region"]
158						), row["bandwidth_account_id"], price: row["premium_price"])
159					}
160				}
161			end
162
163			def next_fallback
164				@memcache.set(cache_key, CBOR.encode([]), 43200)
165				fallback = @fallback.shift
166				self.class.new(
167					fallback.iris_query.merge(enableTNDetail: true),
168					fallback.sql_query,
169					@quantity,
170					fallback: @fallback,
171					memcache: @memcache, db: @db
172				).tns
173			end
174
175			def fetch_cache
176				promise = EMPromise.new
177				@memcache.get(cache_key, &promise.method(:fulfill))
178				result = promise.sync
179				result ? CBOR.decode(result) : nil
180			end
181
182			def cache_key
183				"BandwidthIris_#{@iris_query.to_a.flatten.join(',')}"
184			end
185
186			class Quantity
187				def self.for(form)
188					return new(10) if form.field(ACTION_FIELD)&.value == "feelinglucky"
189
190					rsm_max = form.find(
191						"ns:set/ns:max",
192						ns: "http://jabber.org/protocol/rsm"
193					).first
194					return new(rsm_max.content.to_i) if rsm_max
195
196					new(10)
197				end
198
199				def initialize(quantity)
200					@quantity = quantity
201				end
202
203				def limit(result)
204					(result || [])[0..@quantity - 1]
205				end
206
207				def iris_query
208					{ quantity: [@quantity, 500].min }
209				end
210			end
211		end
212
213		class Tn
214			attr_reader :tel
215
216			def self.for_pending_value(value)
217				if value.start_with?("LocalInventory/")
218					tel, account, price =
219						value.sub(/\ALocalInventory\//, "").split("/", 3)
220					LocalInventory.new(Tn.new(tel), account, price: price.to_d)
221				else
222					Bandwidth.new(Tn.new(value))
223				end
224			end
225
226			def initialize(tel)
227				@tel = tel
228			end
229
230			def formatted_tel
231				@tel =~ /\A\+1(\d{3})(\d{3})(\d+)\Z/
232				"(#{$1}) #{$2}-#{$3}"
233			end
234
235			def to_s
236				formatted_tel
237			end
238
239			def price
240				0
241			end
242
243			def charge(*); end
244
245			class Option < Tn
246				def initialize(full_number:, city:, state:, **)
247					@tel = "+1#{full_number}"
248					@locality = city
249					@region = state
250				end
251
252				def option
253					op = Blather::Stanza::X::Field::Option.new(value: tel, label: to_s)
254					op << reference
255					op
256				end
257
258				def reference
259					Nokogiri::XML::Builder.new { |xml|
260						xml.reference(
261							xmlns: "urn:xmpp:reference:0",
262							begin: 0,
263							end: formatted_tel.length - 1,
264							type: "data",
265							uri: "tel:#{tel}"
266						)
267					}.doc.root
268				end
269
270				def to_s
271					"#{formatted_tel} (#{@locality}, #{@region})"
272				end
273			end
274
275			class Bandwidth < SimpleDelegator
276				def pending_value
277					tel
278				end
279
280				def reserve(customer)
281					BandwidthTnReservationRepo.new.ensure(customer, tel)
282				end
283
284				def order(_, customer)
285					BandwidthTnReservationRepo.new.get(customer, tel).then do |rid|
286						BandwidthTNOrder.create(
287							tel,
288							customer_order_id: customer.customer_id,
289							reservation_id: rid
290						).then(&:poll)
291					end
292				end
293			end
294
295			class LocalInventory < SimpleDelegator
296				attr_reader :price
297
298				def initialize(tn, bandwidth_account_id, price: 0)
299					super(tn)
300					@bandwidth_account_id = bandwidth_account_id
301					@price = price || 0
302				end
303
304				# Creates and inserts transaction charging the customer
305				# for the phone number. If price <= 0 this is a noop.
306				# This method never checks customer balance.
307				#
308				# @param customer [Customer] the customer to charge
309				def charge(customer)
310					return if price <= 0
311
312					transaction(customer).insert
313				end
314
315				# @param customer [Customer] the customer to charge
316				def transaction(customer)
317					Transaction.new(
318						customer_id: customer.customer_id,
319						transaction_id:
320							"#{customer.customer_id}-bill-#{@tel}-at-#{Time.now.to_i}",
321						amount: -price,
322						note: "One-time charge for number: #{formatted_tel}",
323						ignore_duplicate: false
324					)
325				end
326
327				def to_s
328					super + (price > 0 ? " +$%.2f" % price : "")
329				end
330
331				def self.fetch(tn, db: DB)
332					db.query_defer("SELECT * FROM tel_inventory WHERE tel = $1", [tn])
333						.then { |rows|
334						rows.first&.then { |row|
335							new(Tn::Option.new(
336								full_number: row["tel"].sub(/\A\+1/, ""),
337								city: row["locality"],
338								state: row["region"]
339							), row["bandwidth_account_id"], price: row["premium_price"])
340						}
341					}
342				end
343
344				def pending_value
345					"LocalInventory/#{tel}/#{@bandwidth_account_id}/#{price}"
346				end
347
348				def reserve(*)
349					EMPromise.resolve(nil)
350				end
351
352				def order(db, _customer)
353					# Move always moves to wrong account, oops
354					# Also probably can't move from/to same account
355					# BandwidthTnRepo.new.move(
356					# 	tel, customer.customer_id, @bandwidth_account_id
357					# )
358					db.exec_defer("DELETE FROM tel_inventory WHERE tel = $1", [tel])
359						.then { |r| raise unless r.cmd_tuples.positive? }
360				end
361			end
362		end
363
364		class Q
365			def self.register(regex, &block)
366				@queries ||= []
367				@queries << [regex, block]
368			end
369
370			def self.for(q, **kwa)
371				q = replace_region_names(q) unless q.start_with?("~")
372
373				@queries.each do |(regex, block)|
374					match_data = (q =~ regex)
375					return block.call($1 || $&, *$~.to_a[2..-1], **kwa) if match_data
376				end
377
378				raise Fail, "Format not recognized: #{q}"
379			end
380
381			def self.replace_region_names(query)
382				ISO3166::Country[:US].subdivisions.merge(
383					ISO3166::Country[:CA].subdivisions
384				).reduce(query) do |q, (code, region)|
385					([region.name] + Array(region.unofficial_names))
386						.reduce(q) do |r, name|
387							r.sub(/#{name}\s*(?!,)/i, code)
388						end
389				end
390			end
391
392			def initialize(q, **)
393				@q = q
394			end
395
396			def fallback
397				[]
398			end
399
400			{
401				areaCode: [:AreaCode, /\A[2-9][0-9]{2}\Z/],
402				npaNxx: [:NpaNxx, /\A(?:[2-9][0-9]{2}){2}\Z/],
403				npaNxxx: [:NpaNxxx, /\A(?:[2-9][0-9]{2}){2}[0-9]\Z/]
404			}.each do |k, args|
405				klass = const_set(
406					args[0],
407					Class.new(Q) {
408						define_method(:iris_query) do
409							{ k => @q }
410						end
411
412						define_method(:sql_query) do
413							[
414								"SELECT * FROM tel_inventory " \
415								"WHERE available_after < LOCALTIMESTAMP AND tel LIKE $1",
416								"+1#{@q}%"
417							]
418						end
419					}
420				)
421
422				args[1..-1].each do |regex|
423					register(regex) { |q, **| klass.new(q) }
424				end
425			end
426
427			class PostalCode < Q
428				Q.register(/\A\d{5}(?:-\d{4})?\Z/, &method(:new))
429
430				def iris_query
431					{ zip: @q }
432				end
433
434				def sql_query
435					nil
436				end
437			end
438
439			class LocalVanity < Q
440				Q.register(/\A~(.+)\Z/, &method(:new))
441
442				def iris_query
443					{ localVanity: @q }
444				end
445
446				def sql_query
447					[
448						"SELECT * FROM tel_inventory " \
449						"WHERE available_after < LOCALTIMESTAMP AND tel LIKE $1",
450						"%#{q_digits}%"
451					]
452				end
453
454				def q_digits
455					@q
456						.gsub(/[ABC]/i, "2")
457						.gsub(/[DEF]/i, "3")
458						.gsub(/[GHI]/i, "4")
459						.gsub(/[JKL]/i, "5")
460						.gsub(/[MNO]/i, "6")
461						.gsub(/[PQRS]/i, "7")
462						.gsub(/[TUV]/i, "8")
463						.gsub(/[WXYZ]/i, "9")
464				end
465			end
466
467			class State
468				Q.register(/\A[a-zA-Z]{2}\Z/, &method(:new))
469
470				STATE_MAP = {
471					"QC" => "PQ"
472				}.freeze
473
474				def initialize(state, **)
475					@state = STATE_MAP.fetch(state.upcase, state.upcase)
476				end
477
478				def fallback
479					[]
480				end
481
482				def iris_query
483					{ state: @state }
484				end
485
486				def sql_query
487					[
488						"SELECT * FROM tel_inventory " \
489						"WHERE available_after < LOCALTIMESTAMP AND region = $1",
490						@state
491					]
492				end
493
494				def to_s
495					@state
496				end
497			end
498
499			class CityState
500				Q.register(/\A([^,]+)\s*,\s*([a-zA-Z]{2})\Z/, &method(:new))
501
502				CITY_MAP = {
503					"ajax" => "Ajax-Pickering",
504					"kitchener" => "Kitchener-Waterloo",
505					"new york" => "New York City",
506					"pickering" => "Ajax-Pickering",
507					"sault ste marie" => "sault sainte marie",
508					"sault ste. marie" => "sault sainte marie",
509					"south durham" => "Durham",
510					"township of langley" => "Langley",
511					"waterloo" => "Kitchener-Waterloo",
512					"west durham" => "Durham"
513				}.freeze
514
515				def initialize(city, state, db: DB, memcache: MEMCACHE)
516					@city = CITY_MAP.fetch(city.downcase, city)
517					@state = State.new(state)
518					@db = db
519					@memcache = memcache
520				end
521
522				def fallback
523					LazyObject.new do
524						AreaCodeRepo.new(
525							db: @db,
526							geo_code_repo: GeoCodeRepo.new(memcache: @memcache)
527						).find(to_s).sync.map { |area_code|
528							AreaCode.new(area_code)
529						}
530					end
531				end
532
533				def iris_query
534					@state.iris_query.merge(city: @city)
535				end
536
537				def sql_query
538					[
539						"SELECT * FROM tel_inventory " \
540						"WHERE available_after < LOCALTIMESTAMP " \
541						"AND region = $1 AND locality = $2",
542						@state.to_s, @city
543					]
544				end
545
546				def to_s
547					"#{@city}, #{@state}"
548				end
549			end
550		end
551	end
552end