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?(String)
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 [] 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"])
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 = value.sub(/\ALocalInventory\//, "").split("/", 2)
219 LocalInventory.new(Tn.new(tel), account)
220 else
221 Bandwidth.new(Tn.new(value))
222 end
223 end
224
225 def initialize(tel)
226 @tel = tel
227 end
228
229 def formatted_tel
230 @tel =~ /\A\+1(\d{3})(\d{3})(\d+)\Z/
231 "(#{$1}) #{$2}-#{$3}"
232 end
233
234 def to_s
235 formatted_tel
236 end
237
238 class Option < Tn
239 def initialize(full_number:, city:, state:, **)
240 @tel = "+1#{full_number}"
241 @locality = city
242 @region = state
243 end
244
245 def option
246 op = Blather::Stanza::X::Field::Option.new(value: tel, label: to_s)
247 op << reference
248 op
249 end
250
251 def reference
252 Nokogiri::XML::Builder.new { |xml|
253 xml.reference(
254 xmlns: "urn:xmpp:reference:0",
255 begin: 0,
256 end: formatted_tel.length - 1,
257 type: "data",
258 uri: "tel:#{tel}"
259 )
260 }.doc.root
261 end
262
263 def to_s
264 "#{formatted_tel} (#{@locality}, #{@region})"
265 end
266 end
267
268 class Bandwidth < SimpleDelegator
269 def pending_value
270 tel
271 end
272
273 def reserve(customer)
274 BandwidthTnReservationRepo.new.ensure(customer, tel)
275 end
276
277 def order(_, customer)
278 BandwidthTnReservationRepo.new.get(customer, tel).then do |rid|
279 BandwidthTNOrder.create(
280 tel,
281 customer_order_id: customer.customer_id,
282 reservation_id: rid
283 ).then(&:poll)
284 end
285 end
286 end
287
288 class LocalInventory < SimpleDelegator
289 def self.fetch(tn, db: DB)
290 db.query_defer("SELECT * FROM tel_inventory WHERE tel = $1", [tn])
291 .then { |rows|
292 rows.first&.then { |row|
293 new(Tn::Option.new(
294 full_number: row["tel"].sub(/\A\+1/, ""),
295 city: row["locality"],
296 state: row["region"]
297 ), row["bandwidth_account_id"])
298 }
299 }
300 end
301
302 def initialize(tn, bandwidth_account_id)
303 super(tn)
304 @bandwidth_account_id = bandwidth_account_id
305 end
306
307 def pending_value
308 "LocalInventory/#{tel}/#{@bandwidth_account_id}"
309 end
310
311 def reserve(*)
312 EMPromise.resolve(nil)
313 end
314
315 def order(db, _customer)
316 # Move always moves to wrong account, oops
317 # Also probably can't move from/to same account
318 # BandwidthTnRepo.new.move(
319 # tel, customer.customer_id, @bandwidth_account_id
320 # )
321 db.exec_defer("DELETE FROM tel_inventory WHERE tel = $1", [tel])
322 .then { |r| raise unless r.cmd_tuples.positive? }
323 end
324 end
325 end
326
327 class Q
328 def self.register(regex, &block)
329 @queries ||= []
330 @queries << [regex, block]
331 end
332
333 def self.for(q, **kwa)
334 q = replace_region_names(q) unless q.start_with?("~")
335
336 @queries.each do |(regex, block)|
337 match_data = (q =~ regex)
338 return block.call($1 || $&, *$~.to_a[2..-1], **kwa) if match_data
339 end
340
341 raise Fail, "Format not recognized: #{q}"
342 end
343
344 def self.replace_region_names(query)
345 ISO3166::Country[:US].subdivisions.merge(
346 ISO3166::Country[:CA].subdivisions
347 ).reduce(query) do |q, (code, region)|
348 ([region.name] + Array(region.unofficial_names))
349 .reduce(q) do |r, name|
350 r.sub(/#{name}\s*(?!,)/i, code)
351 end
352 end
353 end
354
355 def initialize(q, **)
356 @q = q
357 end
358
359 def fallback
360 []
361 end
362
363 {
364 areaCode: [:AreaCode, /\A[2-9][0-9]{2}\Z/],
365 npaNxx: [:NpaNxx, /\A(?:[2-9][0-9]{2}){2}\Z/],
366 npaNxxx: [:NpaNxxx, /\A(?:[2-9][0-9]{2}){2}[0-9]\Z/]
367 }.each do |k, args|
368 klass = const_set(
369 args[0],
370 Class.new(Q) {
371 define_method(:iris_query) do
372 { k => @q }
373 end
374
375 define_method(:sql_query) do
376 [
377 "SELECT * FROM tel_inventory " \
378 "WHERE available_after < LOCALTIMESTAMP AND tel LIKE $1",
379 "+1#{@q}%"
380 ]
381 end
382 }
383 )
384
385 args[1..-1].each do |regex|
386 register(regex) { |q, **| klass.new(q) }
387 end
388 end
389
390 class PostalCode < Q
391 Q.register(/\A\d{5}(?:-\d{4})?\Z/, &method(:new))
392
393 def iris_query
394 { zip: @q }
395 end
396
397 def sql_query
398 nil
399 end
400 end
401
402 class LocalVanity < Q
403 Q.register(/\A~(.+)\Z/, &method(:new))
404
405 def iris_query
406 { localVanity: @q }
407 end
408
409 def sql_query
410 [
411 "SELECT * FROM tel_inventory " \
412 "WHERE available_after < LOCALTIMESTAMP AND tel LIKE $1",
413 "%#{q_digits}%"
414 ]
415 end
416
417 def q_digits
418 @q
419 .gsub(/[ABC]/i, "2")
420 .gsub(/[DEF]/i, "3")
421 .gsub(/[GHI]/i, "4")
422 .gsub(/[JKL]/i, "5")
423 .gsub(/[MNO]/i, "6")
424 .gsub(/[PQRS]/i, "7")
425 .gsub(/[TUV]/i, "8")
426 .gsub(/[WXYZ]/i, "9")
427 end
428 end
429
430 class State
431 Q.register(/\A[a-zA-Z]{2}\Z/, &method(:new))
432
433 STATE_MAP = {
434 "QC" => "PQ"
435 }.freeze
436
437 def initialize(state, **)
438 @state = STATE_MAP.fetch(state.upcase, state.upcase)
439 end
440
441 def fallback
442 []
443 end
444
445 def iris_query
446 { state: @state }
447 end
448
449 def sql_query
450 [
451 "SELECT * FROM tel_inventory " \
452 "WHERE available_after < LOCALTIMESTAMP AND region = $1",
453 @state
454 ]
455 end
456
457 def to_s
458 @state
459 end
460 end
461
462 class CityState
463 Q.register(/\A([^,]+)\s*,\s*([a-zA-Z]{2})\Z/, &method(:new))
464
465 CITY_MAP = {
466 "ajax" => "Ajax-Pickering",
467 "kitchener" => "Kitchener-Waterloo",
468 "new york" => "New York City",
469 "pickering" => "Ajax-Pickering",
470 "sault ste marie" => "sault sainte marie",
471 "sault ste. marie" => "sault sainte marie",
472 "south durham" => "Durham",
473 "township of langley" => "Langley",
474 "waterloo" => "Kitchener-Waterloo",
475 "west durham" => "Durham"
476 }.freeze
477
478 def initialize(city, state, db: DB, memcache: MEMCACHE)
479 @city = CITY_MAP.fetch(city.downcase, city)
480 @state = State.new(state)
481 @db = db
482 @memcache = memcache
483 end
484
485 def fallback
486 LazyObject.new do
487 AreaCodeRepo.new(
488 db: @db,
489 geo_code_repo: GeoCodeRepo.new(memcache: @memcache)
490 ).find(to_s).sync.map { |area_code|
491 AreaCode.new(area_code)
492 }
493 end
494 end
495
496 def iris_query
497 @state.iris_query.merge(city: @city)
498 end
499
500 def sql_query
501 [
502 "SELECT * FROM tel_inventory " \
503 "WHERE available_after < LOCALTIMESTAMP " \
504 "AND region = $1 AND locality = $2",
505 @state.to_s, @city
506 ]
507 end
508
509 def to_s
510 "#{@city}, #{@state}"
511 end
512 end
513 end
514 end
515end