Skip to content

A platform for community discussion. Free, open, simple.

FIX: Restrict category leaderboards to category-aware scores (#44798)

Gabriel Grubba529155be9b7e
diff --git a/db/structure.sql b/db/structure.sql
index ea995b03c83..b1149b4b0a3 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -6565,7 +6565,8 @@ CREATE TABLE public.gamification_score_events (
points integer NOT NULL,
description text,
created_at timestamp(6) without time zone NOT NULL,
- updated_at timestamp(6) without time zone NOT NULL
+ updated_at timestamp(6) without time zone NOT NULL,
+ category_id integer
);
@@ -26091,6 +26092,7 @@ SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
('20261020161054'),
+('20261020160221'),
('20261019105124'),
('20261019104439'),
('20261018172000'),
diff --git a/plugins/discourse-gamification/README.md b/plugins/discourse-gamification/README.md
index 003e34e2806..4ab38152a86 100644
--- a/plugins/discourse-gamification/README.md
+++ b/plugins/discourse-gamification/README.md
@@ -1,5 +1,28 @@
# **Discourse Gamification** Plugin
+## Category-scoped leaderboards
+
+A leaderboard with its own nonempty **Scorable categories** list counts only
+category-based activity: topics, replies, likes, reactions, and accepted solutions.
+Visits, reading totals, invitations, flags, and chat activity are excluded because
+these scoring sources do not filter by category. Score overrides do not enable these
+sources on a category-scoped leaderboard.
+
+Manual score adjustments count on a category-scoped leaderboard only when they are
+assigned to one of its categories, through `category_id` on the score events API or
+the **Category** field of the workflows "Award score" action. Leaderboards without
+their own category list count uncategorized adjustments, plus categorized ones that
+match the site-wide `scorable_categories` setting when it is set.
+
+Leaderboards without their own category list retain global scoring behavior. The
+site-wide `scorable_categories` setting filters category-based actions while
+retaining site-wide score sources.
+
+After upgrading an existing category-scoped leaderboard, use **Recalculate scores**
+in the gamification admin interface with a start date covering the leaderboard's
+history. Refreshing positions alone does not remove previously calculated global
+points; scheduled recalculations only update recent scores.
+
# User Card
<img width="585" alt="Screen Shot 2022-03-18 at 9 33 24 AM" src="https://user-images.githubusercontent.com/50783505/159036553-b162f5b7-5acd-4134-ba5f-fa8dbb7f8f8f.png">
diff --git a/plugins/discourse-gamification/app/controllers/discourse_gamification/admin_gamification_score_event_controller.rb b/plugins/discourse-gamification/app/controllers/discourse_gamification/admin_gamification_score_event_controller.rb
index 372496d0f3f..a64be652bf2 100644
--- a/plugins/discourse-gamification/app/controllers/discourse_gamification/admin_gamification_score_event_controller.rb
+++ b/plugins/discourse-gamification/app/controllers/discourse_gamification/admin_gamification_score_event_controller.rb
@@ -18,7 +18,7 @@ class DiscourseGamification::AdminGamificationScoreEventController < Admin::Admi
def create
params.require(%i[user_id date points])
- params.permit(:description)
+ params.permit(:description, :category_id)
event =
DiscourseGamification::GamificationScoreEvent.new(
@@ -26,6 +26,7 @@ class DiscourseGamification::AdminGamificationScoreEventController < Admin::Admi
date: params[:date],
points: params[:points],
description: params[:description],
+ category_id: params[:category_id].presence,
)
if event.save
@@ -37,12 +38,16 @@ class DiscourseGamification::AdminGamificationScoreEventController < Admin::Admi
def update
params.require(%i[id points])
- params.permit(:description)
+ params.permit(:description, :category_id)
event = DiscourseGamification::GamificationScoreEvent.find(params[:id])
raise Discourse::NotFound unless event
- event.update(points: params[:points], description: params[:description] || event.description)
+ event.assign_attributes(
+ points: params[:points],
+ description: params[:description] || event.description,
+ )
+ event.category_id = params[:category_id].presence if params.key?(:category_id)
if event.save
render json: success_json
diff --git a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard_score.rb b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard_score.rb
index a99100e8c18..a86e819b5ba 100644
--- a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard_score.rb
+++ b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard_score.rb
@@ -20,7 +20,9 @@ module DiscourseGamification
def self.calculate_scores(leaderboard, since_date: Date.today, only_subclass: nil)
queries =
if only_subclass
- only_subclass.query(leaderboard:)
+ if !Scorable.category_scoped?(leaderboard:) || only_subclass.supports_category_scoping?
+ only_subclass.query(leaderboard:)
+ end
else
scorables_queries(leaderboard:)
end
@@ -31,25 +33,28 @@ module DiscourseGamification
leaderboard_id: leaderboard.id,
)
+ category_ids = Scorable.scorable_category_ids(leaderboard:)
+ score_event_category_filter =
+ if Scorable.category_scoped?(leaderboard:)
+ "AND category_id IN (:category_ids)"
+ elsif category_ids.present?
+ "AND (category_id IS NULL OR category_id IN (:category_ids))"
+ end
+
score_event_query = <<~SQL
SELECT user_id, date, SUM(points) AS points
FROM gamification_score_events
- WHERE date >= :since
+ WHERE date >= :since #{score_event_category_filter}
GROUP BY 1, 2
SQL
- source_queries =
- if queries.present?
- "#{queries} UNION ALL #{score_event_query}"
- else
- score_event_query
- end
+ source_queries = [queries.presence, score_event_query].compact
- DB.exec(<<~SQL, since: since_date, leaderboard_id: leaderboard.id)
+ DB.exec(<<~SQL, since: since_date, leaderboard_id: leaderboard.id, category_ids:)
INSERT INTO gamification_leaderboard_scores (leaderboard_id, user_id, date, score)
SELECT :leaderboard_id, user_id, date, SUM(points) AS score
FROM (
- #{source_queries}
+ #{source_queries.join(" UNION ALL ")}
) AS source
JOIN users AS u ON u.id = source.user_id
WHERE user_id IS NOT NULL
diff --git a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_score_event.rb b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_score_event.rb
index 6efeff9f454..418d2a27c61 100644
--- a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_score_event.rb
+++ b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_score_event.rb
@@ -5,6 +5,13 @@ module DiscourseGamification
self.table_name = "gamification_score_events"
belongs_to :user
+ belongs_to :category, optional: true
+
+ validates :category,
+ presence: {
+ message: :required,
+ },
+ if: -> { !category_id.nil? && will_save_change_to_category_id? }
end
end
@@ -18,6 +25,7 @@ end
# points :integer not null
# created_at :datetime not null
# updated_at :datetime not null
+# category_id :integer
# user_id :integer not null
#
# Indexes
diff --git a/plugins/discourse-gamification/app/serializers/admin_gamification_score_event_serializer.rb b/plugins/discourse-gamification/app/serializers/admin_gamification_score_event_serializer.rb
index 6fc81553fef..08fcd3ceeee 100644
--- a/plugins/discourse-gamification/app/serializers/admin_gamification_score_event_serializer.rb
+++ b/plugins/discourse-gamification/app/serializers/admin_gamification_score_event_serializer.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
class AdminGamificationScoreEventSerializer < ApplicationSerializer
- attributes :id, :user_id, :date, :points, :description, :created_at, :updated_at
+ attributes :id, :user_id, :category_id, :date, :points, :description, :created_at, :updated_at
end
diff --git a/plugins/discourse-gamification/config/locales/client.en.yml b/plugins/discourse-gamification/config/locales/client.en.yml
index 70f89cd8f09..5b3d7ade24b 100644
--- a/plugins/discourse-gamification/config/locales/client.en.yml
+++ b/plugins/discourse-gamification/config/locales/client.en.yml
@@ -49,7 +49,7 @@ en:
scoring_configuration: "Scoring configuration"
scoring_configuration_description: "Override the global scoring rules for this leaderboard. Leave fields empty to use the global defaults."
scorable_categories: "Scorable categories"
- scorable_categories_help: "Categories to include in scoring. Leave empty to use the global setting."
+ scorable_categories_help: "Select categories to count only category-based activity. Visits, reading, invitations, flags, and chat are excluded, and manual score adjustments count only when assigned to one of these categories. Leave empty to use the global scoring settings."
score_overrides: "Score weights"
score_overrides_help: "Override the point values for each action. Leave empty to use the global default. Set to 0 to disable."
weight:
@@ -119,3 +119,5 @@ en:
date_description: "Date the points apply to (YYYY-MM-DD). Defaults to today."
description: "Description"
description_description: "Optional note shown alongside the score event."
+ category_id: "Category"
+ category_id_description: "Optional. Points assigned to a category also count on leaderboards scoped to that category."
diff --git a/plugins/discourse-gamification/config/locales/server.en.yml b/plugins/discourse-gamification/config/locales/server.en.yml
index a05cdad4a44..21086f0f92a 100644
--- a/plugins/discourse-gamification/config/locales/server.en.yml
+++ b/plugins/discourse-gamification/config/locales/server.en.yml
@@ -30,3 +30,4 @@ en:
gamification_score:
invalid_points: "Points must be a non-zero whole number, got: %{points}"
invalid_date: "Invalid date: %{date}"
+ invalid_category: "Category not found: %{category_id}"
diff --git a/plugins/discourse-gamification/db/migrate/20261020160221_add_category_id_to_gamification_score_events.rb b/plugins/discourse-gamification/db/migrate/20261020160221_add_category_id_to_gamification_score_events.rb
new file mode 100644
index 00000000000..b18807ef1d9
--- /dev/null
+++ b/plugins/discourse-gamification/db/migrate/20261020160221_add_category_id_to_gamification_score_events.rb
@@ -0,0 +1,6 @@
+# frozen_string_literal: true
+class AddCategoryIdToGamificationScoreEvents < ActiveRecord::Migration[8.1]
+ def change
+ add_column :gamification_score_events, :category_id, :integer
+ end
+end
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_given.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_given.rb
index 298e4329aa0..51c131a42c5 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_given.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_given.rb
@@ -1,6 +1,10 @@
# frozen_string_literal: true
module DiscourseGamification
class LikeGiven < Scorable
+ def self.supports_category_scoping?
+ true
+ end
+
def self.category_filter(leaderboard: nil)
return "" if scorable_category_list(leaderboard:).empty?
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_received.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_received.rb
index b8f1bd863a4..0c748005044 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_received.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_received.rb
@@ -1,6 +1,10 @@
# frozen_string_literal: true
module DiscourseGamification
class LikeReceived < Scorable
+ def self.supports_category_scoping?
+ true
+ end
+
def self.category_filter(leaderboard: nil)
return "" if scorable_category_list(leaderboard:).empty?
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_created.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_created.rb
index 59545d11be9..31c50502908 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_created.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_created.rb
@@ -2,6 +2,10 @@
module DiscourseGamification
class PostCreated < Scorable
+ def self.supports_category_scoping?
+ true
+ end
+
def self.category_filter(leaderboard: nil)
return "" if scorable_category_list(leaderboard:).empty?
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_given.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_given.rb
index 6ee0e4a4b6a..9c69c8eb255 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_given.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_given.rb
@@ -1,6 +1,10 @@
# frozen_string_literal: true
module DiscourseGamification
class ReactionGiven < Scorable
+ def self.supports_category_scoping?
+ true
+ end
+
def self.enabled?(leaderboard: nil)
defined?(DiscourseReactions) && SiteSetting.discourse_reactions_enabled && super
end
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_received.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_received.rb
index d646803fb4f..4ad836c8a94 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_received.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_received.rb
@@ -1,6 +1,10 @@
# frozen_string_literal: true
module DiscourseGamification
class ReactionReceived < Scorable
+ def self.supports_category_scoping?
+ true
+ end
+
def self.enabled?(leaderboard: nil)
defined?(DiscourseReactions) && SiteSetting.discourse_reactions_enabled && super
end
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/scorable.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/scorable.rb
index c72df298809..47e361724a5 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/scorable.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/scorable.rb
@@ -3,9 +3,19 @@ module DiscourseGamification
class Scorable
class << self
def enabled?(leaderboard: nil)
+ return false if category_scoped?(leaderboard:) && !supports_category_scoping?
+
score_multiplier(leaderboard:) > 0
end
+ def supports_category_scoping?
+ false
+ end
+
+ def category_scoped?(leaderboard:)
+ Array(leaderboard&.scorable_category_ids).compact.present?
+ end
+
def scorable_key
name.demodulize.underscore
end
@@ -17,11 +27,15 @@ module DiscourseGamification
end
def scorable_category_list(leaderboard: nil)
+ scorable_category_ids(leaderboard:).join(", ")
+ end
+
+ def scorable_category_ids(leaderboard: nil)
categories = leaderboard&.scorable_category_ids
if categories.nil?
- SiteSetting.scorable_categories.split("|").map { it.to_i }.join(", ")
+ SiteSetting.scorable_categories.split("|").map { it.to_i }
else
- categories.join(", ")
+ categories.compact
end
end
end
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb
index 0364456be17..b404d4875aa 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb
@@ -1,6 +1,10 @@
# frozen_string_literal: true
module DiscourseGamification
class Solutions < Scorable
+ def self.supports_category_scoping?
+ true
+ end
+
def self.enabled?(leaderboard: nil)
defined?(DiscourseSolved) && SiteSetting.solved_enabled && super
end
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/topic_created.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/topic_created.rb
index 36890b747ca..627a0b13244 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/topic_created.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/topic_created.rb
@@ -2,6 +2,10 @@
module DiscourseGamification
class TopicCreated < Scorable
+ def self.supports_category_scoping?
+ true
+ end
+
def self.category_filter(leaderboard: nil)
return "" if scorable_category_list(leaderboard:).empty?
diff --git a/plugins/discourse-gamification/lib/discourse_workflows/nodes/gamification_score/v1.rb b/plugins/discourse-gamification/lib/discourse_workflows/nodes/gamification_score/v1.rb
index 8251941e24f..c4174522dd2 100644
--- a/plugins/discourse-gamification/lib/discourse_workflows/nodes/gamification_score/v1.rb
+++ b/plugins/discourse-gamification/lib/discourse_workflows/nodes/gamification_score/v1.rb
@@ -27,6 +27,9 @@ if defined?(DiscourseWorkflows)
"description" => {
"type" => %w[string null],
},
+ "category_id" => {
+ "type" => %w[integer null],
+ },
},
}.freeze
@@ -73,6 +76,13 @@ if defined?(DiscourseWorkflows)
expression: true,
},
},
+ category_id: {
+ type: :integer,
+ required: false,
+ ui: {
+ control: :category,
+ },
+ },
},
)
@@ -84,6 +94,7 @@ if defined?(DiscourseWorkflows)
"points" => exec_ctx.get_node_parameter("points", item_index),
"date" => exec_ctx.get_node_parameter("date", item_index),
"description" => exec_ctx.get_node_parameter("description", item_index),
+ "category_id" => exec_ctx.get_node_parameter("category_id", item_index),
}
wrap(process(exec_ctx, config, item_index))
@@ -98,6 +109,7 @@ if defined?(DiscourseWorkflows)
user = exec_ctx.find_user(username: config["username"])
points = parse_points(config["points"], item_index)
date = parse_date(config["date"], item_index)
+ category_id = parse_category_id(config["category_id"], item_index)
event =
::DiscourseGamification::GamificationScoreEvent.create!(
@@ -105,6 +117,7 @@ if defined?(DiscourseWorkflows)
date:,
points:,
description: config["description"].presence,
+ category_id:,
)
{
@@ -114,6 +127,7 @@ if defined?(DiscourseWorkflows)
points: event.points,
date: event.date.to_s,
description: event.description,
+ category_id: event.category_id,
}
end
@@ -131,6 +145,21 @@ if defined?(DiscourseWorkflows)
points
end
+ def parse_category_id(value, item_index)
+ return if value.blank?
+
+ category_id = Integer(value.to_s, exception: false)
+ return category_id if category_id && ::Category.exists?(id: category_id)
+
+ raise_node_error!(
+ I18n.t(
+ "discourse_gamification.discourse_workflows.gamification_score.invalid_category",
+ category_id: value,
+ ),
+ item_index:,
+ )
+ end
+
def parse_date(value, item_index)
return Time.zone.today if value.blank?
diff --git a/plugins/discourse-gamification/spec/lib/discourse_workflows/nodes/gamification_score/v1_spec.rb b/plugins/discourse-gamification/spec/lib/discourse_workflows/nodes/gamification_score/v1_spec.rb
index ce5bf8f20da..dedfecd001e 100644
--- a/plugins/discourse-gamification/spec/lib/discourse_workflows/nodes/gamification_score/v1_spec.rb
+++ b/plugins/discourse-gamification/spec/lib/discourse_workflows/nodes/gamification_score/v1_spec.rb
@@ -109,5 +109,29 @@ RSpec.describe DiscourseWorkflows::Nodes::GamificationScore::V1 do
expect { execute_node(configuration: config) }.to raise_error(DiscourseWorkflows::NodeError)
end
+
+ it "assigns the score event to a category" do
+ category = Fabricate(:category)
+ config = { "username" => user.username, "points" => 5, "category_id" => category.id.to_s }
+
+ result = execute_node(configuration: config)
+
+ expect(DiscourseGamification::GamificationScoreEvent.last.category_id).to eq(category.id)
+ expect(result["category_id"]).to eq(category.id)
+ end
+
+ it "leaves the category empty when blank" do
+ config = { "username" => user.username, "points" => 5, "category_id" => "" }
+
+ execute_node(configuration: config)
+
+ expect(DiscourseGamification::GamificationScoreEvent.last.category_id).to be_nil
+ end
+
+ it "raises when the category does not exist" do
+ config = { "username" => user.username, "points" => 5, "category_id" => "-999" }
+
+ expect { execute_node(configuration: config) }.to raise_error(DiscourseWorkflows::NodeError)
+ end
end
end
diff --git a/plugins/discourse-gamification/spec/models/category_leaderboard_scoring_spec.rb b/plugins/discourse-gamification/spec/models/category_leaderboard_scoring_spec.rb
new file mode 100644
index 00000000000..37633f2e04e
--- /dev/null
+++ b/plugins/discourse-gamification/spec/models/category_leaderboard_scoring_spec.rb
@@ -0,0 +1,257 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseGamification::GamificationLeaderboardScore, type: :model do
+ fab!(:user)
+ fab!(:building_category, :category)
+ fab!(:building_tools_category, :category)
+ fab!(:feedback_category, :category)
+ fab!(:ux_reports_category, :category)
+ fab!(:general_bugs_category, :category)
+ fab!(:support_category, :category)
+
+ fab!(:builders) do
+ Fabricate(
+ :gamification_leaderboard,
+ name: "Builders",
+ scorable_category_ids: [building_category.id, building_tools_category.id],
+ )
+ end
+ fab!(:help) do
+ Fabricate(
+ :gamification_leaderboard,
+ name: "Help",
+ scorable_category_ids: [
+ feedback_category.id,
+ ux_reports_category.id,
+ general_bugs_category.id,
+ ],
+ )
+ end
+ fab!(:support) do
+ Fabricate(
+ :gamification_leaderboard,
+ name: "Support",
+ scorable_category_ids: [support_category.id],
+ )
+ end
+
+ before do
+ today = DB.query_single("SELECT CURRENT_DATE").first
+ freeze_time Time.utc(today.year, today.month, today.day, 12)
+
+ [building_category, building_tools_category].each do |category|
+ Fabricate(:topic, user: user, category: category)
+ end
+
+ 20.times do
+ topic = Fabricate(:topic, user: user, category: support_category)
+ Fabricate(:post, user: user, topic: topic, post_number: 2)
+ end
+ end
+
+ def calculate_and_read_scores(for_user, since_date: Date.current, period: "all_time")
+ [builders, help, support].map do |leaderboard|
+ described_class.calculate_scores(leaderboard, since_date: since_date)
+ cache = DiscourseGamification::LeaderboardCachedView.new(leaderboard)
+ cache.delete
+ cache.create
+ cache.scores(for_user_id: for_user.id, period: period).first&.total_score
+ end
+ end
+
+ describe ".calculate_scores" do
+ it "keeps heavy support topic and reply scores out of the other category leaderboards" do
+ expect(calculate_and_read_scores(user)).to eq([10, nil, 140])
+ end
+
+ it "excludes global activity when category activity is older than the weekly window" do
+ today = DB.query_single("SELECT CURRENT_DATE").first
+ activity_date = today - 10
+ user.topics.update_all(created_at: activity_date)
+ user.posts.update_all(created_at: activity_date)
+ Fabricate(:user_visit, user: user, visited_at: today, time_read: 7200, posts_read: 300)
+
+ expect(calculate_and_read_scores(user, since_date: activity_date, period: "weekly")).to eq(
+ [nil, nil, nil],
+ )
+ expect(calculate_and_read_scores(user, since_date: activity_date)).to eq([10, nil, 140])
+ end
+
+ it "excludes visit, reading, and uncategorized manual points from category leaderboards" do
+ Fabricate(:user_visit, user: user, time_read: 7200, posts_read: 300)
+
+ expect(calculate_and_read_scores(user)).to eq([10, nil, 140])
+
+ DiscourseGamification::GamificationScoreEvent.create!(
+ user: user,
+ date: Date.current,
+ points: 1000,
+ )
+
+ expect(calculate_and_read_scores(user)).to eq([10, nil, 140])
+
+ global = Fabricate(:gamification_leaderboard)
+ described_class.calculate_scores(global)
+ cache = DiscourseGamification::LeaderboardCachedView.new(global)
+ cache.create
+ expect(cache.scores(for_user_id: user.id).first.total_score).to eq(1156)
+
+ visitor = Fabricate(:user)
+ Fabricate(:user_visit, user: visitor, time_read: 7200, posts_read: 300)
+
+ expect(calculate_and_read_scores(visitor)).to eq([nil, nil, nil])
+ end
+
+ it "counts manual points only on leaderboards scoped to their category" do
+ [
+ { points: 1000, category_id: nil },
+ { points: 50, category_id: support_category.id },
+ { points: 7, category_id: building_tools_category.id },
+ { points: -3, category_id: building_category.id },
+ ].each do |attrs|
+ DiscourseGamification::GamificationScoreEvent.create!(
+ user: user,
+ date: Date.current,
+ **attrs,
+ )
+ end
+
+ expect(calculate_and_read_scores(user)).to eq([14, nil, 190])
+
+ global = Fabricate(:gamification_leaderboard)
+ described_class.calculate_scores(global)
+
+ expect(global.leaderboard_scores.where(user: user).sum(:score)).to eq(1204)
+ end
+
+ it "filters categorized manual points by the site category setting on global leaderboards" do
+ SiteSetting.scorable_categories = support_category.id.to_s
+ [
+ { points: 1000, category_id: nil },
+ { points: 50, category_id: support_category.id },
+ { points: 7, category_id: building_category.id },
+ ].each do |attrs|
+ DiscourseGamification::GamificationScoreEvent.create!(
+ user: user,
+ date: Date.current,
+ **attrs,
+ )
+ end
+
+ global = Fabricate(:gamification_leaderboard)
+ described_class.calculate_scores(global)
+
+ expect(global.leaderboard_scores.where(user: user).sum(:score)).to eq(1190)
+ end
+
+ it "ignores blank entries in the category list" do
+ support.update!(scorable_category_ids: [support_category.id, nil])
+ DiscourseGamification::GamificationScoreEvent.create!(
+ user: user,
+ date: Date.current,
+ points: 50,
+ category_id: support_category.id,
+ )
+
+ expect(calculate_and_read_scores(user).last).to eq(190)
+ end
+
+ it "excludes visitors with zero points from category leaderboards" do
+ visitor = Fabricate(:user)
+ Fabricate(:user_visit, user: visitor, time_read: 60, posts_read: 5)
+ [builders, help, support].each do |leaderboard|
+ leaderboard.update!(score_overrides: { "day_visited" => 0 })
+ end
+
+ expect(calculate_and_read_scores(visitor)).to eq([nil, nil, nil])
+ end
+
+ it "excludes invitations, flags, and chat activity even with positive score overrides" do
+ SiteSetting.chat_enabled = true
+ Fabricate(:invite, invited_by: user, redemption_count: 1)
+ Fabricate(:reviewable, created_by: user, status: Reviewable.statuses[:approved])
+ other_user = Fabricate(:user)
+ message = Fabricate(:chat_message, user: user)
+ other_message = Fabricate(:chat_message, user: other_user)
+ Fabricate(:chat_message_reaction, chat_message: message, user: other_user)
+ Fabricate(:chat_message_reaction, chat_message: other_message, user: user)
+ [builders, help, support].each do |leaderboard|
+ leaderboard.update!(
+ score_overrides: {
+ "user_invited" => 100,
+ "flag_created" => 100,
+ "chat_message_created" => 100,
+ "chat_reaction_given" => 100,
+ "chat_reaction_received" => 100,
+ },
+ )
+ end
+
+ expect(calculate_and_read_scores(user)).to eq([10, nil, 140])
+ end
+
+ it "preserves global activity and manual points when inheriting the site category filter" do
+ SiteSetting.scorable_categories = support_category.id.to_s
+ Fabricate(:user_visit, user: user, time_read: 7200, posts_read: 300)
+ DiscourseGamification::GamificationScoreEvent.create!(
+ user: user,
+ date: Date.current,
+ points: 1000,
+ )
+
+ global = Fabricate(:gamification_leaderboard)
+ described_class.calculate_scores(global)
+
+ expect(global.leaderboard_scores.where(user: user).sum(:score)).to eq(1146)
+ expect(calculate_and_read_scores(user)).to eq([10, nil, 140])
+
+ global.update!(scorable_category_ids: [])
+ described_class.calculate_scores(global)
+
+ expect(global.leaderboard_scores.where(user: user).sum(:score)).to eq(1156)
+ end
+
+ it "clears stale scores when all category-based sources are disabled" do
+ help.update!(
+ score_overrides: {
+ "topic_created" => 0,
+ "post_created" => 0,
+ "like_given" => 0,
+ "like_received" => 0,
+ "reaction_given" => 0,
+ "reaction_received" => 0,
+ "solution" => 0,
+ },
+ )
+ help.leaderboard_scores.create!(user: user, date: Date.current, score: 1000)
+ DiscourseGamification::GamificationScoreEvent.create!(
+ user: user,
+ date: Date.current,
+ points: 1000,
+ )
+
+ described_class.calculate_scores(help)
+
+ expect(help.leaderboard_scores.where(user: user)).to be_empty
+ end
+
+ it "removes historical global points with a full leaderboard recalculation" do
+ activity_date = DB.query_single("SELECT CURRENT_DATE").first - 30
+ [builders, help, support].each do |leaderboard|
+ leaderboard.leaderboard_scores.create!(user: user, date: activity_date, score: 1000)
+
+ Jobs::RecalculateLeaderboardScores.new.execute(leaderboard_id: leaderboard.id)
+ end
+
+ scores =
+ [builders, help, support].map do |leaderboard|
+ DiscourseGamification::GamificationLeaderboard
+ .scores_for(leaderboard.id, for_user_id: user.id)
+ .first
+ &.total_score
+ end
+
+ expect(scores).to eq([10, nil, 140])
+ end
+ end
+end
diff --git a/plugins/discourse-gamification/spec/requests/admin_gamification_score_event_controller_spec.rb b/plugins/discourse-gamification/spec/requests/admin_gamification_score_event_controller_spec.rb
index cd861bac085..e70817e5eb2 100644
--- a/plugins/discourse-gamification/spec/requests/admin_gamification_score_event_controller_spec.rb
+++ b/plugins/discourse-gamification/spec/requests/admin_gamification_score_event_controller_spec.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
RSpec.describe DiscourseGamification::AdminGamificationScoreEventController do
+ fab!(:category)
+
let(:current_user) { Fabricate(:admin) }
let(:another_user) { Fabricate(:user) }
let(:score_events) { [] }
@@ -110,4 +112,74 @@ RSpec.describe DiscourseGamification::AdminGamificationScoreEventController do
expect(user_score).to eq(13)
end
end
+
+ describe "#create" do
+ it "assigns the score event to a category" do
+ post "/admin/plugins/gamification/score_events.json",
+ params: {
+ points: 10,
+ user_id: another_user.id,
+ date: Date.today,
+ category_id: category.id,
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["category_id"]).to eq(category.id)
+ expect(DiscourseGamification::GamificationScoreEvent.last.category_id).to eq(category.id)
+ end
+
+ it "rejects a category that does not exist" do
+ expect {
+ post "/admin/plugins/gamification/score_events.json",
+ params: {
+ points: 10,
+ user_id: another_user.id,
+ date: Date.today,
+ category_id: "abc",
+ }
+ }.not_to change { DiscourseGamification::GamificationScoreEvent.count }
+
+ expect(response.status).to eq(422)
+ end
+ end
+
+ describe "#update" do
+ it "keeps the category when omitted and clears it when blank" do
+ event = score_events.last
+
+ put "/admin/plugins/gamification/score_events.json",
+ params: {
+ id: event.id,
+ points: 13,
+ category_id: category.id,
+ }
+
+ expect(response.status).to eq(200)
+ expect(event.reload.category_id).to eq(category.id)
+
+ put "/admin/plugins/gamification/score_events.json", params: { id: event.id, points: 14 }
+
+ expect(event.reload.category_id).to eq(category.id)
+
+ put "/admin/plugins/gamification/score_events.json",
+ params: {
+ id: event.id,
+ points: 14,
+ category_id: "",
+ }
+
+ expect(event.reload.category_id).to be_nil
+ end
+
+ it "updates points after the assigned category is deleted" do
+ event = score_events.last
+ event.update!(category_id: category.id)
+ category.destroy!
+
+ put "/admin/plugins/gamification/score_events.json", params: { id: event.id, points: 14 }
+
+ expect(response.status).to eq(200)
+ expect(event.reload.points).to eq(14)
+ end
+ end
end