1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true
require_relative "./xep0122_field"
class BuyAccountCreditForm
class AmountValidationError < StandardError
def initialize(amount)
super(
"amount #{amount} must be in the range " \
"#{RANGE.first} through #{RANGE.last}"
)
end
end
def self.for(customer)
customer.payment_methods.then do |payment_methods|
new(customer.balance, payment_methods)
end
end
def initialize(balance, payment_methods)
@balance = balance
@payment_methods = payment_methods
end
RANGE = (15..1000).freeze
AMOUNT_FIELD =
XEP0122Field.new(
"xs:decimal",
range: RANGE,
var: "amount",
label: "Amount of credit to buy",
required: true
).field
def balance
{
type: "fixed",
value: "Current balance: $#{'%.2f' % @balance}"
}
end
def add_to_form(form)
form.type = :form
form.title = "Buy Account Credit"
form.fields = [
balance,
@payment_methods.to_list_single,
AMOUNT_FIELD
]
end
def parse(form)
amount = form.field("amount")&.value&.to_s
raise AmountValidationError, amount unless RANGE.include?(amount.to_i)
{
payment_method: @payment_methods.fetch(
form.field("payment_method")&.value.to_i
),
amount: amount
}
end
end