diff --git a/app/services/badge_granter.rb b/app/services/badge_granter.rb index 7e237703d22..7655329d403 100644 --- a/app/services/badge_granter.rb +++ b/app/services/badge_granter.rb @@ -44,7 +44,11 @@ class BadgeGranter I18n.with_locale(@user.effective_locale) do notification = @user.notifications.create( notification_type: Notification.types[:granted_badge], - data: { badge_id: @badge.id, badge_name: @badge.display_name, badge_slug: @badge.slug, username: @user.username}.to_json) + data: { badge_id: @badge.id, + badge_name: @badge.display_name, + badge_slug: @badge.slug, + username: @user.username}.to_json + ) user_badge.update_attributes notification_id: notification.id end end @@ -255,7 +259,8 @@ class BadgeGranter multiple_grant: true # cheat here, cause we only run on backfill and are deleting ) if badge.auto_revoke && full_backfill - sql = "INSERT INTO user_badges(badge_id, user_id, granted_at, granted_by_id, post_id) + sql = " WITH w as ( + INSERT INTO user_badges(badge_id, user_id, granted_at, granted_by_id, post_id) SELECT :id, q.user_id, q.granted_at, -1, #{post_id_field} FROM ( #{badge.query} ) q LEFT JOIN user_badges ub ON @@ -263,6 +268,9 @@ class BadgeGranter #{post_clause} /*where*/ RETURNING id, user_id, granted_at + ) + select w.*, username FROM w + JOIN users u on u.id = w.user_id " builder = SqlBuilder.new(sql) @@ -295,7 +303,12 @@ class BadgeGranter notification = Notification.create!( user_id: row.user_id, notification_type: Notification.types[:granted_badge], - data: { badge_id: badge.id, badge_name: badge.name }.to_json ) + data: { + badge_id: badge.id, + badge_name: badge.name, + badge_slug: badge.slug, + username: row.username + }.to_json ) Badge.exec_sql("UPDATE user_badges SET notification_id = :notification_id WHERE id = :id", notification_id: notification.id, diff --git a/spec/services/badge_granter_spec.rb b/spec/services/badge_granter_spec.rb index f29456dc870..2eef495663b 100644 --- a/spec/services/badge_granter_spec.rb +++ b/spec/services/badge_granter_spec.rb @@ -72,10 +72,12 @@ describe BadgeGranter do end it 'should grant missing badges' do + good_topic = Badge.find(Badge::GoodTopic) + post = Fabricate(:post, like_count: 30) 2.times { BadgeGranter.backfill(Badge.find(Badge::NiceTopic), post_ids: [post.id]) - BadgeGranter.backfill(Badge.find(Badge::GoodTopic)) + BadgeGranter.backfill(good_topic) } # TODO add welcome @@ -83,6 +85,12 @@ describe BadgeGranter do expect(post.user.notifications.count).to eq(2) + notification = post.user.notifications.last + data = notification.data_hash + expect(data["badge_id"]).to eq(good_topic.id) + expect(data["badge_slug"]).to eq(good_topic.slug) + expect(data["username"]).to eq(post.user.username) + expect(Badge.find(Badge::NiceTopic).grant_count).to eq(1) expect(Badge.find(Badge::GoodTopic).grant_count).to eq(1) end