registration.rb

  1# frozen_string_literal: true
  2
  3require "erb"
  4require "ruby-bandwidth-iris"
  5require "securerandom"
  6
  7require_relative "./alt_top_up_form"
  8require_relative "./bandwidth_tn_order"
  9require_relative "./bandwidth_tn_reservation_repo"
 10require_relative "./command"
 11require_relative "./em"
 12require_relative "./invites_repo"
 13require_relative "./oob"
 14require_relative "./parent_code_repo"
 15require_relative "./proxied_jid"
 16require_relative "./tel_selections"
 17require_relative "./welcome_message"
 18
 19def reload_customer(customer)
 20	EMPromise.resolve(nil).then do
 21		Command.execution.customer_repo.find(customer.customer_id)
 22	end
 23end
 24
 25class Registration
 26	def self.for(customer, google_play_userid, tel_selections)
 27		if (reg = customer.registered?)
 28			Registered.for(customer, reg.phone)
 29		else
 30			tel_selections[customer.jid].then(&:choose_tel).then do |tel|
 31				reserve_and_continue(tel_selections, customer, tel).then do
 32					FinishOrStartActivation.for(customer, google_play_userid, tel)
 33				end
 34			end
 35		end
 36	end
 37
 38	def self.reserve_and_continue(tel_selections, customer, tel)
 39		tel.reserve(customer).catch do
 40			tel_selections.delete(customer.jid).then {
 41				tel_selections[customer.jid]
 42			}.then { |choose|
 43				choose.choose_tel(
 44					error: "The JMP number #{tel} is no longer available."
 45				)
 46			}.then { |n_tel| reserve_and_continue(tel_selections, customer, n_tel) }
 47		end
 48	end
 49
 50	class Registered
 51		def self.for(customer, tel)
 52			jid = ProxiedJID.new(customer.jid).unproxied
 53			if jid.domain == CONFIG[:onboarding_domain]
 54				FinishOnboarding.for(customer, tel)
 55			else
 56				new(tel)
 57			end
 58		end
 59
 60		def initialize(tel)
 61			@tel = tel
 62		end
 63
 64		def write
 65			Command.finish("You are already registered with JMP number #{@tel}")
 66		end
 67	end
 68
 69	class FinishOrStartActivation
 70		def self.for(customer, google_play_userid, tel)
 71			if customer.active?
 72				Finish.new(customer, tel)
 73			elsif customer.balance >= CONFIG[:activation_amount_accept]
 74				BillPlan.new(customer, tel)
 75			else
 76				new(customer, google_play_userid, tel)
 77			end
 78		end
 79
 80		def initialize(customer, google_play_userid, tel)
 81			@customer = customer
 82			@tel = tel
 83			@google_play_userid = google_play_userid
 84		end
 85
 86		def write
 87			Command.reply { |reply|
 88				reply.allowed_actions = [:next]
 89				reply.note_type = :info
 90				reply.note_text = File.read("#{__dir__}/../fup.txt")
 91			}.then { Activation.for(@customer, @google_play_userid, @tel).write }
 92		end
 93	end
 94
 95	class Activation
 96		def self.for(customer, google_play_userid, tel)
 97			jid = ProxiedJID.new(customer.jid).unproxied
 98			if CONFIG[:approved_domains].key?(jid.domain.to_sym)
 99				Allow.for(customer, tel, jid)
100			elsif google_play_userid
101				GooglePlay.new(customer, google_play_userid, tel)
102			else
103				new(customer, tel)
104			end
105		end
106
107		def initialize(customer, tel)
108			@customer = customer
109			@tel = tel
110		end
111
112		attr_reader :customer, :tel
113
114		def form
115			FormTemplate.render("registration/activate", tel: tel)
116		end
117
118		def write
119			Command.reply { |reply|
120				reply.allowed_actions = [:next]
121				reply.command << form
122			}.then(&method(:next_step))
123		end
124
125		def next_step(iq)
126			EMPromise.resolve(nil).then do
127				plan = Plan.for_registration(iq.form.field("plan_name").value.to_s)
128				@customer = @customer.with_plan(plan.name)
129				Registration::Payment::InviteCode.new(
130					@customer, @tel, finish: Finish, db: DB, redis: REDIS
131				).parse(iq, force_save_plan: true)
132					.catch_only(InvitesRepo::Invalid) do
133						Payment.for(iq, @customer, @tel).then(&:write)
134					end
135			end
136		end
137
138		class GooglePlay
139			def initialize(customer, google_play_userid, tel)
140				@customer = customer
141				@google_play_userid = google_play_userid
142				@tel = tel
143				@invites = InvitesRepo.new(DB, REDIS)
144				@parent_code_repo = ParentCodeRepo.new(redis: REDIS, db: DB)
145			end
146
147			def used
148				REDIS.sismember("google_play_userids", @google_play_userid)
149			end
150
151			def form
152				FormTemplate.render(
153					"registration/google_play",
154					tel: @tel
155				)
156			end
157
158			def write
159				used.then do |u|
160					next Activation.for(@customer, nil, @tel).write if u.to_s == "1"
161
162					Command.reply { |reply|
163						reply.allowed_actions = [:next]
164						reply.command << form
165					}.then(&method(:activate)).then do
166						Finish.new(@customer, @tel).write
167					end
168				end
169			end
170
171			def activate(iq)
172				plan = Plan.for_registration(iq.form.field("plan_name").value)
173				code = iq.form.field("code")&.value
174				EMPromise.all([
175					@parent_code_repo.find(code),
176					REDIS.sadd("google_play_userids", @google_play_userid)
177				]).then { |(parent, _)|
178					save_active_plan(plan, parent)
179				}.then do
180					use_referral_code(code)
181				end
182			end
183
184		protected
185
186			def save_bogus_transaction
187				Transaction.new(
188					customer_id: @customer.customer_id,
189					transaction_id: "google_play_#{@customer.customer_id}",
190					amount: 0,
191					note: "Activated via Google Play",
192					bonus_eligible?: false
193				).insert
194			end
195
196			def save_active_plan(plan, parent)
197				@customer = @customer.with_plan(plan.name, parent_customer_id: parent)
198				save_bogus_transaction.then do
199					@customer.activate_plan_starting_now
200				end
201			end
202
203			def use_referral_code(code)
204				EMPromise.resolve(nil).then {
205					@invites.claim_code(@customer.customer_id, code) {
206						@customer.extend_plan
207					}
208				}.catch_only(InvitesRepo::Invalid) do
209					@invites.stash_code(@customer.customer_id, code)
210				end
211			end
212		end
213
214		class Allow < Activation
215			def self.for(customer, tel, jid)
216				credit_to = CONFIG[:approved_domains][jid.domain.to_sym]
217				new(customer, tel, credit_to)
218			end
219
220			def initialize(customer, tel, credit_to)
221				super(customer, tel)
222				@credit_to = credit_to
223			end
224
225			def form
226				FormTemplate.render(
227					"registration/allow",
228					tel: tel,
229					domain: customer.jid.domain
230				)
231			end
232
233			def next_step(iq)
234				plan = Plan.for_registration(iq.form.field("plan_name").value.to_s)
235				@customer = customer.with_plan(plan.name)
236				EMPromise.resolve(nil).then { activate }.then do
237					Finish.new(customer, tel).write
238				end
239			end
240
241		protected
242
243			def activate
244				DB.transaction do
245					if @credit_to
246						InvitesRepo.new(DB, REDIS).create_claimed_code(
247							@credit_to,
248							customer.customer_id
249						)
250					end
251					@customer.activate_plan_starting_now
252				end
253			end
254		end
255	end
256
257	module Payment
258		def self.kinds
259			@kinds ||= {}
260		end
261
262		def self.for(iq, customer, tel, finish: Finish, maybe_bill: MaybeBill)
263			kinds.fetch(iq.form.field("activation_method")&.value&.to_s&.to_sym) {
264				raise "Invalid activation method"
265			}.call(customer, tel, finish: finish, maybe_bill: maybe_bill)
266		end
267
268		class CryptoPaymentMethod
269			def crypto_addrs
270				raise NotImplementedError, "Subclass must implement"
271			end
272
273			def reg_form_name
274				raise NotImplementedError, "Subclass must implement"
275			end
276
277			def sell_prices
278				raise NotImplementedError, "Subclass must implement"
279			end
280
281			def initialize(customer, tel, maybe_bill: MaybeBill, **)
282				@customer = customer
283				@customer_id = customer.customer_id
284				@tel = tel
285				@maybe_bill = maybe_bill
286			end
287
288			def save
289				TEL_SELECTIONS.set(@customer.jid, @tel)
290			end
291
292			attr_reader :customer_id, :tel
293
294			def form(rate, addr)
295				FormTemplate.render(
296					reg_form_name,
297					amount: @maybe_bill.price(@tel) / rate,
298					addr: addr
299				)
300			end
301
302			def write
303				EMPromise.all([addr_and_rate, save]).then do |((addr, rate), _)|
304					Command.reply { |reply|
305						reply.allowed_actions = [:prev]
306						reply.status = :canceled
307						reply.command << form(rate, addr)
308					}.then(&method(:handle_possible_prev))
309				end
310			end
311
312		protected
313
314			def handle_possible_prev(iq)
315				raise "Action not allowed" unless iq.prev?
316
317				Activation.for(@customer, nil, @tel).then(&:write)
318			end
319
320			def addr_and_rate
321				EMPromise.all([
322					crypto_addrs.then { |addrs|
323						addrs.first || add_crypto_addr
324					},
325
326					sell_prices.public_send(@customer.currency.to_s.downcase)
327				])
328			end
329		end
330
331		class Bitcoin < CryptoPaymentMethod
332			Payment.kinds[:bitcoin] = method(:new)
333
334			def reg_form_name
335				"registration/btc"
336			end
337
338			def sell_prices
339				BTC_SELL_PRICES
340			end
341
342			def crypto_addrs
343				@customer.btc_addresses
344			end
345
346			def add_crypto_addr
347				@customer.add_btc_address
348			end
349		end
350
351		## Like Bitcoin
352		class BCH < CryptoPaymentMethod
353			Payment.kinds[:bch] = method(:new)
354
355			def reg_form_name
356				"registration/bch"
357			end
358
359			def sell_prices
360				BCH_SELL_PRICES
361			end
362
363			def crypto_addrs
364				@customer.bch_addresses
365			end
366
367			def add_crypto_addr
368				@customer.add_bch_address
369			end
370		end
371
372		class MaybeBill
373			def initialize(customer, tel, finish: Finish)
374				@customer = customer
375				@tel = tel
376				@finish = finish
377			end
378
379			def call
380				reload_customer(@customer).then do |customer|
381					if customer.balance >= CONFIG[:activation_amount_accept]
382						next BillPlan.new(customer, @tel, finish: @finish)
383					end
384
385					yield customer
386				end
387			end
388
389			# @return [Float] The price of the number + activation fee
390			# @param [TelSelection::ChooseTel::Tn] tel The phone number to charge
391			def self.price(tel)
392				CONFIG[:activation_amount] + tel.price
393			end
394		end
395
396		class JustCharge
397			def initialize(customer, *, **)
398				@customer = customer
399			end
400
401			def call; end
402
403			def self.price(tel)
404				tel.price
405			end
406		end
407
408		class CreditCard
409			Payment.kinds[:credit_card] = method(:new)
410
411			def initialize(customer, tel, finish: Finish, maybe_bill: MaybeBill)
412				@customer = customer
413				@tel = tel
414				@finish = finish
415				@maybe_bill = maybe_bill.new(customer, tel, finish: finish)
416				@price = maybe_bill.price(tel)
417			end
418
419			def oob(reply)
420				oob = OOB.find_or_create(reply.command)
421				oob.url = CONFIG[:credit_card_url].call(
422					reply.to.stripped.to_s.gsub("\\", "%5C"),
423					@customer.customer_id
424				) + "&amount=#{@price.ceil}"
425				oob.desc = "Pay by credit card, save, then next here to continue"
426				oob
427			end
428
429			def write
430				Command.reply { |reply|
431					reply.allowed_actions = [:next, :prev]
432					toob = oob(reply)
433					reply.note_type = :info
434					reply.note_text = "#{toob.desc}: #{toob.url}"
435				}.then do |iq|
436					next Activation.for(@customer, nil, @tel).then(&:write) if iq.prev?
437
438					@maybe_bill.call { self }&.then(&:write)
439				end
440			end
441		end
442
443		class InviteCode
444			Payment.kinds[:code] = method(:new)
445
446			FIELDS = [{
447				var: "code",
448				type: "text-single",
449				label: "Your referral code",
450				required: true
451			}].freeze
452
453			def initialize(
454				customer, tel,
455				error: nil, finish: Finish, db: DB, redis: REDIS, **
456			)
457				@customer = customer
458				@tel = tel
459				@error = error
460				@finish = finish
461				@invites_repo = InvitesRepo.new(db, redis)
462				@parent_code_repo = ParentCodeRepo.new(db: db, redis: redis)
463			end
464
465			def add_form(reply)
466				form = reply.form
467				form.type = :form
468				form.title = "Enter Referral Code"
469				form.instructions = @error if @error
470				form.fields = FIELDS
471			end
472
473			def write
474				Command.reply { |reply|
475					reply.allowed_actions = [:next, :prev]
476					add_form(reply)
477				}.then(&method(:parse)).catch_only(InvitesRepo::Invalid) { |e|
478					invalid_code(e).write
479				}
480			end
481
482			def parse(iq, force_save_plan: false)
483				return Activation.for(@customer, nil, @tel).then(&:write) if iq.prev?
484
485				verify(iq.form.field("code")&.value&.to_s, force_save_plan)
486					.then(&:write)
487			end
488
489		protected
490
491			def invalid_code(e)
492				self.class.new(@customer, @tel, error: e.message, finish: @finish)
493			end
494
495			def customer_id
496				@customer.customer_id
497			end
498
499			def verify(code, force_save_plan)
500				@parent_code_repo.claim_code(@customer, code) {
501					check_parent_balance
502				}.catch_only(ParentCodeRepo::Invalid) {
503					(@customer.save_plan! if force_save_plan).then do
504						@invites_repo.claim_code(customer_id, code) {
505							@customer.activate_plan_starting_now
506						}.then { @finish.new(@customer, @tel) }
507					end
508				}
509			end
510
511			def check_parent_balance
512				MaybeBill.new(@customer, @tel, finish: @finish).call do
513					msg = "Account balance not enough to cover the activation"
514					invalid_code(RuntimeError.new(msg))
515				end
516			end
517		end
518
519		class Mail
520			Payment.kinds[:mail] = method(:new)
521
522			def initialize(customer, tel, maybe_bill: MaybeBill, **)
523				@customer = customer
524				@tel = tel
525				@maybe_bill = maybe_bill
526			end
527
528			def form
529				FormTemplate.render(
530					"registration/mail",
531					currency: @customer.currency,
532					price: @maybe_bill.price(@tel),
533					**onboarding_extras
534				)
535			end
536
537			def onboarding_extras
538				jid = ProxiedJID.new(@customer.jid).unproxied
539				return {} unless jid.domain == CONFIG[:onboarding_domain]
540
541				{
542					customer_id: @customer.customer_id,
543					in_note: "Customer ID"
544				}
545			end
546
547			def write
548				Command.reply { |reply|
549					reply.allowed_actions = [:prev]
550					reply.status = :canceled
551					reply.command << form
552				}.then { |iq|
553					raise "Action not allowed" unless iq.prev?
554
555					Activation.for(@customer, nil, @tel).then(&:write)
556				}
557			end
558		end
559	end
560
561	class BillPlan
562		def initialize(customer, tel, finish: Finish)
563			@customer = customer
564			@tel = tel
565			@finish = finish
566		end
567
568		def write
569			@customer.bill_plan(note: "Bill #{@tel} for first month").then do
570				updated_customer =
571					@customer.with_balance(@customer.balance - @customer.monthly_price)
572				@finish.new(updated_customer, @tel).write
573			end
574		end
575	end
576
577	class Finish
578		def initialize(customer, tel)
579			@customer = customer
580			@tel = tel
581			@invites = InvitesRepo.new(DB, REDIS)
582		end
583
584		def write
585			if @customer.balance >= @tel.price
586				@tel.order(DB, @customer).then(
587					->(_) { customer_active_tel_purchased },
588					method(:number_purchase_error)
589				)
590			else
591				buy_number.then {
592					try_again
593				}.then(&:write)
594			end
595		end
596
597		def try_again
598			reload_customer(@customer).then do |customer|
599				Finish.new(customer, @tel)
600			end
601		end
602
603		def form
604			FormTemplate.render(
605				"registration/buy_number",
606				tel: @tel
607			)
608		end
609
610		def buy_number
611			Command.reply { |reply|
612				reply.command << form
613			}.then { |iq|
614				Payment.for(
615					iq, @customer, @tel,
616					maybe_bill: ::Registration::Payment::JustCharge
617				)
618			}.then(&:write)
619		end
620
621	protected
622
623		def number_purchase_error(e)
624			Command.log.error "number_purchase_error", e
625			TEL_SELECTIONS.delete(@customer.jid).then {
626				TEL_SELECTIONS[@customer.jid]
627			}.then { |choose|
628				choose.choose_tel(
629					error: "The JMP number #{@tel} is no longer available."
630				)
631			}.then { |tel| Finish.new(@customer, tel).write }
632		end
633
634		def raise_setup_error(e)
635			Command.log.error "@customer.register! failed", e
636			Command.finish(
637				"There was an error setting up your number, " \
638				"please contact JMP support.",
639				type: :error
640			)
641		end
642
643		def put_default_fwd
644			Bwmsgsv2Repo.new.put_fwd(@customer.customer_id, @tel.tel, CustomerFwd.for(
645				uri: "xmpp:#{@customer.jid}",
646				voicemail_enabled: true
647			))
648		end
649
650		def use_referral_code
651			@invites.use_pending_group_code(@customer.customer_id).then do |credit_to|
652				next unless credit_to
653
654				Transaction.new(
655					customer_id: @customer.customer_id,
656					transaction_id: "referral_#{@customer.customer_id}_#{credit_to}",
657					amount: @customer.monthly_price,
658					note: "Referral Bonus",
659					bonus_eligible?: false
660				).insert
661			end
662		end
663
664		def customer_active_tel_purchased
665			@customer.register!(@tel.tel).catch(&method(:raise_setup_error)).then {
666				EMPromise.all([
667					TEL_SELECTIONS.delete(@customer.jid),
668					put_default_fwd,
669					use_referral_code,
670					@tel.charge(@customer)
671				])
672			}.then do
673				FinishOnboarding.for(@customer, @tel).then(&:write)
674			end
675		end
676	end
677
678	module FinishOnboarding
679		def self.for(customer, tel, db: LazyObject.new { DB })
680			jid = ProxiedJID.new(customer.jid).unproxied
681			if jid.domain == CONFIG[:onboarding_domain]
682				Snikket.for(customer, tel, db: db)
683			else
684				NotOnboarding.new(customer, tel)
685			end
686		end
687
688		class Snikket
689			def self.for(customer, tel, db:)
690				::Snikket::Repo.new(db: db).find_by_customer(customer).then do |is|
691					if is.empty?
692						new(customer, tel, db: db)
693					elsif is[0].bootstrap_token.empty?
694						# This is a need_dns one, try the launch again
695						new(customer, tel, db: db).launch(is[0].domain)
696					else
697						GetInvite.for(customer, is[0], tel, db: db)
698					end
699				end
700			end
701
702			def initialize(customer, tel, error: nil, old: nil, db:)
703				@customer = customer
704				@tel = tel
705				@error = error
706				@db = db
707				@old = old
708			end
709
710			ACTION_VAR = "http://jabber.org/protocol/commands#actions"
711
712			def form
713				FormTemplate.render(
714					"registration/snikket",
715					tel: @tel,
716					error: @error
717				)
718			end
719
720			def write
721				Command.reply { |reply|
722					reply.allowed_actions = [:next]
723					reply.command << form
724				}.then(&method(:next_step))
725			end
726
727			def next_step(iq)
728				subdomain = empty_nil(iq.form.field("subdomain")&.value)
729				domain = "#{subdomain}.snikket.chat"
730				if iq.form.field(ACTION_VAR)&.value == "custom_domain"
731					CustomDomain.new(@customer, @tel, old: @old).write
732				elsif @old && (!subdomain || domain == @old.domain)
733					GetInvite.for(@customer, @old, @tel, db: @db).then(&:write)
734				else
735					launch(domain)
736				end
737			end
738
739			def launch(domain)
740				IQ_MANAGER.write(::Snikket::Launch.new(
741					nil, CONFIG[:snikket_hosting_api], domain: domain
742				)).then { |launched|
743					save_instance_and_wait(domain, launched)
744				}.catch { |e|
745					next EMPromise.reject(e) unless e.respond_to?(:text)
746
747					Snikket.new(@customer, @tel, old: @old, error: e.text, db: @db).write
748				}
749			end
750
751			def save_instance_and_wait(domain, launched)
752				instance = ::Snikket::CustomerInstance.for(@customer, domain, launched)
753				repo = ::Snikket::Repo.new(db: @db)
754				(@old&.domain == domain ? EMPromise.resolve(nil) : repo.del(@old))
755					.then { repo.put(instance) }.then do
756						if launched.status == :needs_dns
757							NeedsDNS.new(@customer, instance, @tel, launched.records).write
758						else
759							GetInvite.for(@customer, instance, @tel, db: @db).then(&:write)
760						end
761					end
762			end
763
764			def empty_nil(s)
765				s.nil? || s.empty? ? nil : s
766			end
767
768			class NeedsDNS < Snikket
769				def initialize(customer, instance, tel, records, db: DB)
770					@customer = customer
771					@instance = instance
772					@tel = tel
773					@records = records
774					@db = db
775				end
776
777				def form
778					FormTemplate.render(
779						"registration/snikket_needs_dns",
780						records: @records
781					)
782				end
783
784				def write
785					Command.reply { |reply|
786						reply.allowed_actions = [:prev, :next]
787						reply.command << form
788					}.then do |iq|
789						if iq.prev?
790							CustomDomain.new(@customer, @tel, old: @instance).write
791						else
792							launch(@instance.domain)
793						end
794					end
795				end
796			end
797
798			class GetInvite
799				def self.for(customer, instance, tel, db: DB)
800					instance.fetch_invite.then do |xmpp_uri|
801						if xmpp_uri
802							GoToInvite.new(xmpp_uri)
803						else
804							new(customer, instance, tel, db: db)
805						end
806					end
807				end
808
809				def initialize(customer, instance, tel, db: DB)
810					@customer = customer
811					@instance = instance
812					@tel = tel
813					@db = db
814				end
815
816				def form
817					FormTemplate.render(
818						"registration/snikket_wait",
819						domain: @instance.domain
820					)
821				end
822
823				def write
824					Command.reply { |reply|
825						reply.allowed_actions = [:prev, :next]
826						reply.command << form
827					}.then do |iq|
828						if iq.prev?
829							Snikket.new(@customer, @tel, old: @instance, db: @db).write
830						else
831							GetInvite.for(@customer, @instance, @tel, db: @db).then(&:write)
832						end
833					end
834				end
835			end
836
837			class GoToInvite
838				def initialize(xmpp_uri)
839					@xmpp_uri = xmpp_uri
840				end
841
842				def write
843					Command.finish do |reply|
844						oob = OOB.find_or_create(reply.command)
845						oob.url = @xmpp_uri
846					end
847				end
848			end
849		end
850
851		class CustomDomain < Snikket
852			def initialize(customer, tel, old: nil, error: nil, db: DB)
853				@customer = customer
854				@tel = tel
855				@error = error
856				@old = old
857				@db = db
858			end
859
860			def form
861				FormTemplate.render(
862					"registration/snikket_custom",
863					tel: @tel,
864					error: @error
865				)
866			end
867
868			def write
869				Command.reply { |reply|
870					reply.allowed_actions = [:prev, :next]
871					reply.command << form
872				}.then do |iq|
873					if iq.prev?
874						Snikket.new(@customer, @tel, db: @db, old: @old).write
875					else
876						launch(empty_nil(iq.form.field("domain")&.value) || @old&.domain)
877					end
878				end
879			end
880		end
881
882		class NotOnboarding
883			def initialize(customer, tel)
884				@customer = customer
885				@tel = tel
886			end
887
888			def write
889				WelcomeMessage.new(@customer, @tel).welcome
890				Command.finish("Your JMP account has been activated as #{@tel}")
891			end
892		end
893	end
894end