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