~singpolyma/sgx-jmp

ref: 8041a508c6d65ec0b52f4ddd3cd80b82b5e9e169 sgx-jmp/sgx_jmp.rb -rw-r--r-- 22.9 KiB
8041a508Christopher Vollick Trust Level in Customer Info 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
# frozen_string_literal: true

require "pg/em/connection_pool"
require "bandwidth"
require "bigdecimal"
require "blather/client/dsl" # Require this first to not auto-include
require "blather/client"
require "braintree"
require "date"
require "dhall"
require "em-hiredis"
require "em_promise"
require "ougai"
require "ruby-bandwidth-iris"
require "sentry-ruby"
require "statsd-instrument"

$stdout.sync = true
LOG = Ougai::Logger.new($stdout)
LOG.level = ENV.fetch("LOG_LEVEL", "info")
LOG.formatter = Ougai::Formatters::Readable.new(
	nil,
	nil,
	plain: !$stdout.isatty
)
Blather.logger = LOG
EM::Hiredis.logger = LOG
StatsD.logger = LOG
LOG.info "Starting"

Sentry.init do |config|
	config.logger = LOG
	config.breadcrumbs_logger = [:sentry_logger]
end

module SentryOugai
	class SentryLogger
		include Sentry::Breadcrumb::SentryLogger
		include Singleton
	end

	def _log(severity, message=nil, ex=nil, data=nil, &block)
		super
		SentryLogger.instance.add_breadcrumb(severity, message || ex.to_s, &block)
	end
end
LOG.extend SentryOugai

CONFIG = Dhall::Coder
	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
	.load(
		"(#{ARGV[0]}) : #{__dir__}/config-schema.dhall",
		transform_keys: ->(k) { k&.to_sym }
	)
WEB_LISTEN =
	if CONFIG[:web].is_a?(Hash)
		[CONFIG[:web][:interface], CONFIG[:web][:port]]
	else
		[CONFIG[:web]]
	end

singleton_class.class_eval do
	include Blather::DSL
	Blather::DSL.append_features(self)
end

require_relative "lib/polyfill"
require_relative "lib/alt_top_up_form"
require_relative "lib/admin_command"
require_relative "lib/add_bitcoin_address"
require_relative "lib/backend_sgx"
require_relative "lib/bwmsgsv2_repo"
require_relative "lib/bandwidth_iris_patch"
require_relative "lib/bandwidth_tn_order"
require_relative "lib/btc_sell_prices"
require_relative "lib/buy_account_credit_form"
require_relative "lib/configure_calls_form"
require_relative "lib/command"
require_relative "lib/command_list"
require_relative "lib/customer"
require_relative "lib/customer_info_form"
require_relative "lib/customer_repo"
require_relative "lib/dummy_command"
require_relative "lib/db_notification"
require_relative "lib/electrum"
require_relative "lib/empty_repo"
require_relative "lib/expiring_lock"
require_relative "lib/em"
require_relative "lib/form_to_h"
require_relative "lib/low_balance"
require_relative "lib/port_in_order"
require_relative "lib/payment_methods"
require_relative "lib/paypal_done"
require_relative "lib/postgres"
require_relative "lib/registration"
require_relative "lib/transaction"
require_relative "lib/tel_selections"
require_relative "lib/session_manager"
require_relative "lib/statsd"
require_relative "web"

ELECTRUM = Electrum.new(**CONFIG[:electrum])
EM::Hiredis::Client.load_scripts_from("./redis_lua")

Faraday.default_adapter = :em_synchrony
BandwidthIris::Client.global_options = {
	account_id: CONFIG[:creds][:account],
	username: CONFIG[:creds][:username],
	password: CONFIG[:creds][:password]
}
BANDWIDTH_VOICE = Bandwidth::Client.new(
	voice_basic_auth_user_name: CONFIG[:creds][:username],
	voice_basic_auth_password: CONFIG[:creds][:password]
).voice_client.client

def new_sentry_hub(stanza, name: nil)
	hub = Sentry.get_current_hub&.new_from_top
	raise "Sentry.init has not been called" unless hub

	hub.push_scope
	hub.current_scope.clear_breadcrumbs
	hub.current_scope.set_transaction_name(name) if name
	hub.current_scope.set_user(jid: stanza.from.stripped.to_s)
	hub
end

class AuthError < StandardError; end

# Braintree is not async, so wrap in EM.defer for now
class AsyncBraintree
	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
		@gateway = Braintree::Gateway.new(
			environment: environment,
			merchant_id: merchant_id,
			public_key: public_key,
			private_key: private_key
		)
		@gateway.config.logger = LOG
	end

	def respond_to_missing?(m, *)
		@gateway.respond_to?(m) || super
	end

	def method_missing(m, *args)
		return super unless respond_to_missing?(m, *args)

		EM.promise_defer(klass: PromiseChain) do
			@gateway.public_send(m, *args)
		end
	end

	class PromiseChain < EMPromise
		def respond_to_missing?(*)
			false && super # We don't actually know what we respond to...
		end

		def method_missing(m, *args)
			return super if respond_to_missing?(m, *args)

			self.then { |o| o.public_send(m, *args) }
		end
	end
end

BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])

def panic(e, hub=nil)
	(Thread.current[:log] || LOG).fatal(
		"Error raised during event loop: #{e.class}",
		e
	)
	if e.is_a?(::Exception)
		(hub || Sentry).capture_exception(e, hint: { background: false })
	else
		(hub || Sentry).capture_message(e.to_s, hint: { background: false })
	end
	exit 1
end

EM.error_handler(&method(:panic))

# Infer anything we might have been notified about while we were down
def catchup_notify(db)
	db.query("SELECT customer_id FROM balances WHERE balance < 5").each do |c|
		db.query("SELECT pg_notify('low_balance', $1)", c.values)
	end
	db.query(<<~SQL).each do |c|
		SELECT customer_id
		FROM customer_plans INNER JOIN balances USING (customer_id)
		WHERE expires_at < LOCALTIMESTAMP AND balance >= 5
	SQL
		db.query("SELECT pg_notify('possible_renewal', $1)", c.values)
	end
end

def poll_for_notify(db)
	db.wait_for_notify_defer.then { |notify|
		repo = CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
		repo.find(notify[:extra]).then do |customer|
			DbNotification.for(notify, customer, repo)
		end
	}.then(&:call).then {
		poll_for_notify(db)
	}.catch(&method(:panic))
end

def load_plans_to_db!
	DB.transaction do
		DB.exec("TRUNCATE plans")
		CONFIG[:plans].each do |plan|
			DB.exec("INSERT INTO plans VALUES ($1)", [plan.to_json])
		end
	end
end

when_ready do
	LOG.info "Ready"
	BLATHER = self
	REDIS = EM::Hiredis.connect
	TEL_SELECTIONS = TelSelections.new
	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
	DB = Postgres.connect(dbname: "jmp")

	DB.hold do |conn|
		conn.query("LISTEN low_balance")
		conn.query("LISTEN possible_renewal")
		catchup_notify(conn)
		poll_for_notify(conn)
	end

	load_plans_to_db!

	EM.add_periodic_timer(3600) do
		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
		ping.from = CONFIG[:component][:jid]
		self << ping
	end

	Web.run(LOG.child, *WEB_LISTEN)
end

# workqueue_count MUST be 0 or else Blather uses threads!
setup(
	CONFIG[:component][:jid],
	CONFIG[:component][:secret],
	CONFIG[:server][:host],
	CONFIG[:server][:port],
	nil,
	nil,
	workqueue_count: 0
)

message to: /\Aaccount@/, body: /./ do |m|
	StatsD.increment("deprecated_account_bot")

	self << m.reply.tap { |out|
		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
	}
end

before(
	:iq,
	type: [:error, :result],
	to: /\Acustomer_/,
	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
) { |iq| halt if IQ_MANAGER.fulfill(iq) }

before nil, to: /\Acustomer_/, from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/ do |s|
	StatsD.increment("stanza_customer")

	sentry_hub = new_sentry_hub(s, name: "stanza_customer")
	CustomerRepo.new(set_user: sentry_hub.current_scope.method(:set_user)).find(
		s.to.node.delete_prefix("customer_")
	).then { |customer|
		customer.stanza_to(s)
	}.catch { |e| panic(e, sentry_hub) }
	halt
end

ADDRESSES_NS = "http://jabber.org/protocol/address"
message(
	to: /\A#{CONFIG[:component][:jid]}\Z/,
	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
) do |m|
	StatsD.increment("inbound_group_text")
	sentry_hub = new_sentry_hub(m, name: "inbound_group_text")

	address = m.find("ns:addresses", ns: ADDRESSES_NS).first
		&.find("ns:address", ns: ADDRESSES_NS)
		&.find { |el| el["jid"].to_s.start_with?("customer_") }
	pass unless address

	CustomerRepo
		.new(set_user: sentry_hub.current_scope.method(:set_user))
		.find_by_jid(address["jid"]).then { |customer|
			m.from = m.from.with(domain: CONFIG[:component][:jid])
			m.to = m.to.with(domain: customer.jid.domain)
			address["jid"] = customer.jid.to_s
			BLATHER << m
		}.catch_only(CustomerRepo::NotFound) { |e|
			BLATHER << m.as_error("forbidden", :auth, e.message)
		}.catch { |e| panic(e, sentry_hub) }
end

# Ignore groupchat messages
# Especially if we have the component join MUC for notifications
message(type: :groupchat) { true }

UNBILLED_TARGETS = Set.new(CONFIG[:unbilled_targets])
def billable_message(m)
	b = m.body
	!UNBILLED_TARGETS.member?(m.to.node) && \
		(b && !b.empty? || m.find("ns:x", ns: OOB.registered_ns).first)
end

class OverLimit < StandardError
	def initialize(customer, usage)
		super("Please contact support")
		@customer = customer
		@usage = usage
	end

	def notify_admin
		ExpiringLock.new("jmp_usage_notify-#{@customer.customer_id}").with do
			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
			BLATHER.say(
				CONFIG[:notify_admin], "#{@customer.customer_id} has used " \
				"#{@usage} messages today", :groupchat
			)
		end
	end
end

class CustomerExpired < StandardError; end

message do |m|
	StatsD.increment("message")

	sentry_hub = new_sentry_hub(m, name: "message")
	today = Time.now.utc.to_date
	CustomerRepo.new(set_user: sentry_hub.current_scope.method(:set_user))
		.find_by_jid(m.from.stripped).then { |customer|
			next customer.stanza_from(m) unless billable_message(m)

			if customer.plan_name && !customer.active?
				raise CustomerExpired, "Your account is expired, please top up"
			end

			EMPromise.all([
				TrustLevelRepo.new.find(customer),
				customer.message_usage((today..today))
			]).then { |(tl, usage)|
				raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
			}.then do
				EMPromise.all([
					customer.incr_message_usage, customer.stanza_from(m)
				])
			end
		}.catch_only(OverLimit) { |e|
			e.notify_admin
			BLATHER << m.as_error("policy-violation", :wait, e.message)
		}.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
			BLATHER << m.as_error("forbidden", :auth, e.message)
		}.catch { |e| panic(e, sentry_hub) }
end

message :error? do |m|
	StatsD.increment("message_error")

	LOG.error "MESSAGE ERROR", stanza: m
end

IQ_MANAGER = SessionManager.new(self, :id)
COMMAND_MANAGER = SessionManager.new(
	self,
	:sessionid,
	timeout: 60 * 60,
	error_if: ->(s) { s.cancel? }
)

disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
	reply = iq.reply
	reply.identities = [{
		name: "JMP.chat",
		type: "sms",
		category: "gateway"
	}]
	reply.features = [
		"http://jabber.org/protocol/disco#info",
		"http://jabber.org/protocol/commands"
	]
	form = Blather::Stanza::X.find_or_create(reply.query)
	form.type = "result"
	form.fields = [
		{
			var: "FORM_TYPE",
			type: "hidden",
			value: "http://jabber.org/network/serverinfo"
		}
	] + CONFIG[:xep0157]
	self << reply
end

disco_info do |iq|
	reply = iq.reply
	reply.identities = [{
		name: "JMP.chat",
		type: "sms",
		category: "client"
	}]
	reply.features = [
		"urn:xmpp:receipts"
	]
	self << reply
end

disco_items node: "http://jabber.org/protocol/commands" do |iq|
	StatsD.increment("command_list")

	sentry_hub = new_sentry_hub(iq, name: iq.node)
	reply = iq.reply
	reply.node = "http://jabber.org/protocol/commands"

	CustomerRepo.new(
		sgx_repo: Bwmsgsv2Repo.new,
		set_user: sentry_hub.current_scope.method(:set_user)
	).find_by_jid(
		iq.from.stripped
	).catch {
		nil
	}.then { |customer|
		CommandList.for(customer, iq.from)
	}.then { |list|
		reply.items = list.map { |item|
			Blather::Stanza::DiscoItems::Item.new(
				iq.to,
				item[:node],
				item[:name]
			)
		}
		self << reply
	}.catch { |e| panic(e, sentry_hub) }
end

iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
	StatsD.increment("extdisco")

	reply = iq.reply
	reply << Nokogiri::XML::Builder.new {
		services(xmlns: "urn:xmpp:extdisco:2") do
			service(
				type: "sip",
				host: CONFIG[:sip_host]
			)
		end
	}.doc.root

	self << reply
end

Command.new(
	"jabber:iq:register",
	"Register",
	list_for: ->(*) { true },
	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
) {
	Command.customer.catch_only(CustomerRepo::NotFound) {
		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
	}.then { |customer|
		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
		Registration.for(customer, TEL_SELECTIONS).then(&:write)
	}.then {
		StatsD.increment("registration.completed")
	}.catch_only(Command::Execution::FinalStanza) do |e|
		StatsD.increment("registration.completed")
		EMPromise.reject(e)
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"info",
	"Show Account Info",
	list_for: ->(*) { true },
	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
) {
	Command.customer.then(&:info).then do |info|
		Command.finish do |reply|
			reply.command << info.form
		end
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"usage",
	"Show Monthly Usage"
) {
	report_for = (Date.today..(Date.today << 1))

	Command.customer.then { |customer|
		customer.usage_report(report_for)
	}.then do |usage_report|
		Command.finish do |reply|
			reply.command << usage_report.form
		end
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"transactions",
	"Show Transactions",
	list_for: ->(customer:, **) { !!customer&.currency }
) {
	Command.customer.then(&:transactions).then do |txs|
		Command.finish do |reply|
			reply.command << FormTemplate.render("transactions", transactions: txs)
		end
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"configure calls",
	"Configure Calls",
	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
) {
	Command.customer.then do |customer|
		cc_form = ConfigureCallsForm.new(customer)
		Command.reply { |reply|
			reply.allowed_actions = [:next]
			reply.command << cc_form.render
		}.then { |iq|
			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
			})
		}.then { Command.finish("Configuration saved!") }
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"ogm",
	"Record Voicemail Greeting",
	list_for: ->(fwd: nil, **) { !!fwd },
	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
) {
	Command.customer.then do |customer|
		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
			cc.from = customer.registered?.phone
			cc.application_id = CONFIG[:sip][:app]
			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
			                "customer_id=#{customer.customer_id}"
		end
		Command.finish("You will now receive a call.")
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"migrate billing",
	"Switch from PayPal or expired trial to new billing",
	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
) {
	EMPromise.all([
		Command.customer,
		Command.reply do |reply|
			reply.allowed_actions = [:next]
			reply.command << FormTemplate.render("migrate_billing")
		end
	]).then do |(customer, iq)|
		Registration::Payment.for(
			iq, customer, customer.registered?.phone,
			final_message: PaypalDone::MESSAGE,
			finish: PaypalDone
		).then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
			BLATHER.say(
				CONFIG[:notify_admin],
				"#{customer.customer_id} migrated to #{customer.currency}",
				:groupchat
			)
			EMPromise.reject(s)
		end
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"credit cards",
	"Credit Card Settings and Management"
) {
	Command.customer.then do |customer|
		url = CONFIG[:credit_card_url].call(
			customer.jid.to_s.gsub("\\", "%5C"),
			customer.customer_id
		)
		desc = "Manage credits cards and settings"
		Command.finish("#{desc}: #{url}") do |reply|
			oob = OOB.find_or_create(reply.command)
			oob.url = url
			oob.desc = desc
		end
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"top up",
	"Buy Account Credit by Credit Card",
	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
) {
	Command.customer.then { |customer|
		BuyAccountCreditForm.for(customer).then do |credit_form|
			Command.reply { |reply|
				reply.allowed_actions = [:complete]
				credit_form.add_to_form(reply.form)
			}.then do |iq|
				Transaction.sale(customer, **credit_form.parse(iq.form))
			end
		end
	}.then { |transaction|
		transaction.insert.then do
			Command.finish("#{transaction} added to your account balance.")
		end
	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
		Command.finish(e.message, type: :error)
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"alt top up",
	"Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
	list_for: ->(customer:, **) { !!customer&.currency }
) {
	Command.customer.then { |customer|
		EMPromise.all([AltTopUpForm.for(customer), customer])
	}.then do |(alt_form, customer)|
		Command.reply { |reply|
			reply.allowed_actions = [:complete]
			reply.command << alt_form.form
		}.then do |iq|
			AddBitcoinAddress.for(iq, alt_form, customer).write
		end
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"plan settings",
	"Manage your plan, including overage limits",
	list_for: ->(customer:, **) { !!customer&.currency }
) {
	Command.customer.then do |customer|
		Command.reply { |reply|
			reply.allowed_actions = [:next]
			reply.command << FormTemplate.render("plan_settings", customer: customer)
		}.then { |iq|
			Command.execution.customer_repo.put_monthly_overage_limit(
				customer,
				iq.form.field("monthly_overage_limit")&.value.to_i
			)
		}.then { Command.finish("Configuration saved!") }
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"referral codes",
	"Refer a friend for free credit"
) {
	Command.customer.then(&:unused_invites).then do |invites|
		if invites.empty?
			Command.finish("You have no more invites right now, try again later.")
		else
			Command.finish do |reply|
				reply.form.type = :result
				reply.form.title = "Unused Invite Codes"
				reply.form.instructions =
					"Each of these codes is single use and gives the person using " \
					"them a free month of JMP service. You will receive credit " \
					"equivalent to one month of free service if they later become " \
					"a paying customer."
				FormTable.new(
					invites.map { |i| [i] },
					code: "Invite Code"
				).add_to_form(reply.form)
			end
		end
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"reset sip account",
	"Create or Reset SIP Account",
	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
) {
	Command.customer.then do |customer|
		sip_account = customer.reset_sip_account
		Command.reply { |reply|
			reply.allowed_actions = [:next]
			form = sip_account.form
			form.type = :form
			form.fields += [{
				type: :boolean, var: "change_fwd",
				label: "Should inbound calls forward to this SIP account?"
			}]
			reply.command << form
		}.then do |fwd|
			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
				Command.execution.customer_repo.put_fwd(
					customer,
					customer.fwd.with(uri: sip_account.uri)
				).then { Command.finish("Inbound calls will now forward to SIP.") }
			else
				Command.finish
			end
		end
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"lnp",
	"Port in your number from another carrier",
	list_for: ->(**) { true }
) {
	using FormToH

	EMPromise.all([
		Command.customer,
		Command.reply do |reply|
			reply.allowed_actions = [:next]
			reply.command << FormTemplate.render("lnp")
		end
	]).then do |(customer, iq)|
		order = PortInOrder.new(iq.form.to_h.slice(
			"BillingTelephoneNumber", "Subscriber", "WirelessInfo"
		).merge("CustomerOrderId" => customer.customer_id))
		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
		url = "https://dashboard.bandwidth.com/portal/r/a/" \
		      "#{CONFIG[:creds][:account]}/orders/portIn/#{order_id}"
		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
		BLATHER.say(
			CONFIG[:notify_admin],
			"New port-in request for #{customer.customer_id}: #{url}",
			:groupchat
		)
		Command.finish(
			"Your port-in request has been accepted, " \
			"support will contact you with next steps"
		)
	end
}.register(self).then(&CommandList.method(:register))

Command.new(
	"customer info",
	"Show Customer Info",
	list_for: ->(customer: nil, **) { customer&.admin? }
) {
	Command.customer.then do |customer|
		raise AuthError, "You are not an admin" unless customer&.admin?

		Command.reply { |reply|
			reply.allowed_actions = [:next]
			reply.command << FormTemplate.render("customer_picker")
		}.then { |response|
			CustomerInfoForm.new(CustomerRepo.new(
				sgx_repo: Bwmsgsv2Repo.new,
				bandwidth_tn_repo: EmptyRepo.new # No CNAM in admin
			)).find_customer(response)
		}.then do |target_customer|
			AdminCommand.new(target_customer).start
		end
	end
}.register(self).then(&CommandList.method(:register))

def reply_with_note(iq, text, type: :info)
	reply = iq.reply
	reply.status = :completed
	reply.note_type = type
	reply.note_text = text

	self << reply
end

Command.new(
	"https://ns.cheogram.com/sgx/jid-switch",
	"Change JID",
	list_for: ->(customer: nil, **) { customer },
	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
) {
	Command.customer.then { |customer|
		Command.reply { |reply|
			reply.command << FormTemplate.render("jid_switch")
		}.then { |response|
			new_jid = response.form.field("jid").value
			repo = Command.execution.customer_repo
			repo.find_by_jid(new_jid)
				.catch_only(CustomerRepo::NotFound) { nil }
				.then { |cust|
					next EMPromise.reject("Customer Already Exists") if cust

					repo.change_jid(customer, new_jid)
				}
		}.then {
			StatsD.increment("changejid.completed")
			Command.finish { |reply|
				reply.note_type = :info
				reply.note_text = "Customer JID Changed"
			}
		}
	}
}.register(self).then(&CommandList.method(:register))

Command.new(
	"web-register",
	"Initiate Register from Web",
	list_for: lambda { |from_jid: nil, **|
		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
	}
) {
	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
		next EMPromise.reject(
			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
		)
	end

	Command.reply { |reply|
		reply.command << FormTemplate.render("web_register")
	}.then do |iq|
		jid = iq.form.field("jid")&.value.to_s.strip
		tel = iq.form.field("tel")&.value.to_s.strip
		if jid !~ /\./
			Command.finish("The Jabber ID you entered was not valid.", type: :error)
		elsif tel !~ /\A\+\d+\Z/
			Command.finish("Invalid telephone number", type: :error)
		else
			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
				cmd.to = CONFIG[:web_register][:to]
				cmd.node = "push-register"
				cmd.form.fields = [{ var: "to", value: jid }]
				cmd.form.type = "submit"
			}).then { |result|
				TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
			}.then { Command.finish }
		end
	end
}.register(self).then(&CommandList.method(:register))

command sessionid: /./ do |iq|
	COMMAND_MANAGER.fulfill(iq)
end

iq type: [:result, :error] do |iq|
	IQ_MANAGER.fulfill(iq)
end

iq type: [:get, :set] do |iq|
	StatsD.increment("unknown_iq")

	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
end