1# frozen_string_literal: true
2
3class CustomerFinancials
4 def initialize(customer_id)
5 @customer_id = customer_id
6 end
7
8 def payment_methods
9 BRAINTREE
10 .customer
11 .find(@customer_id)
12 .catch { OpenStruct.new(payment_methods: []) }
13 .then(PaymentMethods.method(:for_braintree_customer))
14 end
15
16 def btc_addresses
17 REDIS.smembers("jmp_customer_btc_addresses-#{@customer_id}")
18 end
19
20 def add_btc_address
21 REDIS.spopsadd([
22 "jmp_available_btc_addresses",
23 "jmp_customer_btc_addresses-#{@customer_id}"
24 ]).then do |addr|
25 ELECTRUM.notify(
26 addr,
27 CONFIG[:electrum_notify_url].call(addr, @customer_id)
28 )
29 addr
30 end
31 end
32
33 def declines
34 REDIS.get("jmp_pay_decline-#{@customer_id}").then(&:to_i)
35 end
36
37 def mark_decline
38 REDIS.incr("jmp_pay_decline-#{@customer_id}").then do
39 REDIS.expire("jmp_pay_decline-#{@customer_id}", 60 * 60 * 24)
40 end
41 end
42
43 class TransactionInfo
44 value_semantics do
45 transaction_id String
46 created_at Time
47 amount BigDecimal
48 note String, coerce: ->(x) { x || "" }
49 end
50
51 def formatted_amount
52 "$%.4f" % amount
53 end
54 end
55
56 TRANSACTIONS_SQL = <<~SQL
57 SELECT
58 transaction_id,
59 created_at,
60 amount,
61 note
62 FROM transactions
63 WHERE customer_id = $1
64 ORDER BY created_at;
65 SQL
66
67 def transactions
68 txns = DB.query_defer(TRANSACTIONS_SQL, [@customer_id])
69
70 txns.then do |rows|
71 rows.map { |row|
72 TransactionInfo.new(**row.transform_keys(&:to_sym))
73 }
74 end
75 end
76end