~singpolyma/sgx-jmp

sgx-jmp/lib/customer_finacials.rb -rw-r--r-- 1.7 KiB
94298f5dStephen Paul Weber Refactor alt top up to use FormTemplate 2 months 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# frozen_string_literal: true

class CustomerFinancials
	def initialize(customer_id)
		@customer_id = customer_id
	end

	def payment_methods
		EMPromise.all([
			BRAINTREE
				.customer
				.find(@customer_id)
				.catch { OpenStruct.new(payment_methods: []) },
			REDIS.smembers("block_credit_cards")
		]).then { |(braintree, badcards)| PaymentMethods.for(braintree, badcards) }
	end

	def btc_addresses
		REDIS.smembers("jmp_customer_btc_addresses-#{@customer_id}")
	end

	def add_btc_address
		REDIS.spopsadd([
			"jmp_available_btc_addresses",
			"jmp_customer_btc_addresses-#{@customer_id}"
		]).then do |addr|
			ELECTRUM.notify(
				addr,
				CONFIG[:electrum_notify_url].call(addr, @customer_id)
			)
			addr
		end
	end

	def declines
		REDIS.get("jmp_pay_decline-#{@customer_id}").then(&:to_i)
	end

	def mark_decline
		REDIS.incr("jmp_pay_decline-#{@customer_id}").then do
			REDIS.expire("jmp_pay_decline-#{@customer_id}", 60 * 60 * 24)
		end
	end

	def set_declines(num)
		if num.positive?
			REDIS.set("jmp_pay_decline-#{@customer_id}", num)
		else
			REDIS.del("jmp_pay_decline-#{@customer_id}")
		end
	end

	class TransactionInfo
		value_semantics do
			transaction_id String
			created_at Time
			amount BigDecimal
			note String, coerce: ->(x) { x || "" }
		end

		def formatted_amount
			"$%.4f" % amount
		end
	end

	TRANSACTIONS_SQL = <<~SQL
		SELECT
			transaction_id,
			created_at,
			amount,
			note
		FROM transactions
		WHERE customer_id = $1
		ORDER BY created_at;
	SQL

	def transactions
		txns = DB.query_defer(TRANSACTIONS_SQL, [@customer_id])

		txns.then do |rows|
			rows.map { |row|
				TransactionInfo.new(**row.transform_keys(&:to_sym))
			}
		end
	end
end