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