~singpolyma/sgx-jmp

ref: 48adae14cdd37c6b74b5b04bae279823fa85fd43 sgx-jmp/lib/call_attempt_repo.rb -rw-r--r-- 1.1 KiB
48adae14Stephen Paul Weber Try auto top up / low balance notify when not enough balance for a call 1 year, 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# frozen_string_literal: true

require "value_semantics/monkey_patched"
require "lazy_object"

require_relative "call_attempt"

class CallAttemptRepo
	value_semantics do
		db Anything(), default: LazyObject.new { DB }
	end

	def find(customer, other_tel, direction: :outbound, **kwargs)
		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, direction: direction, **kwargs
			)
		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