diff --git a/plugin.rb b/plugin.rb index 13f51a0d..c37e9844 100644 --- a/plugin.rb +++ b/plugin.rb @@ -290,6 +290,10 @@ def self.skip_db? end query = <<~SQL + UPDATE directory_items di + SET solutions = 0 + WHERE di.period_type = :period_type AND di.solutions IS NOT NULL; + WITH x AS ( SELECT p.user_id, COUNT(DISTINCT st.id) AS solutions FROM discourse_solved_solved_topics AS st @@ -310,11 +314,10 @@ def self.skip_db? GROUP BY p.user_id ) UPDATE directory_items di - SET solutions = x.solutions - FROM x - WHERE x.user_id = di.user_id - AND di.period_type = :period_type - AND di.solutions <> x.solutions + SET solutions = x.solutions + FROM x + WHERE x.user_id = di.user_id + AND di.period_type = :period_type; SQL add_directory_column("solutions", query:) diff --git a/spec/models/directory_item_spec.rb b/spec/models/directory_item_spec.rb index 7e2034ce..7b72585f 100644 --- a/spec/models/directory_item_spec.rb +++ b/spec/models/directory_item_spec.rb @@ -101,5 +101,32 @@ ).solutions, ).to eq(1) end + + context "when refreshing across dates" do + it "updates the user's solution count from 1 to 0" do + freeze_time 40.days.ago + DiscourseSolved.accept_answer!(topic_post1, Discourse.system_user) + + DirectoryItem.refresh! + + expect( + DirectoryItem.find_by( + user_id: user.id, + period_type: DirectoryItem.period_types[:monthly], + ).solutions, + ).to eq(1) + + unfreeze_time + + DirectoryItem.refresh! + + expect( + DirectoryItem.find_by( + user_id: user.id, + period_type: DirectoryItem.period_types[:monthly], + ).solutions, + ).to eq(0) + end + end end end