FIX: Don't grant sharing badges to users who don't exist (#13851)

FIX: Don’t grant sharing badges to users who don’t exist (#13851)

In badge queries for ‘First Share’ and ‘Nice/Good/Great Share’ badges, check that the user exists.

For ‘Nice+ Share’ badges, also grant badges if the number of shares is equal to the threshhold count to better match the descriptions.

diff --git a/lib/badge_queries.rb b/lib/badge_queries.rb
index e59476c..0f8a4c4 100644
--- a/lib/badge_queries.rb
+++ b/lib/badge_queries.rb
@@ -61,7 +61,7 @@ module BadgeQueries
       SELECT i.user_id, MIN(i.id) i_id
       FROM incoming_links i
       JOIN badge_posts p on p.id = i.post_id
-      WHERE i.user_id IS NOT NULL
+      JOIN users u on u.id = i.user_id
       GROUP BY i.user_id
     ) as views
     JOIN incoming_links i2 ON i2.id = views.i_id
@@ -196,9 +196,9 @@ module BadgeQueries
         SELECT i.user_id, MIN(i.id) i_id
         FROM incoming_links i
         JOIN badge_posts p on p.id = i.post_id
-        WHERE i.user_id IS NOT NULL
+        JOIN users u on u.id = i.user_id
         GROUP BY i.user_id,i.post_id
-        HAVING COUNT(*) > #{count}
+        HAVING COUNT(*) >= #{count}
       ) as views
       JOIN incoming_links i2 ON i2.id = views.i_id
     SQL
diff --git a/spec/services/badge_granter_spec.rb b/spec/services/badge_granter_spec.rb
index 2b3fe90..fd80190 100644
--- a/spec/services/badge_granter_spec.rb
+++ b/spec/services/badge_granter_spec.rb
@@ -205,6 +205,21 @@ describe BadgeGranter do
         BadgeGranter.backfill(Badge.find(Badge::FirstLike))
       }.to_not change { Notification.where(user_id: user.id).count }
     end
+
+    it 'does not grant sharing badges to deleted users' do
+      post = Fabricate(:post)
+      incoming_links = Fabricate.times(25, :incoming_link, post: post, user: user)
+      user_id = user.id
+      user.destroy!
+
+      nice_share = Badge.find(Badge::NiceShare)
+      first_share = Badge.find(Badge::FirstShare)
+
+      BadgeGranter.backfill(nice_share)
+      BadgeGranter.backfill(first_share)
+
+      expect(UserBadge.where(user_id: user_id).count).to eq(0)
+    end
   end
 
   describe 'grant' do

GitHub sha: efe38efb0aa09903d07994a19d4b3d4b81c524a4

This commit appears in #13851 which was approved by SamSaffron. It was merged by SamSaffron.