fix(invitations): allow re-inviting after an unaccepted invite expires (#2543)

* fix(invitations): allow re-inviting after an unaccepted invite expires

An expired, never-accepted invitation still occupies the partial unique
index `index_invitations_on_email_and_family_id_pending` (predicate
`accepted_at IS NULL`), but the `pending` scope excludes it via the
`expires_at > now` clause. The duplicate-guard validation therefore
passes and the INSERT collides with the index, raising
ActiveRecord::RecordNotUnique — surfaced to the admin as a 500 with no
way to re-invite that address through the UI.

Remove the stale expired row inside the create transaction
(before_create) so the unique slot is freed and the re-invite succeeds.
It runs only after validations pass, so a still-pending (non-expired)
invitation can never be removed here. Add a controller-level rescue of
ActiveRecord::RecordNotUnique as a safety net against a concurrent
double-submit race.

Closes #2535

* refactor(invitations): scope RecordNotUnique rescue to the save

The method-level `rescue ActiveRecord::RecordNotUnique` wrapped the whole
create action, so any future write after @invitation.save (e.g.
accept_for) would silently be reported as a generic invite failure.
Extract save_invitation to scope the rescue to the save alone, and add a
regression test that drives the raced unique-index path directly.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
minion1227
2026-07-07 23:59:54 -07:00
committed by GitHub
parent 94d1e954e1
commit dd707ec91b
4 changed files with 101 additions and 1 deletions

View File

@@ -110,6 +110,32 @@ class InvitationTest < ActiveSupport::TestCase
assert invitation.valid?
end
test "re-inviting an email with an expired unaccepted invitation replaces it without raising" do
email = "expired-reinvite@example.com"
expired = @family.invitations.create!(email: email, role: "member", inviter: @inviter)
expired.update_column(:expires_at, 1.day.ago)
invitation = nil
assert_nothing_raised do
invitation = @family.invitations.create!(email: email, role: "admin", inviter: @inviter)
end
assert invitation.pending?
assert_not Invitation.exists?(expired.id), "stale expired invitation should be removed"
assert_equal 1, @family.invitations.where(email: email).count
end
test "re-invite does not remove a still-pending duplicate (validation blocks first)" do
email = "still-pending@example.com"
pending = @family.invitations.create!(email: email, role: "member", inviter: @inviter)
duplicate = @family.invitations.build(email: email, role: "admin", inviter: @inviter)
assert_not duplicate.valid?
assert Invitation.exists?(pending.id), "an unexpired pending invitation must be preserved"
end
test "can create invitation in same family (uniqueness scoped to family)" do
email = "same-family-test@example.com"