1# frozen_string_literal: true
2
3class BillPlanCommand
4 def self.for(customer)
5 return ForUnregistered.new unless customer.registered?
6
7 unless customer.balance > customer.monthly_price
8 return ForLowBalance.new(customer)
9 end
10
11 new(customer)
12 end
13
14 def initialize(customer)
15 @customer = customer
16 end
17
18 def call
19 @customer.bill_plan
20 Command.reply do |reply|
21 reply.note_type = :info
22 reply.note_text = "Customer billed"
23 end
24 end
25
26 class ForLowBalance
27 def initialize(customer)
28 @customer = customer
29 end
30
31 def call
32 LowBalance.for(@customer).then(&:notify!).then do |amount|
33 return command_for(amount).call if amount&.positive?
34
35 notify_failure
36 Command.reply do |reply|
37 reply.note_type = :error
38 reply.note_text = "Customer balance is too low"
39 end
40 end
41 end
42
43 protected
44
45 def notify_failure
46 m = Blather::Stanza::Message.new
47 m.from = CONFIG[:notify_from]
48 m.body =
49 "Failed to renew account for #{@customer.registered?.phone}. " \
50 "To keep your number, please buy more credit soon."
51 @customer.stanza_to(m)
52 end
53
54 def command_for(amount)
55 BillPlanCommand.for(
56 @customer.with_balance(@customer.balance + amount)
57 )
58 end
59 end
60
61 class ForUnregistered
62 def call
63 Command.reply do |reply|
64 reply.note_type = :error
65 reply.note_text = "Customer is not registered"
66 end
67 end
68 end
69end