~singpolyma/sgx-jmp

ref: 5ad2c9e4ad04c3a1b8215b28a4b2bf61a84ac928 sgx-jmp/lib/low_balance.rb -rw-r--r-- 1.9 KiB
5ad2c9e4Stephen Paul Weber Use billing customer for LowBalance notification 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# frozen_string_literal: true

require_relative "expiring_lock"
require_relative "transaction"

class LowBalance
	def self.for(customer)
		return Locked.new unless customer.registered?

		ExpiringLock.new(
			"jmp_customer_low_balance-#{customer.billing_customer_id}",
			expiry: 60 * 60 * 24 * 7
		).with(-> { Locked.new }) do
			customer.billing_customer.then(&method(:for_no_lock))
		end
	end

	def self.for_no_lock(customer)
		if customer.auto_top_up_amount.positive?
			AutoTopUp.new(customer)
		else
			customer.btc_addresses.then do |btc_addresses|
				new(customer, btc_addresses)
			end
		end
	end

	def initialize(customer, btc_addresses)
		@customer = customer
		@btc_addresses = btc_addresses
	end

	def notify!
		m = Blather::Stanza::Message.new
		m.from = CONFIG[:notify_from]
		m.body =
			"Your balance of $#{'%.4f' % @customer.balance} is low." \
			"#{btc_addresses_for_notification}"
		@customer.stanza_to(m)
		EMPromise.resolve(0)
	end

	def btc_addresses_for_notification
		return if @btc_addresses.empty?

		"\nYou can buy credit by sending any amount of Bitcoin to one of " \
		"these addresses:\n#{@btc_addresses.join("\n")}"
	end

	class AutoTopUp
		def initialize(customer)
			@customer = customer
			@message = Blather::Stanza::Message.new
			@message.from = CONFIG[:notify_from]
		end

		def sale
			Transaction.sale(
				@customer,
				amount: @customer.auto_top_up_amount
			).then do |tx|
				tx.insert.then { tx }
			end
		end

		def failed(e)
			@message.body =
				"Automatic top-up transaction for " \
				"$#{@customer.auto_top_up_amount} failed: #{e.message}"
			0
		end

		def notify!
			sale.then { |tx|
				@message.body =
					"Automatic top-up has charged your default " \
					"payment method and added #{tx} to your balance."
				tx.total
			}.catch(&method(:failed)).then { |amount|
				@customer.stanza_to(@message)
				amount
			}
		end
	end

	class Locked
		def notify!
			EMPromise.resolve(0)
		end
	end
end