~singpolyma/sgx-jmp

sgx-jmp/lib/bill_plan_command.rb -rw-r--r-- 1.9 KiB
4ace3417Stephen Paul Weber Log errors from rev.ai 8 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# frozen_string_literal: true

require_relative "expiring_lock"

class BillPlanCommand
	def self.for(customer)
		return ForUnregistered.new(customer) unless customer.registered?

		unless customer.balance > customer.monthly_price
			return ForLowBalance.new(customer)
		end

		new(customer)
	end

	def initialize(customer)
		@customer = customer
	end

	def reload_customer(db)
		@customer = Command.execution.customer_repo.with(db: db)
			.find(customer_id).sync
	end

	def call
		ExpiringLock.new("jmp_customer_bill_plan-#{customer_id}").with {
			@customer.bill_plan(note: "Renew account plan") { |db|
				reload_customer(db).balance > @customer.monthly_price
			}
		}.then do |billed|
			Command.reply do |reply|
				reply.note_type = billed ? :info : :error
				reply.note_text = "#{customer_id}#{billed ? '' : ' not'} billed"
			end
		end
	end

protected

	def customer_id
		@customer.customer_id
	end

	class ForLowBalance
		def initialize(customer)
			@customer = customer
		end

		def call
			LowBalance.for(@customer).then(&:notify!).then do |amount|
				next command_for(amount).call if amount&.positive?

				notify_failure
				Command.reply do |reply|
					reply.note_type = :error
					reply.note_text = "#{@customer.customer_id} balance is too low"
				end
			end
		end

	protected

		def notify_failure
			m = Blather::Stanza::Message.new
			m.from = CONFIG[:notify_from]
			m.body =
				"Failed to renew account for #{@customer.registered?.phone}. " \
				"To keep your number, please buy more credit soon."
			@customer.stanza_to(m)
		end

		def command_for(amount)
			BillPlanCommand.for(
				@customer.with_balance(@customer.balance + amount)
			)
		end
	end

	class ForUnregistered
		def initialize(customer)
			@customer = customer
		end

		def call
			Command.reply do |reply|
				reply.note_type = :error
				reply.note_text = "#{@customer.customer_id} is not registered"
			end
		end
	end
end