From cf76380c9158a7ab2793a66eb3e74d6a3687cac0 Mon Sep 17 00:00:00 2001
From: Matt Jankowski <matt@jankowski.online>
Date: Tue, 26 Mar 2024 09:12:09 -0400
Subject: [PATCH] Add `AccountStat.by_recent_status`, use in `Account` (#29704)

---
 app/models/account.rb             | 3 ++-
 app/models/account_stat.rb        | 3 +++
 app/models/relationship_filter.rb | 2 +-
 3 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/app/models/account.rb b/app/models/account.rb
index 322a29248e..3739709a13 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -132,12 +132,13 @@ class Account < ApplicationRecord
   scope :auditable, -> { where(id: Admin::ActionLog.select(:account_id).distinct) }
   scope :searchable, -> { without_unapproved.without_suspended.where(moved_to_account_id: nil) }
   scope :discoverable, -> { searchable.without_silenced.where(discoverable: true).joins(:account_stat) }
-  scope :by_recent_status, -> { includes(:account_stat).merge(AccountStat.order('last_status_at DESC NULLS LAST')).references(:account_stat) }
+  scope :by_recent_status, -> { includes(:account_stat).merge(AccountStat.by_recent_status).references(:account_stat) }
   scope :by_recent_activity, -> { left_joins(:user, :account_stat).order(coalesced_activity_timestamps.desc).order(id: :desc) }
   scope :popular, -> { order('account_stats.followers_count desc') }
   scope :by_domain_and_subdomains, ->(domain) { where(domain: Instance.by_domain_and_subdomains(domain).select(:domain)) }
   scope :not_excluded_by_account, ->(account) { where.not(id: account.excluded_from_timeline_account_ids) }
   scope :not_domain_blocked_by_account, ->(account) { where(arel_table[:domain].eq(nil).or(arel_table[:domain].not_in(account.excluded_from_timeline_domains))) }
+  scope :dormant, -> { joins(:account_stat).merge(AccountStat.without_recent_activity) }
 
   after_update_commit :trigger_update_webhooks
 
diff --git a/app/models/account_stat.rb b/app/models/account_stat.rb
index 0fea7732e9..14aa7ef800 100644
--- a/app/models/account_stat.rb
+++ b/app/models/account_stat.rb
@@ -20,6 +20,9 @@ class AccountStat < ApplicationRecord
 
   belongs_to :account, inverse_of: :account_stat
 
+  scope :by_recent_status, -> { order(arel_table[:last_status_at].desc.nulls_last) }
+  scope :without_recent_activity, -> { where(last_status_at: [nil, ...1.month.ago]) }
+
   update_index('accounts', :account)
 
   def following_count
diff --git a/app/models/relationship_filter.rb b/app/models/relationship_filter.rb
index d686f9ed89..828610e46a 100644
--- a/app/models/relationship_filter.rb
+++ b/app/models/relationship_filter.rb
@@ -114,7 +114,7 @@ class RelationshipFilter
   def activity_scope(value)
     case value
     when 'dormant'
-      Account.joins(:account_stat).where(account_stat: { last_status_at: [nil, ...1.month.ago] })
+      Account.dormant
     else
       raise Mastodon::InvalidParameterError, "Unknown activity: #{value}"
     end