1# frozen_string_literal: true
2
3require_relative "expiring_lock"
4require_relative "transaction"
5
6class LowBalance
7 def self.for(customer)
8 return Locked.new unless customer.registered?
9
10 ExpiringLock.new(
11 "jmp_customer_low_balance-#{customer.customer_id}",
12 expiry: 60 * 60 * 24 * 7
13 ).with(-> { Locked.new }) do
14 for_auto_top_up_amount(customer)
15 end
16 end
17
18 def self.for_auto_top_up_amount(customer)
19 if customer.auto_top_up_amount.positive?
20 AutoTopUp.new(customer)
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)
51 @customer = customer
52 @message = Blather::Stanza::Message.new
53 @message.from = CONFIG[:notify_from]
54 end
55
56 def sale
57 Transaction.sale(
58 @customer,
59 amount: @customer.auto_top_up_amount
60 ).then do |tx|
61 tx.insert.then { tx }
62 end
63 end
64
65 def notify!
66 sale.then { |tx|
67 @message.body =
68 "Automatic top-up has charged your default " \
69 "payment method and added #{tx} to your balance."
70 }.catch { |e|
71 @message.body =
72 "Automatic top-up transaction for " \
73 "$#{@customer.auto_top_up_amount} failed: #{e.message}"
74 }.then { @customer.stanza_to(@message) }
75 end
76 end
77
78 class Locked
79 def notify!; end
80 end
81end