The personal finance app for everyone (by everyone)
Ruby
Add bulk invitation flow for admins (#4792)
Tristan the Katana192cd0c78542
diff --git a/app/controllers/invitations_controller.rb b/app/controllers/invitations_controller.rbindex 2fcb79388c..b4a0750156 100644--- a/app/controllers/invitations_controller.rb+++ b/app/controllers/invitations_controller.rb@@ -27,6 +27,57 @@ class InvitationsController < ApplicationControllerredirect_to settings_profile_pathend+ # Bulk invites deliberately exclude the admin role: granting admin to many+ # accounts at once is a privilege-escalation risk, so admins are invited one+ # at a time through the single-invite flow.+ BULK_INVITE_ROLES = %w[member guest].freeze++ def bulk_new+ redirect_to settings_profile_path, alert: t("invitations.create.failure") unless Current.user.admin?+ end++ def bulk_create+ unless Current.user.admin?+ flash[:alert] = t("invitations.create.failure")+ redirect_to settings_profile_path+ return+ end++ unless BULK_INVITE_ROLES.include?(bulk_invitation_role)+ flash[:alert] = t(".invalid_role")+ redirect_to settings_profile_path+ return+ end++ @bulk = BulkInvitation.new(+ family: Current.family,+ inviter: Current.user,+ role: bulk_invitation_role,+ emails: bulk_invitation_params[:emails],+ self_hosted: self_hosted?+ )++ # Reject oversized batches before any invitation is created or mail is+ # queued, so a rejection can never leave partially-processed results. Checked+ # before the empty guard because an oversized raw blob parses to no emails,+ # and "too many" is the accurate reason in that case.+ if @bulk.over_limit?+ flash[:alert] = t(".too_many", max: BulkInvitation::MAX_BULK_INVITES)+ redirect_to settings_profile_path+ return+ end++ if @bulk.emails.empty?+ flash[:alert] = t(".no_emails")+ redirect_to settings_profile_path+ return+ end++ @bulk.process+ @report_text = bulk_report_text(@bulk)+ render :bulk_create+ end+def accept@invitation = Invitation.find_by!(token: params[:id])@@ -61,6 +112,37 @@ class InvitationsController < ApplicationControllerparams.require(:invitation).permit(:email, :role)end+ def bulk_invitation_params+ params.require(:bulk_invitation).permit(:emails)+ end++ # Read role explicitly (not via permit) and validate it against+ # BULK_INVITE_ROLES before use, so role can never be mass-assigned to an+ # arbitrary/escalated value. Guard the shape: a flat (non-hash)+ # bulk_invitation param would raise TypeError on [:role], so return nil and+ # let the BULK_INVITE_ROLES check reject it with the handled flash.+ def bulk_invitation_role+ bulk = params.require(:bulk_invitation)+ bulk.is_a?(ActionController::Parameters) ? bulk[:role] : nil+ end++ def bulk_report_text(bulk)+ header = t(+ "invitations.bulk_create.summary",+ sent: bulk.sent,+ link_only: bulk.link_only,+ invalid: bulk.invalid+ )++ lines = bulk.results.map do |result|+ label = t("invitations.bulk_create.status.#{result.status}")+ detail = result.detail.present? ? " (#{result.detail})" : ""+ "#{result.email} - #{label}#{detail}"+ end++ ([ header, "" ] + lines).join("\n")+ end+# Persist the invitation, treating a raced partial-unique-index violation as# an ordinary save failure. A concurrent double-submit can still slip between# the `no_duplicate_pending_invitation_in_family` validation and the INSERT.diff --git a/app/javascript/controllers/text_download_controller.js b/app/javascript/controllers/text_download_controller.jsnew file mode 100644index 0000000000..f257faf604--- /dev/null+++ b/app/javascript/controllers/text_download_controller.js@@ -0,0 +1,24 @@+import { Controller } from "@hotwired/stimulus";++// Builds a client-side text file download from embedded report text. Keeps the+// user-submitted content out of any href (so it can't become a data:/javascript:+// URI) and avoids data-URI length limits on large batches.+export default class extends Controller {+ static targets = ["source"];+ static values = { filename: String };++ download() {+ const text = this.sourceTarget?.textContent ?? "";+ const blob = new Blob([text], { type: "text/plain" });+ const url = URL.createObjectURL(blob);++ const link = document.createElement("a");+ link.href = url;+ link.download = this.filenameValue || "download.txt";+ document.body.appendChild(link);+ link.click();+ link.remove();++ URL.revokeObjectURL(url);+ }+}diff --git a/app/models/bulk_invitation.rb b/app/models/bulk_invitation.rbnew file mode 100644index 0000000000..a0407b3227--- /dev/null+++ b/app/models/bulk_invitation.rb@@ -0,0 +1,119 @@+# Processes a batch of email addresses into individual Invitations, reusing the+# same per-email rules as InvitationsController#create (duplicate guards,+# self-invite guard, and mailing). An invitation never moves an existing+# account, so each row is simply built, saved and mailed. Collects a per-email+# report so the caller can summarize and export the outcome.+class BulkInvitation+ Result = Struct.new(:email, :status, :detail, keyword_init: true)++ # Splits the raw textarea on commas, semicolons and any whitespace (incl.+ # newlines), downcases/strips, drops blanks, and de-duplicates the batch.+ EMAIL_SEPARATORS = /[,;\s]+/++ # Caps a single submission so one request can't enqueue an unbounded number+ # of invitations/mail jobs. Enforced before any processing begins.+ MAX_BULK_INVITES = 50++ # Rejects an oversized raw blob before it is ever split/mapped, so a huge+ # pasted string (many separators, few real addresses) can't cost full+ # parse-time allocation just to be dropped by the row cap afterwards. Sized+ # to comfortably hold MAX_BULK_INVITES max-length (RFC 5321) addresses plus+ # separators.+ MAX_RAW_INPUT_LENGTH = MAX_BULK_INVITES * 320++ attr_reader :family, :inviter, :role, :emails, :results++ def initialize(family:, inviter:, role:, emails:, self_hosted: false)+ @family = family+ @inviter = inviter+ @role = role+ @self_hosted = self_hosted+ raw = emails.to_s+ @raw_too_long = raw.length > MAX_RAW_INPUT_LENGTH+ parsed = @raw_too_long ? [] : parse_emails(raw)+ # Cap on the submitted count (pre-dedup) so a huge pasted list can't slip+ # through by collapsing to a few addresses after de-duplication.+ @submitted_count = parsed.size+ @emails = parsed.uniq+ @results = []+ end++ def over_limit?+ @raw_too_long || @submitted_count > MAX_BULK_INVITES+ end++ def process+ @results = emails.map { |email| invite(email) }+ self+ end++ def sent+ count(:sent)+ end++ def link_only+ count(:link_only)+ end++ def invalid+ count(:invalid)+ end++ private++ def count(status)+ results.count { |r| r.status == status }+ end++ def invite(email)+ invitation = family.invitations.build(email: email, role: role)+ invitation.inviter = inviter++ unless save_invitation(invitation)+ return Result.new(email: email, status: :invalid, detail: invitation.errors.full_messages.to_sentence)+ end++ deliver_invite(invitation)+ rescue StandardError => e+ # Any unexpected persistence error (lock timeout, connection blip, etc.)+ # must not propagate out of #process and discard the results already+ # collected for earlier rows in this batch — those invitations may already+ # be committed. Report this row as failed and keep going.+ Rails.logger.error("BulkInvitation failed to process invite for #{email}: #{e.message}")+ Result.new(email: email, status: :invalid, detail: I18n.t("invitations.bulk_create.errors.processing_failed"))+ end++ # A failed enqueue (e.g. the job backend is unreachable) must not abort the+ # whole batch and discard the results already collected. The invitation is+ # persisted either way, so report it as failed and let the admin re-invite.+ #+ # On self-hosted instances no mail is enqueued, so reporting :sent would be+ # a lie — the admin has to share the invite link manually. Report :link_only+ # instead so the summary/report reflects that nothing was emailed.+ def deliver_invite(invitation)+ return Result.new(email: invitation.email, status: :link_only) if @self_hosted++ InvitationMailer.invite_email(invitation).deliver_later+ Result.new(email: invitation.email, status: :sent)+ rescue StandardError => e+ Rails.logger.error("BulkInvitation failed to enqueue invite for #{invitation.email}: #{e.message}")+ Result.new(email: invitation.email, status: :invalid, detail: I18n.t("invitations.bulk_create.errors.email_not_queued"))+ end++ # Mirrors InvitationsController#save_invitation: a raced partial-unique-index+ # violation is treated as an ordinary save failure rather than a 500.+ def save_invitation(invitation)+ invitation.save+ rescue ActiveRecord::RecordNotUnique+ false+ end++ # Returns normalized, non-blank addresses preserving order and duplicates;+ # de-duplication happens in the initializer after the raw count is recorded.+ def parse_emails(raw)+ raw.to_s+ .split(EMAIL_SEPARATORS)+ .map { |e| e.strip.downcase }+ .reject(&:blank?)+ end+enddiff --git a/app/views/invitations/bulk_create.html.erb b/app/views/invitations/bulk_create.html.erbnew file mode 100644index 0000000000..48bff557e4--- /dev/null+++ b/app/views/invitations/bulk_create.html.erb@@ -0,0 +1,53 @@+<%+ status_tones = {+ sent: :success,+ link_only: :success,+ invalid: :error+ }+%>+<%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t(".title")) %>++ <% dialog.with_body do %>+ <div class="space-y-4">+ <p class="text-primary text-sm">+ <%= t(".summary", sent: @bulk.sent, link_only: @bulk.link_only, invalid: @bulk.invalid) %>+ </p>++ <% if @bulk.results.any? %>+ <div class="space-y-2 max-h-72 overflow-y-auto">+ <% @bulk.results.each do |result| %>+ <div class="flex items-center justify-between gap-2 bg-container p-3 shadow-border-xs rounded-lg">+ <p class="text-primary text-sm truncate"><%= result.email %></p>+ <%= render DS::Pill.new(+ label: t(".status.#{result.status}"),+ tone: status_tones.fetch(result.status, :neutral),+ marker: false,+ size: :sm+ ) %>+ </div>+ <% end %>+ </div>+ <% end %>++ <div class="flex items-center gap-2" data-controller="text-download" data-text-download-filename-value="invitation-report.txt">+ <span data-text-download-target="source" class="hidden"><%= @report_text %></span>++ <%= render DS::Button.new(+ text: t(".download"),+ variant: :secondary,+ class: "flex-1 justify-center",+ data: { action: "text-download#download" }+ ) %>++ <%= render DS::Link.new(+ text: t(".invite_more"),+ href: bulk_new_invitations_path,+ variant: :primary,+ frame: :modal,+ class: "flex-1 justify-center"+ ) %>+ </div>+ </div>+ <% end %>+<% end %>diff --git a/app/views/invitations/bulk_new.html.erb b/app/views/invitations/bulk_new.html.erbnew file mode 100644index 0000000000..f3e5e9f4dc--- /dev/null+++ b/app/views/invitations/bulk_new.html.erb@@ -0,0 +1,23 @@+<%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t(".title"), subtitle: t(".subtitle", product_name: product_name, moniker: family_moniker_downcase)) %>++ <% dialog.with_body do %>+ <%= styled_form_with url: bulk_create_invitations_path, scope: :bulk_invitation, class: "space-y-4" do |form| %>+ <%= form.text_area :emails,+ required: true,+ rows: 6,+ placeholder: t(".emails_placeholder"),+ label: t(".emails_label") %>++ <%= form.select :role,+ options_for_select([+ (FeatureFlags.intro_ui? ? [t(".role_guest"), "guest"] : nil),+ [t(".role_member"), "member"]+ ].compact),+ {},+ { label: t(".role_label") } %>++ <%= render DS::Button.new(text: t(".submit"), type: "submit", full_width: true) %>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/settings/profiles/show.html.erb b/app/views/settings/profiles/show.html.erbindex a94d1816d4..38f83779b2 100644--- a/app/views/settings/profiles/show.html.erb+++ b/app/views/settings/profiles/show.html.erb@@ -118,6 +118,12 @@<%= icon("plus") %><%= t(".invite_member") %><% end %>+ <%= link_to bulk_new_invitations_path,+ class: "bg-container-inset flex items-center justify-center gap-2 text-secondary mt-1 hover:bg-container-inset-hover rounded-lg px-4 py-2 w-full text-center",+ data: { turbo_frame: :modal } do %>+ <%= icon("users") %>+ <%= t(".invite_multiple") %>+ <% end %><% end %></div></div>diff --git a/config/locales/views/invitations/en.yml b/config/locales/views/invitations/en.ymlindex 3406182182..1cde2f908a 100644--- a/config/locales/views/invitations/en.yml+++ b/config/locales/views/invitations/en.yml@@ -7,6 +7,30 @@ en:joined_household: You have joined the household.message: "%{inviter} has invited you to join as %{role}."title: Join %{family}+ bulk_create:+ download: Download report+ errors:+ email_not_queued: Invitation saved, but the email could not be queued. Remove it and try again.+ processing_failed: Invitation could not be processed. Check for an existing pending invitation before retrying.+ invalid_role: Bulk invitations can only be sent to members and guests.+ invite_more: Invite more+ no_emails: Enter at least one email address.+ status:+ invalid: Could not invite+ link_only: Ready to share+ sent: Invitation sent+ summary: "%{sent} sent, %{link_only} ready to share, %{invalid} failed."+ title: Invitation results+ too_many: You can invite up to %{max} people at a time. Please send fewer.+ bulk_new:+ emails_label: Email Addresses+ emails_placeholder: Enter email addresses separated by commas or new lines+ role_guest: Guest+ role_label: Role+ role_member: Member+ submit: Send Invitations+ subtitle: Invite several people to join your %{moniker} account on %{product_name}+ title: Invite Multiple Peoplecreate:failure: Could not send invitationown_email: "You can't invite yourself."diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex 8329091375..4c858bfc49 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -296,6 +296,7 @@ en:household_title: Householdinvitation_link: Invitation linkinvite_member: Add member+ invite_multiple: Add multiple memberslast_name: Last Namepage_title: Profile Infopending: Pendingdiff --git a/config/routes.rb b/config/routes.rbindex 388a653689..559bd2b7b1 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -793,6 +793,10 @@ Rails.application.routes.draw doresources :invitations, only: [ :new, :create, :destroy ] doget :accept, on: :member+ collection do+ get :bulk_new, path: "bulk"+ post :bulk_create, path: "bulk"+ endend# API routesdiff --git a/test/controllers/invitations_controller_test.rb b/test/controllers/invitations_controller_test.rbindex 8349b6e5a7..756191d412 100644--- a/test/controllers/invitations_controller_test.rb+++ b/test/controllers/invitations_controller_test.rb@@ -181,6 +181,153 @@ class InvitationsControllerTest < ActionDispatch::IntegrationTestassert_equal I18n.t("invitations.create.failure"), flash[:alert]end+ test "should get bulk_new" do+ get bulk_new_invitations_url+ assert_response :success+ assert_select "option[value=?]", "member"+ assert_select "option[value=?]", "admin", count: 0+ end++ test "bulk_create rejects the admin role" do+ assert_no_difference("Invitation.count") do+ post bulk_create_invitations_url, params: {+ bulk_invitation: {+ emails: "[email protected]",+ role: "admin"+ }+ }+ end++ assert_redirected_to settings_profile_path+ assert_equal I18n.t("invitations.bulk_create.invalid_role"), flash[:alert]+ end++ test "bulk_create handles a non-hash bulk_invitation param without 500ing" do+ assert_no_difference("Invitation.count") do+ post bulk_create_invitations_url, params: { bulk_invitation: "member" }+ end++ assert_redirected_to settings_profile_path+ assert_equal I18n.t("invitations.bulk_create.invalid_role"), flash[:alert]+ end++ test "non-admin cannot get bulk_new" do+ sign_in users(:family_member)+ get bulk_new_invitations_url+ assert_redirected_to settings_profile_path+ assert_equal I18n.t("invitations.create.failure"), flash[:alert]+ end++ test "bulk_create sends invitations to multiple new emails" do+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)++ assert_difference("Invitation.count", 2) do+ assert_enqueued_jobs 2, only: ActionMailer::MailDeliveryJob do+ post bulk_create_invitations_url, params: {+ bulk_invitation: {+ emails: "[email protected], [email protected]",+ role: "member"+ }+ }+ end+ end++ assert_response :success+ assert @admin.family.invitations.pending.where(email: "[email protected]").exists?+ assert @admin.family.invitations.pending.where(email: "[email protected]").exists?+ end++ test "bulk_create de-duplicates emails within the batch" do+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)++ assert_difference("Invitation.count", 1) do+ post bulk_create_invitations_url, params: {+ bulk_invitation: {+ role: "member"+ }+ }+ end++ assert_response :success+ assert_equal 1, @admin.family.invitations.where(email: "[email protected]").count+ end++ test "bulk_create invites an existing user's email without moving them and skips blanks" do+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)+ existing_user = users(:empty)+ original_family_id = existing_user.family_id+ assert original_family_id != @admin.family_id++ assert_difference("Invitation.count", 2) do+ post bulk_create_invitations_url, params: {+ bulk_invitation: {+ emails: "#{existing_user.email}, , [email protected]",+ role: "member"+ }+ }+ end++ assert_response :success+ # An invitation never moves an existing account; the blank entry is dropped.+ assert_equal original_family_id, existing_user.reload.family_id+ assert @admin.family.invitations.pending.where(email: existing_user.email).exists?+ assert @admin.family.invitations.pending.where(email: "[email protected]").exists?+ end++ test "bulk_create processes a batch of exactly the cap" do+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)+ emails = Array.new(BulkInvitation::MAX_BULK_INVITES) { |i| "exact#{i}@example.com" }.join("\n")++ assert_difference("Invitation.count", BulkInvitation::MAX_BULK_INVITES) do+ post bulk_create_invitations_url, params: {+ bulk_invitation: { emails: emails, role: "member" }+ }+ end++ assert_response :success+ end++ test "bulk_create rejects an empty batch" do+ assert_no_difference("Invitation.count") do+ post bulk_create_invitations_url, params: {+ bulk_invitation: { emails: " \n ", role: "member" }+ }+ end++ assert_redirected_to settings_profile_path+ assert_equal I18n.t("invitations.bulk_create.no_emails"), flash[:alert]+ end++ test "bulk_create rejects batches over the cap before creating any invitations" do+ emails = Array.new(BulkInvitation::MAX_BULK_INVITES + 1) { |i| "cap#{i}@example.com" }.join("\n")++ assert_no_difference("Invitation.count") do+ post bulk_create_invitations_url, params: {+ bulk_invitation: { emails: emails, role: "member" }+ }+ end++ assert_redirected_to settings_profile_path+ assert_equal I18n.t("invitations.bulk_create.too_many", max: BulkInvitation::MAX_BULK_INVITES), flash[:alert]+ end++ test "non-admin cannot bulk_create invitations" do+ sign_in users(:family_member)++ assert_no_difference("Invitation.count") do+ post bulk_create_invitations_url, params: {+ bulk_invitation: {+ emails: "[email protected]",+ role: "admin"+ }+ }+ end++ assert_redirected_to settings_profile_path+ assert_equal I18n.t("invitations.create.failure"), flash[:alert]+ end+test "accepting an invitation offers account creation only" doget accept_invitation_url(@invitation.token)assert_response :successdiff --git a/test/models/bulk_invitation_test.rb b/test/models/bulk_invitation_test.rbnew file mode 100644index 0000000000..036f3113ff--- /dev/null+++ b/test/models/bulk_invitation_test.rb@@ -0,0 +1,118 @@+require "test_helper"++class BulkInvitationTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper++ setup do+ @admin = users(:family_admin)+ @family = @admin.family+ end++ test "parses, normalizes and de-duplicates emails" do+ bulk = BulkInvitation.new(+ family: @family,+ inviter: @admin,+ role: "member",+ self_hosted: true+ ).process++ assert_equal %w[[email protected] [email protected]], bulk.emails.sort+ assert_equal 2, bulk.link_only+ end++ test "reports invalid entries without persisting them" do+ bulk = BulkInvitation.new(+ family: @family,+ inviter: @admin,+ role: "member",+ emails: "not-an-email, [email protected]",+ self_hosted: true+ ).process++ assert_equal 1, bulk.invalid+ assert_equal 1, bulk.link_only+ invalid = bulk.results.find { |r| r.status == :invalid }+ assert_equal "not-an-email", invalid.email+ assert_not @family.invitations.where(email: "not-an-email").exists?+ end++ test "invites an existing user's email without moving their account" do+ existing_user = users(:empty)+ original_family_id = existing_user.family_id+ assert original_family_id != @family.id++ bulk = BulkInvitation.new(+ family: @family,+ inviter: @admin,+ role: "member",+ emails: existing_user.email,+ self_hosted: true+ ).process++ # An invitation never moves an existing account; it only creates a pending+ # invitation the recipient can act on by signing up.+ assert_equal 1, bulk.link_only+ assert_equal original_family_id, existing_user.reload.family_id+ assert @family.invitations.pending.where(email: existing_user.email).exists?+ end++ test "a failed enqueue does not abort the batch and processing continues" do+ mailer = mock("mailer")+ mailer.stubs(:deliver_later)+ # First address's delivery blows up (e.g. job backend down); the second must+ # still be processed and reported.+ InvitationMailer.stubs(:invite_email).raises(StandardError.new("backend down")).then.returns(mailer)++ bulk = BulkInvitation.new(+ family: @family,+ inviter: @admin,+ role: "member",+ emails: "[email protected], [email protected]",+ self_hosted: false+ ).process++ results_by_email = bulk.results.index_by(&:email)+ assert_equal :invalid, results_by_email["[email protected]"].status+ assert_equal :sent, results_by_email["[email protected]"].status+ assert_equal 1, bulk.invalid+ assert_equal 1, bulk.sent+ # Both invitations persist regardless of enqueue outcome, so the admin can+ # remove the failed one and retry.+ assert @family.invitations.where(email: "[email protected]").exists?+ assert @family.invitations.where(email: "[email protected]").exists?+ end++ test "over_limit? flags batches above the cap" do+ emails = Array.new(BulkInvitation::MAX_BULK_INVITES + 1) { |i| "person#{i}@example.com" }.join(",")++ bulk = BulkInvitation.new(family: @family, inviter: @admin, role: "member", emails: emails)++ assert bulk.over_limit?+ end++ test "over_limit? flags an oversized raw blob without parsing it" do+ emails = "x" * (BulkInvitation::MAX_RAW_INPUT_LENGTH + 1)++ bulk = BulkInvitation.new(family: @family, inviter: @admin, role: "member", emails: emails)++ assert bulk.over_limit?+ assert_empty bulk.emails+ end++ test "reports link_only and enqueues no mail when self_hosted" do+ assert_no_enqueued_jobs only: ActionMailer::MailDeliveryJob do+ bulk = BulkInvitation.new(+ family: @family,+ inviter: @admin,+ role: "member",+ emails: "[email protected]",+ self_hosted: true+ ).process++ assert_equal 1, bulk.link_only+ assert_equal 0, bulk.sent+ assert_equal :link_only, bulk.results.first.status+ end+ end+end