diff --git a/app/controllers/badges_controller.rb b/app/controllers/badges_controller.rb index 03f825c5f42..06cd59080d0 100644 --- a/app/controllers/badges_controller.rb +++ b/app/controllers/badges_controller.rb @@ -16,6 +16,14 @@ class BadgesController < ApplicationController def show params.require(:id) badge = Badge.find(params[:id]) + + if current_user + user_badge = UserBadge.find_by(user_id: current_user.id, badge_id: badge.id) + if user_badge && user_badge.notification + user_badge.notification.update_attributes read: true + end + end + serialized = MultiJson.dump(serialize_data(badge, BadgeSerializer, root: "badge")) respond_to do |format| format.html do diff --git a/app/models/user_badge.rb b/app/models/user_badge.rb index e938a855858..39453322f89 100644 --- a/app/models/user_badge.rb +++ b/app/models/user_badge.rb @@ -7,6 +7,12 @@ class UserBadge < ActiveRecord::Base validates :user_id, presence: true validates :granted_at, presence: true validates :granted_by, presence: true + + # This may be inefficient, but not very easy to optimize unless the data hash + # is converted into a hstore. + def notification + @notification ||= self.user.notifications.where(notification_type: Notification.types[:granted_badge]).where("data LIKE ?", "%" + self.badge_id.to_s + "%").select {|n| n.data_hash["badge_id"] == self.badge_id }.first + end end # == Schema Information diff --git a/app/services/badge_granter.rb b/app/services/badge_granter.rb index a15e7d23f62..11fbec47d45 100644 --- a/app/services/badge_granter.rb +++ b/app/services/badge_granter.rb @@ -49,10 +49,7 @@ class BadgeGranter user_badge.user.save! end - # Delete notification -- This is inefficient, but not very easy to optimize - # unless the data hash is converted into a hstore. - notification = user_badge.user.notifications.where(notification_type: Notification.types[:granted_badge]).where("data LIKE ?", "%" + user_badge.badge_id.to_s + "%").select {|n| n.data_hash["badge_id"] == user_badge.badge_id }.first - notification && notification.destroy + user_badge.notification && user_badge.notification.destroy! end end diff --git a/spec/controllers/badges_controller_spec.rb b/spec/controllers/badges_controller_spec.rb index 61b6994c716..f45ffd50786 100644 --- a/spec/controllers/badges_controller_spec.rb +++ b/spec/controllers/badges_controller_spec.rb @@ -2,6 +2,11 @@ require 'spec_helper' describe BadgesController do let!(:badge) { Fabricate(:badge) } + let(:user) { Fabricate(:user) } + + before do + SiteSetting.enable_badges = true + end context 'index' do it 'should return a list of all badges' do @@ -20,5 +25,13 @@ describe BadgesController do parsed = JSON.parse(response.body) parsed["badge"].should be_present end + + it "should mark the notification as viewed" do + log_in_user(user) + user_badge = BadgeGranter.grant(badge, user) + user_badge.notification.read.should == false + get :show, id: badge.id, format: :json + user_badge.notification.reload.read.should == true + end end end