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 = Dhall::Coder
 50	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
 51	.load(
 52		"(#{ARGV[0]}) : #{__dir__}/config-schema.dhall",
 53		transform_keys: ->(k) { k&.to_sym }
 54	)
 55WEB_LISTEN =
 56	if CONFIG[:web].is_a?(Hash)
 57		[CONFIG[:web][:interface], CONFIG[:web][:port]]
 58	else
 59		[CONFIG[:web]]
 60	end
 61
 62singleton_class.class_eval do
 63	include Blather::DSL
 64	Blather::DSL.append_features(self)
 65end
 66
 67require_relative "lib/polyfill"
 68require_relative "lib/alt_top_up_form"
 69require_relative "lib/admin_command"
 70require_relative "lib/add_bitcoin_address"
 71require_relative "lib/backend_sgx"
 72require_relative "lib/bwmsgsv2_repo"
 73require_relative "lib/bandwidth_iris_patch"
 74require_relative "lib/bandwidth_tn_order"
 75require_relative "lib/btc_sell_prices"
 76require_relative "lib/buy_account_credit_form"
 77require_relative "lib/configure_calls_form"
 78require_relative "lib/command"
 79require_relative "lib/command_list"
 80require_relative "lib/customer"
 81require_relative "lib/customer_info_form"
 82require_relative "lib/customer_repo"
 83require_relative "lib/dummy_command"
 84require_relative "lib/db_notification"
 85require_relative "lib/electrum"
 86require_relative "lib/empty_repo"
 87require_relative "lib/expiring_lock"
 88require_relative "lib/em"
 89require_relative "lib/form_to_h"
 90require_relative "lib/low_balance"
 91require_relative "lib/port_in_order"
 92require_relative "lib/payment_methods"
 93require_relative "lib/paypal_done"
 94require_relative "lib/postgres"
 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		repo = CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
200		repo.find(notify[:extra]).then do |customer|
201			DbNotification.for(notify, customer, repo)
202		end
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 = Postgres.connect(dbname: "jmp")
224
225	DB.hold do |conn|
226		conn.query("LISTEN low_balance")
227		conn.query("LISTEN possible_renewal")
228		catchup_notify(conn)
229		poll_for_notify(conn)
230	end
231
232	load_plans_to_db!
233
234	EM.add_periodic_timer(3600) do
235		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
236		ping.from = CONFIG[:component][:jid]
237		self << ping
238	end
239
240	Web.run(LOG.child, *WEB_LISTEN)
241end
242
243# workqueue_count MUST be 0 or else Blather uses threads!
244setup(
245	CONFIG[:component][:jid],
246	CONFIG[:component][:secret],
247	CONFIG[:server][:host],
248	CONFIG[:server][:port],
249	nil,
250	nil,
251	workqueue_count: 0
252)
253
254message to: /\Aaccount@/, body: /./ do |m|
255	StatsD.increment("deprecated_account_bot")
256
257	self << m.reply.tap { |out|
258		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
259	}
260end
261
262before(
263	:iq,
264	type: [:error, :result],
265	to: /\Acustomer_/,
266	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
267) { |iq| halt if IQ_MANAGER.fulfill(iq) }
268
269before nil, to: /\Acustomer_/, from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/ do |s|
270	StatsD.increment("stanza_customer")
271
272	sentry_hub = new_sentry_hub(s, name: "stanza_customer")
273	CustomerRepo.new(set_user: sentry_hub.current_scope.method(:set_user)).find(
274		s.to.node.delete_prefix("customer_")
275	).then { |customer|
276		customer.stanza_to(s)
277	}.catch { |e| panic(e, sentry_hub) }
278	halt
279end
280
281ADDRESSES_NS = "http://jabber.org/protocol/address"
282message(
283	to: /\A#{CONFIG[:component][:jid]}\Z/,
284	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
285) do |m|
286	StatsD.increment("inbound_group_text")
287	sentry_hub = new_sentry_hub(m, name: "inbound_group_text")
288
289	address = m.find("ns:addresses", ns: ADDRESSES_NS).first
290		&.find("ns:address", ns: ADDRESSES_NS)
291		&.find { |el| el["jid"].to_s.start_with?("customer_") }
292	pass unless address
293
294	CustomerRepo
295		.new(set_user: sentry_hub.current_scope.method(:set_user))
296		.find_by_jid(address["jid"]).then { |customer|
297			m.from = m.from.with(domain: CONFIG[:component][:jid])
298			m.to = m.to.with(domain: customer.jid.domain)
299			address["jid"] = customer.jid.to_s
300			BLATHER << m
301		}.catch_only(CustomerRepo::NotFound) { |e|
302			BLATHER << m.as_error("forbidden", :auth, e.message)
303		}.catch { |e| panic(e, sentry_hub) }
304end
305
306# Ignore groupchat messages
307# Especially if we have the component join MUC for notifications
308message(type: :groupchat) { true }
309
310def billable_message(m)
311	(m.body && !m.body.empty?) || m.find("ns:x", ns: OOB.registered_ns).first
312end
313
314class OverLimit < StandardError
315	def initialize(customer, usage)
316		super("Please contact support")
317		@customer = customer
318		@usage = usage
319	end
320
321	def notify_admin
322		ExpiringLock.new("jmp_usage_notify-#{@customer.customer_id}").with do
323			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
324			BLATHER.say(
325				CONFIG[:notify_admin], "#{@customer.customer_id} has used " \
326				"#{@usage} messages today", :groupchat
327			)
328		end
329	end
330end
331
332message do |m|
333	StatsD.increment("message")
334
335	sentry_hub = new_sentry_hub(m, name: "message")
336	today = Time.now.utc.to_date
337	CustomerRepo
338		.new(set_user: sentry_hub.current_scope.method(:set_user))
339		.find_by_jid(m.from.stripped).then { |customer|
340			next customer.stanza_from(m) unless billable_message(m)
341
342			EMPromise.all([
343				TrustLevelRepo.new.find(customer),
344				customer.message_usage((today..today))
345			]).then { |(tl, usage)|
346				raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
347			}.then do
348				EMPromise.all([
349					customer.incr_message_usage,
350					customer.stanza_from(m)
351				])
352			end
353		}.catch_only(OverLimit) { |e|
354			e.notify_admin
355			BLATHER << m.as_error("policy-violation", :wait, e.message)
356		}.catch_only(CustomerRepo::NotFound) { |e|
357			BLATHER << m.as_error("forbidden", :auth, e.message)
358		}.catch { |e| panic(e, sentry_hub) }
359end
360
361message :error? do |m|
362	StatsD.increment("message_error")
363
364	LOG.error "MESSAGE ERROR", stanza: m
365end
366
367IQ_MANAGER = SessionManager.new(self, :id)
368COMMAND_MANAGER = SessionManager.new(
369	self,
370	:sessionid,
371	timeout: 60 * 60,
372	error_if: ->(s) { s.cancel? }
373)
374
375disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
376	reply = iq.reply
377	reply.identities = [{
378		name: "JMP.chat",
379		type: "sms",
380		category: "gateway"
381	}]
382	reply.features = [
383		"http://jabber.org/protocol/disco#info",
384		"http://jabber.org/protocol/commands"
385	]
386	form = Blather::Stanza::X.find_or_create(reply.query)
387	form.type = "result"
388	form.fields = [
389		{
390			var: "FORM_TYPE",
391			type: "hidden",
392			value: "http://jabber.org/network/serverinfo"
393		}
394	] + CONFIG[:xep0157]
395	self << reply
396end
397
398disco_info do |iq|
399	reply = iq.reply
400	reply.identities = [{
401		name: "JMP.chat",
402		type: "sms",
403		category: "client"
404	}]
405	reply.features = [
406		"urn:xmpp:receipts"
407	]
408	self << reply
409end
410
411disco_items node: "http://jabber.org/protocol/commands" do |iq|
412	StatsD.increment("command_list")
413
414	sentry_hub = new_sentry_hub(iq, name: iq.node)
415	reply = iq.reply
416	reply.node = "http://jabber.org/protocol/commands"
417
418	CustomerRepo.new(
419		sgx_repo: Bwmsgsv2Repo.new,
420		set_user: sentry_hub.current_scope.method(:set_user)
421	).find_by_jid(
422		iq.from.stripped
423	).catch {
424		nil
425	}.then { |customer|
426		CommandList.for(customer, iq.from)
427	}.then { |list|
428		reply.items = list.map { |item|
429			Blather::Stanza::DiscoItems::Item.new(
430				iq.to,
431				item[:node],
432				item[:name]
433			)
434		}
435		self << reply
436	}.catch { |e| panic(e, sentry_hub) }
437end
438
439iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
440	StatsD.increment("extdisco")
441
442	reply = iq.reply
443	reply << Nokogiri::XML::Builder.new {
444		services(xmlns: "urn:xmpp:extdisco:2") do
445			service(
446				type: "sip",
447				host: CONFIG[:sip_host]
448			)
449		end
450	}.doc.root
451
452	self << reply
453end
454
455Command.new(
456	"jabber:iq:register",
457	"Register",
458	list_for: ->(*) { true },
459	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
460) {
461	Command.customer.catch_only(CustomerRepo::NotFound) {
462		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
463		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
464	}.then { |customer|
465		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
466		Registration.for(customer, TEL_SELECTIONS).then(&:write)
467	}.then {
468		StatsD.increment("registration.completed")
469	}.catch_only(Command::Execution::FinalStanza) do |e|
470		StatsD.increment("registration.completed")
471		EMPromise.reject(e)
472	end
473}.register(self).then(&CommandList.method(:register))
474
475Command.new(
476	"info",
477	"Show Account Info",
478	list_for: ->(*) { true },
479	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
480) {
481	Command.customer.then(&:info).then do |info|
482		Command.finish do |reply|
483			reply.command << info.form
484		end
485	end
486}.register(self).then(&CommandList.method(:register))
487
488Command.new(
489	"usage",
490	"Show Monthly Usage"
491) {
492	report_for = (Date.today..(Date.today << 1))
493
494	Command.customer.then { |customer|
495		customer.usage_report(report_for)
496	}.then do |usage_report|
497		Command.finish do |reply|
498			reply.command << usage_report.form
499		end
500	end
501}.register(self).then(&CommandList.method(:register))
502
503Command.new(
504	"transactions",
505	"Show Transactions",
506	list_for: ->(customer:, **) { !!customer&.currency }
507) {
508	Command.customer.then(&:transactions).then do |txs|
509		Command.finish do |reply|
510			reply.command << FormTemplate.render("transactions", transactions: txs)
511		end
512	end
513}.register(self).then(&CommandList.method(:register))
514
515Command.new(
516	"configure calls",
517	"Configure Calls",
518	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
519) {
520	Command.customer.then do |customer|
521		cc_form = ConfigureCallsForm.new(customer)
522		Command.reply { |reply|
523			reply.allowed_actions = [:next]
524			reply.command << cc_form.render
525		}.then { |iq|
526			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
527				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
528			})
529		}.then { Command.finish("Configuration saved!") }
530	end
531}.register(self).then(&CommandList.method(:register))
532
533Command.new(
534	"ogm",
535	"Record Voicemail Greeting",
536	list_for: ->(fwd: nil, **) { !!fwd },
537	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
538) {
539	Command.customer.then do |customer|
540		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
541			cc.from = customer.registered?.phone
542			cc.application_id = CONFIG[:sip][:app]
543			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
544			                "customer_id=#{customer.customer_id}"
545		end
546		Command.finish("You will now receive a call.")
547	end
548}.register(self).then(&CommandList.method(:register))
549
550Command.new(
551	"migrate billing",
552	"Switch from PayPal or expired trial to new billing",
553	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
554	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
555) {
556	EMPromise.all([
557		Command.customer,
558		Command.reply do |reply|
559			reply.allowed_actions = [:next]
560			reply.command << FormTemplate.render("migrate_billing")
561		end
562	]).then do |(customer, iq)|
563		Registration::Payment.for(
564			iq, customer, customer.registered?.phone,
565			final_message: PaypalDone::MESSAGE,
566			finish: PaypalDone
567		).then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
568			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
569			BLATHER.say(
570				CONFIG[:notify_admin],
571				"#{customer.customer_id} migrated to #{customer.currency}",
572				:groupchat
573			)
574			EMPromise.reject(s)
575		end
576	end
577}.register(self).then(&CommandList.method(:register))
578
579Command.new(
580	"credit cards",
581	"Credit Card Settings and Management"
582) {
583	Command.customer.then do |customer|
584		url = CONFIG[:credit_card_url].call(
585			customer.jid.to_s.gsub("\\", "%5C"),
586			customer.customer_id
587		)
588		desc = "Manage credits cards and settings"
589		Command.finish("#{desc}: #{url}") do |reply|
590			oob = OOB.find_or_create(reply.command)
591			oob.url = url
592			oob.desc = desc
593		end
594	end
595}.register(self).then(&CommandList.method(:register))
596
597Command.new(
598	"top up",
599	"Buy Account Credit by Credit Card",
600	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
601	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
602) {
603	Command.customer.then { |customer|
604		BuyAccountCreditForm.for(customer).then do |credit_form|
605			Command.reply { |reply|
606				reply.allowed_actions = [:complete]
607				credit_form.add_to_form(reply.form)
608			}.then do |iq|
609				Transaction.sale(customer, **credit_form.parse(iq.form))
610			end
611		end
612	}.then { |transaction|
613		transaction.insert.then do
614			Command.finish("#{transaction} added to your account balance.")
615		end
616	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
617		Command.finish(e.message, type: :error)
618	end
619}.register(self).then(&CommandList.method(:register))
620
621Command.new(
622	"alt top up",
623	"Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
624	list_for: ->(customer:, **) { !!customer&.currency }
625) {
626	Command.customer.then { |customer|
627		EMPromise.all([AltTopUpForm.for(customer), customer])
628	}.then do |(alt_form, customer)|
629		Command.reply { |reply|
630			reply.allowed_actions = [:complete]
631			reply.command << alt_form.form
632		}.then do |iq|
633			AddBitcoinAddress.for(iq, alt_form, customer).write
634		end
635	end
636}.register(self).then(&CommandList.method(:register))
637
638Command.new(
639	"plan settings",
640	"Manage your plan, including overage limits",
641	list_for: ->(customer:, **) { !!customer&.currency }
642) {
643	Command.customer.then do |customer|
644		Command.reply { |reply|
645			reply.allowed_actions = [:next]
646			reply.command << FormTemplate.render("plan_settings", customer: customer)
647		}.then { |iq|
648			Command.execution.customer_repo.put_monthly_overage_limit(
649				customer,
650				iq.form.field("monthly_overage_limit")&.value.to_i
651			)
652		}.then { Command.finish("Configuration saved!") }
653	end
654}.register(self).then(&CommandList.method(:register))
655
656Command.new(
657	"referral codes",
658	"Refer a friend for free credit"
659) {
660	Command.customer.then(&:unused_invites).then do |invites|
661		if invites.empty?
662			Command.finish("You have no more invites right now, try again later.")
663		else
664			Command.finish do |reply|
665				reply.form.type = :result
666				reply.form.title = "Unused Invite Codes"
667				reply.form.instructions =
668					"Each of these codes is single use and gives the person using " \
669					"them a free month of JMP service. You will receive credit " \
670					"equivalent to one month of free service if they later become " \
671					"a paying customer."
672				FormTable.new(
673					invites.map { |i| [i] },
674					code: "Invite Code"
675				).add_to_form(reply.form)
676			end
677		end
678	end
679}.register(self).then(&CommandList.method(:register))
680
681Command.new(
682	"reset sip account",
683	"Create or Reset SIP Account",
684	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
685) {
686	Command.customer.then do |customer|
687		sip_account = customer.reset_sip_account
688		Command.reply { |reply|
689			reply.allowed_actions = [:next]
690			form = sip_account.form
691			form.type = :form
692			form.fields += [{
693				type: :boolean, var: "change_fwd",
694				label: "Should inbound calls forward to this SIP account?"
695			}]
696			reply.command << form
697		}.then do |fwd|
698			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
699				Command.execution.customer_repo.put_fwd(
700					customer,
701					customer.fwd.with(uri: sip_account.uri)
702				).then { Command.finish("Inbound calls will now forward to SIP.") }
703			else
704				Command.finish
705			end
706		end
707	end
708}.register(self).then(&CommandList.method(:register))
709
710Command.new(
711	"lnp",
712	"Port in your number from another carrier",
713	list_for: ->(**) { true }
714) {
715	using FormToH
716
717	EMPromise.all([
718		Command.customer,
719		Command.reply do |reply|
720			reply.allowed_actions = [:next]
721			reply.command << FormTemplate.render("lnp")
722		end
723	]).then do |(customer, iq)|
724		order = PortInOrder.new(iq.form.to_h.slice(
725			"BillingTelephoneNumber", "Subscriber", "WirelessInfo"
726		).merge("CustomerOrderId" => customer.customer_id))
727		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
728		url = "https://dashboard.bandwidth.com/portal/r/a/" \
729		      "#{CONFIG[:creds][:account]}/orders/portIn/#{order_id}"
730		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
731		BLATHER.say(
732			CONFIG[:notify_admin],
733			"New port-in request for #{customer.customer_id}: #{url}",
734			:groupchat
735		)
736		Command.finish(
737			"Your port-in request has been accepted, " \
738			"support will contact you with next steps"
739		)
740	end
741}.register(self).then(&CommandList.method(:register))
742
743Command.new(
744	"customer info",
745	"Show Customer Info",
746	list_for: ->(customer: nil, **) { customer&.admin? }
747) {
748	Command.customer.then do |customer|
749		raise AuthError, "You are not an admin" unless customer&.admin?
750
751		Command.reply { |reply|
752			reply.allowed_actions = [:next]
753			reply.command << FormTemplate.render("customer_picker")
754		}.then { |response|
755			CustomerInfoForm.new(CustomerRepo.new(
756				sgx_repo: Bwmsgsv2Repo.new,
757				bandwidth_tn_repo: EmptyRepo.new # No CNAM in admin
758			)).find_customer(response)
759		}.then do |target_customer|
760			AdminCommand.new(target_customer).start
761		end
762	end
763}.register(self).then(&CommandList.method(:register))
764
765def reply_with_note(iq, text, type: :info)
766	reply = iq.reply
767	reply.status = :completed
768	reply.note_type = type
769	reply.note_text = text
770
771	self << reply
772end
773
774Command.new(
775	"https://ns.cheogram.com/sgx/jid-switch",
776	"Change JID",
777	list_for: ->(customer: nil, **) { customer },
778	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
779) {
780	Command.customer.then { |customer|
781		Command.reply { |reply|
782			reply.command << FormTemplate.render("jid_switch")
783		}.then { |response|
784			new_jid = response.form.field("jid").value
785			repo = Command.execution.customer_repo
786			repo.find_by_jid(new_jid)
787				.catch_only(CustomerRepo::NotFound) { nil }
788				.then { |cust|
789					next EMPromise.reject("Customer Already Exists") if cust
790
791					repo.change_jid(customer, new_jid)
792				}
793		}.then {
794			StatsD.increment("changejid.completed")
795			Command.finish { |reply|
796				reply.note_type = :info
797				reply.note_text = "Customer JID Changed"
798			}
799		}
800	}
801}.register(self).then(&CommandList.method(:register))
802
803Command.new(
804	"web-register",
805	"Initiate Register from Web",
806	list_for: lambda { |from_jid: nil, **|
807		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
808	}
809) {
810	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
811		next EMPromise.reject(
812			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
813		)
814	end
815
816	Command.reply { |reply|
817		reply.command << FormTemplate.render("web_register")
818	}.then do |iq|
819		jid = iq.form.field("jid")&.value.to_s.strip
820		tel = iq.form.field("tel")&.value.to_s.strip
821		if jid !~ /\./
822			Command.finish("The Jabber ID you entered was not valid.", type: :error)
823		elsif tel !~ /\A\+\d+\Z/
824			Command.finish("Invalid telephone number", type: :error)
825		else
826			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
827				cmd.to = CONFIG[:web_register][:to]
828				cmd.node = "push-register"
829				cmd.form.fields = [{ var: "to", value: jid }]
830				cmd.form.type = "submit"
831			}).then { |result|
832				TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
833			}.then { Command.finish }
834		end
835	end
836}.register(self).then(&CommandList.method(:register))
837
838command sessionid: /./ do |iq|
839	COMMAND_MANAGER.fulfill(iq)
840end
841
842iq type: [:result, :error] do |iq|
843	IQ_MANAGER.fulfill(iq)
844end
845
846iq type: [:get, :set] do |iq|
847	StatsD.increment("unknown_iq")
848
849	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
850end