customer_info.rb

  1# frozen_string_literal: true
  2
  3require "bigdecimal"
  4require "forwardable"
  5require "relative_time"
  6require "value_semantics/monkey_patched"
  7require_relative "proxied_jid"
  8require_relative "customer_plan"
  9require_relative "form_template"
 10
 11class PlanInfo
 12	extend Forwardable
 13
 14	def_delegators :plan, :expires_at, :auto_top_up_amount
 15
 16	def self.for(plan)
 17		return EMPromise.resolve(NoPlan.new) unless plan&.plan_name
 18
 19		plan.activation_date.then do |adate|
 20			new(plan: plan, start_date: adate)
 21		end
 22	end
 23
 24	class NoPlan
 25		def template
 26			FormTemplate.new("")
 27		end
 28
 29		def admin_template
 30			FormTemplate.new("")
 31		end
 32
 33		def status
 34			"Transitional"
 35		end
 36	end
 37
 38	value_semantics do
 39		plan CustomerPlan
 40		start_date Time
 41	end
 42
 43	def template
 44		FormTemplate.for("plan_info", plan_info: self)
 45	end
 46
 47	def admin_template
 48		FormTemplate.for("admin_plan_info", plan_info: self)
 49	end
 50
 51	def monthly_price
 52		"$%.4f / month" % plan.monthly_price
 53	end
 54
 55	def relative_start_date
 56		RelativeTime.in_words(start_date)
 57	end
 58
 59	def formatted_start_date
 60		start_date.strftime("%Y-%m-%d %H:%M:%S")
 61	end
 62
 63	def currency
 64		(plan.currency || "No Currency").to_s
 65	end
 66
 67	def status
 68		plan.active? ? "Active" : "Expired"
 69	end
 70end
 71
 72class CustomerInfo
 73	value_semantics do
 74		plan_info Either(PlanInfo, PlanInfo::NoPlan)
 75		tel Either(String, nil)
 76		balance BigDecimal
 77		cnam Either(String, nil)
 78	end
 79
 80	def self.for(customer, plan)
 81		PlanInfo.for(plan).then do |plan_info|
 82			new(
 83				plan_info: plan_info,
 84				tel: customer.registered? ? customer.registered?.phone : nil,
 85				balance: customer.balance,
 86				cnam: customer.tndetails.dig(:features, :lidb, :subscriber_information)
 87			)
 88		end
 89	end
 90
 91	def form
 92		FormTemplate.render("customer_info", info: self)
 93	end
 94end
 95
 96class AdminInfo
 97	value_semantics do
 98		jid ProxiedJID, coerce: ProxiedJID.method(:new)
 99		customer_id String
100		fwd Either(CustomerFwd, nil)
101		info CustomerInfo
102		api API
103	end
104
105	def self.for(customer, plan)
106		EMPromise.all([
107			CustomerInfo.for(customer, plan),
108			customer.api
109		]).then do |info, api_value|
110			new(
111				jid: customer.jid,
112				customer_id: customer.customer_id,
113				fwd: customer.fwd, info: info, api: api_value
114			)
115		end
116	end
117
118	def form
119		FormTemplate.render("admin_info", admin_info: self)
120	end
121
122	def tel_link
123		[
124			"https://dashboard.bandwidth.com/portal/r/a",
125			CONFIG[:creds][:account],
126			"numbers/details",
127			info.tel.gsub(/\A\+1/, "")
128		].join("/")
129	end
130end