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