customer_usage.rb

 1# frozen_string_literal: true
 2
 3require_relative "./usage_report"
 4
 5class CustomerUsage
 6	def initialize(customer_id)
 7		@customer_id = customer_id
 8	end
 9
10	def report(range)
11		EMPromise.all([
12			messages_by_day(range),
13			minutes_by_day(range)
14		]).then do |args|
15			UsageReport.new(range, *args)
16		end
17	end
18
19	def messages_by_day(range)
20		EMPromise.all(range.first.downto(range.last).map { |day|
21			REDIS.zscore(
22				"jmp_customer_outbound_messages-#{@customer_id}",
23				day.strftime("%Y%m%d")
24			).then { |c| [day, c.to_i] if c }
25		}).then { |r| Hash[r.compact].tap { |h| h.default = 0 } }
26	end
27
28	QUERY_FOR_MINUTES = <<~SQL
29		SELECT
30			date_trunc('day', start)::date as day,
31			CEIL(SUM(billsec)/60.0)::integer as minutes
32		FROM cdr
33		WHERE customer_id=$1 and start >= $3 and start < $2
34		GROUP BY date_trunc('day', start);
35	SQL
36
37	def minutes_by_day(range)
38		DB.query_defer(
39			QUERY_FOR_MINUTES,
40			[@customer_id, range.first, range.last]
41		).then do |result|
42			result.each_with_object(Hash.new(0)) do |row, minutes|
43				minutes[row["day"]] = row["minutes"]
44			end
45		end
46	end
47end