~singpolyma/jmp-pay

ref: 7c438f83822c6a2f41da32b93bbaa48203f0932b jmp-pay/bin/billing_monthly_cronjob -rwxr-xr-x 3.5 KiB
7c438f83Stephen Paul Weber Notify customer when renewal fails due to low balance 1 year, 5 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/ruby
# frozen_string_literal: true

# Usage: ./billing_monthly_cronjob '{
#        healthchecks_url = "https://hc-ping.com/...",
#        notify_using = {
#          jid = "",
#          password = "",
#          target = \(tel: Text) -> "${tel}@cheogram.com"
#        },
#        plans = ./plans.dhall
#        }'

require "bigdecimal"
require "date"
require "dhall"
require "net/http"
require "pg"
require "redis"

require_relative "../lib/blather_notify"

CONFIG = Dhall.load(<<-DHALL).sync
	let Quota = < unlimited | limited: { included: Natural, price: Natural } >
	let Currency = < CAD | USD >
	in
	(#{ARGV[0]}) : {
		healthchecks_url: Text,
		notify_using: { jid: Text, password: Text, target: Text -> Text },
		plans: List {
			name: Text,
			currency: Currency,
			monthly_price: Natural,
			minutes: Quota,
			messages: Quota
		}
	}
DHALL

Net::HTTP.post_form(URI("#{CONFIG[:healthchecks_url]}/start"), {})

REDIS = Redis.new
db = PG.connect(dbname: "jmp")
db.type_map_for_results = PG::BasicTypeMapForResults.new(db)
db.type_map_for_queries = PG::BasicTypeMapForQueries.new(db)

BlatherNotify.start(
	CONFIG[:notify_using][:jid],
	CONFIG[:notify_using][:password]
)

RENEW_UNTIL = Date.today >> 1

class Stats
	def initialize(**kwargs)
		@stats = kwargs
	end

	def add(stat, value)
		@stats[stat] += value
	end

	def to_h
		@stats.transform_values { |v| v.is_a?(BigDecimal) ? v.to_s("F") : v }
	end
end

stats = Stats.new(
	not_renewed: 0,
	renewed: 0,
	revenue: BigDecimal.new(0)
)

class Plan
	def self.from_name(plan_name)
		plan = CONFIG[:plans].find { |p| p[:name].to_s == plan_name }
		new(plan) if plan
	end

	def initialize(plan)
		@plan = plan
	end

	def price
		BigDecimal.new(@plan["monthly_price"].to_i) * 0.0001
	end

	def bill_customer(db, customer_id)
		transaction_id = "#{customer_id}-renew-until-#{RENEW_UNTIL}"
		db.exec_params(<<-SQL, [customer_id, transaction_id, -price])
			INSERT INTO transactions
				(customer_id, transaction_id, amount, note)
			VALUES
				($1, $2, $3, 'Renew account plan')
		SQL
	end

	def renew(db, customer_id, expires_at)
		bill_customer(db, customer_id)

		params = [RENEW_UNTIL, customer_id, expires_at]
		db.exec_params(<<-SQL, params)
		  UPDATE plan_log SET expires_at=$1
		  WHERE customer_id=$2 AND expires_at=$3
		SQL
	end
end

class ExpiredCustomer
	def self.for(row)
		plan = Plan.from_name(row["plan_name"])
		if row["balance"] < plan.price
			WithLowBalance.new(row, plan)
		else
			new(row, plan)
		end
	end

	def initialize(row, plan)
		@row = row
		@plan = plan
	end

	def try_renew(db, stats)
		@plan.renew(
			db,
			@row["customer_id"],
			@row["expires_at"]
		)

		stats.add(:renewed, 1)
		stats.add(:revenue, plan.price)
	end

	class WithLowBalance < ExpiredCustomer
		def try_renew(_, stats)
			jid = REDIS.get("jmp_customer_jid-#{@row['customer_id']}")
			tel = REDIS.lindex("catapult_cred-#{jid}", 3)
			BlatherNotify.say(
				CONFIG[:notify_using][:target].call(tel.to_s),
				format_renewal_notification(tel)
			)

			stats.add(:not_renewed, 1)
		end

	protected

		def format_renewal_notification(tel)
			<<~NOTIFY
				Failed to renew account for #{tel},
				balance of #{@row['balance']} is too low.
				To keep your number, please buy more credit soon.
			NOTIFY
		end
	end
end

db.transaction do
	db.exec(
		<<-SQL
		SELECT customer_id, plan_name, expires_at, balance
		FROM customer_plans INNER JOIN balances USING (customer_id)
		WHERE expires_at <= NOW()
		SQL
	).each do |row|
		ExpiredCustomer.for(row).try_renew(db, stats)
	end
end

Net::HTTP.post_form(URI(CONFIG[:healthchecks_url].to_s), **stats.to_h)