# 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) 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