1# frozen_string_literal: true
2
3class BuyAccountCreditForm
4 class AmountValidationError < StandardError
5 def initialize(amount)
6 super(
7 "amount #{amount} must be in the range " \
8 "#{RANGE.first} through #{RANGE.last}"
9 )
10 end
11 end
12
13 def self.for(customer)
14 customer.payment_methods.then do |payment_methods|
15 new(customer.balance, payment_methods)
16 end
17 end
18
19 def initialize(balance, payment_methods)
20 @balance = balance
21 @payment_methods = payment_methods
22 end
23
24 RANGE = (15..1000).freeze
25
26 def form
27 FormTemplate.render(
28 :top_up,
29 balance: @balance,
30 payment_methods: @payment_methods,
31 range: RANGE
32 )
33 end
34
35 def parse(form)
36 amount = form.field("amount")&.value&.to_s
37 raise AmountValidationError, amount unless RANGE.include?(amount.to_i)
38
39 {
40 payment_method: @payment_methods.fetch(
41 form.field("payment_method")&.value.to_i
42 ),
43 amount: amount
44 }
45 end
46end