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		auto_top_up_amount Integer
 12		tel Either(String, nil)
 13		balance BigDecimal
 14		expires_at Either(Time, nil)
 15	end
 16
 17	def self.for(customer, plan, expires_at)
 18		fetch_inputs(customer, plan).then do |(auto_top_up_amount, registration)|
 19			new(
 20				plan: plan,
 21				auto_top_up_amount: auto_top_up_amount,
 22				tel: registration ? registration.phone : nil,
 23				balance: customer.balance,
 24				expires_at: expires_at
 25			)
 26		end
 27	end
 28
 29	def self.fetch_inputs(customer, plan)
 30		EMPromise.all([
 31			plan.auto_top_up_amount,
 32			customer.registered?
 33		])
 34	end
 35
 36	def account_status
 37		if plan.plan_name.nil?
 38			"Transitional"
 39		elsif plan.active?
 40			"Active"
 41		else
 42			"Expired"
 43		end
 44	end
 45
 46	def next_renewal
 47		{ var: "Next renewal", value: expires_at.strftime("%Y-%m-%d") } if expires_at
 48	end
 49
 50	def monthly_amount
 51		return unless plan.monthly_price
 52		{ var: "Renewal", value: "$%.4f / month" % plan.monthly_price }
 53	end
 54
 55	def auto_top_up
 56		{
 57			label: "Auto Top-up"
 58		}.merge(
 59			if auto_top_up_amount.positive?
 60				{ value: auto_top_up_amount.to_s, var: "auto_top_up_amount" }
 61			else
 62				{ value: "No" }
 63			end
 64		)
 65	end
 66
 67	def fields
 68		[
 69			{ var: "Account Status", value: account_status },
 70			{ var: "Phone Number", value: tel || "Not Registered" },
 71			{ var: "Balance", value: "$%.4f" % balance },
 72			monthly_amount,
 73			next_renewal,
 74			auto_top_up,
 75			{ var: "Currency", value: (plan.currency || "No Currency").to_s }
 76		].compact
 77	end
 78end
 79
 80class AdminInfo
 81	value_semantics do
 82		jid ProxiedJID, coerce: ProxiedJID.method(:new)
 83		customer_id String
 84		info CustomerInfo
 85		api API
 86	end
 87
 88	def self.for(customer, plan, expires_at)
 89		EMPromise.all([
 90			CustomerInfo.for(customer, plan, expires_at),
 91			customer.api
 92		]).then do |info, api_value|
 93			new(
 94				jid: customer.jid,
 95				customer_id: customer.customer_id,
 96				info: info, api: api_value
 97			)
 98		end
 99	end
100
101	def fields
102		info.fields + [
103			{ var: "JID", value: jid.unproxied.to_s },
104			{ var: "Cheo JID", value: jid.to_s },
105			{ var: "Customer ID", value: customer_id },
106			{ var: "Plan", value: info.plan.plan_name || "No Plan" },
107			{ var: "API", value: api.to_s }
108		]
109	end
110end