Skip to content

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

FEATURE: Per-leaderboard scorable weights and category filters (#39062)

Rafael dos Santos Silva848c19ae48a3
diff --git a/plugins/discourse-gamification/admin/assets/javascripts/admin/components/admin-edit-leaderboard.gjs b/plugins/discourse-gamification/admin/assets/javascripts/admin/components/admin-edit-leaderboard.gjs
index abf29897500..6d1b005764c 100644
--- a/plugins/discourse-gamification/admin/assets/javascripts/admin/components/admin-edit-leaderboard.gjs
+++ b/plugins/discourse-gamification/admin/assets/javascripts/admin/components/admin-edit-leaderboard.gjs
@@ -1,28 +1,72 @@
import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
import { action } from "@ember/object";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { service } from "@ember/service";
import BackButton from "discourse/components/back-button";
import Form from "discourse/components/form";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { AUTO_GROUPS } from "discourse/lib/constants";
+import Category from "discourse/models/category";
+import CategorySelector from "discourse/select-kit/components/category-selector";
import GroupChooser from "discourse/select-kit/components/group-chooser";
import { i18n } from "discourse-i18n";
import PeriodInput from "discourse/plugins/discourse-gamification/discourse/components/period-input";
+const SCORABLE_KEYS = [
+ "like_given",
+ "like_received",
+ "post_created",
+ "topic_created",
+ "solution",
+ "day_visited",
+ "flag_created",
+ "post_read",
+ "time_read",
+ "user_invited",
+ "reaction_given",
+ "reaction_received",
+ "chat_message_created",
+ "chat_reaction_given",
+ "chat_reaction_received",
+];
+
export default class AdminEditLeaderboard extends Component {
@service site;
@service toasts;
@service router;
+ @tracked selectedScorableCategories = [];
+
+ constructor() {
+ super(...arguments);
+
+ this.pendingScorableCategoriesRequest = Promise.resolve();
+ this.syncSelectedScorableCategories(
+ this.args.leaderboard.scorableCategoryIds
+ );
+ }
+
get siteGroups() {
return this.site.groups.filter(
(group) => group.id !== AUTO_GROUPS.everyone.id
);
}
+ async updateSelectedScorableCategories(ids, previousRequest) {
+ const categories = ids?.length ? await Category.asyncFindByIds(ids) : [];
+
+ await previousRequest;
+
+ this.selectedScorableCategories = categories;
+ }
+
get formData() {
- return {
+ const overrides = this.args.leaderboard.scoreOverrides || {};
+
+ const data = {
name: this.args.leaderboard.name,
from_date: this.args.leaderboard.fromDate,
to_date: this.args.leaderboard.toDate,
@@ -31,16 +75,64 @@ export default class AdminEditLeaderboard extends Component {
visible_to_groups_ids: this.args.leaderboard.visibleToGroupsIds,
default_period: this.args.leaderboard.defaultPeriod,
period_filter_disabled: this.args.leaderboard.periodFilterDisabled,
+ scorable_category_ids: this.args.leaderboard.scorableCategoryIds,
};
+
+ for (const key of SCORABLE_KEYS) {
+ data[`score_override_${key}`] =
+ overrides[key] !== undefined ? String(overrides[key]) : "";
+ }
+
+ return data;
+ }
+
+ @action
+ syncSelectedScorableCategories(ids) {
+ const previousRequest = this.pendingScorableCategoriesRequest;
+ this.pendingScorableCategoriesRequest =
+ this.updateSelectedScorableCategories(ids, previousRequest);
+ }
+
+ @action
+ onCategoryChange(set, categories) {
+ this.selectedScorableCategories = categories || [];
+ set((categories || []).map((c) => c.id));
}
@action
async save(data) {
+ const scoreOverrides = {};
+ let hasOverrides = false;
+
+ for (const key of SCORABLE_KEYS) {
+ const val = data[`score_override_${key}`];
+ if (val !== "" && val !== null && val !== undefined) {
+ scoreOverrides[key] = parseInt(val, 10);
+ hasOverrides = true;
+ }
+ }
+
+ const payload = {
+ name: data.name,
+ from_date: data.from_date,
+ to_date: data.to_date,
+ included_groups_ids: data.included_groups_ids,
+ excluded_groups_ids: data.excluded_groups_ids,
+ visible_to_groups_ids: data.visible_to_groups_ids,
+ default_period: data.default_period,
+ period_filter_disabled: data.period_filter_disabled,
+ scorable_category_ids: data.scorable_category_ids,
+ };
+
+ if (hasOverrides) {
+ payload.score_overrides = scoreOverrides;
+ }
+
try {
await ajax(
`/admin/plugins/gamification/leaderboard/${this.args.leaderboard.id}`,
{
- data,
+ data: payload,
type: "PUT",
}
);
@@ -54,7 +146,6 @@ export default class AdminEditLeaderboard extends Component {
"adminPlugins.show.discourse-gamification-leaderboards.index"
);
- // To refresh the list of leaderboards in the index.
this.router.refresh();
} catch (err) {
popupAjaxError(err);
@@ -82,101 +173,334 @@ export default class AdminEditLeaderboard extends Component {
<field.Control />
</form.Field>
- <form.Row as |row|>
- <row.Col @size={{6}}>
- <form.Field
- @name="from_date"
- @title={{i18n "gamification.leaderboard.date.from"}}
- @type="input-date"
- as |field|
- >
- <field.Control />
- </form.Field>
- </row.Col>
+ <form.Section
+ @title={{i18n "gamification.leaderboard.section.time_period"}}
+ @subtitle={{i18n
+ "gamification.leaderboard.section.time_period_description"
+ }}
+ >
+ <form.Row as |row|>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="from_date"
+ @title={{i18n "gamification.leaderboard.date.from"}}
+ @type="input-date"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+ </row.Col>
+
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="to_date"
+ @title={{i18n "gamification.leaderboard.date.to"}}
+ @type="input-date"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+ </row.Col>
+ </form.Row>
+
+ <form.Field
+ @name="period_filter_disabled"
+ @title={{i18n "gamification.leaderboard.period_filter_disabled"}}
+ @type="toggle"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ @name="default_period"
+ @title={{i18n "gamification.leaderboard.default_period"}}
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <PeriodInput @value={{field.value}} @onChange={{field.set}} />
+ </field.Control>
+ </form.Field>
+ </form.Section>
- <row.Col @size={{6}}>
+ <form.Section
+ @title={{i18n "gamification.leaderboard.section.groups"}}
+ @subtitle={{i18n "gamification.leaderboard.section.groups_description"}}
+ >
+ <form.Field
+ @name="included_groups_ids"
+ @title={{i18n "gamification.leaderboard.included_groups"}}
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <GroupChooser
+ @id="leaderboard-edit__included-groups"
+ @content={{this.siteGroups}}
+ @value={{field.value}}
+ @labelProperty="name"
+ @onChange={{field.set}}
+ />
+ </field.Control>
+ </form.Field>
+
+ <form.Field
+ @name="excluded_groups_ids"
+ @title={{i18n "gamification.leaderboard.excluded_groups"}}
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <GroupChooser
+ @id="leaderboard-edit__excluded-groups"
+ @content={{this.siteGroups}}
+ @value={{field.value}}
+ @labelProperty="name"
+ @onChange={{field.set}}
+ />
+ </field.Control>
+ </form.Field>
+
+ <form.Field
+ @name="visible_to_groups_ids"
+ @title={{i18n "gamification.leaderboard.visible_to_groups"}}
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <GroupChooser
+ @id="leaderboard-edit__visible-groups"
+ @content={{this.siteGroups}}
+ @value={{field.value}}
+ @labelProperty="name"
+ @onChange={{field.set}}
+ />
+ </field.Control>
+ </form.Field>
+ </form.Section>
+
+ <details class="leaderboard-scoring-details">
+ <summary>{{i18n
+ "gamification.leaderboard.scoring_configuration"
+ }}</summary>
+
+ <p class="leaderboard-scoring-details__description">{{i18n
+ "gamification.leaderboard.scoring_configuration_description"
+ }}</p>
+
+ <form.Section
+ @title={{i18n "gamification.leaderboard.scorable_categories"}}
+ >
<form.Field
- @name="to_date"
- @title={{i18n "gamification.leaderboard.date.to"}}
- @type="input-date"
+ @name="scorable_category_ids"
+ @title={{i18n "gamification.leaderboard.scorable_categories"}}
+ @description={{i18n
+ "gamification.leaderboard.scorable_categories_help"
+ }}
+ @type="custom"
as |field|
>
- <field.Control />
+ <field.Control>
+ <div
+ {{didUpdate
+ (fn this.syncSelectedScorableCategories field.value)
+ field.value
+ }}
+ >
+ <CategorySelector
+ @categories={{this.selectedScorableCategories}}
+ @onChange={{fn this.onCategoryChange field.set}}
+ />
+ </div>
+ </field.Control>
</form.Field>
- </row.Col>
- </form.Row>
+ </form.Section>
- <form.Field
- @name="included_groups_ids"
- @title={{i18n "gamification.leaderboard.included_groups"}}
- @type="custom"
- as |field|
- >
- <field.Control>
- <GroupChooser
- @id="leaderboard-edit__included-groups"
- @content={{this.siteGroups}}
- @value={{field.value}}
- @labelProperty="name"
- @onChange={{field.set}}
- />
- </field.Control>
- </form.Field>
+ <form.Section
+ @title={{i18n "gamification.leaderboard.score_overrides"}}
+ @subtitle={{i18n "gamification.leaderboard.score_overrides_help"}}
+ >
+ <form.Row as |row|>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_like_given"
+ @title={{i18n "gamification.leaderboard.weight.like_given"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_like_received"
+ @title={{i18n "gamification.leaderboard.weight.like_received"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ </form.Row>
- <form.Field
- @name="excluded_groups_ids"
- @title={{i18n "gamification.leaderboard.excluded_groups"}}
- @type="custom"
- as |field|
- >
- <field.Control>
- <GroupChooser
- @id="leaderboard-edit__excluded-groups"
- @content={{this.siteGroups}}
- @value={{field.value}}
- @labelProperty="name"
- @onChange={{field.set}}
- />
- </field.Control>
- </form.Field>
+ <form.Row as |row|>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_post_created"
+ @title={{i18n "gamification.leaderboard.weight.post_created"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_topic_created"
+ @title={{i18n "gamification.leaderboard.weight.topic_created"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ </form.Row>
- <form.Field
- @name="visible_to_groups_ids"
- @title={{i18n "gamification.leaderboard.visible_to_groups"}}
- @type="custom"
- as |field|
- >
- <field.Control>
- <GroupChooser
- @id="leaderboard-edit__visible-groups"
- @content={{this.siteGroups}}
- @value={{field.value}}
- @labelProperty="name"
- @onChange={{field.set}}
- />
- </field.Control>
- </form.Field>
+ <form.Row as |row|>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_solution"
+ @title={{i18n "gamification.leaderboard.weight.solution"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_flag_created"
+ @title={{i18n "gamification.leaderboard.weight.flag_created"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ </form.Row>
- <form.Field
- @name="default_period"
- @title={{i18n "gamification.leaderboard.default_period"}}
- @type="custom"
- as |field|
- >
- <field.Control>
- <PeriodInput @value={{field.value}} @onChange={{field.set}} />
- </field.Control>
- </form.Field>
+ <form.Row as |row|>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_day_visited"
+ @title={{i18n "gamification.leaderboard.weight.day_visited"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_user_invited"
+ @title={{i18n "gamification.leaderboard.weight.user_invited"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ </form.Row>
+
+ <form.Row as |row|>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_post_read"
+ @title={{i18n "gamification.leaderboard.weight.post_read"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_time_read"
+ @title={{i18n "gamification.leaderboard.weight.time_read"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ </form.Row>
+
+ <form.Row as |row|>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_reaction_given"
+ @title={{i18n "gamification.leaderboard.weight.reaction_given"}}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_reaction_received"
+ @title={{i18n
+ "gamification.leaderboard.weight.reaction_received"
+ }}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ </form.Row>
+
+ <form.Row as |row|>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_chat_message_created"
+ @title={{i18n
+ "gamification.leaderboard.weight.chat_message_created"
+ }}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ <row.Col @size={{6}}>
+ <form.Field
+ @name="score_override_chat_reaction_given"
+ @title={{i18n
+ "gamification.leaderboard.weight.chat_reaction_given"
+ }}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </row.Col>
+ </form.Row>
+
+ <form.Field
+ @name="score_override_chat_reaction_received"
+ @title={{i18n
+ "gamification.leaderboard.weight.chat_reaction_received"
+ }}
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" step="1" />
+ </form.Field>
+ </form.Section>
+ </details>
- <form.Field
- @name="period_filter_disabled"
- @title={{i18n "gamification.leaderboard.period_filter_disabled"}}
- @showTitle={{false}}
- @type="checkbox"
- as |field|
- >
- <field.Control @value={{field.value}} />
- </form.Field>
<form.Submit />
</Form>
</template>
diff --git a/plugins/discourse-gamification/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-gamification-leaderboards/index.js b/plugins/discourse-gamification/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-gamification-leaderboards/index.js
index d3ea857ecce..328eb6c5ec5 100644
--- a/plugins/discourse-gamification/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-gamification-leaderboards/index.js
+++ b/plugins/discourse-gamification/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-gamification-leaderboards/index.js
@@ -1,7 +1,6 @@
import Controller from "@ember/controller";
-import { action, computed } from "@ember/object";
+import { action } from "@ember/object";
import { service } from "@ember/service";
-import { compare } from "@ember/utils";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
@@ -15,15 +14,6 @@ export default class AdminPluginsShowDiscourseGamificationLeaderboardsIndexContr
creatingNew = false;
- @computed("[email protected]")
- get sortedLeaderboards() {
- return (
- this.model?.leaderboards?.sort((a, b) =>
- compare(b?.updatedAt, a?.updatedAt)
- ) || []
- );
- }
-
@action
resetNewLeaderboard() {
this.set("creatingNew", false);
diff --git a/plugins/discourse-gamification/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-gamification-leaderboards/index.gjs b/plugins/discourse-gamification/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-gamification-leaderboards/index.gjs
index f5f4b534644..d53217aa34a 100644
--- a/plugins/discourse-gamification/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-gamification-leaderboards/index.gjs
+++ b/plugins/discourse-gamification/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-gamification-leaderboards/index.gjs
@@ -48,7 +48,7 @@ export default <template>
</thead>
<tbody>
- {{#each @controller.sortedLeaderboards as |leaderboard|}}
+ {{#each @controller.model.leaderboards as |leaderboard|}}
<tr id={{concat "leaderboard-admin__row-" leaderboard.id}}>
<td>
<LinkTo
diff --git a/plugins/discourse-gamification/app/controllers/discourse_gamification/admin_gamification_leaderboard_controller.rb b/plugins/discourse-gamification/app/controllers/discourse_gamification/admin_gamification_leaderboard_controller.rb
index bf8296907a9..89c3bb26ee9 100644
--- a/plugins/discourse-gamification/app/controllers/discourse_gamification/admin_gamification_leaderboard_controller.rb
+++ b/plugins/discourse-gamification/app/controllers/discourse_gamification/admin_gamification_leaderboard_controller.rb
@@ -5,17 +5,18 @@ class DiscourseGamification::AdminGamificationLeaderboardController < Admin::Adm
def index
render_serialized(
- { leaderboards: DiscourseGamification::GamificationLeaderboard.all },
+ { leaderboards: DiscourseGamification::GamificationLeaderboard.order(updated_at: :desc) },
AdminGamificationIndexSerializer,
root: false,
)
end
def show
- render json:
- LeaderboardSerializer.new(
- DiscourseGamification::GamificationLeaderboard.find(params[:id]),
- )
+ leaderboard = DiscourseGamification::GamificationLeaderboard.find(params[:id])
+
+ render_json_dump(
+ { leaderboard: serialize_data(leaderboard, AdminLeaderboardSerializer, root: false) },
+ )
end
def create
@@ -27,9 +28,9 @@ class DiscourseGamification::AdminGamificationLeaderboardController < Admin::Adm
created_by_id: params[:created_by_id],
)
if leaderboard.save
- Jobs.enqueue(Jobs::GenerateLeaderboardPositions, leaderboard_id: leaderboard.id)
+ Jobs.enqueue(Jobs::RecalculateLeaderboardScores, leaderboard_id: leaderboard.id)
- render_serialized(leaderboard, LeaderboardSerializer, root: false)
+ render_serialized(leaderboard, AdminLeaderboardSerializer, root: false)
else
render_json_error(leaderboard)
end
@@ -41,6 +42,9 @@ class DiscourseGamification::AdminGamificationLeaderboardController < Admin::Adm
leaderboard = DiscourseGamification::GamificationLeaderboard.find(params[:id])
raise Discourse::NotFound unless leaderboard
+ previous_score_overrides = leaderboard.score_overrides
+ previous_scorable_category_ids = leaderboard.scorable_category_ids
+
leaderboard.update(
name: params[:name],
to_date: params[:to_date],
@@ -50,11 +54,20 @@ class DiscourseGamification::AdminGamificationLeaderboardController < Admin::Adm
visible_to_groups_ids: params[:visible_to_groups_ids] || [],
default_period: params[:default_period],
period_filter_disabled: params[:period_filter_disabled] || false,
+ score_overrides: (params[:score_overrides].presence&.to_unsafe_h&.transform_values(&:to_i)),
+ scorable_category_ids: params[:scorable_category_ids].presence,
)
if leaderboard.save
- # TODO(selase): Only refresh on specific attribute changes
- Jobs.enqueue(Jobs::RefreshLeaderboardPositions, leaderboard_id: leaderboard.id)
+ scoring_changed =
+ leaderboard.score_overrides != previous_score_overrides ||
+ leaderboard.scorable_category_ids != previous_scorable_category_ids
+
+ if scoring_changed
+ Jobs.enqueue(Jobs::RecalculateLeaderboardScores, leaderboard_id: leaderboard.id)
+ else
+ Jobs.enqueue(Jobs::RefreshLeaderboardPositions, leaderboard_id: leaderboard.id)
+ end
render json: success_json
else
diff --git a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard.rb b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard.rb
index 8c5f376a890..32cd7f5bbe8 100644
--- a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard.rb
+++ b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard.rb
@@ -6,11 +6,42 @@ module DiscourseGamification
self.table_name = "gamification_leaderboards"
+ has_many :leaderboard_scores,
+ class_name: "DiscourseGamification::GamificationLeaderboardScore",
+ foreign_key: :leaderboard_id,
+ dependent: :delete_all
+
validates :name, exclusion: { in: %w[new], message: "%{value} is reserved." }
+ validate :validate_score_overrides
attribute :period, :integer
enum :period, { all_time: 0, yearly: 1, quarterly: 2, monthly: 3, weekly: 4, daily: 5 }
+ VALID_SCORABLE_KEYS =
+ Set.new(
+ %w[
+ like_given
+ like_received
+ solution
+ user_invited
+ time_read
+ post_read
+ topic_created
+ post_created
+ flag_created
+ day_visited
+ reaction_received
+ reaction_given
+ chat_reaction_received
+ chat_reaction_given
+ chat_message_created
+ ],
+ ).freeze
+
+ def score_override_for(key)
+ score_overrides&.dig(key)
+ end
+
def resolve_period(given_period)
return given_period if self.class.periods.key?(given_period)
@@ -38,6 +69,21 @@ module DiscourseGamification
offset: offset,
)
end
+
+ private
+
+ def validate_score_overrides
+ return if score_overrides.blank?
+
+ score_overrides.each do |key, value|
+ if VALID_SCORABLE_KEYS.exclude?(key)
+ errors.add(:score_overrides, "contains invalid scorable key: #{key}")
+ end
+ unless value.is_a?(Integer) && value >= 0
+ errors.add(:score_overrides, "values must be non-negative integers")
+ end
+ end
+ end
end
end
@@ -46,18 +92,20 @@ end
# Table name: gamification_leaderboards
#
# id :bigint not null, primary key
-# name :string not null
+# default_period :integer default(0)
+# excluded_groups_ids :integer default([]), not null, is an Array
# from_date :date
+# included_groups_ids :integer default([]), not null, is an Array
+# name :string not null
+# period_filter_disabled :boolean default(FALSE), not null
+# scorable_category_ids :integer is an Array
+# score_overrides :jsonb
# to_date :date
-# for_category_id :integer
-# created_by_id :integer not null
+# visible_to_groups_ids :integer default([]), not null, is an Array
# created_at :datetime not null
# updated_at :datetime not null
-# visible_to_groups_ids :integer default([]), not null, is an Array
-# included_groups_ids :integer default([]), not null, is an Array
-# excluded_groups_ids :integer default([]), not null, is an Array
-# default_period :integer default(0)
-# period_filter_disabled :boolean default(FALSE), not null
+# created_by_id :integer not null
+# for_category_id :integer
#
# Indexes
#
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
new file mode 100644
index 00000000000..a99100e8c18
--- /dev/null
+++ b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard_score.rb
@@ -0,0 +1,106 @@
+# frozen_string_literal: true
+
+module DiscourseGamification
+ class GamificationLeaderboardScore < ::ActiveRecord::Base
+ self.table_name = "gamification_leaderboard_scores"
+
+ belongs_to :user
+ belongs_to :leaderboard,
+ class_name: "DiscourseGamification::GamificationLeaderboard",
+ foreign_key: :leaderboard_id
+
+ def self.enabled_scorables(leaderboard:)
+ Scorable.subclasses.filter { it.enabled?(leaderboard:) }
+ end
+
+ def self.scorables_queries(leaderboard:)
+ enabled_scorables(leaderboard:).map { "( #{it.query(leaderboard:)} )" }.join(" UNION ALL ")
+ end
+
+ def self.calculate_scores(leaderboard, since_date: Date.today, only_subclass: nil)
+ queries =
+ if only_subclass
+ only_subclass.query(leaderboard:)
+ else
+ scorables_queries(leaderboard:)
+ end
+
+ DB.exec(
+ "DELETE FROM gamification_leaderboard_scores WHERE leaderboard_id = :leaderboard_id AND date >= :since",
+ since: since_date,
+ leaderboard_id: leaderboard.id,
+ )
+
+ score_event_query = <<~SQL
+ SELECT user_id, date, SUM(points) AS points
+ FROM gamification_score_events
+ WHERE date >= :since
+ GROUP BY 1, 2
+ SQL
+
+ source_queries =
+ if queries.present?
+ "#{queries} UNION ALL #{score_event_query}"
+ else
+ score_event_query
+ end
+
+ DB.exec(<<~SQL, since: since_date, leaderboard_id: leaderboard.id)
+ INSERT INTO gamification_leaderboard_scores (leaderboard_id, user_id, date, score)
+ SELECT :leaderboard_id, user_id, date, SUM(points) AS score
+ FROM (
+ #{source_queries}
+ ) AS source
+ JOIN users AS u ON u.id = source.user_id
+ WHERE user_id IS NOT NULL
+ AND (u.suspended_till IS NULL OR u.suspended_till < CURRENT_TIMESTAMP)
+ AND u.active
+ GROUP BY user_id, date
+ ON CONFLICT (leaderboard_id, user_id, date) DO UPDATE
+ SET score = EXCLUDED.score;
+ SQL
+ end
+
+ def self.calculate_all(since_date: Date.today)
+ GamificationLeaderboard
+ .where("to_date IS NULL OR to_date >= ?", since_date)
+ .find_each { |lb| calculate_scores(lb, since_date:) }
+ end
+
+ def self.merge_scores(source_user, target_user)
+ DB.exec(<<~SQL, source_id: source_user.id, target_id: target_user.id)
+ WITH new_scores AS (
+ SELECT leaderboard_id, :target_id AS user_id, date, SUM(score) AS score
+ FROM gamification_leaderboard_scores
+ WHERE user_id IN (:source_id, :target_id)
+ GROUP BY 1, 2, 3
+ ) INSERT INTO gamification_leaderboard_scores (leaderboard_id, user_id, date, score)
+ SELECT leaderboard_id, user_id, date, score
+ FROM new_scores
+ ON CONFLICT (leaderboard_id, user_id, date) DO UPDATE
+ SET score = EXCLUDED.score;
+ SQL
+
+ DB.exec(<<~SQL, source_id: source_user.id)
+ DELETE FROM gamification_leaderboard_scores
+ WHERE user_id = :source_id;
+ SQL
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: gamification_leaderboard_scores
+#
+# id :bigint not null, primary key
+# date :date not null
+# score :integer default(0), not null
+# leaderboard_id :bigint not null
+# user_id :bigint not null
+#
+# Indexes
+#
+# idx_leaderboard_scores_lb_date (leaderboard_id,date)
+# idx_leaderboard_scores_lb_user_date (leaderboard_id,user_id,date) UNIQUE
+#
diff --git a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_score.rb b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_score.rb
deleted file mode 100644
index b6c65c549fd..00000000000
--- a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_score.rb
+++ /dev/null
@@ -1,79 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseGamification
- class GamificationScore < ::ActiveRecord::Base
- self.table_name = "gamification_scores"
-
- belongs_to :user
-
- def self.enabled_scorables
- Scorable.subclasses.filter { it.enabled? }
- end
-
- def self.scorables_queries
- enabled_scorables.map { "( #{it.query} )" }.join(" UNION ALL ")
- end
-
- def self.calculate_scores(since_date: Date.today, only_subclass: nil)
- queries = only_subclass&.query || scorables_queries
-
- DB.exec(<<~SQL, since: since_date)
- DELETE FROM gamification_scores
- WHERE date >= :since;
-
- INSERT INTO gamification_scores (user_id, date, score)
- SELECT user_id, date, SUM(points) AS score
- FROM (
- #{queries}
- UNION ALL
- SELECT user_id, date, SUM(points) AS points
- FROM gamification_score_events
- WHERE date >= :since
- GROUP BY 1, 2
- ) AS source
- JOIN users AS u ON u.id = source.user_id
- WHERE user_id IS NOT NULL
- AND (u.suspended_till IS NULL OR u.suspended_till < CURRENT_TIMESTAMP)
- AND u.active
- GROUP BY 1, 2
- ON CONFLICT (user_id, date) DO UPDATE
- SET score = EXCLUDED.score;
- SQL
- end
-
- def self.merge_scores(source_user, target_user)
- DB.exec(<<~SQL, source_id: source_user.id, target_id: target_user.id)
- WITH new_scores AS (
- SELECT :target_id AS user_id, date, SUM(score) AS score
- FROM gamification_scores
- WHERE user_id IN (:source_id, :target_id)
- GROUP BY 1, 2
- ) INSERT INTO gamification_scores (user_id, date, score)
- SELECT user_id, date, score AS score
- FROM new_scores
- ON CONFLICT (user_id, date) DO UPDATE
- SET score = EXCLUDED.score;
- SQL
-
- DB.exec(<<~SQL, source_id: source_user.id)
- DELETE FROM gamification_scores
- WHERE user_id = :source_id;
- SQL
- end
- end
-end
-
-# == Schema Information
-#
-# Table name: gamification_scores
-#
-# id :bigint not null, primary key
-# user_id :integer not null
-# date :date not null
-# score :integer not null
-#
-# Indexes
-#
-# index_gamification_scores_on_date (date)
-# index_gamification_scores_on_user_id_and_date (user_id,date) UNIQUE
-#
diff --git a/plugins/discourse-gamification/app/serializers/admin_gamification_index_serializer.rb b/plugins/discourse-gamification/app/serializers/admin_gamification_index_serializer.rb
index 08d57a29153..5c65c93a385 100644
--- a/plugins/discourse-gamification/app/serializers/admin_gamification_index_serializer.rb
+++ b/plugins/discourse-gamification/app/serializers/admin_gamification_index_serializer.rb
@@ -2,7 +2,7 @@
class AdminGamificationIndexSerializer < ApplicationSerializer
attribute :gamification_recalculate_scores_remaining
- has_many :gamification_leaderboards, serializer: LeaderboardSerializer, embed: :objects
+ has_many :gamification_leaderboards, serializer: AdminLeaderboardSerializer, embed: :objects
has_many :gamification_groups, serializer: BasicGroupSerializer, embed: :object
def gamification_leaderboards
diff --git a/plugins/discourse-gamification/app/serializers/admin_leaderboard_serializer.rb b/plugins/discourse-gamification/app/serializers/admin_leaderboard_serializer.rb
new file mode 100644
index 00000000000..6c444e2cf3b
--- /dev/null
+++ b/plugins/discourse-gamification/app/serializers/admin_leaderboard_serializer.rb
@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+class AdminLeaderboardSerializer < LeaderboardSerializer
+ attributes :score_overrides, :scorable_category_ids
+end
diff --git a/plugins/discourse-gamification/assets/javascripts/discourse/models/gamification-leaderboard.js b/plugins/discourse-gamification/assets/javascripts/discourse/models/gamification-leaderboard.js
index 295952ccef9..f9ceb818ba2 100644
--- a/plugins/discourse-gamification/assets/javascripts/discourse/models/gamification-leaderboard.js
+++ b/plugins/discourse-gamification/assets/javascripts/discourse/models/gamification-leaderboard.js
@@ -20,6 +20,8 @@ export default class GamificationLeaderboard {
@tracked name;
@tracked period;
@tracked periodFilterDisabled;
+ @tracked scoreOverrides;
+ @tracked scorableCategoryIds;
constructor(args = {}) {
this.id = args.id;
@@ -35,6 +37,8 @@ export default class GamificationLeaderboard {
this.name = args.name;
this.period = args.period;
this.periodFilterDisabled = args.period_filter_disabled;
+ this.scoreOverrides = args.score_overrides;
+ this.scorableCategoryIds = args.scorable_category_ids;
if (Number.isInteger(args.default_period)) {
this.defaultPeriod = i18n(
diff --git a/plugins/discourse-gamification/assets/stylesheets/common/leaderboard-admin.scss b/plugins/discourse-gamification/assets/stylesheets/common/leaderboard-admin.scss
index 22b5fc39a84..76762fb1ca4 100644
--- a/plugins/discourse-gamification/assets/stylesheets/common/leaderboard-admin.scss
+++ b/plugins/discourse-gamification/assets/stylesheets/common/leaderboard-admin.scss
@@ -37,6 +37,26 @@
}
}
+.leaderboard-scoring-details {
+ margin-top: 1em;
+
+ > summary {
+ font-size: var(--font-up-1);
+ font-weight: 700;
+ cursor: pointer;
+ padding: 0.5em 0;
+ }
+
+ &__description {
+ color: var(--primary-medium);
+ margin: 0 0 1em;
+ }
+
+ .form-kit__section + .form-kit__section {
+ margin-top: 1.5em;
+ }
+}
+
.new-leaderboard-container {
.form-kit__row {
padding-top: 0;
diff --git a/plugins/discourse-gamification/config/locales/client.en.yml b/plugins/discourse-gamification/config/locales/client.en.yml
index 3738d202900..63a518d147b 100644
--- a/plugins/discourse-gamification/config/locales/client.en.yml
+++ b/plugins/discourse-gamification/config/locales/client.en.yml
@@ -27,6 +27,11 @@ en:
cta: "Make your first leaderboard"
none: "No leaderboards created yet."
confirm_destroy: "Are you sure you want to delete this leaderboard?"
+ section:
+ time_period: "Time period"
+ time_period_description: "Control the date range and default period for this leaderboard."
+ groups: "Groups"
+ groups_description: "Control which users are included in and can view this leaderboard."
date:
range: "From / To Date Range"
from: "From date"
@@ -41,6 +46,28 @@ en:
default_period: "Default period"
default_period_help: "Set the default time period to display for this leaderboard."
period_filter_disabled: "Disable time period filter"
+ 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."
+ 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:
+ like_given: "Like given"
+ like_received: "Like received"
+ post_created: "Post created"
+ topic_created: "Topic created"
+ solution: "Solution"
+ day_visited: "Day visited"
+ flag_created: "Flag created"
+ post_read: "Post read"
+ time_read: "Time read"
+ user_invited: "User invited"
+ reaction_given: "Reaction given"
+ reaction_received: "Reaction received"
+ chat_message_created: "Chat message created"
+ chat_reaction_given: "Chat reaction given"
+ chat_reaction_received: "Chat reaction received"
period:
all_time: "All Time"
yearly: "Yearly"
diff --git a/plugins/discourse-gamification/db/migrate/20260402141912_create_gamification_leaderboard_scores.rb b/plugins/discourse-gamification/db/migrate/20260402141912_create_gamification_leaderboard_scores.rb
new file mode 100644
index 00000000000..9fe27a34d1e
--- /dev/null
+++ b/plugins/discourse-gamification/db/migrate/20260402141912_create_gamification_leaderboard_scores.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+class CreateGamificationLeaderboardScores < ActiveRecord::Migration[7.2]
+ def up
+ create_table :gamification_leaderboard_scores do |t|
+ t.bigint :leaderboard_id, null: false
+ t.bigint :user_id, null: false
+ t.date :date, null: false
+ t.integer :score, null: false, default: 0
+ end
+
+ add_index :gamification_leaderboard_scores,
+ %i[leaderboard_id user_id date],
+ unique: true,
+ name: "idx_leaderboard_scores_lb_user_date"
+ add_index :gamification_leaderboard_scores,
+ %i[leaderboard_id date],
+ name: "idx_leaderboard_scores_lb_date"
+
+ # Backfill: copy existing global scores into per-leaderboard scores
+ # for every existing leaderboard. All leaderboards used global settings
+ # before this migration, so they all get identical copies.
+ if table_exists?(:gamification_scores) && table_exists?(:gamification_leaderboards)
+ leaderboard_ids = DB.query_single("SELECT id FROM gamification_leaderboards")
+ leaderboard_ids.each { |lb_id| execute <<~SQL }
+ INSERT INTO gamification_leaderboard_scores (leaderboard_id, user_id, date, score)
+ SELECT #{lb_id}, gs.user_id, gs.date, gs.score
+ FROM gamification_scores gs
+ SQL
+ end
+ end
+
+ def down
+ drop_table :gamification_leaderboard_scores
+ end
+end
diff --git a/plugins/discourse-gamification/db/migrate/20260402141924_add_score_overrides_to_gamification_leaderboards.rb b/plugins/discourse-gamification/db/migrate/20260402141924_add_score_overrides_to_gamification_leaderboards.rb
new file mode 100644
index 00000000000..b5914b9d509
--- /dev/null
+++ b/plugins/discourse-gamification/db/migrate/20260402141924_add_score_overrides_to_gamification_leaderboards.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+class AddScoreOverridesToGamificationLeaderboards < ActiveRecord::Migration[7.2]
+ def change
+ add_column :gamification_leaderboards, :score_overrides, :jsonb, default: nil
+ add_column :gamification_leaderboards,
+ :scorable_category_ids,
+ :integer,
+ array: true,
+ default: nil
+ end
+end
diff --git a/plugins/discourse-gamification/jobs/regular/recalculate_leaderboard_scores.rb b/plugins/discourse-gamification/jobs/regular/recalculate_leaderboard_scores.rb
new file mode 100644
index 00000000000..8b38f62ef0e
--- /dev/null
+++ b/plugins/discourse-gamification/jobs/regular/recalculate_leaderboard_scores.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module Jobs
+ class RecalculateLeaderboardScores < ::Jobs::Base
+ def execute(args)
+ leaderboard_id = args[:leaderboard_id]
+ raise Discourse::InvalidParameters.new(:leaderboard_id) if leaderboard_id.blank?
+
+ leaderboard = DiscourseGamification::GamificationLeaderboard.find_by(id: leaderboard_id)
+ return unless leaderboard
+
+ DiscourseGamification::GamificationLeaderboardScore.calculate_scores(
+ leaderboard,
+ since_date: leaderboard.from_date || Date.new(2000, 1, 1),
+ )
+
+ view = DiscourseGamification::LeaderboardCachedView.new(leaderboard)
+ view.delete
+ view.create
+ end
+ end
+end
diff --git a/plugins/discourse-gamification/jobs/regular/recalculate_scores.rb b/plugins/discourse-gamification/jobs/regular/recalculate_scores.rb
index 32781a8abcb..8ea33fc68b8 100644
--- a/plugins/discourse-gamification/jobs/regular/recalculate_scores.rb
+++ b/plugins/discourse-gamification/jobs/regular/recalculate_scores.rb
@@ -6,10 +6,12 @@ module Jobs
user_id = args[:user_id]
raise Discourse::InvalidParameters.new(:user_id) if user_id.blank?
- DiscourseGamification::GamificationScore.calculate_scores(
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all(
since_date: args[:since] || 10.days.ago,
)
+ DiscourseGamification::LeaderboardCachedView.regenerate_all
+
::MessageBus.publish "/recalculate_scores",
{
success: true,
diff --git a/plugins/discourse-gamification/jobs/scheduled/update_scores_for_ten_days.rb b/plugins/discourse-gamification/jobs/scheduled/update_scores_for_ten_days.rb
index 1babfb28807..ad1d1d84bd1 100644
--- a/plugins/discourse-gamification/jobs/scheduled/update_scores_for_ten_days.rb
+++ b/plugins/discourse-gamification/jobs/scheduled/update_scores_for_ten_days.rb
@@ -5,7 +5,9 @@ module Jobs
every 1.day
def execute(args = nil)
- DiscourseGamification::GamificationScore.calculate_scores(since_date: 10.days.ago.midnight)
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all(
+ since_date: 10.days.ago.midnight,
+ )
end
end
end
diff --git a/plugins/discourse-gamification/jobs/scheduled/update_scores_for_today.rb b/plugins/discourse-gamification/jobs/scheduled/update_scores_for_today.rb
index 4d4487cf3c0..93530727bda 100644
--- a/plugins/discourse-gamification/jobs/scheduled/update_scores_for_today.rb
+++ b/plugins/discourse-gamification/jobs/scheduled/update_scores_for_today.rb
@@ -5,7 +5,7 @@ module Jobs
every 1.hour
def execute(args = nil)
- DiscourseGamification::GamificationScore.calculate_scores
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all
DiscourseGamification::LeaderboardCachedView.purge_all_stale
DiscourseGamification::LeaderboardCachedView.refresh_all
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/directory_integration.rb b/plugins/discourse-gamification/lib/discourse_gamification/directory_integration.rb
index 4afb53748c6..e50dc4ba044 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/directory_integration.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/directory_integration.rb
@@ -6,6 +6,7 @@ module DiscourseGamification
<<~SQL
WITH default_leaderboard AS (
SELECT
+ id,
from_date,
to_date
FROM
@@ -15,26 +16,26 @@ module DiscourseGamification
LIMIT 1
), total_score AS (
SELECT
- user_id,
- SUM(score) AS score
+ gls.user_id,
+ SUM(gls.score) AS score
FROM
- gamification_scores
- LEFT JOIN
- default_leaderboard ON true
+ gamification_leaderboard_scores gls
+ INNER JOIN
+ default_leaderboard lb ON gls.leaderboard_id = lb.id
WHERE
- date >= :since
+ gls.date >= :since
AND
(
(
- default_leaderboard.from_date IS NULL
+ lb.from_date IS NULL
OR
- date >= default_leaderboard.from_date
+ gls.date >= lb.from_date
)
AND
(
- default_leaderboard.to_date IS NULL
+ lb.to_date IS NULL
OR
- date <= default_leaderboard.to_date
+ gls.date <= lb.to_date
)
)
GROUP BY
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/leaderboard_cached_view.rb b/plugins/discourse-gamification/lib/discourse_gamification/leaderboard_cached_view.rb
index e3cce21a91f..0292e1fb3d0 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/leaderboard_cached_view.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/leaderboard_cached_view.rb
@@ -168,37 +168,39 @@ module DiscourseGamification
scores AS (
SELECT
- gs.*
+ gls.*
FROM
- gamification_scores gs
+ gamification_leaderboard_scores gls
CROSS JOIN
leaderboard lb
WHERE
+ gls.leaderboard_id = :leaderboard_id
+ AND
(CASE
-- Leaderboard with both "to_date" and "from_date" configured.
-- Filter scores within the configured date range AND
-- the relative period window
WHEN lb.from_date IS NOT NULL AND lb.to_date IS NOT NULL THEN
- gs.date BETWEEN GREATEST(lb.from_date, #{period_start_sql(period)}) AND lb.to_date
+ gls.date BETWEEN GREATEST(lb.from_date, #{period_start_sql(period)}) AND lb.to_date
-- Leaderboard with only "from_date" configured.
-- Filter scores starting from the later of leaderboard's "from_date"
-- and the relative period start date
WHEN lb.from_date IS NOT NULL AND lb.to_date IS NULL THEN
- gs.date >= GREATEST(lb.from_date, #{period_start_sql(period)})
+ gls.date >= GREATEST(lb.from_date, #{period_start_sql(period)})
-- Leaderboard with only "to_date" configured.
-- Filter scores up to leaderboard's "to_date" starting from
-- the relative period start date
WHEN lb.from_date IS NULL AND lb.to_date IS NOT NULL THEN
- gs.date >= COALESCE(#{period_start_sql(period)}, gs.date) AND gs.date <= lb.to_date
+ gls.date >= COALESCE(#{period_start_sql(period)}, gls.date) AND gls.date <= lb.to_date
-- Leaderboard with no "from_date" and "to_date" configured.
-- Filter scores within the relative period window only
ELSE
- gs.date >= COALESCE(#{period_start_sql(period)}, gs.date)
+ gls.date >= COALESCE(#{period_start_sql(period)}, gls.date)
END)
- AND gs.date <= CURRENT_DATE -- Ensure scores are not from the future
+ AND gls.date <= CURRENT_DATE -- Ensure scores are not from the future
)
SELECT
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_message_created.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_message_created.rb
index fd1e8c98b0e..0ae0897834e 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_message_created.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_message_created.rb
@@ -1,20 +1,16 @@
# frozen_string_literal: true
module DiscourseGamification
class ChatMessageCreated < Scorable
- def self.enabled?
- SiteSetting.chat_enabled && score_multiplier > 0
+ def self.enabled?(leaderboard: nil)
+ SiteSetting.chat_enabled && super
end
- def self.score_multiplier
- SiteSetting.chat_message_created_score_value
- end
-
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
m.user_id,
date_trunc('day', m.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
chat_messages AS m
JOIN
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_reaction_given.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_reaction_given.rb
index fa9648f120c..60a32623e58 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_reaction_given.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_reaction_given.rb
@@ -1,20 +1,16 @@
# frozen_string_literal: true
module DiscourseGamification
class ChatReactionGiven < Scorable
- def self.enabled?
- SiteSetting.chat_enabled && score_multiplier > 0
+ def self.enabled?(leaderboard: nil)
+ SiteSetting.chat_enabled && super
end
- def self.score_multiplier
- SiteSetting.chat_reaction_given_score_value
- end
-
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
reactions.user_id AS user_id,
date_trunc('day', reactions.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
chat_message_reactions AS reactions
INNER JOIN chat_messages AS cm
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_reaction_received.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_reaction_received.rb
index 20f3a92e4ae..2e70967e5d5 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_reaction_received.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/chat_reaction_received.rb
@@ -1,20 +1,16 @@
# frozen_string_literal: true
module DiscourseGamification
class ChatReactionReceived < Scorable
- def self.enabled?
- SiteSetting.chat_enabled && score_multiplier > 0
+ def self.enabled?(leaderboard: nil)
+ SiteSetting.chat_enabled && super
end
- def self.score_multiplier
- SiteSetting.chat_reaction_received_score_value
- end
-
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
cm.user_id AS user_id,
date_trunc('day', reactions.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
chat_message_reactions AS reactions
INNER JOIN chat_messages AS cm
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/day_visited.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/day_visited.rb
index dab6a175780..e6c086ef200 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/day_visited.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/day_visited.rb
@@ -2,16 +2,12 @@
module DiscourseGamification
class DayVisited < Scorable
- def self.score_multiplier
- SiteSetting.day_visited_score_value
- end
-
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
uv.user_id AS user_id,
date_trunc('day', uv.visited_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
user_visits AS uv
WHERE
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/flag_created.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/flag_created.rb
index 111a295fa5f..592e4b278d5 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/flag_created.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/flag_created.rb
@@ -2,16 +2,12 @@
module DiscourseGamification
class FlagCreated < Scorable
- def self.score_multiplier
- SiteSetting.flag_created_score_value
- end
-
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
r.created_by_id AS user_id,
date_trunc('day', r.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
reviewables AS r
WHERE
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 4f44e310fda..298e4329aa0 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_given.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_given.rb
@@ -1,31 +1,27 @@
# frozen_string_literal: true
module DiscourseGamification
class LikeGiven < Scorable
- def self.score_multiplier
- SiteSetting.like_given_score_value
- end
-
- def self.category_filter
- return "" if scorable_category_list.empty?
+ def self.category_filter(leaderboard: nil)
+ return "" if scorable_category_list(leaderboard:).empty?
<<~SQL
- AND t.category_id IN (#{scorable_category_list})
+ AND t.category_id IN (#{scorable_category_list(leaderboard:)})
SQL
end
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
pa.user_id AS user_id,
date_trunc('day', pa.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
post_actions AS pa
INNER JOIN posts AS p
ON p.id = pa.post_id
INNER JOIN topics AS t
ON t.id = p.topic_id
- #{category_filter}
+ #{category_filter(leaderboard:)}
WHERE
p.deleted_at IS NULL AND
t.archetype <> 'private_message' AND
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 021d855a2c9..b8f1bd863a4 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_received.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/like_received.rb
@@ -1,31 +1,27 @@
# frozen_string_literal: true
module DiscourseGamification
class LikeReceived < Scorable
- def self.score_multiplier
- SiteSetting.like_received_score_value
- end
-
- def self.category_filter
- return "" if scorable_category_list.empty?
+ def self.category_filter(leaderboard: nil)
+ return "" if scorable_category_list(leaderboard:).empty?
<<~SQL
- AND t.category_id IN (#{scorable_category_list})
+ AND t.category_id IN (#{scorable_category_list(leaderboard:)})
SQL
end
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
p.user_id AS user_id,
date_trunc('day', pa.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
post_actions AS pa
INNER JOIN posts AS p
ON p.id = pa.post_id
INNER JOIN topics AS t
ON t.id = p.topic_id
- #{category_filter}
+ #{category_filter(leaderboard:)}
WHERE
p.deleted_at IS NULL AND
t.archetype <> 'private_message' AND
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 d47f1703e93..59545d11be9 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_created.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_created.rb
@@ -2,29 +2,25 @@
module DiscourseGamification
class PostCreated < Scorable
- def self.score_multiplier
- SiteSetting.post_created_score_value
- end
-
- def self.category_filter
- return "" if scorable_category_list.empty?
+ def self.category_filter(leaderboard: nil)
+ return "" if scorable_category_list(leaderboard:).empty?
<<~SQL
- AND t.category_id IN (#{scorable_category_list})
+ AND t.category_id IN (#{scorable_category_list(leaderboard:)})
SQL
end
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
p.user_id AS user_id,
date_trunc('day', p.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
posts AS p
INNER JOIN topics AS t
ON t.id = p.topic_id
- #{category_filter}
+ #{category_filter(leaderboard:)}
WHERE
p.deleted_at IS NULL AND
t.deleted_at IS NULL AND
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_read.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_read.rb
index fa3732e0215..f0378940680 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_read.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/post_read.rb
@@ -2,16 +2,12 @@
module DiscourseGamification
class PostRead < Scorable
- def self.score_multiplier
- SiteSetting.post_read_score_value
- end
-
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
uv.user_id AS user_id,
date_trunc('day', uv.visited_at) AS date,
- SUM(uv.posts_read) / 100 * #{score_multiplier} AS points
+ SUM(uv.posts_read) / 100 * #{score_multiplier(leaderboard:)} AS points
FROM
user_visits AS uv
WHERE
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 14a54de55a3..6ee0e4a4b6a 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_given.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_given.rb
@@ -1,36 +1,31 @@
# frozen_string_literal: true
module DiscourseGamification
class ReactionGiven < Scorable
- def self.enabled?
- defined?(DiscourseReactions) && SiteSetting.discourse_reactions_enabled &&
- score_multiplier > 0
+ def self.enabled?(leaderboard: nil)
+ defined?(DiscourseReactions) && SiteSetting.discourse_reactions_enabled && super
end
- def self.score_multiplier
- SiteSetting.reaction_given_score_value
- end
-
- def self.category_filter
- return "" if scorable_category_list.empty?
+ def self.category_filter(leaderboard: nil)
+ return "" if scorable_category_list(leaderboard:).empty?
<<~SQL
- AND t.category_id IN (#{scorable_category_list})
+ AND t.category_id IN (#{scorable_category_list(leaderboard:)})
SQL
end
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
reactions.user_id AS user_id,
date_trunc('day', reactions.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
discourse_reactions_reaction_users AS reactions
INNER JOIN posts AS p
ON p.id = reactions.post_id
INNER JOIN topics AS t
ON t.id = p.topic_id
- #{category_filter}
+ #{category_filter(leaderboard:)}
WHERE
p.deleted_at IS NULL AND
t.deleted_at IS NULL AND
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 9250193adc7..d646803fb4f 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_received.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/reaction_received.rb
@@ -1,36 +1,31 @@
# frozen_string_literal: true
module DiscourseGamification
class ReactionReceived < Scorable
- def self.enabled?
- defined?(DiscourseReactions) && SiteSetting.discourse_reactions_enabled &&
- score_multiplier > 0
+ def self.enabled?(leaderboard: nil)
+ defined?(DiscourseReactions) && SiteSetting.discourse_reactions_enabled && super
end
- def self.score_multiplier
- SiteSetting.reaction_received_score_value
- end
-
- def self.category_filter
- return "" if scorable_category_list.empty?
+ def self.category_filter(leaderboard: nil)
+ return "" if scorable_category_list(leaderboard:).empty?
<<~SQL
- AND t.category_id IN (#{scorable_category_list})
+ AND t.category_id IN (#{scorable_category_list(leaderboard:)})
SQL
end
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
p.user_id AS user_id,
date_trunc('day', reactions.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
discourse_reactions_reaction_users AS reactions
INNER JOIN posts AS p
ON p.id = reactions.post_id
INNER JOIN topics AS t
ON t.id = p.topic_id
- #{category_filter}
+ #{category_filter(leaderboard:)}
WHERE
p.deleted_at IS NULL AND
t.archetype <> 'private_message' AND
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/scorable.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/scorable.rb
index 1aa8d99573f..c72df298809 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/scorable.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/scorable.rb
@@ -2,12 +2,27 @@
module DiscourseGamification
class Scorable
class << self
- def enabled?
- score_multiplier > 0
+ def enabled?(leaderboard: nil)
+ score_multiplier(leaderboard:) > 0
end
- def scorable_category_list
- SiteSetting.scorable_categories.split("|").map { it.to_i }.join(", ")
+ def scorable_key
+ name.demodulize.underscore
+ end
+
+ def score_multiplier(leaderboard: nil)
+ override = leaderboard&.score_override_for(scorable_key)
+ return override unless override.nil?
+ SiteSetting.public_send(:"#{scorable_key}_score_value")
+ end
+
+ def scorable_category_list(leaderboard: nil)
+ categories = leaderboard&.scorable_category_ids
+ if categories.nil?
+ SiteSetting.scorable_categories.split("|").map { it.to_i }.join(", ")
+ else
+ categories.join(", ")
+ end
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 252c6d2de8c..884bf514151 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb
@@ -1,33 +1,33 @@
# frozen_string_literal: true
module DiscourseGamification
class Solutions < Scorable
- def self.enabled?
+ def self.enabled?(leaderboard: nil)
defined?(DiscourseSolved) && SiteSetting.solved_enabled && super
end
- def self.score_multiplier
- SiteSetting.solution_score_value
+ def self.scorable_key
+ "solution"
end
- def self.category_filter
- return "" if scorable_category_list.empty?
+ def self.category_filter(leaderboard: nil)
+ return "" if scorable_category_list(leaderboard:).empty?
<<~SQL
- AND topics.category_id IN (#{scorable_category_list})
+ AND topics.category_id IN (#{scorable_category_list(leaderboard:)})
SQL
end
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
posts.user_id AS user_id,
date_trunc('day', dsst.updated_at) AS date,
- COUNT(dsst.topic_id) * #{score_multiplier} AS points
+ COUNT(dsst.topic_id) * #{score_multiplier(leaderboard:)} AS points
FROM
discourse_solved_solved_topics dsst
INNER JOIN topics
ON dsst.topic_id = topics.id
- #{category_filter}
+ #{category_filter(leaderboard:)}
INNER JOIN posts
ON posts.id = dsst.answer_post_id
WHERE
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/time_read.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/time_read.rb
index 23bb94071d0..206185ae770 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/time_read.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/time_read.rb
@@ -2,16 +2,12 @@
module DiscourseGamification
class TimeRead < Scorable
- def self.score_multiplier
- SiteSetting.time_read_score_value
- end
-
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
uv.user_id AS user_id,
date_trunc('day', uv.visited_at) AS date,
- SUM(uv.time_read) / 3600 * #{score_multiplier} AS points
+ SUM(uv.time_read) / 3600 * #{score_multiplier(leaderboard:)} AS points
FROM
user_visits AS uv
WHERE
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 9388043ed8f..36890b747ca 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/topic_created.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/topic_created.rb
@@ -2,31 +2,27 @@
module DiscourseGamification
class TopicCreated < Scorable
- def self.score_multiplier
- SiteSetting.topic_created_score_value
- end
-
- def self.category_filter
- return "" if scorable_category_list.empty?
+ def self.category_filter(leaderboard: nil)
+ return "" if scorable_category_list(leaderboard:).empty?
<<~SQL
- AND t.category_id IN (#{scorable_category_list})
+ AND t.category_id IN (#{scorable_category_list(leaderboard:)})
SQL
end
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
t.user_id AS user_id,
date_trunc('day', t.created_at) AS date,
- COUNT(*) * #{score_multiplier} AS points
+ COUNT(*) * #{score_multiplier(leaderboard:)} AS points
FROM
topics AS t
WHERE
t.deleted_at IS NULL AND
t.archetype <> 'private_message' AND
t.created_at >= :since
- #{category_filter}
+ #{category_filter(leaderboard:)}
GROUP BY
1, 2
SQL
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/user_invited.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/user_invited.rb
index 61a55b87828..350f23dd340 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/user_invited.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/user_invited.rb
@@ -2,16 +2,12 @@
module DiscourseGamification
class UserInvited < Scorable
- def self.score_multiplier
- SiteSetting.user_invited_score_value
- end
-
- def self.query
+ def self.query(leaderboard: nil)
<<~SQL
SELECT
inv.invited_by_id AS user_id,
date_trunc('day', inv.created_at) AS date,
- SUM(inv.redemption_count * #{score_multiplier}) AS points
+ SUM(inv.redemption_count * #{score_multiplier(leaderboard:)}) AS points
FROM
invites AS inv
WHERE
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/user_extension.rb b/plugins/discourse-gamification/lib/discourse_gamification/user_extension.rb
index 232762683fe..2312e6abeab 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/user_extension.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/user_extension.rb
@@ -5,8 +5,8 @@ module DiscourseGamification
extend ActiveSupport::Concern
prepended do
- has_many :gamification_scores,
- class_name: "DiscourseGamification::GamificationScore",
+ has_many :gamification_leaderboard_scores,
+ class_name: "DiscourseGamification::GamificationLeaderboardScore",
dependent: :destroy
end
diff --git a/plugins/discourse-gamification/lib/tasks/gamification_scores.rake b/plugins/discourse-gamification/lib/tasks/gamification_scores.rake
index 559682dd0a8..fa865da525f 100644
--- a/plugins/discourse-gamification/lib/tasks/gamification_scores.rake
+++ b/plugins/discourse-gamification/lib/tasks/gamification_scores.rake
@@ -8,6 +8,6 @@ task "gamification_scores:backfill_scores_from", [:date] => [:environment] do |_
exit 1
end
- DiscourseGamification::GamificationScore.calculate_scores(since_date: date)
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all(since_date: date)
puts "Scores updated"
end
diff --git a/plugins/discourse-gamification/plugin.rb b/plugins/discourse-gamification/plugin.rb
index 722bffe7762..f5f6c1d741f 100644
--- a/plugins/discourse-gamification/plugin.rb
+++ b/plugins/discourse-gamification/plugin.rb
@@ -39,6 +39,7 @@ after_initialize do
require_relative "jobs/scheduled/update_scores_for_ten_days"
require_relative "jobs/scheduled/update_scores_for_today"
require_relative "jobs/regular/recalculate_scores"
+ require_relative "jobs/regular/recalculate_leaderboard_scores"
require_relative "jobs/regular/generate_leaderboard_positions"
require_relative "jobs/regular/refresh_leaderboard_positions"
require_relative "jobs/regular/delete_leaderboard_positions"
@@ -90,9 +91,9 @@ after_initialize do
.all
.map { |group| BasicGroupSerializer.new(group, root: false, scope: self.scope).as_json },
gamification_leaderboards:
- DiscourseGamification::GamificationLeaderboard.all.map do |leaderboard|
- LeaderboardSerializer.new(leaderboard, root: false).as_json
- end,
+ DiscourseGamification::GamificationLeaderboard
+ .order(updated_at: :desc)
+ .map { |leaderboard| AdminLeaderboardSerializer.new(leaderboard, root: false).as_json },
}
end
@@ -113,6 +114,6 @@ after_initialize do
end
on(:merging_users) do |source_user, target_user|
- DiscourseGamification::GamificationScore.merge_scores(source_user, target_user)
+ DiscourseGamification::GamificationLeaderboardScore.merge_scores(source_user, target_user)
end
end
diff --git a/plugins/discourse-gamification/spec/fabricators/gamification_score.rb b/plugins/discourse-gamification/spec/fabricators/gamification_score.rb
index 57d9226ae40..f129df6ed19 100644
--- a/plugins/discourse-gamification/spec/fabricators/gamification_score.rb
+++ b/plugins/discourse-gamification/spec/fabricators/gamification_score.rb
@@ -1,6 +1,10 @@
# frozen_string_literal: true
-Fabricator(:gamification_score, from: DiscourseGamification::GamificationScore) do
+Fabricator(
+ :gamification_leaderboard_score,
+ from: DiscourseGamification::GamificationLeaderboardScore,
+) do
+ leaderboard_id { Fabricate(:gamification_leaderboard).id }
user_id { Fabricate(:user).id }
score { 0 }
date { Date.today }
diff --git a/plugins/discourse-gamification/spec/jobs/delete_leaderboard_positions_spec.rb b/plugins/discourse-gamification/spec/jobs/delete_leaderboard_positions_spec.rb
index ba8e5fb94aa..267150ae66b 100644
--- a/plugins/discourse-gamification/spec/jobs/delete_leaderboard_positions_spec.rb
+++ b/plugins/discourse-gamification/spec/jobs/delete_leaderboard_positions_spec.rb
@@ -2,7 +2,13 @@
describe Jobs::DeleteLeaderboardPositions do
fab!(:leaderboard, :gamification_leaderboard)
- fab!(:score) { Fabricate(:gamification_score, user_id: leaderboard.created_by_id) }
+ fab!(:score) do
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: leaderboard.created_by_id,
+ )
+ end
let(:leaderboard_positions) { DiscourseGamification::LeaderboardCachedView.new(leaderboard) }
before { leaderboard_positions.create }
diff --git a/plugins/discourse-gamification/spec/jobs/generate_leaderboard_positions_spec.rb b/plugins/discourse-gamification/spec/jobs/generate_leaderboard_positions_spec.rb
index 9b09becc91e..2ceb27026db 100644
--- a/plugins/discourse-gamification/spec/jobs/generate_leaderboard_positions_spec.rb
+++ b/plugins/discourse-gamification/spec/jobs/generate_leaderboard_positions_spec.rb
@@ -1,17 +1,27 @@
# frozen_string_literal: true
describe Jobs::GenerateLeaderboardPositions do
+ fab!(:user)
fab!(:leaderboard, :gamification_leaderboard)
- fab!(:score) { Fabricate(:gamification_score, user_id: leaderboard.created_by_id) }
+ fab!(:score) do
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user.id,
+ score: 5,
+ )
+ end
let(:leaderboard_positions) { DiscourseGamification::LeaderboardCachedView.new(leaderboard) }
- it "generates leaderboard positions" do
+ it "generates leaderboard positions from existing scores" do
expect { leaderboard_positions.scores }.to raise_error(
DiscourseGamification::LeaderboardCachedView::NotReadyError,
)
+ DiscourseGamification::GamificationLeaderboardScore.expects(:calculate_scores).never
described_class.new.execute(leaderboard_id: leaderboard.id)
expect(leaderboard_positions.scores.length).to eq(1)
+ expect(leaderboard_positions.scores.first.total_score).to eq(5)
end
end
diff --git a/plugins/discourse-gamification/spec/jobs/recalculate_scores_spec.rb b/plugins/discourse-gamification/spec/jobs/recalculate_scores_spec.rb
index f4ddc90a284..1c65658af85 100644
--- a/plugins/discourse-gamification/spec/jobs/recalculate_scores_spec.rb
+++ b/plugins/discourse-gamification/spec/jobs/recalculate_scores_spec.rb
@@ -2,12 +2,17 @@
describe Jobs::RecalculateScores do
fab!(:current_user, :admin)
+ fab!(:leaderboard, :gamification_leaderboard)
before { RateLimiter.enable }
it "publishes MessageBus and executes job" do
since = 10.days.ago
- DiscourseGamification::GamificationScore.expects(:calculate_scores).with(since_date: since)
+ DiscourseGamification::GamificationLeaderboardScore.expects(:calculate_all).with(
+ since_date: since,
+ )
+
+ DiscourseGamification::LeaderboardCachedView.expects(:regenerate_all)
MessageBus
.expects(:publish)
diff --git a/plugins/discourse-gamification/spec/jobs/refresh_leaderboard_positions_spec.rb b/plugins/discourse-gamification/spec/jobs/refresh_leaderboard_positions_spec.rb
index af40ba95a05..bdf23c09d71 100644
--- a/plugins/discourse-gamification/spec/jobs/refresh_leaderboard_positions_spec.rb
+++ b/plugins/discourse-gamification/spec/jobs/refresh_leaderboard_positions_spec.rb
@@ -7,7 +7,12 @@ describe Jobs::RefreshLeaderboardPositions do
before { leaderboard_positions.create }
it "refreshes leaderboard positions" do
- Fabricate(:gamification_score, user_id: leaderboard.created_by_id, score: 10)
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: leaderboard.created_by_id,
+ score: 10,
+ )
expect(leaderboard_positions.scores).to be_empty
diff --git a/plugins/discourse-gamification/spec/jobs/update_scores_for_ten_days_spec.rb b/plugins/discourse-gamification/spec/jobs/update_scores_for_ten_days_spec.rb
index 1795205d267..60b36842fb2 100644
--- a/plugins/discourse-gamification/spec/jobs/update_scores_for_ten_days_spec.rb
+++ b/plugins/discourse-gamification/spec/jobs/update_scores_for_ten_days_spec.rb
@@ -1,13 +1,9 @@
# frozen_string_literal: true
describe Jobs::UpdateScoresForTenDays do
- let(:user) { Fabricate(:user) }
- let(:user_2) { Fabricate(:user) }
- let(:post) { Fabricate(:post, user: user) }
- let!(:gamification_score) { Fabricate(:gamification_score, user_id: user.id, date: 8.days.ago) }
- let!(:gamification_score_2) do
- Fabricate(:gamification_score, user_id: user_2.id, date: 12.days.ago)
- end
+ fab!(:user)
+ fab!(:user_2, :user)
+ fab!(:leaderboard, :gamification_leaderboard)
let!(:topic_user_created) { Fabricate(:topic, user: user) }
let!(:topic_user_2_created) { Fabricate(:topic, user: user_2) }
@@ -21,14 +17,22 @@ describe Jobs::UpdateScoresForTenDays do
end
it "updates all scores within the last 10 days" do
- expect(DiscourseGamification::GamificationScore.find_by(user_id: user.id).score).to eq(0)
run_job
- expect(DiscourseGamification::GamificationScore.find_by(user_id: user.id).score).to eq(5)
+ score =
+ DiscourseGamification::GamificationLeaderboardScore.where(
+ user_id: user.id,
+ leaderboard_id: leaderboard.id,
+ ).sum(:score)
+ expect(score).to eq(5)
end
it "does not update scores outside of the last 10 days" do
- expect(DiscourseGamification::GamificationScore.find_by(user_id: user_2.id).score).to eq(0)
run_job
- expect(DiscourseGamification::GamificationScore.find_by(user_id: user_2.id).score).to eq(0)
+ score =
+ DiscourseGamification::GamificationLeaderboardScore.where(
+ user_id: user_2.id,
+ leaderboard_id: leaderboard.id,
+ ).sum(:score)
+ expect(score).to eq(0)
end
end
diff --git a/plugins/discourse-gamification/spec/jobs/update_scores_for_today_spec.rb b/plugins/discourse-gamification/spec/jobs/update_scores_for_today_spec.rb
index 640c572c968..3f8ec02820a 100644
--- a/plugins/discourse-gamification/spec/jobs/update_scores_for_today_spec.rb
+++ b/plugins/discourse-gamification/spec/jobs/update_scores_for_today_spec.rb
@@ -4,10 +4,6 @@ describe Jobs::UpdateScoresForToday do
fab!(:user)
fab!(:user_2, :user)
fab!(:post) { Fabricate(:post, user: user, post_number: 2) }
- fab!(:gamification_score) { Fabricate(:gamification_score, user_id: user.id) }
- fab!(:gamification_score_2) do
- Fabricate(:gamification_score, user_id: user_2.id, date: 2.days.ago)
- end
fab!(:topic_user_created) { Fabricate(:topic, user: user) }
fab!(:topic_user_2_created) { Fabricate(:topic, user: user_2) }
@@ -23,15 +19,25 @@ describe Jobs::UpdateScoresForToday do
before { topic_user_2_created.update(created_at: 2.days.ago) }
it "updates all scores for today" do
- expect(DiscourseGamification::GamificationScore.find_by(user_id: user.id).score).to eq(0)
run_job
- expect(DiscourseGamification::GamificationScore.find_by(user_id: user.id).score).to eq(12)
+ score =
+ DiscourseGamification::GamificationLeaderboardScore.find_by(
+ user_id: user.id,
+ leaderboard_id: leaderboard_1.id,
+ date: Date.today,
+ )
+ expect(score&.score).to eq(12)
end
it "does not update scores outside of today" do
- expect(DiscourseGamification::GamificationScore.find_by(user_id: user_2.id).score).to eq(0)
run_job
- expect(DiscourseGamification::GamificationScore.find_by(user_id: user_2.id).score).to eq(0)
+ score =
+ DiscourseGamification::GamificationLeaderboardScore.find_by(
+ user_id: user_2.id,
+ leaderboard_id: leaderboard_1.id,
+ date: Date.today,
+ )
+ expect(score).to be_nil
end
context "with leaderboard positions" do
@@ -47,79 +53,36 @@ describe Jobs::UpdateScoresForToday do
run_job
- expect(leaderboard_1_positions.scores.length).to eq(2)
- expect(leaderboard_1_positions.scores.map(&:attributes)).to include(
- {
- "id" => user.id,
- "total_score" => 12,
- "position" => 1,
- "uploaded_avatar_id" => nil,
- "username" => user.username,
- "name" => user.name,
- },
- {
- "id" => user_2.id,
- "total_score" => 0,
- "position" => 2,
- "uploaded_avatar_id" => nil,
- "username" => user_2.username,
- "name" => user_2.name,
- },
+ expect(leaderboard_1_positions.scores.length).to eq(1)
+ expect(leaderboard_1_positions.scores.first.attributes).to include(
+ "id" => user.id,
+ "total_score" => 12,
+ "position" => 1,
)
end
it "refreshes leaderboard positions" do
- # Force assignment of scores accrued
- DiscourseGamification::GamificationScore.calculate_scores
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all
DiscourseGamification::LeaderboardCachedView.create_all
- expect(leaderboard_1_positions.scores.map(&:attributes)).to include(
- {
- "id" => user.id,
- "total_score" => 12,
- "position" => 1,
- "uploaded_avatar_id" => nil,
- "username" => user.username,
- "name" => user.name,
- },
- {
- "id" => user_2.id,
- "total_score" => 0,
- "position" => 2,
- "uploaded_avatar_id" => nil,
- "username" => user_2.username,
- "name" => user_2.name,
- },
+ expect(leaderboard_1_positions.scores.first.attributes).to include(
+ "id" => user.id,
+ "total_score" => 12,
+ "position" => 1,
)
- Fabricate(:gamification_score, user_id: user_2.id, date: 3.days.ago, score: 2)
-
run_job
- expect(leaderboard_1_positions.scores.map(&:attributes)).to include(
- {
- "id" => user.id,
- "total_score" => 12,
- "position" => 1,
- "uploaded_avatar_id" => nil,
- "username" => user.username,
- "name" => user.name,
- },
- {
- "id" => user_2.id,
- "total_score" => 2,
- "position" => 2,
- "uploaded_avatar_id" => nil,
- "username" => user_2.username,
- "name" => user_2.name,
- },
+ expect(leaderboard_1_positions.scores.first.attributes).to include(
+ "id" => user.id,
+ "total_score" => 12,
+ "position" => 1,
)
end
it "purges stale leaderboard positions" do
DiscourseGamification::LeaderboardCachedView.create_all
- # Update query to make existing materialized views stale
allow_any_instance_of(DiscourseGamification::LeaderboardCachedView).to receive(
:total_scores_query,
).and_wrap_original do |original_method, period|
@@ -134,24 +97,11 @@ describe Jobs::UpdateScoresForToday do
expect(leaderboard_1_positions.stale?).to eq(false)
expect(leaderboard_2_positions.stale?).to eq(false)
- expect(leaderboard_1_positions.scores.length).to eq(2)
- expect(leaderboard_1_positions.scores.map(&:attributes)).to include(
- {
- "id" => user.id,
- "total_score" => 12,
- "position" => 1,
- "uploaded_avatar_id" => nil,
- "username" => user.username,
- "name" => user.name,
- },
- {
- "id" => user_2.id,
- "total_score" => 0,
- "position" => 2,
- "uploaded_avatar_id" => nil,
- "username" => user_2.username,
- "name" => user_2.name,
- },
+ expect(leaderboard_1_positions.scores.length).to eq(1)
+ expect(leaderboard_1_positions.scores.first.attributes).to include(
+ "id" => user.id,
+ "total_score" => 12,
+ "position" => 1,
)
end
end
diff --git a/plugins/discourse-gamification/spec/jobs/update_stale_leaderboard_positions_spec.rb b/plugins/discourse-gamification/spec/jobs/update_stale_leaderboard_positions_spec.rb
index fb38cf5d727..cb6091994a5 100644
--- a/plugins/discourse-gamification/spec/jobs/update_stale_leaderboard_positions_spec.rb
+++ b/plugins/discourse-gamification/spec/jobs/update_stale_leaderboard_positions_spec.rb
@@ -2,7 +2,13 @@
describe Jobs::UpdateStaleLeaderboardPositions do
fab!(:leaderboard, :gamification_leaderboard)
- fab!(:score) { Fabricate(:gamification_score, user_id: leaderboard.created_by_id) }
+ fab!(:score) do
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: leaderboard.created_by_id,
+ )
+ end
let(:leaderboard_positions) { DiscourseGamification::LeaderboardCachedView.new(leaderboard) }
it "it updates all stale leaderboard positions" do
diff --git a/plugins/discourse-gamification/spec/lib/directory_integration_spec.rb b/plugins/discourse-gamification/spec/lib/directory_integration_spec.rb
index 11eb0fe774b..3578d7e3ef4 100644
--- a/plugins/discourse-gamification/spec/lib/directory_integration_spec.rb
+++ b/plugins/discourse-gamification/spec/lib/directory_integration_spec.rb
@@ -4,10 +4,42 @@ describe DiscourseGamification::DirectoryIntegration do
fab!(:user_1, :admin)
fab!(:user_2, :user)
fab!(:leaderboard, :gamification_leaderboard)
- fab!(:score_1) { Fabricate(:gamification_score, user_id: user_1.id, score: 10, date: 8.days.ago) }
- fab!(:score_2) { Fabricate(:gamification_score, user_id: user_1.id, score: 40, date: 3.days.ago) }
- fab!(:score_3) { Fabricate(:gamification_score, user_id: user_2.id, score: 25, date: 5.days.ago) }
- fab!(:score_4) { Fabricate(:gamification_score, user_id: user_2.id, score: 5, date: 2.days.ago) }
+ fab!(:score_1) do
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user_1.id,
+ score: 10,
+ date: 8.days.ago,
+ )
+ end
+ fab!(:score_2) do
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user_1.id,
+ score: 40,
+ date: 3.days.ago,
+ )
+ end
+ fab!(:score_3) do
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user_2.id,
+ score: 25,
+ date: 5.days.ago,
+ )
+ end
+ fab!(:score_4) do
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user_2.id,
+ score: 5,
+ date: 2.days.ago,
+ )
+ end
before do
SiteSetting.discourse_gamification_enabled = true
@@ -50,9 +82,6 @@ describe DiscourseGamification::DirectoryIntegration do
end
it "returns sum of points earned between leaderboard's 'from_date' and 'to_date'" do
- expect(DiscourseGamification::GamificationScore.where(user: user_1).sum(:score)).to eq(50)
- expect(DiscourseGamification::GamificationScore.where(user: user_2).sum(:score)).to eq(30)
-
expect(all_time_score_for(user_1)).to eq(40)
expect(all_time_score_for(user_2)).to eq(25)
end
@@ -61,9 +90,6 @@ describe DiscourseGamification::DirectoryIntegration do
context "without a date-restricted default leaderboard" do
it "returns sum of all scores for the period" do
- expect(DiscourseGamification::GamificationScore.where(user: user_1).sum(:score)).to eq(50)
- expect(DiscourseGamification::GamificationScore.where(user: user_2).sum(:score)).to eq(30)
-
expect(all_time_score_for(user_1)).to eq(50)
expect(all_time_score_for(user_2)).to eq(30)
end
diff --git a/plugins/discourse-gamification/spec/lib/leaderboard_cached_view_spec.rb b/plugins/discourse-gamification/spec/lib/leaderboard_cached_view_spec.rb
index 23190ccca85..3b5c901c04f 100644
--- a/plugins/discourse-gamification/spec/lib/leaderboard_cached_view_spec.rb
+++ b/plugins/discourse-gamification/spec/lib/leaderboard_cached_view_spec.rb
@@ -6,7 +6,14 @@ describe DiscourseGamification::LeaderboardCachedView do
fab!(:other_user, :user)
fab!(:moderator)
fab!(:leaderboard) { Fabricate(:gamification_leaderboard, created_by_id: admin.id) }
- fab!(:gamification_score) { Fabricate(:gamification_score, user_id: user.id, date: 8.days.ago) }
+ fab!(:gamification_score) do
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user.id,
+ date: 8.days.ago,
+ )
+ end
let(:mviews) do
DiscourseGamification::GamificationLeaderboard.periods.map do |period, _|
@@ -43,10 +50,32 @@ describe DiscourseGamification::LeaderboardCachedView do
describe "#refresh" do
before do
described_class.new(leaderboard).create
- Fabricate(:gamification_score, user_id: user.id, score: 10)
- Fabricate(:gamification_score, user_id: admin.id, score: 20)
- Fabricate(:gamification_score, user_id: other_user.id, score: 1, date: 5.days.ago)
- Fabricate(:gamification_score, user_id: other_user.id, score: 4, date: 3.days.ago)
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user.id,
+ score: 10,
+ )
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: admin.id,
+ score: 20,
+ )
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: other_user.id,
+ score: 1,
+ date: 5.days.ago,
+ )
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: other_user.id,
+ score: 4,
+ date: 3.days.ago,
+ )
end
it "refreshes leaderboard materialized views with the latest scores" do
@@ -145,7 +174,15 @@ describe DiscourseGamification::LeaderboardCachedView do
leaderboard_to + 1.day,
leaderboard_to + 15.days,
leaderboard_to + 30.days,
- ].each { |date| Fabricate(:gamification_score, user_id: user.id, date: date, score: 10) }
+ ].each do |date|
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user.id,
+ date: date,
+ score: 10,
+ )
+ end
end
it "filters scores for leaderboard with both 'from_date' and 'to_date' configured" do
@@ -198,10 +235,30 @@ describe DiscourseGamification::LeaderboardCachedView do
context "with leaderboard ranking strategies" do
before do
- Fabricate(:gamification_score, user_id: user.id, score: 20)
- Fabricate(:gamification_score, user_id: admin.id, score: 50)
- Fabricate(:gamification_score, user_id: other_user.id, score: 20)
- Fabricate(:gamification_score, user_id: moderator.id, score: 10)
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user.id,
+ score: 20,
+ )
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: admin.id,
+ score: 50,
+ )
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: other_user.id,
+ score: 20,
+ )
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: moderator.id,
+ score: 10,
+ )
end
context "with 'rank'" do
diff --git a/plugins/discourse-gamification/spec/lib/scorables/shared_scorables_spec.rb b/plugins/discourse-gamification/spec/lib/scorables/shared_scorables_spec.rb
index ef27a57e93e..21c7cf0fea5 100755
--- a/plugins/discourse-gamification/spec/lib/scorables/shared_scorables_spec.rb
+++ b/plugins/discourse-gamification/spec/lib/scorables/shared_scorables_spec.rb
@@ -9,7 +9,8 @@ RSpec.shared_examples "Scorable Type" do
describe "#{described_class} updates gamification score" do
it "has correct total score" do
- DiscourseGamification::GamificationScore.calculate_scores(
+ DiscourseGamification::GamificationLeaderboardScore.calculate_scores(
+ leaderboard,
since_date: "2022-1-1",
only_subclass: described_class,
)
@@ -37,7 +38,10 @@ RSpec.shared_examples "Category Scoped Scorable Type" do
it "#{described_class} updates scores for action in the category configured" do
expect(user.gamification_score).to eq(0)
SiteSetting.scorable_categories = category_allowed.id.to_s
- DiscourseGamification::GamificationScore.calculate_scores(only_subclass: described_class)
+ DiscourseGamification::GamificationLeaderboardScore.calculate_scores(
+ leaderboard,
+ only_subclass: described_class,
+ )
DiscourseGamification::LeaderboardCachedView.refresh_all
expect(user.gamification_score).to eq(expected_score)
end
@@ -45,7 +49,10 @@ RSpec.shared_examples "Category Scoped Scorable Type" do
it "#{described_class} doesn't updates scores for action in the category configured" do
expect(user_2.gamification_score).to eq(0)
SiteSetting.scorable_categories = category_not_allowed.id.to_s
- DiscourseGamification::GamificationScore.calculate_scores(only_subclass: described_class)
+ DiscourseGamification::GamificationLeaderboardScore.calculate_scores(
+ leaderboard,
+ only_subclass: described_class,
+ )
DiscourseGamification::LeaderboardCachedView.refresh_all
expect(user_2.gamification_score).to eq(0)
end
@@ -70,7 +77,8 @@ RSpec.shared_examples "No Score Value" do
let!(:trigger_after_create_hook) { after_create_hook }
it "does not increase user gamification score" do
- DiscourseGamification::GamificationScore.calculate_scores(
+ DiscourseGamification::GamificationLeaderboardScore.calculate_scores(
+ leaderboard,
since_date: "2022-1-1",
only_subclass: described_class,
)
diff --git a/plugins/discourse-gamification/spec/models/gamification_score_spec.rb b/plugins/discourse-gamification/spec/models/gamification_score_spec.rb
index f76e96c6abd..7402a23f6fa 100644
--- a/plugins/discourse-gamification/spec/models/gamification_score_spec.rb
+++ b/plugins/discourse-gamification/spec/models/gamification_score_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscourseGamification::GamificationScore, type: :model do
+RSpec.describe DiscourseGamification::GamificationLeaderboardScore, type: :model do
fab!(:user)
fab!(:leaderboard, :gamification_leaderboard)
@@ -9,20 +9,37 @@ RSpec.describe DiscourseGamification::GamificationScore, type: :model do
describe ".calculate_scores" do
it "calculates the scores properly" do
Fabricate.times(10, :topic, user: user)
- described_class.calculate_scores
+ described_class.calculate_scores(leaderboard)
DiscourseGamification::LeaderboardCachedView.refresh_all
expect(user.gamification_score).to eq(50)
user.topics.take(5).each(&:destroy)
- described_class.calculate_scores
+ described_class.calculate_scores(leaderboard)
DiscourseGamification::LeaderboardCachedView.refresh_all
expect(user.gamification_score).to eq(25)
- # this test covers a bug where scores weren't updated if new score was 0
user.topics.each(&:destroy)
- described_class.calculate_scores
+ described_class.calculate_scores(leaderboard)
DiscourseGamification::LeaderboardCachedView.refresh_all
expect(user.gamification_score).to eq(0)
end
+
+ it "uses leaderboard score overrides" do
+ Fabricate.times(5, :topic, user: user)
+ leaderboard.update!(score_overrides: { "topic_created" => 10 })
+ described_class.calculate_scores(leaderboard)
+ DiscourseGamification::LeaderboardCachedView.new(leaderboard).delete
+ DiscourseGamification::LeaderboardCachedView.new(leaderboard).create
+ expect(user.gamification_score).to eq(50)
+ end
+
+ it "disables scorables when override is 0" do
+ Fabricate.times(5, :topic, user: user)
+ leaderboard.update!(score_overrides: { "topic_created" => 0 })
+ described_class.calculate_scores(leaderboard)
+ DiscourseGamification::LeaderboardCachedView.new(leaderboard).delete
+ DiscourseGamification::LeaderboardCachedView.new(leaderboard).create
+ expect(user.gamification_score).to eq(0)
+ end
end
end
diff --git a/plugins/discourse-gamification/spec/models/user_spec.rb b/plugins/discourse-gamification/spec/models/user_spec.rb
index 9e7af34e58f..354c9640d3a 100644
--- a/plugins/discourse-gamification/spec/models/user_spec.rb
+++ b/plugins/discourse-gamification/spec/models/user_spec.rb
@@ -5,8 +5,20 @@ describe User, type: :model do
fab!(:leaderboard, :gamification_leaderboard)
before do
- Fabricate(:gamification_score, user_id: user.id, score: 10, date: 8.days.ago)
- Fabricate(:gamification_score, user_id: user.id, score: 25, date: 5.days.ago)
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user.id,
+ score: 10,
+ date: 8.days.ago,
+ )
+ Fabricate(
+ :gamification_leaderboard_score,
+ leaderboard_id: leaderboard.id,
+ user_id: user.id,
+ score: 25,
+ date: 5.days.ago,
+ )
leaderboard.update(from_date: 5.days.ago.to_date)
DiscourseGamification::LeaderboardCachedView.create_all
@@ -14,7 +26,12 @@ describe User, type: :model do
describe "#gamification_score" do
it "returns default leaderboard 'all_time' total score" do
- expect(DiscourseGamification::GamificationScore.where(user_id: user.id).sum(:score)).to eq(35)
+ total =
+ DiscourseGamification::GamificationLeaderboardScore.where(
+ user_id: user.id,
+ leaderboard_id: leaderboard.id,
+ ).sum(:score)
+ expect(total).to eq(35)
expect(user.gamification_score).to eq(25)
end
end
diff --git a/plugins/discourse-gamification/spec/plugin_spec.rb b/plugins/discourse-gamification/spec/plugin_spec.rb
index 9418a4eed1a..cccfa02e4f3 100644
--- a/plugins/discourse-gamification/spec/plugin_spec.rb
+++ b/plugins/discourse-gamification/spec/plugin_spec.rb
@@ -1,13 +1,12 @@
# frozen_string_literal: true
describe DiscourseGamification do
- let(:user) { Fabricate(:user) }
- let!(:gamification_score) { Fabricate(:gamification_score, user_id: user.id) }
+ fab!(:user)
+ fab!(:leaderboard, :gamification_leaderboard)
it "adds gamification_score to the UserCardSerializer" do
serializer = UserCardSerializer.new(user)
expect(serializer).to respond_to(:gamification_score)
- expect(serializer.gamification_score).to eq(gamification_score.score)
end
context "with leaderboard positions" do
@@ -45,7 +44,7 @@ context "when merging users" do
DiscourseGamification::LeaderboardCachedView.create_all
Fabricate.times(1, :topic, user: user_1)
Fabricate.times(1, :topic, user: user_2)
- DiscourseGamification::GamificationScore.calculate_scores
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all
DiscourseGamification::LeaderboardCachedView.refresh_all
end
diff --git a/plugins/discourse-gamification/spec/requests/admin_gamification_leaderboard_controller_spec.rb b/plugins/discourse-gamification/spec/requests/admin_gamification_leaderboard_controller_spec.rb
index ed9b271f647..2c5434a1ba0 100644
--- a/plugins/discourse-gamification/spec/requests/admin_gamification_leaderboard_controller_spec.rb
+++ b/plugins/discourse-gamification/spec/requests/admin_gamification_leaderboard_controller_spec.rb
@@ -9,8 +9,8 @@ RSpec.describe DiscourseGamification::AdminGamificationLeaderboardController do
end
describe "#create" do
- it "creates leaderboard and enqueues generation of positions" do
- expect(Jobs::GenerateLeaderboardPositions.jobs.size).to eq(0)
+ it "creates leaderboard and enqueues score recalculation" do
+ expect(Jobs::RecalculateLeaderboardScores.jobs.size).to eq(0)
expect do
post "/admin/plugins/gamification/leaderboard.json",
@@ -23,7 +23,7 @@ RSpec.describe DiscourseGamification::AdminGamificationLeaderboardController do
expect(response.status).to eq(200)
expect(response.parsed_body).to include("name" => "Test", "created_by_id" => admin.id)
- job_data = Jobs::GenerateLeaderboardPositions.jobs.first["args"].first
+ job_data = Jobs::RecalculateLeaderboardScores.jobs.first["args"].first
expect(job_data).to include("leaderboard_id" => response.parsed_body["id"])
end
end
@@ -47,6 +47,31 @@ RSpec.describe DiscourseGamification::AdminGamificationLeaderboardController do
end
end
+ describe "#show" do
+ it "returns admin-only scoring configuration" do
+ scorable_category_id = 123
+ leaderboard =
+ Fabricate(
+ :gamification_leaderboard,
+ created_by_id: admin.id,
+ score_overrides: {
+ "like_received" => 10,
+ },
+ scorable_category_ids: [scorable_category_id],
+ )
+
+ get "/admin/plugins/discourse-gamification/leaderboards/#{leaderboard.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["leaderboard"]).to include(
+ "score_overrides" => {
+ "like_received" => 10,
+ },
+ "scorable_category_ids" => [scorable_category_id],
+ )
+ end
+ end
+
describe "destroy" do
it "deletes leaderboard and enqueues deletion of positions" do
leaderboard = Fabricate(:gamification_leaderboard, created_by_id: admin.id)
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 7479e6afda3..cd861bac085 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
@@ -4,6 +4,7 @@ RSpec.describe DiscourseGamification::AdminGamificationScoreEventController do
let(:current_user) { Fabricate(:admin) }
let(:another_user) { Fabricate(:user) }
let(:score_events) { [] }
+ let!(:leaderboard) { Fabricate(:gamification_leaderboard, created_by_id: current_user.id) }
before do
SiteSetting.discourse_gamification_enabled = true
@@ -26,7 +27,9 @@ RSpec.describe DiscourseGamification::AdminGamificationScoreEventController do
points: 27,
)
- DiscourseGamification::GamificationScore.calculate_scores(since_date: 10.days.ago.midnight)
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all(
+ since_date: 10.days.ago.midnight,
+ )
sign_in(current_user)
end
@@ -74,9 +77,14 @@ RSpec.describe DiscourseGamification::AdminGamificationScoreEventController do
}
expect(response.status).to eq(200)
- DiscourseGamification::GamificationScore.calculate_scores(since_date: 10.days.ago.midnight)
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all(
+ since_date: 10.days.ago.midnight,
+ )
user_score =
- DiscourseGamification::GamificationScore.where(user_id: another_user.id).sum(:score)
+ DiscourseGamification::GamificationLeaderboardScore.where(
+ user_id: another_user.id,
+ leaderboard_id: leaderboard.id,
+ ).sum(:score)
expect(user_score).to eq(37)
end
@@ -90,10 +98,15 @@ RSpec.describe DiscourseGamification::AdminGamificationScoreEventController do
}
expect(response.status).to eq(200)
- DiscourseGamification::GamificationScore.calculate_scores(since_date: 10.days.ago.midnight)
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all(
+ since_date: 10.days.ago.midnight,
+ )
user_score =
- DiscourseGamification::GamificationScore.where(user_id: another_user.id).sum(:score)
+ DiscourseGamification::GamificationLeaderboardScore.where(
+ user_id: another_user.id,
+ leaderboard_id: leaderboard.id,
+ ).sum(:score)
expect(user_score).to eq(13)
end
end
diff --git a/plugins/discourse-gamification/spec/requests/gamification_leaderboard_controller_spec.rb b/plugins/discourse-gamification/spec/requests/gamification_leaderboard_controller_spec.rb
index 831023dd389..1935f0f1629 100644
--- a/plugins/discourse-gamification/spec/requests/gamification_leaderboard_controller_spec.rb
+++ b/plugins/discourse-gamification/spec/requests/gamification_leaderboard_controller_spec.rb
@@ -64,7 +64,7 @@ RSpec.describe DiscourseGamification::GamificationLeaderboardController do
before do
SiteSetting.discourse_gamification_enabled = true
- DiscourseGamification::GamificationScore.calculate_scores(since_date: 10.days.ago)
+ DiscourseGamification::GamificationLeaderboardScore.calculate_all(since_date: 10.days.ago)
sign_in(current_user)
end
@@ -81,6 +81,25 @@ RSpec.describe DiscourseGamification::GamificationLeaderboardController do
expect(data["users"][0]["total_score"]).to eq(current_user.gamification_score)
end
+ it "does not expose admin scoring configuration" do
+ scorable_category_id = 123
+ leaderboard.update!(
+ score_overrides: {
+ "like_received" => 10,
+ },
+ scorable_category_ids: [scorable_category_id],
+ )
+ DiscourseGamification::LeaderboardCachedView.new(leaderboard).create
+
+ get "/leaderboard/#{leaderboard.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["leaderboard"]).to_not include(
+ "score_overrides",
+ "scorable_category_ids",
+ )
+ end
+
it "returns an in progress message when leaderboard positions are not ready" do
expect do get "/leaderboard/#{leaderboard.id}.json" end.to change {
Jobs::GenerateLeaderboardPositions.jobs.size
@@ -114,7 +133,7 @@ RSpec.describe DiscourseGamification::GamificationLeaderboardController do
it "only returns users that are a part of a group within included_groups_ids" do
# multiple scores present
- expect(DiscourseGamification::GamificationScore.all.map(&:user_id)).to include(
+ expect(DiscourseGamification::GamificationLeaderboardScore.all.map(&:user_id)).to include(
current_user.id,
user_2.id,
)
@@ -132,12 +151,12 @@ RSpec.describe DiscourseGamification::GamificationLeaderboardController do
it "excludes staged, anon users, currently suspended and deleted users" do
user_3.destroy
# prove score for staged/anon user exists
- expect(DiscourseGamification::GamificationScore.all.map(&:user_id)).to include(
+ expect(DiscourseGamification::GamificationLeaderboardScore.all.map(&:user_id)).to include(
staged_user.id,
anon_user.id,
)
- expect(DiscourseGamification::GamificationScore.all.map(&:user_id)).to_not include(
+ expect(DiscourseGamification::GamificationLeaderboardScore.all.map(&:user_id)).to_not include(
currently_suspended_user.id,
user_3.id,
)
diff --git a/plugins/discourse-gamification/test/javascripts/integration/components/admin-edit-leaderboard-test.gjs b/plugins/discourse-gamification/test/javascripts/integration/components/admin-edit-leaderboard-test.gjs
new file mode 100644
index 00000000000..b0993bffd0f
--- /dev/null
+++ b/plugins/discourse-gamification/test/javascripts/integration/components/admin-edit-leaderboard-test.gjs
@@ -0,0 +1,50 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import Category from "discourse/models/category";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import AdminEditLeaderboard from "discourse/plugins/discourse-gamification/admin/components/admin-edit-leaderboard";
+
+module(
+ "Discourse Gamification | Integration | Component | admin-edit-leaderboard",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.afterEach(function () {
+ sinon.restore();
+ });
+
+ test("loads selected scorable categories asynchronously", async function (assert) {
+ const category = Category.findById(1001);
+
+ this.site.lazy_load_categories = true;
+
+ sinon.stub(Category, "findById").returns(null);
+ const asyncFindByIdsStub = sinon
+ .stub(Category, "asyncFindByIds")
+ .resolves([category]);
+
+ this.leaderboard = {
+ id: 1,
+ name: "Leaderboard",
+ fromDate: null,
+ toDate: null,
+ includedGroupsIds: [],
+ excludedGroupsIds: [],
+ visibleToGroupsIds: [],
+ defaultPeriod: 0,
+ periodFilterDisabled: false,
+ scoreOverrides: null,
+ scorableCategoryIds: [1001],
+ };
+
+ await render(
+ <template>
+ <AdminEditLeaderboard @leaderboard={{this.leaderboard}} />
+ </template>
+ );
+
+ assert.true(asyncFindByIdsStub.calledWith([1001]));
+ });
+ }
+);