~singpolyma/sgx-jmp

ref: 934772529eecfb46e4a879824cec6e43e4872fce sgx-jmp/lib/customer_repo.rb -rw-r--r-- 1.6 KiB
93477252Stephen Paul Weber Customer always has a JID 2 years 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
# frozen_string_literal: true

require_relative "customer"
require_relative "polyfill"

class CustomerRepo
	def initialize(redis: REDIS, db: DB, braintree: BRAINTREE)
		@redis = redis
		@db = db
		@braintree = braintree
	end

	def find(customer_id)
		@redis.get("jmp_customer_jid-#{customer_id}").then do |jid|
			raise "No jid" unless jid
			find_inner(customer_id, jid)
		end
	end

	def find_by_jid(jid)
		@redis.get("jmp_customer_id-#{jid}").then do |customer_id|
			raise "No customer id" unless customer_id
			find_inner(customer_id, jid)
		end
	end

	def create(jid)
		@braintree.customer.create.then do |result|
			raise "Braintree customer create failed" unless result.success?
			cid = result.customer.id
			@redis.msetnx(
				"jmp_customer_id-#{jid}", cid, "jmp_customer_jid-#{cid}", jid
			).then do |redis_result|
				raise "Saving new customer to redis failed" unless redis_result == 1
				Customer.new(cid, Blather::JID.new(jid))
			end
		end
	end

protected

	def hydrate_plan(customer_id, raw_customer)
		raw_customer.dup.tap do |data|
			data[:plan] = CustomerPlan.new(
				customer_id,
				plan: data.delete(:plan_name)&.then(&Plan.method(:for)),
				expires_at: data.delete(:expires_at)
			)
		end
	end

	def find_inner(customer_id, jid)
		result = @db.query_defer(<<~SQL, [customer_id])
			SELECT COALESCE(balance,0) AS balance, plan_name, expires_at
			FROM customer_plans LEFT JOIN balances USING (customer_id)
			WHERE customer_id=$1 LIMIT 1
		SQL
		result.then do |rows|
			data = hydrate_plan(customer_id, rows.first&.transform_keys(&:to_sym) || {})
			Customer.new(customer_id, Blather::JID.new(jid), **data)
		end
	end
end