~singpolyma/sgx-jmp

ref: 4ffa367cd34b6d847c781b89e2fa50f16fc7878f sgx-jmp/lib/buy_account_credit_form.rb -rw-r--r-- 930 bytes
4ffa367cStephen Paul Weber Refactor BuyAccountCreditForm 2 years ago
                                                                                
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
# frozen_string_literal: true

require_relative "./xep0122_field"

class BuyAccountCreditForm
	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

	AMOUNT_FIELD =
		XEP0122Field.new(
			"xs:decimal",
			range: (0..1000),
			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)
		{
			payment_method: @payment_methods.fetch(
				form.field("payment_method")&.value.to_i
			),
			amount: form.field("amount")&.value&.to_s
		}
	end
end