dmails: update unread dmail count when dmail is hard deleted.

When a dmail is hard deleted, update the user's unread dmail count and
delete any associated mod reports.

Dmails aren't normally hard deleted, except when there's a large spam
wave that necessitates manual intervention.
This commit is contained in:
evazion
2020-08-28 11:28:28 -05:00
parent 319a2c011f
commit 5baeb3eecc
2 changed files with 28 additions and 2 deletions

View File

@@ -6,10 +6,11 @@ class Dmail < ApplicationRecord
belongs_to :owner, :class_name => "User"
belongs_to :to, :class_name => "User"
belongs_to :from, :class_name => "User"
has_many :moderation_reports, as: :model
has_many :moderation_reports, as: :model, dependent: :destroy
before_create :autoreport_spam
after_save :update_unread_dmail_count
after_destroy :update_unread_dmail_count
after_commit :send_email, on: :create
deletable
@@ -160,7 +161,7 @@ class Dmail < ApplicationRecord
end
def update_unread_dmail_count
return unless saved_change_to_id? || saved_change_to_is_read? || saved_change_to_is_deleted?
return unless saved_change_to_id? || saved_change_to_is_read? || saved_change_to_is_deleted? || destroyed?
owner.with_lock do
unread_count = owner.dmails.active.unread.count

View File

@@ -104,6 +104,31 @@ class DmailTest < ActiveSupport::TestCase
end
end
context "destroying a dmail" do
setup do
@recipient = create(:user)
@dmail = Dmail.create_split(from: @user, to: @recipient, creator_ip_addr: "127.0.0.1", title: "foo", body: "foo")
@modreport = create(:moderation_report, model: @dmail)
end
should "update both users' unread dmail counts" do
assert_equal(0, @user.reload.unread_dmail_count)
assert_equal(1, @recipient.reload.unread_dmail_count)
@user.dmails.last.destroy!
@recipient.dmails.last.destroy!
assert_equal(0, @user.reload.unread_dmail_count)
assert_equal(0, @recipient.reload.unread_dmail_count)
end
should "destroy any associated moderation reports" do
assert_equal(1, @dmail.moderation_reports.count)
@dmail.destroy!
assert_equal(0, @dmail.moderation_reports.count)
end
end
context "during validation" do
subject { FactoryBot.build(:dmail) }