diff --git a/app/models/user.rb b/app/models/user.rb index fdbade8895..3836730d18 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -70,7 +70,7 @@ class User < ApplicationRecord :confirmable belongs_to :account, inverse_of: :user - belongs_to :invite, counter_cache: :uses, optional: true + belongs_to :invite, optional: true belongs_to :created_by_application, class_name: 'Doorkeeper::Application', optional: true belongs_to :role, class_name: 'UserRole', optional: true accepts_nested_attributes_for :account @@ -115,6 +115,7 @@ class User < ApplicationRecord before_validation :sanitize_role before_create :set_approved before_create :set_age_verified_at + after_create :increment_invite_uses after_commit :send_pending_devise_notifications after_create_commit :trigger_webhooks @@ -524,4 +525,8 @@ class User < ApplicationRecord def trigger_webhooks TriggerWebhookWorker.perform_async('account.created', 'Account', account_id) end + + def increment_invite_uses + invite&.increment!(:uses) + end end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 2b5021176f..3c9f4466bb 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -25,6 +25,21 @@ RSpec.describe User do describe 'Associations' do it { is_expected.to belong_to(:account).required } it { is_expected.to have_many(:login_activities) } + it { is_expected.to belong_to(:invite).optional } + it { is_expected.to have_many(:invites).inverse_of(:user).dependent(false) } + it { is_expected.to have_one(:invite_request).inverse_of(:user).dependent(:destroy).class_name(UserInviteRequest) } + + describe 'invite' do + let(:invite) { Fabricate(:invite) } + + it 'increments invite uses on creation but does not decrement it on deletion' do + expect { Fabricate(:user, email: 'alice@example.com', invite: invite) } + .to change { invite.reload.uses }.by(1) + + expect { described_class.find_by(email: 'alice@example.com').destroy } + .to_not(change { invite.reload.uses }) + end + end end describe 'Validations' do diff --git a/spec/system/auth/registrations_spec.rb b/spec/system/auth/registrations_spec.rb index acc4d89975..35d72de51a 100644 --- a/spec/system/auth/registrations_spec.rb +++ b/spec/system/auth/registrations_spec.rb @@ -122,6 +122,7 @@ RSpec.describe 'Auth Registration' do expect { fill_in_and_submit_form(apply: false) } .to change(User, :count).by(1) + .and change { invite.reload.uses }.by(1) expect(User.find_by(email: 'test@example.com')) .to have_attributes(approved: true)