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
45		"\nYou can buy credit by sending any amount of Bitcoin to one of " \
46		"these addresses:\n#{@btc_addresses.join("\n")}"
47	end
48
49	class AutoTopUp
50		def initialize(customer, auto_top_up_amount)
51			@customer = customer
52			@auto_top_up_amount = auto_top_up_amount
53			@message = Blather::Stanza::Message.new
54			@message.from = CONFIG[:notify_from]
55		end
56
57		def sale
58			Transaction.sale(@customer, amount: @auto_top_up_amount).then do |tx|
59				tx.insert.then { tx }
60			end
61		end
62
63		def notify!
64			sale.then { |tx|
65				@message.body =
66					"Automatic top-up has charged your default " \
67					"payment method and added #{tx} to your balance."
68			}.catch { |e|
69				@message.body =
70					"Automatic top-up transaction for " \
71					"$#{@auto_top_up_amount} failed: #{e.message}"
72			}.then { @customer.stanza_to(@message) }
73		end
74	end
75
76	class Locked
77		def notify!; end
78	end
79end