1# frozen_string_literal: true
2
3require "bigdecimal"
4
5class CustomerFinancials
6 def initialize(customer_id)
7 @customer_id = customer_id
8 end
9
10 def payment_methods
11 EMPromise.all([
12 BRAINTREE
13 .customer
14 .find(@customer_id)
15 .catch { OpenStruct.new(payment_methods: []) },
16 REDIS.smembers("block_credit_cards")
17 ]).then { |(braintree, badcards)| PaymentMethods.for(braintree, badcards) }
18 end
19
20 def btc_addresses
21 REDIS.smembers("jmp_customer_btc_addresses-#{@customer_id}")
22 end
23
24 def bch_addresses
25 REDIS.smembers("jmp_customer_bch_addresses-#{@customer_id}")
26 end
27
28 def add_btc_address
29 REDIS.spopsadd([
30 "jmp_available_btc_addresses",
31 "jmp_customer_btc_addresses-#{@customer_id}"
32 ]).then do |addr|
33 ELECTRUM.notify(
34 addr,
35 CONFIG[:electrum_notify_url].call(addr, @customer_id, "btc")
36 )
37 addr
38 end
39 end
40
41 def add_bch_address
42 REDIS.spopsadd([
43 "jmp_available_bch_addresses",
44 "jmp_customer_bch_addresses-#{@customer_id}"
45 ]).then do |addr|
46 ELECTRUM_BCH.notify(
47 addr,
48 CONFIG[:electrum_notify_url].call(addr, @customer_id, "bch")
49 )
50 addr
51 end
52 end
53
54 def declines
55 REDIS.get("jmp_pay_decline-#{@customer_id}").then(&:to_i)
56 end
57
58 def mark_decline
59 REDIS.incr("jmp_pay_decline-#{@customer_id}").then do
60 REDIS.expire("jmp_pay_decline-#{@customer_id}", 60 * 60 * 24)
61 end
62 end
63
64 def set_declines(num)
65 if num.positive?
66 REDIS.set("jmp_pay_decline-#{@customer_id}", num)
67 else
68 REDIS.del("jmp_pay_decline-#{@customer_id}")
69 end
70 end
71
72 class TransactionInfo
73 value_semantics do
74 transaction_id String
75 created_at Time
76 amount BigDecimal
77 note String, coerce: ->(x) { x || "" }
78 end
79
80 def formatted_amount
81 "$%.4f" % amount
82 end
83 end
84
85 TRANSACTIONS_SQL = <<~SQL
86 SELECT
87 transaction_id,
88 created_at,
89 amount,
90 note
91 FROM transactions
92 WHERE customer_id = $1
93 ORDER BY created_at;
94 SQL
95
96 def transactions
97 txns = DB.query_defer(TRANSACTIONS_SQL, [@customer_id])
98
99 txns.then do |rows|
100 rows.map { |row|
101 TransactionInfo.new(**row.transform_keys(&:to_sym))
102 }
103 end
104 end
105end