1# frozen_string_literal: true
2
3class BillPlanCommand
4 def self.for(customer)
5 return ForUnregistered.new(customer) 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(note: "Renew account plan")
20 Command.reply do |reply|
21 reply.note_type = :info
22 reply.note_text = "#{@customer.customer_id} 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 next 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.customer_id} 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 initialize(customer)
63 @customer = customer
64 end
65
66 def call
67 Command.reply do |reply|
68 reply.note_type = :error
69 reply.note_text = "#{@customer.customer_id} is not registered"
70 end
71 end
72 end
73end