low_balance.rb

 1# frozen_string_literal: true
 2
 3require_relative "expiring_lock"
 4require_relative "transaction"
 5
 6class LowBalance
 7	def self.for(customer)
 8		ExpiringLock.new(
 9			"jmp_customer_low_balance-#{customer.customer_id}",
10			expiry: 60 * 60 * 24 * 7
11		).with(-> { Locked.new }) do
12			customer.auto_top_up_amount.then do |auto_top_up_amount|
13				for_auto_top_up_amount(customer, auto_top_up_amount)
14			end
15		end
16	end
17
18	def self.for_auto_top_up_amount(customer, auto_top_up_amount)
19		if auto_top_up_amount.positive?
20			AutoTopUp.new(customer, auto_top_up_amount)
21		else
22			customer.btc_addresses.then do |btc_addresses|
23				new(customer, btc_addresses)
24			end
25		end
26	end
27
28	def initialize(customer, btc_addresses)
29		@customer = customer
30		@btc_addresses = btc_addresses
31	end
32
33	def notify!
34		m = Blather::Stanza::Message.new
35		m.from = CONFIG[:notify_from]
36		m.body =
37			"Your balance of $#{'%.4f' % @customer.balance} is low." \
38			"#{btc_addresses_for_notification}"
39		@customer.stanza_to(m)
40	end
41
42	def btc_addresses_for_notification
43		return if @btc_addresses.empty?
44		"\nYou can buy credit by sending any amount of Bitcoin to one of " \
45		"these addresses:\n#{@btc_addresses.join("\n")}"
46	end
47
48	class AutoTopUp
49		def initialize(customer, auto_top_up_amount)
50			@customer = customer
51			@auto_top_up_amount = auto_top_up_amount
52			@message = Blather::Stanza::Message.new
53			@message.from = CONFIG[:notify_from]
54		end
55
56		def sale
57			Transaction.sale(@customer, amount: @auto_top_up_amount).then do |tx|
58				tx.insert.then { tx }
59			end
60		end
61
62		def notify!
63			sale.then { |tx|
64				@message.body =
65					"Automatic top-up has charged your default " \
66					"payment method and added #{tx} to your balance."
67			}.catch { |e|
68				@message.body =
69					"Automatic top-up transaction for " \
70					"$#{@auto_top_up_amount} failed: #{e.message}"
71			}.then { @customer.stanza_to(@message) }
72		end
73	end
74
75	class Locked
76		def notify!; end
77	end
78end