~singpolyma/sgx-jmp

ref: da30c371e56b8bb577897f1151b59c24e209127f sgx-jmp/lib/cdr.rb -rw-r--r-- 1.4 KiB
da30c371Stephen Paul Weber Allow finishing admin command 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# frozen_string_literal: true

require "value_semantics/monkey_patched"

class CDR
	module Disposition
		def self.===(other)
			["NO ANSWER", "ANSWERED", "BUSY", "FAILED", "VOICEMAIL"].include?(other)
		end

		CAUSES = {
			timeout: "NO ANSWER",
			rejected: "NO ANSWER",
			cancel: "NO ANSWER",
			hangup: "ANSWERED",
			busy: "BUSY"
		}.freeze

		def self.for(cause, tag)
			return tag if tag == "VOICEMAIL"

			CAUSES.fetch(cause.to_sym, "FAILED")
		end
	end

	value_semantics do
		cdr_id String
		customer_id String
		start Time
		billsec Integer
		disposition Disposition
		tel(/\A\+\d+\Z/)
		direction Either(:inbound, :outbound)
	end

	def self.for(event, **kwargs)
		start = Time.parse(event["startTime"])

		new({
			cdr_id: "sgx-jmp/#{event['callId']}",
			start: start,
			billsec: (Time.parse(event["endTime"]) - start).ceil,
			disposition: Disposition.for(event["cause"], event["tag"])
		}.merge(kwargs))
	end

	def self.for_inbound(customer_id, event)
		self.for(
			event,
			customer_id: customer_id,
			tel: event["from"],
			direction: :inbound
		)
	end

	def self.for_outbound(event)
		self.for(
			event,
			customer_id: event["from"].sub(/^\+/, ""),
			tel: event["to"],
			direction: :outbound
		)
	end

	def save
		columns, values = to_h.to_a.transpose
		DB.query_defer(<<~SQL, values)
			INSERT INTO cdr (#{columns.join(',')})
			VALUES ($1, $2, $3, $4, $5, $6, $7)
		SQL
	end
end