plan.rb

 1# frozen_string_literal: true
 2
 3class Plan
 4	def self.for(plan_name)
 5		plan = CONFIG[:plans].find { |p| p[:name] == plan_name }
 6		raise "No plan by that name" unless plan
 7
 8		new(plan)
 9	end
10
11	def initialize(plan)
12		@plan = plan
13	end
14
15	def name
16		@plan[:name]
17	end
18
19	def currency
20		@plan[:currency]
21	end
22
23	def monthly_price
24		BigDecimal(@plan[:monthly_price]) / 10000
25	end
26
27	def merchant_account
28		CONFIG[:braintree][:merchant_accounts].fetch(currency) do
29			raise "No merchant account for this currency"
30		end
31	end
32
33	def minute_limit
34		CallingLimit.new(Limit.for("minute", @plan[:minutes]))
35	end
36
37	def message_limit
38		Limit.for("message", @plan[:messages])
39	end
40
41	class Limit
42		def self.for(unit, from_config)
43			case from_config
44			when :unlimited
45				Unlimited.new(unit)
46			else
47				new(unit: unit, **from_config)
48			end
49		end
50
51		value_semantics do
52			unit String
53			included Integer
54			price Integer
55		end
56
57		def to_s
58			"#{included} #{unit}s " \
59			"(overage $#{'%.4f' % (price.to_d / 10000)} / #{unit})"
60		end
61
62		def to_d
63			included.to_d / 10000
64		end
65
66		class Unlimited
67			def initialize(unit)
68				@unit = unit
69			end
70
71			def to_s
72				"unlimited #{@unit}s"
73			end
74		end
75	end
76
77	class CallingLimit
78		def initialize(limit)
79			@limit = limit
80		end
81
82		def to_d
83			@limit.to_d
84		end
85
86		def to_s
87			"#{'$%.4f' % to_d} of calling credit per calendar month " \
88			"(overage $#{'%.4f' % (@limit.price.to_d / 10000)} / minute)"
89		end
90	end
91end