~singpolyma/sgx-jmp

ref: 2f7a1b60192a14c86ef9a1f727ea9369cfedc2c6 sgx-jmp/lib/customer_plan.rb -rw-r--r-- 1.8 KiB
2f7a1b60Stephen Paul Weber Merge branch 'more-tel-selection-coverage' 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
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
73
74
75
76
77
78
79
80
81
82
83
84
# frozen_string_literal: true

require "forwardable"

require_relative "em"

class CustomerPlan
	extend Forwardable

	attr_reader :expires_at

	def_delegator :@plan, :name, :plan_name
	def_delegators :@plan, :currency, :merchant_account, :monthly_price

	def initialize(customer_id, plan: nil, expires_at: Time.now)
		@customer_id = customer_id
		@plan = plan || OpenStruct.new
		@expires_at = expires_at
	end

	def active?
		plan_name && @expires_at > Time.now
	end

	def with_plan_name(plan_name)
		self.class.new(
			@customer_id,
			plan: Plan.for(plan_name),
			expires_at: @expires_at
		)
	end

	def auto_top_up_amount
		REDIS.get("jmp_customer_auto_top_up_amount-#{@customer_id}").then(&:to_i)
	end

	def bill_plan
		EM.promise_fiber do
			DB.transaction do
				charge_for_plan
				add_one_month_to_current_plan unless activate_plan_starting_now
			end
		end
	end

	def activate_plan_starting_now
		DB.exec(<<~SQL, [@customer_id, plan_name]).cmd_tuples.positive?
			INSERT INTO plan_log
				(customer_id, plan_name, date_range)
			VALUES ($1, $2, tsrange(LOCALTIMESTAMP, LOCALTIMESTAMP + '1 month'))
			ON CONFLICT DO NOTHING
		SQL
	end

protected

	def charge_for_plan
		params = [
			@customer_id,
			"#{@customer_id}-bill-#{plan_name}-at-#{Time.now.to_i}",
			-@plan.monthly_price
		]
		DB.exec(<<~SQL, params)
			INSERT INTO transactions
				(customer_id, transaction_id, created_at, amount)
			VALUES ($1, $2, LOCALTIMESTAMP, $3)
		SQL
	end

	def add_one_month_to_current_plan
		DB.exec(<<~SQL, [@customer_id])
			UPDATE plan_log SET date_range=range_merge(
				date_range,
				tsrange(
					LOCALTIMESTAMP,
					GREATEST(upper(date_range), LOCALTIMESTAMP) + '1 month'
				)
			)
			WHERE
				customer_id=$1 AND
				date_range && tsrange(LOCALTIMESTAMP, LOCALTIMESTAMP + '1 month')
		SQL
	end
end