Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

frontend side state management

ulferts7356242d9b08
diff --git a/app/components/filters_component.html.erb b/app/components/filters_component.html.erb
index e0a8b738dfc..0fab3fba3f1 100644
--- a/app/components/filters_component.html.erb
+++ b/app/components/filters_component.html.erb
@@ -1,13 +1,13 @@
<div data-controller="filters"
data-application-target="dynamic"
data-filters-display-filters-value="<%= show_filters_section? %>">
-
+
<div class="op-filters-header">
- <%= render(Primer::Beta::Button.new(
+ <%= render(Primer::Beta::Button.new(
scheme: :secondary,
data: { 'filters-target': 'filterFormToggle',
'action': 'filters#toggleDisplayFilters',
- 'test-selector': 'project-filter-toggle' })) do %>
+ 'test-selector': 'filter-component-toggle' })) do %>
<%= t(:label_filter) %>
<%= render(Primer::Beta::Counter.new(count: filters_count, round: true, hide_if_zero: false, scheme: :default)) %>
<% end %>
@@ -31,8 +31,7 @@
data-action="filters#toggleDisplayFilters"></a>
<legend><%= t(:label_filter_plural) %></legend>
<ul class="advanced-filters--filters">
- <% allowed_filters.each do |filter| %>
- <% filter_active = query.find_active_filter(filter.name).present? %>
+ <% each_filter do |filter, filter_active| %>
<% filter_boolean = filter.is_a?(Queries::Filters::Shared::BooleanFilter) %>
<li class="advanced-filters--filter <%= filter_active ? '' : 'hidden' %>"
@@ -139,4 +138,4 @@
<% end %>
</fieldset>
<% end %>
-</div>
\ No newline at end of file
+</div>
diff --git a/app/components/filters_component.rb b/app/components/filters_component.rb
index c08ff7b4948..6080476d2e8 100644
--- a/app/components/filters_component.rb
+++ b/app/components/filters_component.rb
@@ -40,12 +40,23 @@ class FiltersComponent < ApplicationComponent
params[:filters].present? && !params.key?(:hide_filters_section)
end
+ # Returns filters, active and inactive.
+ # In case a filter is active, the active one will be preferred over the inactive one.
+ def each_filter
+ allowed_filters.map do |filter|
+ active_filter = query.find_active_filter(filter.name)
+ filter_active = active_filter.present?
+
+ yield(filter_active ? active_filter : filter, filter_active)
+ end
+ end
+
def allowed_filters
- query
- .available_filters
+ query
+ .available_filters
end
def filters_count
query.filters.count
- end
+ end
end
diff --git a/app/components/projects/index_page_header_component.html.erb b/app/components/projects/index_page_header_component.html.erb
index 9278353225f..808f0e9fff3 100644
--- a/app/components/projects/index_page_header_component.html.erb
+++ b/app/components/projects/index_page_header_component.html.erb
@@ -43,7 +43,14 @@
if current_user.logged?
menu.with_item(
label: t('button_save'),
- href: new_projects_query_path(filters: params[:filters])
+ href: new_projects_query_path,
+ content_arguments: {
+ data: {
+ controller: "params-from-query",
+ 'application-target': "dynamic",
+ 'params-from-query-allowed-value': '["filters"]'
+ }
+ }
) do |item|
item.with_leading_visual_icon(icon: :'op-save')
end
@@ -94,13 +101,18 @@
end
end %>
<% else %>
- <% header.with_title(mt: 2, mb: 2, data: { 'test-selector': 'project-query-name'}) do
- primer_form_with(model: query,
- url: projects_queries_path,
- scope: '',
- id: 'project-save-form') do |f|
- render(Queries::Projects::Create.new(f, params:))
- end
- end %>
+ <% header.with_title(mt: 2, mb: 2, data: { 'test-selector': 'project-query-name'}) do
+ primer_form_with(model: query,
+ url: projects_queries_path,
+ scope: 'query',
+ data: {
+ controller: "params-from-query",
+ 'application-target': "dynamic",
+ 'params-from-query-allowed-value': '["filters"]'
+ },
+ id: 'project-save-form') do |f|
+ render(Queries::Projects::Create.new(f))
+ end
+ end %>
<% end %>
<% end %>
diff --git a/app/components/projects/table_component.html.erb b/app/components/projects/table_component.html.erb
index 32c50810249..75faa0f8ef8 100644
--- a/app/components/projects/table_component.html.erb
+++ b/app/components/projects/table_component.html.erb
@@ -53,14 +53,22 @@ See COPYRIGHT and LICENSE files for more details.
</div>
</th>
<% elsif sortable_column?(name) %>
- <%= build_sort_header name, options %>
+ <%= build_sort_header name,
+ options.merge(data:
+ {
+ controller: "params-from-query",
+ 'application-target': "dynamic",
+ 'params-from-query-allowed-value': '["query_id"]',
+ 'params-from-query-all-anchors-value': "true"
+ }
+ ) %>
<% else %>
<th>
<div class="generic-table--sort-header-outer">
<div class="generic-table--sort-header">
- <span>
- <%= options[:caption] %>
- </span>
+ <span>
+ <%= options[:caption] %>
+ </span>
</div>
</div>
</th>
@@ -68,11 +76,15 @@ See COPYRIGHT and LICENSE files for more details.
<% end %>
<th class="-right">
<div class="generic-table--header-outer">
- <div class="generic-table--header">
+ <div class="generic-table--header"
+ data-controller="params-from-query"
+ data-application-target="dynamic"
+ data-params-from-query-all-anchors-value="true"
+ data-params-from-query-allowed-value='["query_id", "per_page", "page", "sortBy", "filters"]'>
<% if params[:expand] == 'all' %>
- <%= link_to t(:button_collapse_all), { params: helpers.safe_query_params(%w{filters page per_page sortBy}).except(:expand) } %>
+ <%= link_to t(:button_collapse_all) %>
<% else %>
- <%= link_to t(:button_expand_all), { params: helpers.safe_query_params(%w{filters page per_page sortBy}).merge(expand: 'all') } %>
+ <%= link_to t(:button_expand_all), { params: { expand: 'all' } } %>
<% end %>
</div>
</div>
@@ -96,6 +108,11 @@ See COPYRIGHT and LICENSE files for more details.
</div>
</div>
<% if paginated? %>
- <%= helpers.pagination_links_full model %>
+ <div data-controller="params-from-query"
+ data-application-target="dynamic"
+ data-params-from-query-all-anchors-value="true"
+ data-params-from-query-allowed-value='["query_id"]'>
+ <%= helpers.pagination_links_full model, { blocked_url_params: [:query_id] } %>
+ </div>
<% end %>
</div>
diff --git a/app/controllers/projects/queries_controller.rb b/app/controllers/projects/queries_controller.rb
index 6724d87bea2..68a1b9d2840 100644
--- a/app/controllers/projects/queries_controller.rb
+++ b/app/controllers/projects/queries_controller.rb
@@ -33,18 +33,22 @@ class Projects::QueriesController < ApplicationController
before_action :require_login
before_action :find_query, only: :destroy
+ current_menu_item [:new, :create] do
+ :projects
+ end
+
def new
- query = load_query
- query.name = params[:name]
+ call = load_query(existing: false)
+
render template: '/projects/index',
layout: 'global',
- locals: { query:, state: :edit }
+ locals: { query: call.result, state: :edit }
end
def create
call = Queries::Projects::ProjectQueries::CreateService
.new(user: current_user)
- .call(load_query.attributes.merge(name: params[:name]))
+ .call(permitted_query_params)
if call.success?
redirect_to projects_path(query_id: call.result.id)
diff --git a/app/controllers/projects/query_loading.rb b/app/controllers/projects/query_loading.rb
index bfdc90c081c..b5555985b02 100644
--- a/app/controllers/projects/query_loading.rb
+++ b/app/controllers/projects/query_loading.rb
@@ -27,10 +27,35 @@
# ++
module Projects
module QueryLoading
- def load_query
- params[:query_id] ||= 'all'
+ def load_query(existing: true, contract: EmptyContract)
+ query = if existing
+ Queries::Projects::Factory.find(params[:query_id])
+ else
+ Queries::Projects::ProjectQuery.new
+ end
- ParamsToQueryService.new(Project, current_user).call(params)
+ Queries::Projects::ProjectQueries::SetAttributesService
+ .new(user: current_user,
+ model: query,
+ contract_class: contract)
+ .call(permitted_query_params)
+ end
+
+ private
+
+ def permitted_query_params
+ query_params = if params[:query]
+ params
+ .require(:query)
+ .permit(:name)
+ .to_h
+ else
+ {}
+ end
+
+ query_params.merge!(Queries::ParamsParser.parse(params))
+
+ query_params.with_indifferent_access
end
end
end
diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb
index 9130bba8c98..815dad66dac 100644
--- a/app/controllers/projects_controller.rb
+++ b/app/controllers/projects_controller.rb
@@ -48,13 +48,13 @@ class ProjectsController < ApplicationController
end
def index
- query = load_query
+ call = load_query(contract: Queries::Projects::ProjectQueries::CreateContract)
respond_to do |format|
format.html do
- flash.now[:error] = query.errors.full_messages unless query.valid?
+ flash.now[:error] = call.errors.full_messages unless call.success?
- render layout: 'global', locals: { query:, state: :show }
+ render layout: 'global', locals: { query: call.result, state: :show }
end
format.any(*supported_export_formats) do
diff --git a/app/controllers/queries/params_parser.rb b/app/controllers/queries/params_parser.rb
new file mode 100644
index 00000000000..f59b8a2fa27
--- /dev/null
+++ b/app/controllers/queries/params_parser.rb
@@ -0,0 +1,81 @@
+# -- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2010-2024 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+# ++
+module Queries
+ class ParamsParser
+ class << self
+ def parse(params)
+ query_params = {}
+
+ query_params[:filters] = parse_filters_from_params(params) if params[:filters].present?
+ query_params[:orders] = parse_orders_from_params(params) if params[:sortBy].present?
+
+ query_params
+ end
+
+ private
+
+ def parse_filters_from_params(params)
+ filters = params[:filters].split(/(?<!\\)&/)
+
+ filters.map do |filter|
+ filter_parts = filter.split
+
+ {
+ attribute: filter_parts[0],
+ operator: filter_parts[1],
+ values: parse_filter_value(filter_parts[2..].join(' '))
+ }
+ end
+ end
+
+ def parse_filter_value(values)
+ if values.start_with?("[") && values.end_with?("]")
+ values[1..-2].scan(/['"](.*?)['"]/).flatten.map { |v| escape_filter_value(v) }
+ else
+ [escape_filter_value(values.gsub('\&', '&'))]
+ end
+ end
+
+ def escape_filter_value(value)
+ if value.start_with?('"') && value.end_with?('"')
+ value[1..-2].gsub('\&', '&').gsub('\"', '"')
+ else
+ value.gsub('\&', '&')
+ end
+ end
+
+ def parse_orders_from_params(params)
+ JSON.parse(params[:sortBy])
+ .to_h
+ .map { |k, v| { attribute: k, direction: v } }
+ rescue JSON::ParserError
+ [{ attribute: 'invalid', direction: 'asc' }]
+ end
+ end
+ end
+end
diff --git a/app/forms/queries/projects/create.rb b/app/forms/queries/projects/create.rb
index 6a01b1f9b15..c53f999538f 100644
--- a/app/forms/queries/projects/create.rb
+++ b/app/forms/queries/projects/create.rb
@@ -29,22 +29,8 @@
class Queries::Projects::Create < ApplicationForm
include OpenProject::StaticRouting::UrlHelpers
- attr_accessor :params
-
- def initialize(params:, **options)
- super(**options)
-
- self.params = params
- end
-
form do |query_form|
query_form.group(layout: :horizontal) do |group|
- # TODO: rather then relying on the params, serialize the query filters
- group.hidden(
- name: :filters,
- value: params[:filters]
- )
-
group.text_field(
visually_hide_label: true,
required: true,
@@ -65,8 +51,8 @@ class Queries::Projects::Create < ApplicationForm
scheme: :secondary,
label: I18n.t(:button_cancel),
tag: :a,
- # TODO: rather then relying on the params, serialize the query filters
- href: OpenProject::StaticRouting::StaticUrlHelpers.new.projects_path(filters: params[:filters])
+ data: { 'params-from-query-target': 'anchor' },
+ href: OpenProject::StaticRouting::StaticUrlHelpers.new.projects_path
)
end
end
diff --git a/app/helpers/pagination_helper.rb b/app/helpers/pagination_helper.rb
index 72d4cb25160..72389977c07 100644
--- a/app/helpers/pagination_helper.rb
+++ b/app/helpers/pagination_helper.rb
@@ -166,6 +166,11 @@ module PaginationHelper
protected
+ def merge_get_params(url_params)
+ params = super
+ params.except(*blocked_url_params)
+ end
+
def page_number(page)
if page == current_page
tag(:li, page, class: 'op-pagination--item op-pagination--item_current')
@@ -197,6 +202,10 @@ module PaginationHelper
''
end
end
+
+ def blocked_url_params
+ @options[:blocked_url_params] || [] # rubocop:disable Rails/HelperInstanceVariable
+ end
end
private
diff --git a/app/helpers/sort_helper.rb b/app/helpers/sort_helper.rb
index e9ade0c7d7e..53040871852 100644
--- a/app/helpers/sort_helper.rb
+++ b/app/helpers/sort_helper.rb
@@ -284,7 +284,7 @@ module SortHelper
sort_options = { sort_key => sort_param }
# Don't lose other params.
- link_to_content_update(h(caption), safe_query_params(%w{filters page per_page expand}).merge(sort_options), html_options)
+ link_to_content_update(h(caption), safe_query_params(%w{filters per_page expand}).merge(sort_options), html_options)
end
# Returns a table header <th> tag with a sort link for the named column
diff --git a/app/models/queries/base_query.rb b/app/models/queries/base_query.rb
index 1efd55914a1..bc2d1befa9f 100644
--- a/app/models/queries/base_query.rb
+++ b/app/models/queries/base_query.rb
@@ -85,7 +85,7 @@ module Queries::BaseQuery
def order(hash)
hash.each do |attribute, direction|
order = order_for(attribute)
- order.direction = direction
+ order.direction = direction.to_sym
orders << order
end
diff --git a/app/models/queries/projects/factory.rb b/app/models/queries/projects/factory.rb
index 790e927099d..08820f3df55 100644
--- a/app/models/queries/projects/factory.rb
+++ b/app/models/queries/projects/factory.rb
@@ -46,6 +46,8 @@ class Queries::Projects::Factory
static_query_status_off_track
when 'at_risk'
static_query_status_at_risk
+ when nil
+ list_with(:'projects.lists.all')
end
end
@@ -89,9 +91,7 @@ class Queries::Projects::Factory
def list_with(name)
Queries::Projects::ProjectQuery.new(name: I18n.t(name)) do |query|
- yield query
-
- query.order(lft: :asc)
+ yield query if block_given?
end
end
end
diff --git a/app/models/queries/serialization/filters.rb b/app/models/queries/serialization/filters.rb
index 1d54edbd68b..368da55df61 100644
--- a/app/models/queries/serialization/filters.rb
+++ b/app/models/queries/serialization/filters.rb
@@ -34,7 +34,7 @@ class Queries::Serialization::Filters
return [] if serialized_filter_hash.nil?
serialized_filter_hash.map do |serialized_filter|
- filter = filter_for(serialized_filter['field'], no_memoization: true)
+ filter = filter_for(serialized_filter['attribute'], no_memoization: true)
filter.operator = serialized_filter['operator']
filter.values = serialized_filter['values']
@@ -43,9 +43,13 @@ class Queries::Serialization::Filters
end
def dump(filters)
+ self.class.dump(filters)
+ end
+
+ def self.dump(filters)
(filters || []).map do |filter|
{
- field: filter.field,
+ attribute: filter.field,
operator: filter.operator,
values: filter.values
}
diff --git a/app/services/queries/projects/project_queries/set_attributes_service.rb b/app/services/queries/projects/project_queries/set_attributes_service.rb
index b9f675a4766..61ff8d420a5 100644
--- a/app/services/queries/projects/project_queries/set_attributes_service.rb
+++ b/app/services/queries/projects/project_queries/set_attributes_service.rb
@@ -27,8 +27,19 @@
# ++
class Queries::Projects::ProjectQueries::SetAttributesService < BaseServices::SetAttributes
+ private
+
+ def set_attributes(params)
+ set_filters(params.delete(:filters))
+ set_order(params.delete(:orders))
+
+ super
+ end
+
def set_default_attributes(_params)
set_default_user
+ set_default_filter
+ set_default_order
end
def set_default_user
@@ -36,4 +47,30 @@ class Queries::Projects::ProjectQueries::SetAttributesService < BaseServices::Se
model.user = user
end
end
+
+ def set_default_order
+ return if model.orders.any?
+
+ model.order(lft: :asc)
+ end
+
+ def set_default_filter
+ return if model.filters.any?
+
+ model.where('active', '=', OpenProject::Database::DB_VALUE_TRUE)
+ end
+
+ def set_filters(filters)
+ return unless filters
+
+ filters.each do |filter|
+ model.where(filter[:attribute], filter[:operator], filter[:values])
+ end
+ end
+
+ def set_order(orders)
+ return unless orders
+
+ model.order(orders.to_h { |o| [o[:attribute], o[:direction]] })
+ end
end
diff --git a/frontend/src/stimulus/controllers/dynamic/filters.controller.ts b/frontend/src/stimulus/controllers/dynamic/filters.controller.ts
index 452602388a7..701e9569f91 100644
--- a/frontend/src/stimulus/controllers/dynamic/filters.controller.ts
+++ b/frontend/src/stimulus/controllers/dynamic/filters.controller.ts
@@ -31,13 +31,6 @@
import { Controller } from '@hotwired/stimulus';
-interface Filter {
- [key:string]:{
- operator:string;
- values:string[];
- };
-}
-
export default class FiltersController extends Controller {
static targets = [
'filterFormToggle',
@@ -196,7 +189,7 @@ export default class FiltersController extends Controller {
const filters = this.parseFilters();
const orderParam = this.getUrlParameter('sortBy');
- let queryString = `?filters=${encodeURIComponent(JSON.stringify(filters))}`;
+ let queryString = `?filters=${encodeURIComponent(filters.join('&'))}`;
if (orderParam) {
queryString = `${queryString}&sortBy=${encodeURIComponent(orderParam)}`;
}
@@ -206,7 +199,7 @@ export default class FiltersController extends Controller {
private parseFilters() {
const advancedFilters = this.filterTargets.filter((filter) => !filter.classList.contains('hidden'));
- const filters:Filter[] = [];
+ const filters:string[] = [];
advancedFilters.forEach((filter) => {
const filterName = filter.getAttribute('filter-name');
@@ -214,13 +207,12 @@ export default class FiltersController extends Controller {
const parsedOperator = this.operatorTargets.find((operator) => operator.getAttribute('data-filter-name') === filterName)?.value;
if (filterName && filterType && parsedOperator) {
- const parsedValue = this.parseFilterValue(filterName, filterType, parsedOperator);
+ const parsedValue = this.parseFilterValue(filterName, filterType, parsedOperator) as string[]|null;
if (parsedValue) {
- const currentFilter:Filter = {
- [filterName]: { operator: parsedOperator, values: parsedValue as string[] },
- };
- filters.push(currentFilter);
+ const valuesString = parsedValue.length > 1 ? `[${parsedValue.map((v) => `"${this.replaceAmpersand(v)}"`).join(',')}]` : this.replaceAmpersand(parsedValue[0]);
+
+ filters.push(`${filterName} ${parsedOperator} ${valuesString}`);
}
}
});
@@ -228,6 +220,10 @@ export default class FiltersController extends Controller {
return filters;
}
+ private replaceAmpersand(value:string) {
+ return value && value.length > 0 ? value.replace(/&/g, '\\&') : '';
+ }
+
private readonly operatorsWithoutValues = ['*', '!*', 't', 'w'];
private readonly selectFilterTypes = ['list', 'list_all', 'list_optional'];
private readonly dateFilterTypes = ['datetime_past', 'date'];
diff --git a/frontend/src/stimulus/controllers/dynamic/params-from-query.controller.ts b/frontend/src/stimulus/controllers/dynamic/params-from-query.controller.ts
new file mode 100644
index 00000000000..0c5598de69f
--- /dev/null
+++ b/frontend/src/stimulus/controllers/dynamic/params-from-query.controller.ts
@@ -0,0 +1,110 @@
+/*
+ * -- copyright
+ * OpenProject is an open source project management software.
+ * Copyright (C) 2010-2024 the OpenProject GmbH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License version 3.
+ *
+ * OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+ * Copyright (C) 2006-2013 Jean-Philippe Lang
+ * Copyright (C) 2010-2013 the ChiliProject Team
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * See COPYRIGHT and LICENSE files for more details.
+ * ++
+ */
+
+import { Controller } from '@hotwired/stimulus';
+
+export default class ParamsFromQueryController extends Controller {
+ static targets = [
+ 'anchor',
+ 'form',
+ ];
+
+ declare readonly hasFormTarget:boolean;
+ declare readonly hasAnchorTarget:boolean;
+
+ static values = {
+ allAnchors: Boolean,
+ allowed: Array,
+ };
+
+ declare allAnchorsValue:boolean;
+ declare allowedValue:string[];
+
+ initialize() {
+ if (this.allAnchorsValue) {
+ this.element.querySelectorAll('a').forEach((target) => {
+ this.appendParamsToHref(target);
+ });
+ }
+ }
+
+ connect() {
+ if (this.element.tagName === 'FORM' && !this.hasFormTarget) {
+ this.addFieldsToForm(this.element as HTMLFormElement);
+ } else if (this.element.tagName === 'A' && !this.hasAnchorTarget) {
+ this.appendParamsToHref(this.element as HTMLAnchorElement);
+ }
+ }
+
+ anchorTargetConnected(target:HTMLAnchorElement) {
+ this.appendParamsToHref(target);
+ }
+
+ formTargetConnected(target:HTMLFormElement) {
+ this.addFieldsToForm(target);
+ }
+
+ appendParamsToHref(target:HTMLAnchorElement) {
+ const currentHref = target.getAttribute('href') || '';
+ const currentHrefParams = new URLSearchParams(currentHref.split('?')[1] || '');
+
+ this.forEachMatchingUrlParam((key, value) => {
+ currentHrefParams.append(key, value);
+ });
+
+ target.setAttribute('href', `${currentHref.split('?')[0]}?${currentHrefParams.toString()}`);
+ }
+
+ addFieldsToForm(form:HTMLFormElement) {
+ this.forEachMatchingUrlParam((key, value) => {
+ const filterElement = document.createElement('input');
+ filterElement.type = 'hidden';
+ filterElement.name = key;
+ filterElement.value = value;
+
+ form.appendChild(filterElement);
+ });
+
+ return true;
+ }
+
+ private forEachMatchingUrlParam(callback:(key:string, value:string) => void) {
+ const paramsString = window.location.search.substring(1);
+ const searchParams = new URLSearchParams(paramsString);
+
+ searchParams.forEach((value, key) => {
+ this.allowedValue.forEach((allowedKey) => {
+ if (key.startsWith(allowedKey)) {
+ callback(key, value);
+ }
+ });
+ });
+ }
+}
diff --git a/lib/open_project/safe_params.rb b/lib/open_project/safe_params.rb
index 85315f96160..c572dd4f274 100644
--- a/lib/open_project/safe_params.rb
+++ b/lib/open_project/safe_params.rb
@@ -31,9 +31,5 @@ module OpenProject
def safe_query_params(whitelist = [], current_request = request)
current_request.query_parameters.select { |k, _| whitelist.include?(k) }
end
-
- def pagination_params_whitelist(current_request = request)
- safe_query_params(%w(per_page page), current_request)
- end
end
end
diff --git a/spec/controllers/queries/params_parser_spec.rb b/spec/controllers/queries/params_parser_spec.rb
new file mode 100644
index 00000000000..cab1819b38b
--- /dev/null
+++ b/spec/controllers/queries/params_parser_spec.rb
@@ -0,0 +1,165 @@
+# frozen_string_literal: true
+
+# -- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2010-2024 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+# ++
+
+require 'spec_helper'
+
+RSpec.describe Queries::ParamsParser, type: :model do
+ let(:params) do
+ {}
+ end
+
+ subject { described_class.parse(params.with_indifferent_access) }
+
+ describe '.parse' do
+ context 'without any params' do
+ it 'returns an empty array' do
+ expect(subject)
+ .to be_empty
+ end
+ end
+
+ context 'with a single filter with a single value' do
+ let(:params) do
+ {
+ filters: "active = t"
+ }
+ end
+
+ it 'returns the parsed filter' do
+ expect(subject[:filters])
+ .to contain_exactly({ attribute: 'active', operator: '=', values: ['t'] })
+ end
+ end
+
+ context 'with a single filter with multiple values having single quotes' do
+ let(:params) do
+ {
+ filters: "active = ['t', 'f']"
+ }
+ end
+
+ it 'returns the parsed filter' do
+ expect(subject[:filters])
+ .to contain_exactly({ attribute: 'active', operator: '=', values: %w[t f] })
+ end
+ end
+
+ context 'with a single filter with multiple values having double quotes' do
+ let(:params) do
+ {
+ filters: "active = [\"t\", \"f\"]"
+ }
+ end
+
+ it 'returns the parsed filter' do
+ expect(subject[:filters])
+ .to contain_exactly({ attribute: 'active', operator: '=', values: %w[t f] })
+ end
+ end
+
+ context 'with a single filter with a single value with , and & (escaped)' do
+ let(:params) do
+ {
+ filters: 'active = something, or another thing \& something else'
+ }
+ end
+
+ it 'returns the parsed filter' do
+ expect(subject[:filters])
+ .to contain_exactly({ attribute: 'active', operator: '=', values: ["something, or another thing & something else"] })
+ end
+ end
+
+ context 'with a single filter with a single value with " (escaped)' do
+ let(:params) do
+ {
+ filters: 'active = "something, or another thing \" something else"'
+ }
+ end
+
+ it 'returns the parsed filter' do
+ expect(subject[:filters])
+ .to contain_exactly({ attribute: 'active', operator: '=', values: ["something, or another thing \" something else"] })
+ end
+ end
+
+ context 'with a single filter with a no value' do
+ let(:params) do
+ {
+ filters: 'cf_512 !* '
+ }
+ end
+
+ it 'returns the parsed filter' do
+ expect(subject[:filters])
+ .to contain_exactly({ attribute: 'cf_512', operator: '!*', values: [""] })
+ end
+ end
+
+ context 'with sortBy with a single value' do
+ let(:params) do
+ {
+ sortBy: JSON.dump([%w[name asc]])
+ }
+ end
+
+ it 'returns the parsed filter' do
+ expect(subject[:orders])
+ .to eql [{ attribute: 'name', direction: 'asc' }]
+ end
+ end
+
+ context 'with sortBy with a multiple value' do
+ let(:params) do
+ {
+ sortBy: JSON.dump([%w[name asc], %w[created_at desc]])
+ }
+ end
+
+ it 'returns the parsed filter' do
+ expect(subject[:orders])
+ .to eql [{ attribute: 'name', direction: 'asc' }, { attribute: 'created_at', direction: 'desc' }]
+ end
+ end
+
+ context 'with an invalid sortBy' do
+ let(:params) do
+ {
+ sortBy: "[sjfkdsjfkd}"
+ }
+ end
+
+ it 'returns an invalid sort order' do
+ expect(subject[:orders])
+ .to eql [{ attribute: 'invalid', direction: 'asc' }]
+ end
+ end
+ end
+end
diff --git a/spec/features/projects/projects_index_spec.rb b/spec/features/projects/projects_index_spec.rb
index e7d810c717e..8bfeeb240cb 100644
--- a/spec/features/projects/projects_index_spec.rb
+++ b/spec/features/projects/projects_index_spec.rb
@@ -305,18 +305,21 @@ RSpec.describe 'Projects index page',
projects_page.expect_projects_listed(public_project)
projects_page.expect_projects_not_listed(project, # Filtered out
development_project) # Present on page 1
- expect(page).to have_no_text('Next') # Filters kept active, so there is no third page.
+ projects_page.expect_total_pages(2) # Filters kept active, so there is no third page.
# Sorts DESC by name
click_on 'Ascending sorted by "Name"'
wait_for_reload
- # On page 2 the same filters should still be intact but the order should be DESC on name
- projects_page.expect_projects_listed(development_project)
+ # Clicking on sorting resets the page to the first one
+ projects_page.expect_current_page_number(1)
+
+ # The same filters should still be intact but the order should be DESC on name
+ projects_page.expect_projects_listed(public_project)
projects_page.expect_projects_not_listed(project, # Filtered out
- public_project) # Present on page 1
+ development_project) # Present on page 2
- expect(page).to have_no_text('Next') # Filters kept active, so there is no third page.
+ projects_page.expect_total_pages(2) # Filters kept active, so there is no third page.
expect(page).to have_css('.sort.desc', text: 'NAME')
# Sending the filter form again what implies to compose the request freshly
@@ -328,7 +331,7 @@ RSpec.describe 'Projects index page',
projects_page.expect_projects_listed(public_project)
projects_page.expect_projects_not_listed(development_project, # as it is on the second page
project) # as it filtered out
- expect(page).to have_text('Next') # as the result set is larger than 1
+ projects_page.expect_total_pages(2) # as the result set is larger than 1
expect(page).to have_css('.sort.desc', text: 'NAME')
end
end
diff --git a/spec/services/queries/projects/project_queries/set_attributes_service_spec.rb b/spec/services/queries/projects/project_queries/set_attributes_service_spec.rb
index 226465c502a..25806d3c868 100644
--- a/spec/services/queries/projects/project_queries/set_attributes_service_spec.rb
+++ b/spec/services/queries/projects/project_queries/set_attributes_service_spec.rb
@@ -80,15 +80,83 @@ RSpec.describe Queries::Projects::ProjectQueries::SetAttributesService, type: :m
context 'with params' do
let(:params) do
{
- name: 'Foobar'
+ name: 'Foobar',
+ filters: [
+ {
+ attribute: 'id',
+ operator: '=',
+ values: %w[1 2 3]
+ },
+ {
+ attribute: 'active',
+ operator: '!',
+ values: ['t']
+ }
+ ],
+ orders: [
+ {
+ attribute: 'id',
+ direction: 'asc'
+ },
+ {
+ attribute: 'name',
+ direction: 'desc'
+ }
+ ]
}
end
- it 'assigns the params' do
+ it 'assigns the name param' do
subject
expect(model_instance.name).to eq 'Foobar'
end
+
+ it 'assigns the filter param' do
+ subject
+
+ expect(model_instance.filters)
+ .to(be_all { |f| f.is_a?(Queries::Projects::Filters::ProjectFilter) })
+
+ expect(model_instance.filters.map { |f| [f.name, f.operator, f.values] })
+ .to eql [[:id, '=', %w[1 2 3]], [:active, '!', ['t']]]
+ end
+
+ it 'assigns the orders param' do
+ subject
+
+ expect(model_instance.orders)
+ .to(be_all { |f| f.is_a?(Queries::Orders::Base) })
+
+ expect(model_instance.orders.map { |o| [o.name, o.direction] })
+ .to eql [["id", :asc], ["name", :desc]]
+ end
+ end
+
+ context 'without params' do
+ let(:params) do
+ {}
+ end
+
+ it 'assigns a default orders' do
+ subject
+
+ expect(model_instance.orders)
+ .to(be_all { |f| f.is_a?(Queries::Orders::Base) })
+
+ expect(model_instance.orders.map { |o| [o.name, o.direction] })
+ .to eql [%i[lft asc]]
+ end
+
+ it 'assigns a default filter param' do
+ subject
+
+ expect(model_instance.filters)
+ .to(be_all { |f| f.is_a?(Queries::Projects::Filters::ProjectFilter) })
+
+ expect(model_instance.filters.map { |f| [f.name, f.operator, f.values] })
+ .to eql [[:active, '=', %w[t]]]
+ end
end
context 'with an invalid contract' do
diff --git a/spec/support/pages/projects/index.rb b/spec/support/pages/projects/index.rb
index 48e495fc34d..cb3110ce86b 100644
--- a/spec/support/pages/projects/index.rb
+++ b/spec/support/pages/projects/index.rb
@@ -86,6 +86,19 @@ module Pages
end
end
+ def expect_current_page_number(number)
+ expect(page)
+ .to have_css('.op-pagination--item_current', text: number)
+ end
+
+ def expect_total_pages(number)
+ expect(page)
+ .to have_css('.op-pagination--item', text: number)
+
+ expect(page)
+ .to have_no_css('.op-pagination--item', text: number + 1)
+ end
+
def set_sidebar_filter(filter_name)
within '#main-menu' do
click_link text: filter_name
@@ -208,7 +221,7 @@ module Pages
def open_filters
retry_block do
- page.find('[data-test-selector="project-filter-toggle"]').click
+ page.find('[data-test-selector="filter-component-toggle"]').click
page.find_field('Add filter', visible: true)
end
end