diff --git a/lib/customer.rb b/lib/customer.rb index 8dd8c9bd74a33934e9dda4ea05ff5b5f75799120..ce37abe26c8d549f885177ee1e93313c13337bdb 100644 --- a/lib/customer.rb +++ b/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) diff --git a/lib/invites_repo.rb b/lib/invites_repo.rb index b862d33054a5e6d9b291d896803e1fcf8842f191..dac00bd6a91929d2f8aeeca01640cf25a53021d3 100644 --- a/lib/invites_repo.rb +++ b/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 == "" diff --git a/sgx_jmp.rb b/sgx_jmp.rb index 5d53ed48291e12428586dd130a223d5759b5e91c..21eb24b7b48b0662f1e65896e1066771f4734096 100644 --- a/sgx_jmp.rb +++ b/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