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
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Rework Reporting controller using Request.JS
Alexander Brandon Colesfd0f316db5be
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex e17e18eb5ce..55fa8acf1bc 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -76,7 +76,7 @@ class CategoriesController < ApplicationControllerendend- def destroy+ def destroy # rubocop:disable Metrics/AbcSize@issue_count = @category.work_packages.sizeif @issue_count == 0# No issue assigned to this categorydiff --git a/frontend/src/stimulus/controllers/dynamic/reporting/page.controller.ts b/frontend/src/stimulus/controllers/dynamic/reporting/page.controller.tsindex ed11652bfed..8dff6dd2c38 100644--- a/frontend/src/stimulus/controllers/dynamic/reporting/page.controller.ts+++ b/frontend/src/stimulus/controllers/dynamic/reporting/page.controller.ts@@ -29,6 +29,7 @@*/import { Controller } from '@hotwired/stimulus';+import { FetchRequestError, post, ValidationError } from 'core-stimulus/helpers/request-helpers';import dragula from 'dragula';import jQuery from 'jquery';import 'tablesorter';@@ -329,7 +330,7 @@ export default class PageController extends Controller {}private loadAvailableValuesForFilterFromRemote(select:JQuery, filterName:string, callbackFunc:() => void) {- const url = select.attr('data-remote-url');+ const url = select.attr('data-remote-url')!;const jsonPostSelectValues = select.attr('data-initially-selected');let postSelectValues:string[]|undefined;@@ -341,32 +342,31 @@ export default class PageController extends Controller {window.global_prefix = '';}- void jQuery.ajax({- url,- method: 'POST',- data: {+ jQuery(`select[data-filter-name='${filterName}']`).prop('disabled', true);++ void post(url, {+ body: {filter_name: filterName,values: jsonPostSelectValues,},- beforeSend: () => {- jQuery(`select[data-filter-name='${filterName}']`).prop('disabled', true);- jQuery('#ajax-indicator').show();- },- complete: (xhr) => {- const tagName = select.prop('tagName') as string;-- select.html(xhr.responseText);- jQuery(`select[data-filter-name='${filterName}']`).prop('disabled', false);-- if (tagName && tagName.toLowerCase() === 'select') {- if (!postSelectValues || postSelectValues.length === 0) {- (select[0] as HTMLSelectElement).selectedIndex = 0;- } else {- this.selectValues(select, postSelectValues);- }+ responseKind: 'html',+ })+ .then((response) => response.html)+ .then((html) => {+ const tagName = select.prop('tagName') as string;++ select.html(html);+ jQuery(`select[data-filter-name='${filterName}']`).prop('disabled', false);++ if (tagName && tagName.toLowerCase() === 'select') {+ if (!postSelectValues || postSelectValues.length === 0) {+ (select[0] as HTMLSelectElement).selectedIndex = 0;+ } else {+ this.selectValues(select, postSelectValues);}- callbackFunc();- },+ }++ callbackFunc();});}@@ -725,9 +725,9 @@ export default class PageController extends Controller {return;}- const failureCallback = (response:JQuery.jqXHR) => {+ const failureCallback = (error:unknown) => {jQuery('#result-table').html('');- this.defaultFailureCallback(response);+ this.defaultFailureCallback(error);};element[0].addEventListener('click', (e:Event) => {@@ -737,45 +737,44 @@ export default class PageController extends Controller {});}- private sendSettingsData(targetUrl:string, callback:(response:string) => void, failureCallback?:(response:JQuery.jqXHR) => void) {+ private sendSettingsData(targetUrl:string, callback:(_result:string) => void, failureCallback?:(_error:unknown) => void) {const errorCallback = failureCallback || this.defaultFailureCallback;this.clearFlash();- void jQuery.ajax({- url: targetUrl,- method: 'POST',- data: this.serializeSettingsForm(),- beforeSend: () => {- jQuery('#ajax-indicator').show();- },- error: errorCallback,- success: callback,- });+ void post(targetUrl, { body: this.serializeSettingsForm() })+ .then((response) => {+ if (response.unprocessableEntity) {+ return response.text.then((errorText) => { throw new ValidationError(errorText); });+ }+ if (!response.ok) {+ throw new FetchRequestError(response.statusCode);+ }++ return response.text;+ })+ .then(callback)+ .catch(errorCallback);}private serializeSettingsForm() {- let retStr = jQuery('#query_form').serialize();- const groupingStr = ['rows', 'columns'].reduce((grouping, type) => {- const elementMap = jQuery(`#group-by--${type} .group-by--selected-element`)- .map((i, el) => {- return `groups[${type}][]=${el.dataset.groupBy as string}`;- })- .get();-- return grouping + elementMap.reduce((allGroupStr, groupStr) => {- return `${allGroupStr}&${groupStr}`;- }, '');- }, '');-- if (groupingStr.length > 0) {- retStr += groupingStr;- }- return retStr;+ const queryForm = document.querySelector<HTMLFormElement>('#query_form')!;+ const formData = new FormData(queryForm);++ ['rows', 'columns'].forEach((type) => {+ Array.from(document.querySelectorAll<HTMLElement>(`#group-by--${type} .group-by--selected-element`))+ .map((el) => el.dataset.groupBy)+ .filter((value) => value !== undefined)+ .forEach((value) => {+ formData.append(`groups[${type}][]`, value);+ });+ });++ return formData;}- private defaultFailureCallback = (response:JQuery.jqXHR) => {- if (response.status >= 400 && response.status < 500) {- this.flash(response.responseText);+ private defaultFailureCallback = (error:unknown) => {+ if (error instanceof ValidationError) {+ this.flash(error.message);} else {this.flash(window.I18n.t('js.reporting_engine.label_response_error'));}diff --git a/frontend/src/stimulus/helpers/request-helpers.ts b/frontend/src/stimulus/helpers/request-helpers.tsnew file mode 100644index 00000000000..eb19244765d--- /dev/null+++ b/frontend/src/stimulus/helpers/request-helpers.ts@@ -0,0 +1,59 @@+/*+ * -- copyright+ * OpenProject is an open source project management software.+ * Copyright (C) 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 { FetchRequest, FetchResponse, Options } from '@rails/request.js';++export function post(url:string|URL, options?:Options) {+ const request = new FetchRequest('post', url, options);+ return withAjaxIndicator(request.perform());+}++function withAjaxIndicator(request:Promise<FetchResponse>) {+ jQuery('#ajax-indicator').show();++ return request.then((response) => {+ jQuery('#ajax-indicator').hide();+ return response;+ });+}++export class FetchRequestError extends Error {+ constructor(public _errorCode:number, message = 'HTTP Error', options:ErrorOptions = {}) {+ super(message, options);+ this.name = 'FetchRequestError';+ }+}++export class ValidationError extends FetchRequestError {+ constructor(message:string, options:ErrorOptions = {}) {+ super(422, message, options);+ this.name = 'ValidationError';+ }+}diff --git a/modules/reporting/app/controllers/cost_reports_controller.rb b/modules/reporting/app/controllers/cost_reports_controller.rbindex f2af430f2fc..e99e2533d6a 100644--- a/modules/reporting/app/controllers/cost_reports_controller.rb+++ b/modules/reporting/app/controllers/cost_reports_controller.rb@@ -57,6 +57,7 @@ class CostReportsController < ApplicationControllerhelper_method :allowed_in_report?include ReportingHelper+helper ReportingHelperhelper { def engine; @report_engine; end }@@ -127,6 +128,19 @@ class CostReportsController < ApplicationController@project ? :costs : :cost_reports_globalend+ ##+ # Show a saved record, if found. Raises RecordNotFound if the specified query+ # at :id does not exist+ def show+ if @query+ store_query+ table+ render action: "index", locals: { menu_name: project_or_global_menu } unless performed?+ else+ raise ActiveRecord::RecordNotFound+ end+ end+### Create a new saved query. Returns the redirect url to an XHR or redirects directlydef create@@ -145,31 +159,6 @@ class CostReportsController < ApplicationControllerendend- ##- # Show a saved record, if found. Raises RecordNotFound if the specified query- # at :id does not exist- def show- if @query- store_query- table- render action: "index", locals: { menu_name: project_or_global_menu } unless performed?- else- raise ActiveRecord::RecordNotFound- end- end-- ##- # Delete a saved record, if found. Redirects to index on success, raises a- # RecordNotFound if the query at :id does not exist- def destroy- if @query- @query.destroy if allowed_in_report?(:destroy, @query)- else- raise ActiveRecord::RecordNotFound- end- redirect_to action: "index", default: 1, id: nil- end-### Update a record with new query parameters and save it. Redirects to the# specified record or renders the updated table on XHR@@ -192,6 +181,18 @@ class CostReportsController < ApplicationControllerendend+ ##+ # Delete a saved record, if found. Redirects to index on success, raises a+ # RecordNotFound if the query at :id does not exist+ def destroy+ if @query+ @query.destroy if allowed_in_report?(:destroy, @query)+ else+ raise ActiveRecord::RecordNotFound+ end+ redirect_to action: "index", default: 1, id: nil+ end+### Rename a record and update its publicity. Redirects to the updated record or# renders the updated name on XHR@@ -212,7 +213,7 @@ class CostReportsController < ApplicationControllerend# renders option tags for each available value for a single filter- def available_values+ def available_values # rubocop:disable Metrics/AbcSizename = params[:filter_name]return unless name@@ -221,9 +222,9 @@ class CostReportsController < ApplicationControllerfilter = f_cls.new.tap do |f|f.values = JSON.parse(params[:values].tr("'", '"')) if params[:values].present? && params[:values]end- render_widget Widget::Filters::Option, filter, to: canvas = +""+ render_widget Widget::Filters::Option, filter, to: canvas = +"".html_safe- render plain: canvas, layout: !request.xhr?+ render html: canvas, layout: !request.xhr?end##