# frozen_string_literal: true
require_relative "customer"
class CustomerRepo
def initialize(redis: REDIS, db: DB, braintree: BRAINTREE)
@redis = redis
@db = db
@braintree = braintree
end
def find(customer_id)
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|
Customer.new(customer_id, **rows.first&.transform_keys(&:to_sym) || {})
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(customer_id)
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)
end
end
end
end