diff --git a/lib/tel_selections.rb b/lib/tel_selections.rb index ef7aa49fe7108719c8070be413b4d7e85660cd3d..c6bf949011f40ca75ec13ea2d8404eeb82c2eea5 100644 --- a/lib/tel_selections.rb +++ b/lib/tel_selections.rb @@ -87,8 +87,8 @@ class TelSelections q.iris_query .merge(enableTNDetail: true, LCA: false) .merge(Quantity.for(form).iris_query), - fallback: q.fallback, - memcache: memcache + q.sql_query, + fallback: q.fallback, memcache: memcache, db: db ) end @@ -101,30 +101,50 @@ class TelSelections "810" end - def initialize(iris_query, fallback: [], memcache: MEMCACHE) + def initialize( + iris_query, sql_query, fallback: [], memcache: MEMCACHE, db: DB + ) @iris_query = iris_query + @sql_query = sql_query @fallback = fallback @memcache = memcache + @db = db end def tns Command.log.debug("BandwidthIris::AvailableNumber.list", @iris_query) unless (result = fetch_cache) - result = BandwidthIris::AvailableNumber.list(@iris_query) + result = + BandwidthIris::AvailableNumber.list(@iris_query) + + fetch_local_inventory.sync end return next_fallback if result.empty? && !@fallback.empty? result.map { |tn| Tn.new(**tn) } end + def fetch_local_inventory + @db.query_defer(@sql_query[0], @sql_query[1..-1]).then { |rows| + rows.map { |row| + { + full_number: row["tel"].sub(/\A\+1/, ""), + city: row["locality"], + state: row["region"] + } + } + } + end + def next_fallback @memcache.set(cache_key, CBOR.encode([]), 43200) + fallback = @fallback.shift self.class.new( - @fallback.shift.iris_query.merge( + fallback.iris_query.merge( enableTNDetail: true, quantity: @iris_query[:quantity] ), + fallback.sql_query, fallback: @fallback, - memcache: @memcache + memcache: @memcache, db: @db ).tns end diff --git a/test/test_tel_selections.rb b/test/test_tel_selections.rb index 00d960cf8f11f56e110d9b570c75c481d0853e6e..3315796f1d2a3a81acfa7d7f7497d7965b8d5e6f 100644 --- a/test/test_tel_selections.rb +++ b/test/test_tel_selections.rb @@ -122,6 +122,35 @@ class TelSelectionsTest < Minitest::Test ) end em :test_fallback + + def test_local_inventory + stub_request( + :get, + "https://dashboard.bandwidth.com/v1.0/accounts//availableNumbers" \ + "?city=Kitchener-Waterloo&enableTNDetail=true&lCA=false&" \ + "quantity=10&state=ON" + ).to_return(status: 200, body: "") + + db = FakeDB.new( + ["ON", "Kitchener-Waterloo"] => [{ + "tel" => "+122655512345", + "region" => "ON", + "locality" => "Kitchener-Waterloo" + }] + ) + form = Blather::Stanza::X.new + form.fields = [{ var: "q", value: "Kitchener, ON" }] + tns = execute_command do + TelSelections::ChooseTel::AvailableNumber + .for(form, db: db, memcache: FakeMemcache.new) + .tns + end + assert_equal( + ["(226) 555-12345 (Kitchener-Waterloo, ON)"], + tns.map(&:to_s) + ) + end + em :test_local_inventory end class TnTest < Minitest::Test