1# frozen_string_literal: true
2
3require_relative "./payment_methods"
4require_relative "./plan"
5
6class Customer
7 def self.for_jid(jid)
8 REDIS.get("jmp_customer_id-#{jid}").then do |customer_id|
9 raise "No customer id" unless customer_id
10 for_customer_id(customer_id)
11 end
12 end
13
14 def self.for_customer_id(customer_id)
15 result = DB.query_defer(<<~SQL, [customer_id])
16 SELECT COALESCE(balance,0) AS balance, plan_name
17 FROM customer_plans LEFT JOIN balances USING (customer_id)
18 WHERE customer_id=$1 LIMIT 1
19 SQL
20 result.then do |rows|
21 new(customer_id, **rows.first&.transform_keys(&:to_sym) || {})
22 end
23 end
24
25 attr_reader :balance
26
27 def initialize(customer_id, plan_name: nil, balance: BigDecimal.new(0))
28 @plan = plan_name && Plan.for(plan_name)
29 @customer_id = customer_id
30 @balance = balance
31 end
32
33 def merchant_account
34 @plan.merchant_account
35 end
36
37 def payment_methods
38 @payment_methods ||=
39 BRAINTREE
40 .customer
41 .find(@customer_id)
42 .then(PaymentMethods.method(:for_braintree_customer))
43 end
44end