1# frozen_string_literal: true
2
3require_relative "./xep0122_field"
4
5class BuyAccountCreditForm
6 def self.for(customer)
7 @customer.payment_methods.then do |payment_methods|
8 new(customer.balance, payment_methods)
9 end
10 end
11
12 def initialize(balance, payment_methods)
13 @balance = balance
14 @payment_methods = payment_methods
15 end
16
17 AMOUNT_FIELD =
18 XEP0122Field.new(
19 "xs:decimal",
20 range: (0..1000),
21 var: "amount",
22 label: "Amount of credit to buy",
23 required: true
24 ).field
25
26 def balance
27 {
28 type: "fixed",
29 value: "Current balance: $#{'%.2f' % @balance}"
30 }
31 end
32
33 def add_to_form(form)
34 form.type = :form
35 form.title = "Buy Account Credit"
36 form.fields = [
37 balance,
38 @payment_methods.to_list_single,
39 AMOUNT_FIELD
40 ]
41 end
42
43 def parse(form)
44 {
45 payment_method: @payment_methods.fetch(
46 form.field("payment_method")&.value.to_i
47 ),
48 amount: form.field("amount")&.value&.to_s
49 }
50 end
51end