~singpolyma/sgx-jmp

ref: 4be555de103e992ee7e03feb48b45c1eca917c45 sgx-jmp/lib/customer.rb -rw-r--r-- 1.0 KiB
4be555deStephen Paul Weber Split logic out into testable objects 1 year, 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
# frozen_string_literal: true

require_relative "./payment_methods"
require_relative "./plan"

class Customer
	def self.for_jid(jid)
		REDIS.get("jmp_customer_id-#{jid}").then do |customer_id|
			raise "No customer id" unless customer_id
			for_customer_id(customer_id)
		end
	end

	def self.for_customer_id(customer_id)
		result = DB.query_defer(<<~SQL, [customer_id])
			SELECT COALESCE(balance,0) AS balance, plan_name
			FROM customer_plans LEFT JOIN balances USING (customer_id)
			WHERE customer_id=$1 LIMIT 1
		SQL
		result.then do |rows|
			new(customer_id, **rows.first&.transform_keys(&:to_sym) || {})
		end
	end

	attr_reader :balance

	def initialize(customer_id, plan_name: nil, balance: BigDecimal.new(0))
		@plan = plan_name && Plan.for(plan_name)
		@customer_id = customer_id
		@balance = balance
	end

	def merchant_account
		@plan.merchant_account
	end

	def payment_methods
		@payment_methods ||=
			BRAINTREE
			.customer
			.find(@customer_id)
			.then(PaymentMethods.method(:for_braintree_customer))
	end
end