Show group invite code as part of referral codes

Stephen Paul Weber created

Creating it if it does not exist.

Change summary

lib/customer.rb     |  4 ----
lib/invites_repo.rb | 15 +++++++++++++++
sgx_jmp.rb          | 30 ++++++++++++++++--------------
3 files changed, 31 insertions(+), 18 deletions(-)

Detailed changes

lib/customer.rb 🔗

@@ -93,10 +93,6 @@ class Customer
 		EMPromise.resolve(self)
 	end
 
-	def unused_invites
-		InvitesRepo.new(DB).unused_invites(customer_id)
-	end
-
 	def stanza_to(stanza)
 		stanza = stanza.dup
 		stanza.to = jid.with(resource: stanza.to&.resource)

lib/invites_repo.rb 🔗

@@ -1,5 +1,8 @@
 # frozen_string_literal: true
 
+require "multibases"
+require "securerandom"
+
 class InvitesRepo
 	class Invalid < StandardError; end
 
@@ -15,6 +18,18 @@ class InvitesRepo
 		promise.then { |result| result.map { |row| row["code"] } }
 	end
 
+	def find_or_create_group_code(customer_id)
+		@redis.get("jmp_customer_group_code-#{customer_id}").then do |code|
+			next code if code
+
+			code = Multibases.pack("base32upper", SecureRandom.bytes(4)).to_s
+			EMPromise.all([
+				@redis.set("jmp_customer_group_code-#{customer_id}", code),
+				@redis.hset("jmp_group_codes", code, customer_id)
+			]).then { code }
+		end
+	end
+
 	def stash_code(customer_id, code)
 		return EMPromise.resolve(nil) if code.to_s.strip == ""
 

sgx_jmp.rb 🔗

@@ -696,25 +696,27 @@ Command.new(
 	"referral codes",
 	"👥 Refer a friend for free credit"
 ) {
-	Command.customer.then(&:unused_invites).then do |invites|
+	repo = InvitesRepo.new
+	Command.customer.then { |customer|
+		EMPromise.all([
+			repo.find_or_create_group_code(customer.customer_id),
+			repo.unused_invites(customer.customer_id)
+		])
+	}.then do |(group_code, invites)|
 		if invites.empty?
 			Command.finish(
-				"You have no more referral codes right now, " \
-				"try again later."
+				"This code will provide credit equivalent to one month of service " \
+				"to anyone after they sign up and pay: #{group_code}\n\n" \
+				"You will receive credit equivalent to one month of service once " \
+				"their payment clears."
 			)
 		else
 			Command.finish do |reply|
-				reply.form.type = :result
-				reply.form.title = "Unused Referral 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)
+				reply.command << FormTemplate.render(
+					"codes",
+					invites: invites,
+					group_code: group_code
+				)
 			end
 		end
 	end