~singpolyma/sgx-jmp

ref: a9ebca9a66da1fa0e10bee066a6ba71fe31177a3 sgx-jmp/lib/customer_usage.rb -rw-r--r-- 1.1 KiB
a9ebca9aStephen Paul Weber Usage command 1 year, 9 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
# frozen_string_literal: true

require_relative "./usage_report"

class CustomerUsage
	def initialize(customer_id)
		@customer_id = customer_id
	end

	def report(range)
		EMPromise.all([
			messages_by_day(range),
			minutes_by_day(range)
		]).then do |args|
			UsageReport.new(range, *args)
		end
	end

	def messages_by_day(range)
		EMPromise.all(range.first.downto(range.last).map { |day|
			REDIS.zscore(
				"jmp_customer_outbound_messages-#{@customer_id}",
				day.strftime("%Y%m%d")
			).then { |c| [day, c.to_i] if c }
		}).then { |r| Hash[r.compact].tap { |h| h.default = 0 } }
	end

	QUERY_FOR_MINUTES = <<~SQL
		SELECT
			date_trunc('day', start)::date as day,
			CEIL(SUM(billsec)/60.0)::integer as minutes
		FROM cdr
		WHERE customer_id=$1 and start >= $3 and start < $2
		GROUP BY date_trunc('day', start);
	SQL

	def minutes_by_day(range)
		DB.query_defer(
			QUERY_FOR_MINUTES,
			[@customer_id, range.first, range.last]
		).then do |result|
			result.each_with_object(Hash.new(0)) do |row, minutes|
				minutes[row["day"]] = row["minutes"]
			end
		end
	end
end