# frozen_string_literal: true
require "value_semantics/monkey_patched"
require_relative "call_attempt"
class CallAttemptRepo
value_semantics do
db Anything(), default: LazyObject.new { DB }
end
def find(customer, other_tel, digits=nil, direction=:outbound)
EMPromise.all([
find_rate(customer.plan_name, other_tel, direction),
find_usage(customer.customer_id)
]).then do |(rate, usage)|
CallAttempt.for(customer, other_tel, rate, usage, digits)
end
end
protected
def find_usage(customer_id)
promise = db.query_defer(<<~SQL, [customer_id])
SELECT COALESCE(SUM(charge), 0) AS a FROM cdr_with_charge
WHERE
customer_id=$1 AND
start > DATE_TRUNC('month', LOCALTIMESTAMP)
SQL
promise.then { |rows| -(rows.first&.dig("a") || 0) }
end
def find_rate(plan_name, other_tel, direction)
promise = db.query_defer(<<~SQL, [plan_name, other_tel, direction])
SELECT rate FROM call_rates
WHERE
plan_name=$1 AND
$2 LIKE prefix || '%' AND
direction=$3
ORDER BY prefix DESC
LIMIT 1;
SQL
promise.then { |rows| rows.first&.dig("rate") }
end
end