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