~singpolyma/sgx-jmp

ref: 8dd92b96258d14d431e9966d0534631c7fdc0214 sgx-jmp/lib/trust_level_repo.rb -rw-r--r-- 1.1 KiB
8dd92b96Stephen Paul Weber Merge branch 'admin-actions' 5 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
45
46
47
# frozen_string_literal: true

require "lazy_object"
require "value_semantics/monkey_patched"

require_relative "trust_level"

class TrustLevelRepo
	value_semantics do
		db    Anything(), default: LazyObject.new { DB }
		redis Anything(), default: LazyObject.new { REDIS }
	end

	def find(customer)
		EMPromise.all([
			find_manual(customer.customer_id),
			fetch_settled_amount(customer.customer_id)
		]).then do |(manual, row)|
			TrustLevel.for(
				manual: manual,
				plan_name: customer.plan_name,
				**row
			)
		end
	end

	def find_manual(customer_id)
		redis.get("jmp_customer_trust_level-#{customer_id}")
	end

	def put(customer_id, trust_level)
		if trust_level
			redis.set("jmp_customer_trust_level-#{customer_id}", trust_level)
		else
			redis.del("jmp_customer_trust_level-#{customer_id}")
		end
	end

protected

	def fetch_settled_amount(customer_id)
		db.query_one(<<~SQL, customer_id, default: {})
			SELECT COALESCE(SUM(amount), 0) AS settled_amount FROM transactions
			WHERE customer_id=$1 AND settled_after < LOCALTIMESTAMP AND amount > 0
		SQL
	end
end