sgx_jmp.rb

  1# frozen_string_literal: true
  2
  3require "pg/em/connection_pool"
  4require "bandwidth"
  5require "bigdecimal"
  6require "blather/client/dsl" # Require this first to not auto-include
  7require "blather/client"
  8require "braintree"
  9require "date"
 10require "dhall"
 11require "em-hiredis"
 12require "em_promise"
 13require "ougai"
 14require "ruby-bandwidth-iris"
 15require "sentry-ruby"
 16require "statsd-instrument"
 17
 18$stdout.sync = true
 19LOG = Ougai::Logger.new($stdout)
 20LOG.level = ENV.fetch("LOG_LEVEL", "info")
 21LOG.formatter = Ougai::Formatters::Readable.new(
 22	nil,
 23	nil,
 24	plain: !$stdout.isatty
 25)
 26Blather.logger = LOG
 27EM::Hiredis.logger = LOG
 28StatsD.logger = LOG
 29LOG.info "Starting"
 30
 31Sentry.init do |config|
 32	config.logger = LOG
 33	config.breadcrumbs_logger = [:sentry_logger]
 34end
 35
 36module SentryOugai
 37	class SentryLogger
 38		include Sentry::Breadcrumb::SentryLogger
 39		include Singleton
 40	end
 41
 42	def _log(severity, message=nil, ex=nil, data=nil, &block)
 43		super
 44		SentryLogger.instance.add_breadcrumb(severity, message || ex.to_s, &block)
 45	end
 46end
 47LOG.extend SentryOugai
 48
 49CONFIG =
 50	Dhall::Coder
 51	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
 52	.load(
 53		"(#{ARGV[0]}) : #{__dir__}/config-schema.dhall",
 54		transform_keys: ->(k) { k&.to_sym }
 55	)
 56WEB_LISTEN =
 57	if CONFIG[:web].is_a?(Hash)
 58		[CONFIG[:web][:interface], CONFIG[:web][:port]]
 59	else
 60		[CONFIG[:web]]
 61	end
 62
 63singleton_class.class_eval do
 64	include Blather::DSL
 65	Blather::DSL.append_features(self)
 66end
 67
 68require_relative "lib/polyfill"
 69require_relative "lib/alt_top_up_form"
 70require_relative "lib/admin_command"
 71require_relative "lib/add_bitcoin_address"
 72require_relative "lib/backend_sgx"
 73require_relative "lib/bwmsgsv2_repo"
 74require_relative "lib/bandwidth_iris_patch"
 75require_relative "lib/bandwidth_tn_order"
 76require_relative "lib/btc_sell_prices"
 77require_relative "lib/buy_account_credit_form"
 78require_relative "lib/configure_calls_form"
 79require_relative "lib/command"
 80require_relative "lib/command_list"
 81require_relative "lib/customer"
 82require_relative "lib/customer_info_form"
 83require_relative "lib/customer_repo"
 84require_relative "lib/dummy_command"
 85require_relative "lib/db_notification"
 86require_relative "lib/electrum"
 87require_relative "lib/empty_repo"
 88require_relative "lib/expiring_lock"
 89require_relative "lib/em"
 90require_relative "lib/form_to_h"
 91require_relative "lib/low_balance"
 92require_relative "lib/port_in_order"
 93require_relative "lib/payment_methods"
 94require_relative "lib/paypal_done"
 95require_relative "lib/registration"
 96require_relative "lib/transaction"
 97require_relative "lib/tel_selections"
 98require_relative "lib/session_manager"
 99require_relative "lib/statsd"
100require_relative "web"
101
102ELECTRUM = Electrum.new(**CONFIG[:electrum])
103EM::Hiredis::Client.load_scripts_from("./redis_lua")
104
105Faraday.default_adapter = :em_synchrony
106BandwidthIris::Client.global_options = {
107	account_id: CONFIG[:creds][:account],
108	username: CONFIG[:creds][:username],
109	password: CONFIG[:creds][:password]
110}
111BANDWIDTH_VOICE = Bandwidth::Client.new(
112	voice_basic_auth_user_name: CONFIG[:creds][:username],
113	voice_basic_auth_password: CONFIG[:creds][:password]
114).voice_client.client
115
116def new_sentry_hub(stanza, name: nil)
117	hub = Sentry.get_current_hub&.new_from_top
118	raise "Sentry.init has not been called" unless hub
119
120	hub.push_scope
121	hub.current_scope.clear_breadcrumbs
122	hub.current_scope.set_transaction_name(name) if name
123	hub.current_scope.set_user(jid: stanza.from.stripped.to_s)
124	hub
125end
126
127class AuthError < StandardError; end
128
129# Braintree is not async, so wrap in EM.defer for now
130class AsyncBraintree
131	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
132		@gateway = Braintree::Gateway.new(
133			environment: environment,
134			merchant_id: merchant_id,
135			public_key: public_key,
136			private_key: private_key
137		)
138		@gateway.config.logger = LOG
139	end
140
141	def respond_to_missing?(m, *)
142		@gateway.respond_to?(m) || super
143	end
144
145	def method_missing(m, *args)
146		return super unless respond_to_missing?(m, *args)
147
148		EM.promise_defer(klass: PromiseChain) do
149			@gateway.public_send(m, *args)
150		end
151	end
152
153	class PromiseChain < EMPromise
154		def respond_to_missing?(*)
155			false && super # We don't actually know what we respond to...
156		end
157
158		def method_missing(m, *args)
159			return super if respond_to_missing?(m, *args)
160
161			self.then { |o| o.public_send(m, *args) }
162		end
163	end
164end
165
166BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
167
168def panic(e, hub=nil)
169	(Thread.current[:log] || LOG).fatal(
170		"Error raised during event loop: #{e.class}",
171		e
172	)
173	if e.is_a?(::Exception)
174		(hub || Sentry).capture_exception(e, hint: { background: false })
175	else
176		(hub || Sentry).capture_message(e.to_s, hint: { background: false })
177	end
178	exit 1
179end
180
181EM.error_handler(&method(:panic))
182
183# Infer anything we might have been notified about while we were down
184def catchup_notify(db)
185	db.query("SELECT customer_id FROM balances WHERE balance < 5").each do |c|
186		db.query("SELECT pg_notify('low_balance', $1)", c.values)
187	end
188	db.query(<<~SQL).each do |c|
189		SELECT customer_id
190		FROM customer_plans INNER JOIN balances USING (customer_id)
191		WHERE expires_at < LOCALTIMESTAMP AND balance >= 5
192	SQL
193		db.query("SELECT pg_notify('possible_renewal', $1)", c.values)
194	end
195end
196
197def poll_for_notify(db)
198	db.wait_for_notify_defer.then { |notify|
199		CustomerRepo
200			.new(sgx_repo: Bwmsgsv2Repo.new)
201			.find(notify[:extra])
202			.then { |customer| DbNotification.for(notify, customer) }
203	}.then(&:call).then {
204		poll_for_notify(db)
205	}.catch(&method(:panic))
206end
207
208def load_plans_to_db!
209	DB.transaction do
210		DB.exec("TRUNCATE plans")
211		CONFIG[:plans].each do |plan|
212			DB.exec("INSERT INTO plans VALUES ($1)", [plan.to_json])
213		end
214	end
215end
216
217when_ready do
218	LOG.info "Ready"
219	BLATHER = self
220	REDIS = EM::Hiredis.connect
221	TEL_SELECTIONS = TelSelections.new
222	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
223	DB = PG::EM::ConnectionPool.new(dbname: "jmp") { |conn|
224		conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
225		conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
226	}
227
228	DB.hold do |conn|
229		conn.query("LISTEN low_balance")
230		conn.query("LISTEN possible_renewal")
231		catchup_notify(conn)
232		poll_for_notify(conn)
233	end
234
235	load_plans_to_db!
236
237	EM.add_periodic_timer(3600) do
238		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
239		ping.from = CONFIG[:component][:jid]
240		self << ping
241	end
242
243	Web.run(LOG.child, *WEB_LISTEN)
244end
245
246# workqueue_count MUST be 0 or else Blather uses threads!
247setup(
248	CONFIG[:component][:jid],
249	CONFIG[:component][:secret],
250	CONFIG[:server][:host],
251	CONFIG[:server][:port],
252	nil,
253	nil,
254	workqueue_count: 0
255)
256
257message to: /\Aaccount@/, body: /./ do |m|
258	StatsD.increment("deprecated_account_bot")
259
260	self << m.reply.tap { |out|
261		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
262	}
263end
264
265before(
266	:iq,
267	type: [:error, :result],
268	to: /\Acustomer_/,
269	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
270) { |iq| halt if IQ_MANAGER.fulfill(iq) }
271
272before nil, to: /\Acustomer_/, from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/ do |s|
273	StatsD.increment("stanza_customer")
274
275	sentry_hub = new_sentry_hub(s, name: "stanza_customer")
276	CustomerRepo.new(set_user: sentry_hub.current_scope.method(:set_user)).find(
277		s.to.node.delete_prefix("customer_")
278	).then { |customer|
279		customer.stanza_to(s)
280	}.catch { |e| panic(e, sentry_hub) }
281	halt
282end
283
284ADDRESSES_NS = "http://jabber.org/protocol/address"
285message(
286	to: /\A#{CONFIG[:component][:jid]}\Z/,
287	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
288) do |m|
289	StatsD.increment("inbound_group_text")
290	sentry_hub = new_sentry_hub(m, name: "inbound_group_text")
291
292	address = m.find("ns:addresses", ns: ADDRESSES_NS).first
293		&.find("ns:address", ns: ADDRESSES_NS)
294		&.find { |el| el["jid"].to_s.start_with?("customer_") }
295	pass unless address
296
297	CustomerRepo
298		.new(set_user: sentry_hub.current_scope.method(:set_user))
299		.find_by_jid(address["jid"]).then { |customer|
300			m.from = m.from.with(domain: CONFIG[:component][:jid])
301			m.to = m.to.with(domain: customer.jid.domain)
302			address["jid"] = customer.jid.to_s
303			BLATHER << m
304		}.catch_only(CustomerRepo::NotFound) { |e|
305			BLATHER << m.as_error("forbidden", :auth, e.message)
306		}.catch { |e| panic(e, sentry_hub) }
307end
308
309# Ignore groupchat messages
310# Especially if we have the component join MUC for notifications
311message(type: :groupchat) { true }
312
313def billable_message(m)
314	(m.body && !m.body.empty?) || m.find("ns:x", ns: OOB.registered_ns).first
315end
316
317def notify_admin_of_usage(customer, usage, today)
318	ExpiringLock.new("jmp_usage_notify-#{customer.customer_id}").with do
319		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
320		BLATHER.say(
321			CONFIG[:notify_admin], "#{customer.customer_id} has used " \
322			"#{usage} messages since #{today - 30}", :groupchat
323		)
324	end
325end
326
327message do |m|
328	StatsD.increment("message")
329
330	sentry_hub = new_sentry_hub(m, name: "message")
331	today = Time.now.utc.to_date
332	CustomerRepo
333		.new(set_user: sentry_hub.current_scope.method(:set_user))
334		.find_by_jid(m.from.stripped).then { |customer|
335			EMPromise.all([
336				(customer.incr_message_usage if billable_message(m)),
337				customer.message_usage((today..(today - 30))).then do |usage|
338					if usage < 4500
339						customer.stanza_from(m)
340					else
341						BLATHER << m.as_error(
342							"policy-violation", :wait, "Please contact support"
343						)
344					end
345					notify_admin_of_usage(customer, usage, today) if usage > 900
346				end
347			])
348		}.catch_only(CustomerRepo::NotFound) { |e|
349			BLATHER << m.as_error("forbidden", :auth, e.message)
350		}.catch { |e| panic(e, sentry_hub) }
351end
352
353message :error? do |m|
354	StatsD.increment("message_error")
355
356	LOG.error "MESSAGE ERROR", stanza: m
357end
358
359IQ_MANAGER = SessionManager.new(self, :id)
360COMMAND_MANAGER = SessionManager.new(
361	self,
362	:sessionid,
363	timeout: 60 * 60,
364	error_if: ->(s) { s.cancel? }
365)
366
367disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
368	reply = iq.reply
369	reply.identities = [{
370		name: "JMP.chat",
371		type: "sms",
372		category: "gateway"
373	}]
374	reply.features = [
375		"http://jabber.org/protocol/disco#info",
376		"http://jabber.org/protocol/commands"
377	]
378	form = Blather::Stanza::X.find_or_create(reply.query)
379	form.type = "result"
380	form.fields = [
381		{
382			var: "FORM_TYPE",
383			type: "hidden",
384			value: "http://jabber.org/network/serverinfo"
385		}
386	] + CONFIG[:xep0157]
387	self << reply
388end
389
390disco_info do |iq|
391	reply = iq.reply
392	reply.identities = [{
393		name: "JMP.chat",
394		type: "sms",
395		category: "client"
396	}]
397	reply.features = [
398		"urn:xmpp:receipts"
399	]
400	self << reply
401end
402
403disco_items node: "http://jabber.org/protocol/commands" do |iq|
404	StatsD.increment("command_list")
405
406	sentry_hub = new_sentry_hub(iq, name: iq.node)
407	reply = iq.reply
408	reply.node = "http://jabber.org/protocol/commands"
409
410	CustomerRepo.new(
411		sgx_repo: Bwmsgsv2Repo.new,
412		set_user: sentry_hub.current_scope.method(:set_user)
413	).find_by_jid(
414		iq.from.stripped
415	).catch {
416		nil
417	}.then { |customer|
418		CommandList.for(customer, iq.from)
419	}.then { |list|
420		reply.items = list.map { |item|
421			Blather::Stanza::DiscoItems::Item.new(
422				iq.to,
423				item[:node],
424				item[:name]
425			)
426		}
427		self << reply
428	}.catch { |e| panic(e, sentry_hub) }
429end
430
431iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
432	StatsD.increment("extdisco")
433
434	reply = iq.reply
435	reply << Nokogiri::XML::Builder.new {
436		services(xmlns: "urn:xmpp:extdisco:2") do
437			service(
438				type: "sip",
439				host: CONFIG[:sip_host]
440			)
441		end
442	}.doc.root
443
444	self << reply
445end
446
447Command.new(
448	"jabber:iq:register",
449	"Register",
450	list_for: ->(*) { true },
451	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
452) {
453	Command.customer.catch_only(CustomerRepo::NotFound) {
454		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
455		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
456	}.then { |customer|
457		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
458		Registration.for(customer, TEL_SELECTIONS).then(&:write)
459	}.then {
460		StatsD.increment("registration.completed")
461	}.catch_only(Command::Execution::FinalStanza) do |e|
462		StatsD.increment("registration.completed")
463		EMPromise.reject(e)
464	end
465}.register(self).then(&CommandList.method(:register))
466
467Command.new(
468	"info",
469	"Show Account Info",
470	list_for: ->(*) { true },
471	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
472) {
473	Command.customer.then(&:info).then do |info|
474		Command.finish do |reply|
475			reply.command << info.form
476		end
477	end
478}.register(self).then(&CommandList.method(:register))
479
480Command.new(
481	"usage",
482	"Show Monthly Usage"
483) {
484	report_for = (Date.today..(Date.today << 1))
485
486	Command.customer.then { |customer|
487		customer.usage_report(report_for)
488	}.then do |usage_report|
489		Command.finish do |reply|
490			reply.command << usage_report.form
491		end
492	end
493}.register(self).then(&CommandList.method(:register))
494
495Command.new(
496	"transactions",
497	"Show Transactions",
498	list_for: ->(customer:, **) { !!customer&.currency }
499) {
500	Command.customer.then(&:transactions).then do |txs|
501		Command.finish do |reply|
502			reply.command << FormTemplate.render("transactions", transactions: txs)
503		end
504	end
505}.register(self).then(&CommandList.method(:register))
506
507Command.new(
508	"configure calls",
509	"Configure Calls",
510	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
511) {
512	Command.customer.then do |customer|
513		cc_form = ConfigureCallsForm.new(customer)
514		Command.reply { |reply|
515			reply.allowed_actions = [:next]
516			reply.command << cc_form.render
517		}.then { |iq|
518			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
519				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
520			})
521		}.then { Command.finish("Configuration saved!") }
522	end
523}.register(self).then(&CommandList.method(:register))
524
525Command.new(
526	"ogm",
527	"Record Voicemail Greeting",
528	list_for: ->(fwd: nil, **) { !!fwd },
529	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
530) {
531	Command.customer.then do |customer|
532		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
533			cc.from = customer.registered?.phone
534			cc.application_id = CONFIG[:sip][:app]
535			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
536			                "customer_id=#{customer.customer_id}"
537		end
538		Command.finish("You will now receive a call.")
539	end
540}.register(self).then(&CommandList.method(:register))
541
542Command.new(
543	"migrate billing",
544	"Switch from PayPal or expired trial to new billing",
545	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
546	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
547) {
548	EMPromise.all([
549		Command.customer,
550		Command.reply do |reply|
551			reply.allowed_actions = [:next]
552			reply.command << FormTemplate.render("migrate_billing")
553		end
554	]).then do |(customer, iq)|
555		Registration::Payment.for(
556			iq, customer, customer.registered?.phone,
557			final_message: PaypalDone::MESSAGE,
558			finish: PaypalDone
559		).then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
560			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
561			BLATHER.say(
562				CONFIG[:notify_admin],
563				"#{customer.customer_id} migrated to #{customer.currency}",
564				:groupchat
565			)
566			EMPromise.reject(s)
567		end
568	end
569}.register(self).then(&CommandList.method(:register))
570
571Command.new(
572	"credit cards",
573	"Credit Card Settings and Management"
574) {
575	Command.customer.then do |customer|
576		url = CONFIG[:credit_card_url].call(
577			customer.jid.to_s.gsub("\\", "%5C"),
578			customer.customer_id
579		)
580		desc = "Manage credits cards and settings"
581		Command.finish("#{desc}: #{url}") do |reply|
582			oob = OOB.find_or_create(reply.command)
583			oob.url = url
584			oob.desc = desc
585		end
586	end
587}.register(self).then(&CommandList.method(:register))
588
589Command.new(
590	"top up",
591	"Buy Account Credit by Credit Card",
592	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
593	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
594) {
595	Command.customer.then { |customer|
596		BuyAccountCreditForm.for(customer).then do |credit_form|
597			Command.reply { |reply|
598				reply.allowed_actions = [:complete]
599				credit_form.add_to_form(reply.form)
600			}.then do |iq|
601				Transaction.sale(customer, **credit_form.parse(iq.form))
602			end
603		end
604	}.then { |transaction|
605		transaction.insert.then do
606			Command.finish("#{transaction} added to your account balance.")
607		end
608	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
609		Command.finish(e.message, type: :error)
610	end
611}.register(self).then(&CommandList.method(:register))
612
613Command.new(
614	"alt top up",
615	"Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
616	list_for: ->(customer:, **) { !!customer&.currency }
617) {
618	Command.customer.then { |customer|
619		EMPromise.all([AltTopUpForm.for(customer), customer])
620	}.then do |(alt_form, customer)|
621		Command.reply { |reply|
622			reply.allowed_actions = [:complete]
623			reply.command << alt_form.form
624		}.then do |iq|
625			AddBitcoinAddress.for(iq, alt_form, customer).write
626		end
627	end
628}.register(self).then(&CommandList.method(:register))
629
630Command.new(
631	"plan settings",
632	"Manage your plan, including overage limits",
633	list_for: ->(customer:, **) { !!customer&.currency }
634) {
635	Command.customer.then do |customer|
636		Command.reply { |reply|
637			reply.allowed_actions = [:next]
638			reply.command << FormTemplate.render("plan_settings", customer: customer)
639		}.then { |iq|
640			Command.execution.customer_repo.put_monthly_overage_limit(
641				customer,
642				iq.form.field("monthly_overage_limit")&.value.to_i
643			)
644		}.then { Command.finish("Configuration saved!") }
645	end
646}.register(self).then(&CommandList.method(:register))
647
648Command.new(
649	"referral codes",
650	"Refer a friend for free credit"
651) {
652	Command.customer.then(&:unused_invites).then do |invites|
653		if invites.empty?
654			Command.finish("You have no more invites right now, try again later.")
655		else
656			Command.finish do |reply|
657				reply.form.type = :result
658				reply.form.title = "Unused Invite Codes"
659				reply.form.instructions =
660					"Each of these codes is single use and gives the person using " \
661					"them a free month of JMP service. You will receive credit " \
662					"equivalent to one month of free service if they later become " \
663					"a paying customer."
664				FormTable.new(
665					invites.map { |i| [i] },
666					code: "Invite Code"
667				).add_to_form(reply.form)
668			end
669		end
670	end
671}.register(self).then(&CommandList.method(:register))
672
673Command.new(
674	"reset sip account",
675	"Create or Reset SIP Account",
676	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
677) {
678	Command.customer.then do |customer|
679		sip_account = customer.reset_sip_account
680		Command.reply { |reply|
681			reply.allowed_actions = [:next]
682			form = sip_account.form
683			form.type = :form
684			form.fields += [{
685				type: :boolean, var: "change_fwd",
686				label: "Should inbound calls forward to this SIP account?"
687			}]
688			reply.command << form
689		}.then do |fwd|
690			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
691				Command.execution.customer_repo.put_fwd(
692					customer,
693					customer.fwd.with(uri: sip_account.uri)
694				).then { Command.finish("Inbound calls will now forward to SIP.") }
695			else
696				Command.finish
697			end
698		end
699	end
700}.register(self).then(&CommandList.method(:register))
701
702Command.new(
703	"lnp",
704	"Port in your number from another carrier",
705	list_for: ->(**) { true }
706) {
707	using FormToH
708
709	EMPromise.all([
710		Command.customer,
711		Command.reply do |reply|
712			reply.allowed_actions = [:next]
713			reply.command << FormTemplate.render("lnp")
714		end
715	]).then do |(customer, iq)|
716		order = PortInOrder.new(iq.form.to_h.slice(
717			"BillingTelephoneNumber", "Subscriber", "WirelessInfo"
718		).merge("CustomerOrderId" => customer.customer_id))
719		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
720		url = "https://dashboard.bandwidth.com/portal/r/a/" \
721		      "#{CONFIG[:creds][:account]}/orders/portIn/#{order_id}"
722		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
723		BLATHER.say(
724			CONFIG[:notify_admin],
725			"New port-in request for #{customer.customer_id}: #{url}",
726			:groupchat
727		)
728		Command.finish(
729			"Your port-in request has been accepted, " \
730			"support will contact you with next steps"
731		)
732	end
733}.register(self).then(&CommandList.method(:register))
734
735Command.new(
736	"customer info",
737	"Show Customer Info",
738	list_for: ->(customer: nil, **) { customer&.admin? }
739) {
740	Command.customer.then do |customer|
741		raise AuthError, "You are not an admin" unless customer&.admin?
742
743		Command.reply { |reply|
744			reply.allowed_actions = [:next]
745			reply.command << FormTemplate.render("customer_picker")
746		}.then { |response|
747			CustomerInfoForm.new(CustomerRepo.new(
748				sgx_repo: Bwmsgsv2Repo.new,
749				bandwidth_tn_repo: EmptyRepo.new # No CNAM in admin
750			)).find_customer(response)
751		}.then do |target_customer|
752			AdminCommand.new(target_customer).start
753		end
754	end
755}.register(self).then(&CommandList.method(:register))
756
757def reply_with_note(iq, text, type: :info)
758	reply = iq.reply
759	reply.status = :completed
760	reply.note_type = type
761	reply.note_text = text
762
763	self << reply
764end
765
766Command.new(
767	"web-register",
768	"Initiate Register from Web",
769	list_for: lambda { |from_jid: nil, **|
770		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
771	}
772) {
773	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
774		next EMPromise.reject(
775			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
776		)
777	end
778
779	Command.reply { |reply|
780		reply.command << FormTemplate.render("web_register")
781	}.then do |iq|
782		jid = iq.form.field("jid")&.value.to_s.strip
783		tel = iq.form.field("tel")&.value.to_s.strip
784		if jid !~ /\./
785			Command.finish("The Jabber ID you entered was not valid.", type: :error)
786		elsif tel !~ /\A\+\d+\Z/
787			Command.finish("Invalid telephone number", type: :error)
788		else
789			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
790				cmd.to = CONFIG[:web_register][:to]
791				cmd.node = "push-register"
792				cmd.form.fields = [{ var: "to", value: jid }]
793				cmd.form.type = "submit"
794			}).then { |result|
795				TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
796			}.then { Command.finish }
797		end
798	end
799}.register(self).then(&CommandList.method(:register))
800
801command sessionid: /./ do |iq|
802	COMMAND_MANAGER.fulfill(iq)
803end
804
805iq type: [:result, :error] do |iq|
806	IQ_MANAGER.fulfill(iq)
807end
808
809iq type: [:get, :set] do |iq|
810	StatsD.increment("unknown_iq")
811
812	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
813end