customer_info.rb

 1# frozen_string_literal: true
 2
 3require "bigdecimal"
 4require "value_semantics/monkey_patched"
 5require_relative "proxied_jid"
 6require_relative "customer_plan"
 7
 8class CustomerInfo
 9	value_semantics do
10		plan CustomerPlan
11		tel Either(String, nil)
12		balance BigDecimal
13		expires_at Either(Time, nil)
14	end
15
16	def self.for(customer, plan, expires_at)
17		customer.registered?.then do |registration|
18			new(
19				plan: plan,
20				tel: registration ? registration.phone : nil,
21				balance: customer.balance,
22				expires_at: expires_at
23			)
24		end
25	end
26
27	def account_status
28		if plan.plan_name.nil?
29			"Transitional"
30		elsif plan.active?
31			"Active"
32		else
33			"Expired"
34		end
35	end
36
37	def next_renewal
38		{ var: "Next renewal", value: expires_at.strftime("%Y-%m-%d") } if expires_at
39	end
40
41	def monthly_amount
42		return unless plan.monthly_price
43		{ var: "Renewal", value: "$%.4f / month" % plan.monthly_price }
44	end
45
46	def fields
47		[
48			{ var: "Account Status", value: account_status },
49			{ var: "Phone Number", value: tel || "Not Registered" },
50			{ var: "Balance", value: "$%.4f" % balance },
51			monthly_amount,
52			next_renewal,
53			{ var: "Currency", value: (plan.currency || "No Currency").to_s }
54		].compact
55	end
56end
57
58class AdminInfo
59	value_semantics do
60		jid ProxiedJID, coerce: ProxiedJID.method(:new)
61		customer_id String
62		info CustomerInfo
63		api API
64	end
65
66	def self.for(customer, plan, expires_at)
67		EMPromise.all([
68			CustomerInfo.for(customer, plan, expires_at),
69			customer.api
70		]).then do |info, api_value|
71			new(
72				jid: customer.jid,
73				customer_id: customer.customer_id,
74				info: info, api: api_value
75			)
76		end
77	end
78
79	def fields
80		info.fields + [
81			{ var: "JID", value: jid.unproxied.to_s },
82			{ var: "Cheo JID", value: jid.to_s },
83			{ var: "Customer ID", value: customer_id },
84			{ var: "Plan", value: info.plan.plan_name || "No Plan" },
85			{ var: "API", value: api.to_s }
86		]
87	end
88end