Skip to content

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

FIX: Let non-staff assigners search for assignable users

Régis Hanola4d57de6d2a4
diff --git a/plugins/discourse-assign/app/controllers/discourse_assign/assign_controller.rb b/plugins/discourse-assign/app/controllers/discourse_assign/assign_controller.rb
index 5a87cfd3a4d..f56d3568838 100644
--- a/plugins/discourse-assign/app/controllers/discourse_assign/assign_controller.rb
+++ b/plugins/discourse-assign/app/controllers/discourse_assign/assign_controller.rb
@@ -4,60 +4,47 @@ module DiscourseAssign
class AssignController < ApplicationController
requires_plugin PLUGIN_NAME
requires_login
+
+ SEARCH_LIMIT = 6
+
before_action :ensure_logged_in, :ensure_assign_allowed
def suggestions
- target = assignment_target_from_params
- raise Discourse::InvalidAccess if target && !guardian.can_assign?(target)
-
- users = [current_user, *recent_assignees(target)]
- assign_allowed_groups =
- if target
- DiscourseAssign::AssignmentPermissions.assign_allowed_groups_for_target(
- current_user,
- target,
- )
- else
- DiscourseAssign::AssignmentPermissions.assign_allowed_groups_for_user(current_user)
- end
- assignable_group_ids =
- if target
- DiscourseAssign::AssignmentPermissions.allowed_group_ids_for_target(current_user, target)
- else
- Group.assignable(current_user).pluck(:id)
- end
+ target = optional_assignable_target
render json: {
- assign_allowed_on_groups: assign_allowed_groups.pluck(:name),
- assign_allowed_for_groups:
- Group.visible_groups(current_user).where(id: assignable_group_ids).pluck(:name),
- suggestions:
- ActiveModel::ArraySerializer.new(
- users,
- scope: guardian,
- each_serializer: FoundUserSerializer,
- include_status: true,
- ),
+ suggestions: serialize_users([current_user, *recent_assignees(target)]),
+ groups: serialize_groups(searchable_groups(target)),
}
end
- def unassign
- target_id = params.require(:target_id)
- target_type = params.require(:target_type)
- raise Discourse::NotFound if !Assignment.valid_type?(target_type)
- target = target_type.constantize.where(id: target_id).first
- raise Discourse::NotFound if target.blank? || !guardian.can_see?(target)
- raise Discourse::InvalidAccess if !guardian.can_assign?(target)
+ def search
+ term = params.require(:term).strip
+ raise Discourse::InvalidParameters.new(:term) if term.blank?
+ target = optional_assignable_target
- assigner = Assigner.new(target, current_user)
- assigner.unassign
+ users =
+ UserSearch.new(
+ term,
+ searching_user: current_user,
+ user_ids: assignable_user_ids(target),
+ limit: SEARCH_LIMIT,
+ ).search
+ groups = Group.search_groups(term, groups: searchable_groups(target), sort: :auto)
+
+ render json: {
+ users: serialize_users(users),
+ groups: serialize_groups(groups.limit(SEARCH_LIMIT)),
+ }
+ end
+
+ def unassign
+ Assigner.new(assignable_target_from_params, current_user).unassign
render json: success_json
end
def assign
- target_id = params.require(:target_id)
- target_type = params.require(:target_type)
username = params.permit(:username)["username"].presence
group_name = params.permit(:group_name)["group_name"].presence
note = params.permit(:note)["note"].presence
@@ -65,10 +52,7 @@ module DiscourseAssign
should_notify = params.permit(:should_notify)["should_notify"]
should_notify = (should_notify.present? ? should_notify.to_s == "true" : true)
- raise Discourse::NotFound if !Assignment.valid_type?(target_type)
-
- target = target_type.constantize.where(id: target_id).first
- raise Discourse::NotFound if target.blank? || !guardian.can_see?(target)
+ target = target_from_params
assign_to = DiscourseAssign::AssigneeResolver.resolve!(guardian, username:, group_name:)
@@ -181,17 +165,39 @@ module DiscourseAssign
raise Discourse::InvalidAccess.new unless current_user.can_assign?
end
- def recent_assignees(target)
- allowed_user_ids =
- if target
- DiscourseAssign::AssignmentPermissions.allowed_user_ids_for_target(target)
- else
- DiscourseAssign::AssignmentPermissions.assignable_user_ids_for_user(current_user)
- end
+ def assignable_user_ids(target)
+ DiscourseAssign::AssignmentPermissions.assignable_user_ids(target, assigner: current_user)
+ end
+
+ def searchable_groups(target)
+ groups =
+ Group.visible_groups(current_user).where(
+ id:
+ DiscourseAssign::AssignmentPermissions.assignable_groups(
+ target,
+ assigner: current_user,
+ ).select(:id),
+ )
+ DiscoursePluginRegistry.apply_modifier(:groups_for_users_search, groups)
+ end
+
+ def serialize_users(users)
+ ActiveModel::ArraySerializer.new(
+ users,
+ scope: guardian,
+ each_serializer: FoundUserSerializer,
+ include_status: true,
+ )
+ end
+
+ def serialize_groups(groups)
+ groups.pluck(:name, :full_name).map { |name, full_name| { name:, full_name: } }
+ end
+ def recent_assignees(target)
User
.where.not(id: current_user.id)
- .where(id: allowed_user_ids)
+ .where(id: assignable_user_ids(target))
.joins(<<~SQL)
JOIN(
SELECT assigned_to_id user_id, MAX(created_at) last_assigned
@@ -213,17 +219,24 @@ module DiscourseAssign
.limit(5)
end
- def assignment_target_from_params
- return if params[:target_id].blank? && params[:target_type].blank?
-
- target_id = params.require(:target_id)
+ def target_from_params
target_type = params.require(:target_type)
raise Discourse::NotFound if !Assignment.valid_type?(target_type)
- target = target_type.constantize.where(id: target_id).first
+ target = target_type.constantize.find_by(id: params.require(:target_id))
raise Discourse::NotFound if target.blank? || !guardian.can_see?(target)
target
end
+
+ def assignable_target_from_params
+ target_from_params.tap { |target| guardian.ensure_can_assign!(target) }
+ end
+
+ def optional_assignable_target
+ return if params[:target_id].blank? && params[:target_type].blank?
+
+ assignable_target_from_params
+ end
end
end
diff --git a/plugins/discourse-assign/app/models/assignment.rb b/plugins/discourse-assign/app/models/assignment.rb
index e26dd4aaf31..f6723b077c7 100644
--- a/plugins/discourse-assign/app/models/assignment.rb
+++ b/plugins/discourse-assign/app/models/assignment.rb
@@ -101,7 +101,7 @@ class Assignment < ActiveRecord::Base
return if !assigned_to
allowed_user_ids =
- DiscourseAssign::AssignmentPermissions.allowed_user_ids_for_target(target || topic)
+ DiscourseAssign::AssignmentPermissions.assignable_user_ids(target || topic).pluck(:id)
return if allowed_user_ids.blank?
serializer_class = assigned_to_user? ? BasicUserSerializer : BasicGroupSerializer
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/components/assignment-chooser.js b/plugins/discourse-assign/assets/javascripts/discourse/components/assignment-chooser.js
deleted file mode 100644
index fbf6899e168..00000000000
--- a/plugins/discourse-assign/assets/javascripts/discourse/components/assignment-chooser.js
+++ /dev/null
@@ -1,47 +0,0 @@
-import { classNames } from "@ember-decorators/component";
-import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
-import { selectKitOptions } from "discourse/select-kit/components/select-kit";
-
-@classNames("email-group-user-chooser")
-@selectKitOptions({
- assignmentGroups: null,
-})
-export default class AssignmentChooser extends EmailGroupUserChooser {
- async search(filter = "") {
- const assignmentGroups = this.assignmentGroupResults(filter);
- const resultsPromise = super.search(filter);
-
- if (!resultsPromise) {
- return assignmentGroups.length ? assignmentGroups : undefined;
- }
-
- const results = await resultsPromise;
-
- if (!Array.isArray(results)) {
- return results;
- }
-
- const resultIds = new Set(results.map((result) => result.id));
- return [
- ...results,
- ...assignmentGroups.filter((group) => !resultIds.has(group.id)),
- ];
- }
-
- assignmentGroupResults(filter) {
- const normalizedFilter = (filter || "").toLowerCase();
-
- return (this.selectKit.options.assignmentGroups || [])
- .filter(
- (groupName) =>
- !normalizedFilter ||
- groupName.toLowerCase().includes(normalizedFilter)
- )
- .map((groupName) => ({
- id: groupName,
- name: groupName,
- full_name: groupName,
- isGroup: true,
- }));
- }
-}
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/components/assignment.gjs b/plugins/discourse-assign/assets/javascripts/discourse/components/assignment.gjs
index 0f1e95e3489..85ce5374682 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/components/assignment.gjs
+++ b/plugins/discourse-assign/assets/javascripts/discourse/components/assignment.gjs
@@ -4,11 +4,11 @@ import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { service } from "@ember/service";
import ComboBox from "discourse/select-kit/components/combo-box";
+import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
import { not } from "discourse/truth-helpers";
import DTextarea from "discourse/ui-kit/d-textarea";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
-import AssignmentChooser from "./assignment-chooser";
export default class Assignment extends Component {
@service siteSettings;
@@ -30,15 +30,8 @@ export default class Assignment extends Component {
return this.taskActions.suggestionsFor(this.targetId, this.targetType);
}
- get allowedGroups() {
- return this.taskActions.allowedGroupsFor(this.targetId, this.targetType);
- }
-
- get allowedGroupsForAssignment() {
- return this.taskActions.allowedGroupsForAssignmentFor(
- this.targetId,
- this.targetType
- );
+ get searchUrl() {
+ return this.taskActions.searchUrlFor(this.targetId, this.targetType);
}
get status() {
@@ -76,8 +69,8 @@ export default class Assignment extends Component {
}
@action
- setAssignee([newAssignee]) {
- if (this.allowedGroupsForAssignment.includes(newAssignee)) {
+ setAssignee([newAssignee], [item]) {
+ if (item?.isGroup) {
this.args.assignment.username = null;
this.args.assignment.group_name = newAssignee;
} else {
@@ -99,18 +92,14 @@ export default class Assignment extends Component {
{{if this.showAssigneeIeEmptyError 'assignee-error'}}"
>
<label>{{i18n "discourse_assign.assign_modal.assignee_label"}}</label>
- <AssignmentChooser
+ <EmailGroupUserChooser
autocomplete="off"
@id="assignee-chooser"
@onChange={{this.setAssignee}}
@options={{hash
mobilePlacementStrategy="absolute"
- includeGroups=true
- customSearchOptions=(hash
- assignableGroups=true defaultSearchResults=this.suggestions
- )
- assignmentGroups=this.allowedGroupsForAssignment
- groupMembersOf=this.allowedGroups
+ searchUrl=this.searchUrl
+ customSearchOptions=(hash defaultSearchResults=this.suggestions)
maximum=1
tabindex=1
expandedOnInsert=(not this.assignee)
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/services/task-actions.js b/plugins/discourse-assign/assets/javascripts/discourse/services/task-actions.js
index f87f1a91ca4..dd3b0c01cee 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/services/task-actions.js
+++ b/plugins/discourse-assign/assets/javascripts/discourse/services/task-actions.js
@@ -11,23 +11,9 @@ export default class TaskActions extends Service {
@service modal;
@tracked suggestionsRevision = 0;
- #allowedGroupsByTarget = new Map();
- #allowedGroupsForAssignmentByTarget = new Map();
#suggestionsByTarget = new Map();
#suggestionsPromisesByTarget = new Map();
- get suggestions() {
- return this.suggestionsFor();
- }
-
- get allowedGroups() {
- return this.allowedGroupsFor();
- }
-
- get allowedGroupsForAssignment() {
- return this.allowedGroupsForAssignmentFor();
- }
-
suggestionsFor(targetId, targetType = "Topic") {
manuallyTrack(this.suggestionsRevision);
this.#ensureSuggestions(targetId, targetType);
@@ -39,26 +25,9 @@ export default class TaskActions extends Service {
);
}
- allowedGroupsFor(targetId, targetType = "Topic") {
- manuallyTrack(this.suggestionsRevision);
- this.#ensureSuggestions(targetId, targetType);
-
- return (
- this.#allowedGroupsByTarget.get(
- this.#suggestionsKey(targetId, targetType)
- ) || []
- );
- }
-
- allowedGroupsForAssignmentFor(targetId, targetType = "Topic") {
- manuallyTrack(this.suggestionsRevision);
- this.#ensureSuggestions(targetId, targetType);
-
- return (
- this.#allowedGroupsForAssignmentByTarget.get(
- this.#suggestionsKey(targetId, targetType)
- ) || []
- );
+ searchUrlFor(targetId, targetType = "Topic") {
+ const query = new URLSearchParams(this.#targetParams(targetId, targetType));
+ return query.size ? `/assign/search?${query}` : "/assign/search";
}
unassign(targetId, targetType = "Topic") {
@@ -171,29 +140,26 @@ export default class TaskActions extends Service {
}
async #fetchSuggestions(key, targetId, targetType) {
- const data = {};
-
- if (targetId) {
- data.target_id = targetId;
- data.target_type = targetType;
- }
-
- const response = await ajax("/assign/suggestions", { data });
+ const response = await ajax("/assign/suggestions", {
+ data: this.#targetParams(targetId, targetType),
+ });
if (this.isDestroying) {
return;
}
- this.#suggestionsByTarget.set(key, response.suggestions);
- this.#allowedGroupsByTarget.set(key, response.assign_allowed_on_groups);
- this.#allowedGroupsForAssignmentByTarget.set(
- key,
- response.assign_allowed_for_groups
- );
+ this.#suggestionsByTarget.set(key, [
+ ...response.suggestions,
+ ...response.groups,
+ ]);
this.#suggestionsPromisesByTarget.delete(key);
this.suggestionsRevision++;
}
+ #targetParams(targetId, targetType) {
+ return targetId ? { target_id: targetId, target_type: targetType } : {};
+ }
+
#suggestionsKey(targetId, targetType) {
return targetId ? `${targetType}:${targetId}` : "default";
}
diff --git a/plugins/discourse-assign/config/routes.rb b/plugins/discourse-assign/config/routes.rb
index 5d08284d0d5..c858926c50d 100644
--- a/plugins/discourse-assign/config/routes.rb
+++ b/plugins/discourse-assign/config/routes.rb
@@ -5,6 +5,7 @@ DiscourseAssign::Engine.routes.draw do
put "/assign" => "assign#assign"
put "/unassign" => "assign#unassign"
get "/suggestions" => "assign#suggestions"
+ get "/search" => "assign#search"
get "/assigned" => "assign#assigned"
get "/members/:group_name" => "assign#group_members"
end
diff --git a/plugins/discourse-assign/lib/assigner.rb b/plugins/discourse-assign/lib/assigner.rb
index 1f3256b32c3..a3c7d97cfeb 100644
--- a/plugins/discourse-assign/lib/assigner.rb
+++ b/plugins/discourse-assign/lib/assigner.rb
@@ -11,8 +11,8 @@ class ::Assigner
def self.backfill_auto_assign
staff_mention =
User
- .assign_allowed
- .pluck("username")
+ .where(id: DiscourseAssign::AssignmentPermissions.assignable_user_ids(nil))
+ .pluck(:username)
.map { |name| "p.cooked ILIKE '%mention%@#{name}%'" }
.join(" OR ")
@@ -96,10 +96,7 @@ class ::Assigner
end
def self.is_last_staff_post?(post)
- allowed_user_ids =
- DiscourseAssign::AssignmentPermissions.allowed_user_ids_for_target(post.topic)
- return false if allowed_user_ids.empty?
-
+ allowed_user_ids = DiscourseAssign::AssignmentPermissions.assignable_user_ids(post.topic)
Post.where(topic_id: post.topic_id, user_id: allowed_user_ids).maximum(:post_number) ==
post.post_number
end
@@ -109,7 +106,7 @@ class ::Assigner
if mentions.present?
User
.human_users
- .where(id: DiscourseAssign::AssignmentPermissions.allowed_user_ids_for_target(post.topic))
+ .where(id: DiscourseAssign::AssignmentPermissions.assignable_user_ids(post.topic))
.where(username_lower: mentions.map(&:downcase))
.first
end
@@ -141,12 +138,7 @@ class ::Assigner
def allowed_user_ids
@allowed_user_ids ||=
- DiscourseAssign::AssignmentPermissions.allowed_user_ids_for_target(@target)
- end
-
- def allowed_group_ids
- @allowed_group_ids ||=
- DiscourseAssign::AssignmentPermissions.allowed_group_ids_for_target(@assigned_by, @target)
+ DiscourseAssign::AssignmentPermissions.assignable_user_ids(@target).pluck(:id)
end
def can_assign_to?(assign_to)
@@ -165,9 +157,12 @@ class ::Assigner
def can_be_assigned?(assign_to)
if assign_to.is_a?(User)
- allowed_user_ids.include?(assign_to.id)
+ DiscourseAssign::AssignmentPermissions.assignable_user_ids(@target).exists?(id: assign_to.id)
else
- allowed_group_ids.include?(assign_to.id)
+ DiscourseAssign::AssignmentPermissions.assignable_groups(
+ @target,
+ assigner: @assigned_by,
+ ).exists?(id: assign_to.id)
end
end
diff --git a/plugins/discourse-assign/lib/discourse_assign/assignment_permissions.rb b/plugins/discourse-assign/lib/discourse_assign/assignment_permissions.rb
index a2fa91b9bb9..cc9e0975bbb 100644
--- a/plugins/discourse-assign/lib/discourse_assign/assignment_permissions.rb
+++ b/plugins/discourse-assign/lib/discourse_assign/assignment_permissions.rb
@@ -5,45 +5,27 @@ module DiscourseAssign
CATEGORY_ADDITIONAL_ASSIGN_ALLOWED_GROUPS = "additional_assign_allowed_on_groups"
class << self
- def allowed_user_ids_for_target(target)
- ids = Set.new(admin_user_ids)
- ids.merge(user_ids_in_groups(global_group_ids))
- ids.merge(user_ids_in_groups(scoped_group_ids_for_category(category_id_for(target))))
- ids.to_a
- end
-
- def allowed_group_ids_for_target(user, target)
- ids = Set.new(Group.assignable(user).pluck(:id))
- ids.merge(scoped_group_ids_for_category(category_id_for(target)))
- ids.to_a
- end
-
- def assign_allowed_groups_for_target(user, target)
- Group.visible_groups(user).where(
- id: global_group_ids | scoped_group_ids_for_category(category_id_for(target)),
- )
- end
-
- def assign_allowed_groups_for_user(user)
+ # Without a target, these are the users the assigner may assign anywhere.
+ def assignable_user_ids(target, assigner: nil)
group_ids =
- if user&.guardian&.can_assign_globally?
- global_group_ids | all_scoped_group_ids
+ if target
+ global_group_ids | scoped_group_ids_for_category(category_id_for(target))
+ elsif assigner&.guardian&.can_assign_globally?
+ all_assign_allowed_group_ids
else
- global_group_ids | scoped_group_ids_for_user(user)
+ global_group_ids | scoped_group_ids_for_user(assigner)
end
- Group.visible_groups(user).where(id: group_ids)
+ admin_ids = User.human_users.admins.select(:id)
+ member_ids = GroupUser.where(group_id: group_ids).select(:user_id)
+ User.from("(#{admin_ids.to_sql} UNION #{member_ids.to_sql}) AS users").select(:id)
end
- def assignable_user_ids_for_user(user)
- group_ids =
- if user&.guardian&.can_assign_globally?
- global_group_ids | all_scoped_group_ids
- else
- global_group_ids | scoped_group_ids_for_user(user)
- end
+ def assignable_groups(target, assigner:)
+ groups = Group.assignable(assigner)
+ return groups if !target
- (admin_user_ids | user_ids_in_groups(group_ids)).uniq
+ groups.or(Group.where(id: scoped_group_ids_for_category(category_id_for(target))))
end
def all_assign_allowed_group_ids
@@ -76,7 +58,7 @@ module DiscourseAssign
def scoped_group_ids_for_user(user)
return [] if user.blank?
- all_scoped_group_ids & group_ids_for(user)
+ all_scoped_group_ids & user.group_ids
end
def scoped_group_ids_for_category(category_id)
@@ -92,20 +74,6 @@ module DiscourseAssign
private
- def group_ids_for(user)
- user.group_ids
- end
-
- def admin_user_ids
- User.human_users.admins.pluck(:id)
- end
-
- def user_ids_in_groups(group_ids)
- return [] if group_ids.blank?
-
- GroupUser.where(group_id: group_ids).pluck(:user_id)
- end
-
def group_ids_from_value(value)
value.to_s.split("|").map(&:to_i).reject(&:zero?)
end
diff --git a/plugins/discourse-assign/lib/random_assign_utils.rb b/plugins/discourse-assign/lib/random_assign_utils.rb
index a3898ca8e71..3522f922092 100644
--- a/plugins/discourse-assign/lib/random_assign_utils.rb
+++ b/plugins/discourse-assign/lib/random_assign_utils.rb
@@ -118,7 +118,7 @@ class RandomAssignUtils
users =
group
.users
- .where(id: DiscourseAssign::AssignmentPermissions.allowed_user_ids_for_target(topic))
+ .where(id: DiscourseAssign::AssignmentPermissions.assignable_user_ids(topic))
.where.not(
id:
User
diff --git a/plugins/discourse-assign/plugin.rb b/plugins/discourse-assign/plugin.rb
index 41cea73cf92..fb8ae5a2423 100644
--- a/plugins/discourse-assign/plugin.rb
+++ b/plugins/discourse-assign/plugin.rb
@@ -105,11 +105,6 @@ after_initialize do
self.value = value.to_i if name == frequency_field
end
- add_class_method(:group, :assign_allowed_groups) do
- allowed_groups = SiteSetting.assign_allowed_on_groups.split("|")
- where(id: allowed_groups)
- end
-
add_to_class(:user, :can_assign?) do |target = nil|
if target
guardian.can_assign?(target)
@@ -135,28 +130,6 @@ after_initialize do
add_to_class(:group, :can_show_assigned_tab?) { assignable_level > Group::ALIAS_LEVELS[:nobody] }
- add_class_method(:user, :assign_allowed) do
- allowed_groups = SiteSetting.assign_allowed_on_groups.split("|")
-
- # The UNION against admin users is necessary because bot users like the system user are given the admin status but
- # are not added into the admin group.
- where(
- "users.id IN (
- SELECT
- user_id
- FROM group_users
- WHERE group_users.group_id IN (?)
-
- UNION
-
- SELECT id
- FROM users
- WHERE users.admin
- )",
- allowed_groups,
- )
- end
-
add_model_callback(Group, :before_update) do
if name_changed?
SiteSetting.assign_allowed_on_groups =
diff --git a/plugins/discourse-assign/spec/plugin_helper.rb b/plugins/discourse-assign/spec/plugin_helper.rb
index 424ad1c549a..6a0cc33bb9d 100644
--- a/plugins/discourse-assign/spec/plugin_helper.rb
+++ b/plugins/discourse-assign/spec/plugin_helper.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
module DiscourseAssignSpecHelpers
- def allow_group_to_assign_in_category(category, group)
+ def allow_group_to_assign_in_category(category, *groups)
category.custom_fields[
DiscourseAssign::AssignmentPermissions::CATEGORY_ADDITIONAL_ASSIGN_ALLOWED_GROUPS
- ] = group.id.to_s
+ ] = groups.map(&:id).join("|")
category.save_custom_fields
end
end
diff --git a/plugins/discourse-assign/spec/requests/assign_controller_spec.rb b/plugins/discourse-assign/spec/requests/assign_controller_spec.rb
index 5791db510ae..d5a30095e1a 100644
--- a/plugins/discourse-assign/spec/requests/assign_controller_spec.rb
+++ b/plugins/discourse-assign/spec/requests/assign_controller_spec.rb
@@ -54,29 +54,17 @@ RSpec.describe DiscourseAssign::AssignController do
assignee
end
- it "only includes users in allowed groups and not disallowed groups" do
- Assigner.new(post.topic, admin).assign(allowed_user)
-
- get "/assign/suggestions.json"
- suggestions = JSON.parse(response.body)["suggestions"].map { |u| u["username"] }
-
- expect(suggestions).to contain_exactly(allowed_user.username, admin.username)
- expect(suggestions).to_not include(user_in_non_allowed_group)
+ def suggested_usernames
+ response.parsed_body["suggestions"].map { |user| user["username"] }
end
- it "does include only visible assign_allowed_on_groups" do
- sign_in(non_admin_staff) # Need to use non-admin to test. Admins can see all groups
-
- visible_group = Fabricate(:group, visibility_level: Group.visibility_levels[:members])
- visible_group.add(non_admin_staff)
- invisible_group = Fabricate(:group, visibility_level: Group.visibility_levels[:members])
-
- SiteSetting.assign_allowed_on_groups = "#{visible_group.id}|#{invisible_group.id}"
+ it "only suggests recent assignees who can still be assigned" do
+ Assigner.new(post.topic, admin).assign(allowed_user)
+ Fabricate(:post_assignment, assigned_to: user_in_non_allowed_group, assigned_by_user: admin)
get "/assign/suggestions.json"
- assign_allowed_on_groups = JSON.parse(response.body)["assign_allowed_on_groups"]
- expect(assign_allowed_on_groups).to contain_exactly(visible_group.name)
+ expect(suggested_usernames).to contain_exactly(allowed_user.username, admin.username)
end
it "suggests the current user + the last 5 previously assigned users" do
@@ -84,29 +72,18 @@ RSpec.describe DiscourseAssign::AssignController do
get "/assign/suggestions.json"
- suggestions = response.parsed_body["suggestions"].map { |u| u["username"] }
- expect(suggestions).to contain_exactly(admin.username, *assignees[1..5])
+ expect(suggested_usernames).to contain_exactly(admin.username, *assignees[1..5])
end
- it "doesn't suggest users on holiday" do
+ it "doesn't suggest users on holiday, except the current user" do
user_on_vacation = assign_user_to_post
- user_on_vacation.upsert_custom_fields(
- DiscourseAssign::DiscourseCalendar::HOLIDAY_CUSTOM_FIELD => "t",
- )
-
- get "/assign/suggestions.json"
-
- suggestions = response.parsed_body["suggestions"].map { |u| u["username"] }
- expect(suggestions).to_not include(user_on_vacation.username)
- end
-
- it "suggests the current user even if they're on holiday" do
- admin.upsert_custom_fields(DiscourseAssign::DiscourseCalendar::HOLIDAY_CUSTOM_FIELD => "t")
+ [user_on_vacation, admin].each do |user|
+ user.upsert_custom_fields(DiscourseAssign::DiscourseCalendar::HOLIDAY_CUSTOM_FIELD => "t")
+ end
get "/assign/suggestions.json"
- suggestions = response.parsed_body["suggestions"].map { |u| u["username"] }
- expect(suggestions).to include(admin.username)
+ expect(suggested_usernames).to contain_exactly(admin.username)
end
it "excludes other users from the suggestions when they already reached the max assigns limit" do
@@ -115,30 +92,158 @@ RSpec.describe DiscourseAssign::AssignController do
Fabricate(:post_assignment, assigned_to: another_user, assigned_by_user: admin)
get "/assign/suggestions.json"
- suggestions = JSON.parse(response.body)["suggestions"].map { |u| u["username"] }
- expect(suggestions).to contain_exactly(admin.username)
+ expect(suggested_usernames).to contain_exactly(admin.username)
end
- it "returns target scoped groups when suggestions are requested for a scoped category" do
+ it "suggests the visible groups assignable on the target" do
SiteSetting.assign_allowed_on_groups = ""
- category = Fabricate(:category)
- topic = Fabricate(:post).topic.tap { |topic| topic.update!(category: category) }
+ topic = Fabricate(:topic, category: Fabricate(:category))
scoped_group = Fabricate(:group)
+ hidden_group = Fabricate(:group, visibility_level: Group.visibility_levels[:owners])
scoped_user = Fabricate(:user, groups: [scoped_group])
- allow_group_to_assign_in_category(category, scoped_group)
+ allow_group_to_assign_in_category(topic.category, scoped_group, hidden_group)
sign_in(scoped_user)
get "/assign/suggestions.json", params: { target_id: topic.id, target_type: "Topic" }
- expect(response.status).to eq(200)
- expect(response.parsed_body["assign_allowed_on_groups"]).to contain_exactly(scoped_group.name)
- expect(response.parsed_body["assign_allowed_for_groups"]).to contain_exactly(
+ expect(response.parsed_body["groups"].map { |group| group["name"] }).to contain_exactly(
scoped_group.name,
)
end
end
+ describe "#search" do
+ before_all { SearchIndexer.enable }
+
+ fab!(:team_a) do
+ Fabricate(
+ :group,
+ name: "team_a",
+ members_visibility_level: Group.visibility_levels[:members],
+ assignable_level: Group::ALIAS_LEVELS[:members_mods_and_admins],
+ )
+ end
+ fab!(:team_b) do
+ Fabricate(
+ :group,
+ name: "team_b",
+ members_visibility_level: Group.visibility_levels[:members],
+ assignable_level: Group::ALIAS_LEVELS[:members_mods_and_admins],
+ )
+ end
+ fab!(:assigner) { Fabricate(:user, username: "assigner", groups: [team_a]) }
+ fab!(:target_alice) { Fabricate(:user, username: "target_alice", groups: [team_a]) }
+ fab!(:target_bob) { Fabricate(:user, username: "target_bob", groups: [team_b]) }
+ fab!(:target_carol) { Fabricate(:user, username: "target_carol", groups: [non_allowed_group]) }
+ fab!(:target_admin) { Fabricate(:admin, username: "target_admin") }
+
+ let(:topic) { post.topic }
+
+ before { SiteSetting.assign_allowed_on_groups = "#{team_a.id}|#{team_b.id}" }
+
+ def search(term, target = topic)
+ params = { term: }
+ params.merge!(target_id: target.id, target_type: target.class.name) if target
+ get "/assign/search.json", params:
+ end
+
+ def usernames
+ response.parsed_body["users"].map { |user| user["username"] }
+ end
+
+ def group_names
+ response.parsed_body["groups"].map { |group| group["name"] }
+ end
+
+ it "finds assignable users, even in groups whose members the assigner cannot see" do
+ sign_in(assigner)
+ search("target")
+
+ expect(usernames).to contain_exactly(
+ target_alice.username,
+ target_bob.username,
+ target_admin.username,
+ )
+ end
+
+ it "finds visible groups the assigner can assign on the target" do
+ scoped_group = Fabricate(:group, name: "team_scoped")
+ hidden_group =
+ Fabricate(:group, name: "team_hidden", visibility_level: Group.visibility_levels[:owners])
+ allow_group_to_assign_in_category(topic.category, scoped_group, hidden_group)
+ sign_in(assigner)
+
+ search("team")
+
+ expect(group_names).to contain_exactly(team_a.name, scoped_group.name)
+ end
+
+ it "rejects blank terms and targets the assigner cannot see" do
+ sign_in(assigner)
+
+ search(" ")
+ expect(response.status).to eq(400)
+
+ search("target", Fabricate(:private_message_topic))
+ expect(response.status).to eq(404)
+ end
+
+ context "with only category-scoped groups" do
+ before { SiteSetting.assign_allowed_on_groups = "" }
+
+ it "finds members of groups scoped to the target's category" do
+ scoped_group = Fabricate(:group, members_visibility_level: Group.visibility_levels[:owners])
+ scoped_group.add(target_carol)
+ allow_group_to_assign_in_category(topic.category, scoped_group)
+ sign_in(admin)
+
+ search("target_carol")
+ expect(usernames).to contain_exactly(target_carol.username)
+
+ search("target_carol", post)
+ expect(usernames).to contain_exactly(target_carol.username)
+
+ search("target_carol", Fabricate(:topic, category: Fabricate(:category)))
+ expect(usernames).to be_empty
+ end
+
+ it "finds what the assigner can assign anywhere when there is no target" do
+ own_group = Fabricate(:group)
+ own_group.add(assigner)
+ own_group.add(target_carol)
+ allow_group_to_assign_in_category(Fabricate(:category), own_group)
+ allow_group_to_assign_in_category(Fabricate(:category), team_b)
+
+ sign_in(assigner)
+ search("target", nil)
+ expect(usernames).to contain_exactly(target_carol.username, target_admin.username)
+
+ search("team", nil)
+ expect(group_names).to contain_exactly(team_a.name)
+
+ sign_in(admin)
+ search("target", nil)
+ expect(usernames).to contain_exactly(
+ target_bob.username,
+ target_carol.username,
+ target_admin.username,
+ )
+ end
+
+ it "denies users who cannot assign the target" do
+ scoped_group = Fabricate(:group)
+ scoped_group.add(assigner)
+ allow_group_to_assign_in_category(Fabricate(:category), scoped_group)
+ sign_in(assigner)
+
+ search("target")
+
+ expect(response.status).to eq(403)
+ end
+ end
+ end
+
describe "#unassign" do
include_context "with group that is allowed to assign"
@@ -319,28 +424,19 @@ RSpec.describe DiscourseAssign::AssignController do
expect(post.topic.posts.pluck(:raw)).not_to include(oversized_note)
end
- it "assigns topic with note to a user" do
+ it "assigns topic with a note and a status to a user" do
put "/assign/assign.json",
params: {
target_id: post.topic_id,
target_type: "Topic",
username: allowed_user.username,
note: "do dis pls",
- }
-
- expect(post.topic.reload.assignment.note).to eq("do dis pls")
- end
-
- it "assigns topic with a set status to a user" do
- put "/assign/assign.json",
- params: {
- target_id: post.topic_id,
- target_type: "Topic",
- username: allowed_user.username,
status: "In Progress",
}
- expect(post.topic.reload.assignment.status).to eq("In Progress")
+ assignment = post.topic.reload.assignment
+ expect(assignment.note).to eq("do dis pls")
+ expect(assignment.status).to eq("In Progress")
end
it "assigns topic with default status to a user" do
diff --git a/plugins/discourse-assign/test/javascripts/acceptance/assign-enabled-test.js b/plugins/discourse-assign/test/javascripts/acceptance/assign-enabled-test.js
index a90f66d6fb8..ed25f484e2a 100644
--- a/plugins/discourse-assign/test/javascripts/acceptance/assign-enabled-test.js
+++ b/plugins/discourse-assign/test/javascripts/acceptance/assign-enabled-test.js
@@ -39,8 +39,7 @@ acceptance("Assign mobile", function (needs) {
server.get("/assign/suggestions", () => {
return helper.response({
success: true,
- assign_allowed_groups: false,
- assign_allowed_for_groups: [],
+ groups: [],
suggestions: [
{
id: 19,
@@ -80,8 +79,7 @@ acceptance("Assign desktop", function (needs) {
server.get("/assign/suggestions", () => {
return helper.response({
success: true,
- assign_allowed_groups: false,
- assign_allowed_for_groups: [],
+ groups: [],
suggestions: [
{
id: 19,
@@ -157,8 +155,7 @@ acceptance("Assign Status enabled", function (needs) {
server.get("/assign/suggestions", () => {
return helper.response({
success: true,
- assign_allowed_groups: false,
- assign_allowed_for_groups: [],
+ groups: [],
suggestions: [
{
id: 19,
@@ -218,8 +215,7 @@ acceptance("Assign Status disabled", function (needs) {
server.get("/assign/suggestions", () => {
return helper.response({
success: true,
- assign_allowed_groups: false,
- assign_allowed_for_groups: [],
+ groups: [],
suggestions: [
{
id: 19,
diff --git a/plugins/discourse-assign/test/javascripts/acceptance/edit-assignments-modal-test.js b/plugins/discourse-assign/test/javascripts/acceptance/edit-assignments-modal-test.js
index 6731b854b9f..e47a22667e5 100644
--- a/plugins/discourse-assign/test/javascripts/acceptance/edit-assignments-modal-test.js
+++ b/plugins/discourse-assign/test/javascripts/acceptance/edit-assignments-modal-test.js
@@ -30,15 +30,10 @@ acceptance("Edit assignments modal", function (needs) {
];
server.get("/assign/suggestions", () =>
helper.response({
- assign_allowed_for_groups: [],
+ groups: [],
suggestions,
})
);
- server.get("/u/search/users", () =>
- helper.response({
- users: suggestions,
- })
- );
});
test("reassigning topic", async function (assert) {
diff --git a/plugins/discourse-assign/test/javascripts/acceptance/post-popup-menu-test.js b/plugins/discourse-assign/test/javascripts/acceptance/post-popup-menu-test.js
index 961a2988e51..3368d57bdae 100644
--- a/plugins/discourse-assign/test/javascripts/acceptance/post-popup-menu-test.js
+++ b/plugins/discourse-assign/test/javascripts/acceptance/post-popup-menu-test.js
@@ -45,13 +45,16 @@ acceptance("Post popup menu", function (needs) {
server.get("/assign/suggestions", () =>
helper.response({
- assign_allowed_for_groups: [],
+ groups: [],
suggestions: [{ username: new_assignee_username }],
})
);
- server.get("/u/search/users", () =>
- helper.response({ users: [{ username: new_assignee_username }] })
+ server.get("/assign/search", () =>
+ helper.response({
+ users: [{ username: new_assignee_username }],
+ groups: [],
+ })
);
});
diff --git a/plugins/discourse-assign/test/javascripts/integration/components/assign-user-form-test.gjs b/plugins/discourse-assign/test/javascripts/integration/components/assign-user-form-test.gjs
index 8f1fab2d2d9..80862a2216d 100644
--- a/plugins/discourse-assign/test/javascripts/integration/components/assign-user-form-test.gjs
+++ b/plugins/discourse-assign/test/javascripts/integration/components/assign-user-form-test.gjs
@@ -3,6 +3,7 @@ import { focus, render, triggerKeyEvent } from "@ember/test-helpers";
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
import { i18n } from "discourse-i18n";
import AssignUserForm from "discourse/plugins/discourse-assign/discourse/components/assign-user-form";
@@ -13,12 +14,50 @@ module("Integration | Component | AssignUserForm", function (hooks) {
pretender.get("/assign/suggestions", () =>
response({
suggestions: [],
- assign_allowed_on_groups: [],
- assign_allowed_for_groups: [],
+ groups: [],
})
);
});
+ test("searches assignees for the target and assigns groups as groups", async function (assert) {
+ let params;
+ pretender.get("/assign/search", (request) => {
+ params = request.queryParams;
+ return response({
+ users: [{ username: "searched_user" }],
+ groups: [{ name: "searched_team" }],
+ });
+ });
+ const model = trackedObject({ targetId: 42, targetType: "Post" });
+ const formApi = {};
+ const onSubmit = () => {};
+ const assigneeChooser = selectKit("#assignee-chooser");
+
+ await render(
+ <template>
+ <AssignUserForm
+ @formApi={{formApi}}
+ @model={{model}}
+ @onSubmit={{onSubmit}}
+ />
+ </template>
+ );
+ await assigneeChooser.fillInFilter("searched");
+
+ assert.strictEqual(params.term, "searched");
+ assert.strictEqual(params.target_id, "42");
+ assert.strictEqual(params.target_type, "Post");
+ assert.deepEqual(
+ assigneeChooser.displayedContent().map((row) => row.id),
+ ["searched_user", "searched_team"]
+ );
+
+ await assigneeChooser.selectRowByValue("searched_team");
+
+ assert.strictEqual(model.group_name, "searched_team");
+ assert.strictEqual(model.username, null);
+ });
+
for (const modifier of ["metaKey", "ctrlKey"]) {
test(`${modifier}+Enter submits from the assignee picker and note`, async function (assert) {
const model = trackedObject({
diff --git a/plugins/discourse-assign/test/javascripts/integration/components/assignment-chooser-test.gjs b/plugins/discourse-assign/test/javascripts/integration/components/assignment-chooser-test.gjs
deleted file mode 100644
index 652778c264d..00000000000
--- a/plugins/discourse-assign/test/javascripts/integration/components/assignment-chooser-test.gjs
+++ /dev/null
@@ -1,78 +0,0 @@
-import { hash } from "@ember/helper";
-import { render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import pretender, { response } from "discourse/tests/helpers/create-pretender";
-import selectKit from "discourse/tests/helpers/select-kit-helper";
-import AssignmentChooser from "discourse/plugins/discourse-assign/discourse/components/assignment-chooser";
-
-module("Integration | Component | AssignmentChooser", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.set("assignmentGroups", ["category_team", "staff"]);
- this.set("assignee", null);
- this.set("onChange", () => {});
- this.set("subject", selectKit(".email-group-user-chooser"));
- });
-
- test("includes assignment groups missing from user search", async function (assert) {
- pretender.get("/u/search/users", () =>
- response({
- users: [{ username: "category_user" }],
- groups: [],
- })
- );
-
- await render(
- <template>
- <AssignmentChooser
- @onChange={{this.onChange}}
- @options={{hash
- includeGroups=true
- assignmentGroups=this.assignmentGroups
- customSearchOptions=(hash assignableGroups=true)
- }}
- @value={{this.assignee}}
- />
- </template>
- );
-
- await this.subject.expand();
- await this.subject.fillInFilter("category");
-
- assert
- .dom(".email-group-user-chooser-row[data-value='category_team']")
- .exists("the category-scoped group is included");
- });
-
- test("does not duplicate groups returned by user search", async function (assert) {
- pretender.get("/u/search/users", () =>
- response({
- users: [],
- groups: [{ name: "staff", full_name: "Staff" }],
- })
- );
-
- await render(
- <template>
- <AssignmentChooser
- @onChange={{this.onChange}}
- @options={{hash
- includeGroups=true
- assignmentGroups=this.assignmentGroups
- customSearchOptions=(hash assignableGroups=true)
- }}
- @value={{this.assignee}}
- />
- </template>
- );
-
- await this.subject.expand();
- await this.subject.fillInFilter("staff");
-
- assert
- .dom(".email-group-user-chooser-row[data-value='staff']")
- .exists({ count: 1 }, "the group appears once");
- });
-});
diff --git a/plugins/discourse-assign/test/javascripts/integration/components/bulk-assign-user-test.gjs b/plugins/discourse-assign/test/javascripts/integration/components/bulk-assign-user-test.gjs
index 3715ec02108..0f9aeb60cd0 100644
--- a/plugins/discourse-assign/test/javascripts/integration/components/bulk-assign-user-test.gjs
+++ b/plugins/discourse-assign/test/javascripts/integration/components/bulk-assign-user-test.gjs
@@ -12,8 +12,7 @@ module("Integration | Component | BulkActionsAssignUser", function (hooks) {
pretender.get("/assign/suggestions", () =>
response({
suggestions: [],
- assign_allowed_on_groups: [],
- assign_allowed_for_groups: [],
+ groups: [],
})
);
});