customer.rb

 1# frozen_string_literal: true
 2
 3require "forwardable"
 4
 5require_relative "./blather_ext"
 6require_relative "./customer_plan"
 7require_relative "./customer_usage"
 8require_relative "./backend_sgx"
 9require_relative "./ibr"
10require_relative "./payment_methods"
11require_relative "./plan"
12require_relative "./sip_account"
13
14class Customer
15	extend Forwardable
16
17	attr_reader :customer_id, :balance
18	def_delegators :@plan, :active?, :activate_plan_starting_now, :bill_plan,
19	               :currency, :merchant_account, :plan_name
20	def_delegators :@sgx, :register!, :registered?, :fwd_timeout=
21	def_delegators :@usage, :usage_report, :message_usage, :incr_message_usage
22
23	def initialize(
24		customer_id,
25		plan_name: nil,
26		expires_at: Time.now,
27		balance: BigDecimal.new(0),
28		sgx: BackendSgx.new(customer_id)
29	)
30		@plan = CustomerPlan.new(
31			customer_id,
32			plan: plan_name && Plan.for(plan_name), expires_at: expires_at
33		)
34		@usage = CustomerUsage.new(customer_id)
35		@customer_id = customer_id
36		@balance = balance
37		@sgx = sgx
38	end
39
40	def with_plan(plan_name)
41		self.class.new(
42			@customer_id,
43			balance: @balance,
44			expires_at: expires_at,
45			plan_name: plan_name
46		)
47	end
48
49	def payment_methods
50		BRAINTREE
51			.customer
52			.find(@customer_id)
53			.catch { OpenStruct.new(payment_methods: []) }
54			.then(PaymentMethods.method(:for_braintree_customer))
55	end
56
57	def jid
58		@jid ||= REDIS.get("jmp_customer_jid-#{customer_id}").then do |sjid|
59			Blather::JID.new(sjid)
60		end
61	end
62
63	def stanza_to(stanza)
64		jid.then do |jid|
65			stanza = stanza.dup
66			stanza.to = jid.with(resource: stanza.to&.resource)
67			stanza.from = stanza.from.with(domain: CONFIG[:component][:jid])
68			BLATHER << stanza
69		end
70	end
71
72	def stanza_from(stanza)
73		BLATHER << @sgx.stanza(stanza)
74	end
75
76	def sip_account
77		SipAccount.find(customer_id)
78	end
79
80	def reset_sip_account
81		SipAccount::New.new(username: customer_id).put.catch do
82			sip_account.then { |acct| acct.with_random_password.put }
83		end
84	end
85
86	def btc_addresses
87		REDIS.smembers("jmp_customer_btc_addresses-#{customer_id}")
88	end
89
90	def add_btc_address
91		REDIS.spopsadd([
92			"jmp_available_btc_addresses",
93			"jmp_customer_btc_addresses-#{customer_id}"
94		])
95	end
96
97	protected def_delegator :@plan, :expires_at
98end