admin_command.rb

  1# frozen_string_literal: true
  2
  3require_relative "bill_plan_command"
  4require_relative "customer_info_form"
  5require_relative "financial_info"
  6require_relative "form_template"
  7
  8class AdminCommand
  9	def initialize(target_customer, customer_repo)
 10		@target_customer = target_customer
 11		@customer_repo = customer_repo
 12	end
 13
 14	def start
 15		@target_customer.admin_info.then { |info|
 16			reply(info.form)
 17		}.then { menu_or_done }
 18	end
 19
 20	def reply(form)
 21		Command.reply { |reply|
 22			reply.allowed_actions = [:next, :complete]
 23			reply.command << form
 24		}
 25	end
 26
 27	def menu_or_done(command_action=:execute)
 28		return Command.finish("Done") if command_action == :complete
 29
 30		reply(FormTemplate.render("admin_menu")).then do |response|
 31			if response.form.field("action")
 32				handle(response.form.field("action").value, response.action)
 33			end
 34		end
 35	end
 36
 37	def handle(action, command_action)
 38		if respond_to?("action_#{action}")
 39			send("action_#{action}")
 40		else
 41			new_context(action)
 42		end.then { menu_or_done(command_action) }
 43	end
 44
 45	def new_context(q)
 46		CustomerInfoForm.new(@customer_repo)
 47			.parse_something(q).then do |new_customer|
 48				if new_customer.respond_to?(:customer_id)
 49					AdminCommand.new(new_customer, @customer_repo).start
 50				else
 51					reply(new_customer.form)
 52				end
 53			end
 54	end
 55
 56	def action_info
 57		# Refresh the data
 58		new_context(@target_customer.customer_id)
 59	end
 60
 61	def action_financial
 62		AdminFinancialInfo.for(@target_customer).then do |financial_info|
 63			reply(FormTemplate.render(
 64				"admin_financial_info",
 65				info: financial_info
 66			)).then {
 67				pay_methods(financial_info)
 68			}.then {
 69				transactions(financial_info)
 70			}
 71		end
 72	end
 73
 74	def action_bill_plan
 75		BillPlanCommand.for(@target_customer).call
 76	end
 77
 78	def notify_customer(body)
 79		m = Blather::Stanza::Message.new
 80		m.from = CONFIG[:notify_from]
 81		m.body = body
 82		@target_customer.stanza_to(m)
 83	end
 84
 85	def action_cancel_account
 86		notify_customer("Your JMP account has been cancelled.").then {
 87			EMPromise.all([
 88				@target_customer.stanza_to(
 89					Blather::Stanza::Iq::IBR.new(:set).tap(&:remove!)
 90				),
 91				@target_customer.deregister!,
 92				@customer_repo.disconnect_tel(@target_customer)
 93			])
 94		}
 95	end
 96
 97	def pay_methods(financial_info)
 98		reply(FormTemplate.render(
 99			"admin_payment_methods",
100			**financial_info.to_h
101		))
102	end
103
104	def transactions(financial_info)
105		reply(FormTemplate.render(
106			"admin_transaction_list",
107			transactions: financial_info.transactions
108		))
109	end
110end