Skip to content

Commit

Permalink
refactor ControllerWithQuery and cleanup strings
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandermeindl committed Jan 21, 2025
1 parent da69030 commit 7f857ab
Show file tree
Hide file tree
Showing 16 changed files with 119 additions and 118 deletions.
119 changes: 119 additions & 0 deletions app/controllers/concerns/controller_with_query.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# frozen_string_literal: true

module ControllerWithQuery
extend ActiveSupport::Concern

included do |base|
# NOTE: set it to queried class, this is required for all methods!
base.class_attribute :queried_class_name

rescue_from Query::StatementInvalid, with: :query_statement_invalid

helper :queries
helper :additionals_queries

# NOTE: order of includes matters for query helpers (required for csv)
include QueriesHelper
include AdditionalsQueriesHelper
end

def additionals_query_class
Object.const_get :"#{queried_class_name.to_s.camelcase}Query"
end

def additionals_retrieve_query(user_filter: nil, search_string: nil)
session_key = additionals_query_session_key
query_class = additionals_query_class

if params[:query_id].present?
additionals_load_query_id(query_class,
session_key,
params[:query_id],
user_filter:,
search_string:)
elsif api_request? ||
params[:set_filter] ||
session[session_key].nil? ||
session[session_key][:project_id] != (@project ? @project.id : nil)
# Give it a name, required to be valid
@query = query_class.new name: '_', project: @project
@query.project = @project
@query.user_filter = user_filter if user_filter
@query.search_string = search_string if search_string
@query.build_from_params params
session[session_key] = { project_id: @query.project_id }
# session has a limit to 4k, we have to use a cache for it for larger data
Rails.cache.write(additionals_query_cache_key,
filters: @query.filters,
group_by: @query.group_by,
column_names: @query.column_names,
totalable_names: @query.totalable_names,
sort_criteria: params[:sort].presence || @query.sort_criteria.to_a)
else
# retrieve from session
@query = query_class.find_by id: session[session_key][:id] if session[session_key][:id]
session_data = Rails.cache.read additionals_query_cache_key
@query ||= query_class.new(name: '_',
project: @project,
filters: session_data.nil? ? nil : session_data[:filters],
group_by: session_data.nil? ? nil : session_data[:group_by],
column_names: session_data.nil? ? nil : session_data[:column_names],
totalable_names: session_data.nil? ? nil : session_data[:totalable_names],
sort_criteria: params[:sort].presence || (session_data.nil? ? nil : session_data[:sort_criteria]))
@query.project = @project
@query.user_filter = user_filter if user_filter
@query.display_type = params[:display_type] if params[:display_type]

if params[:sort].present?
@query.sort_criteria = params[:sort]
# we have to write cache for sort order
Rails.cache.write(additionals_query_cache_key,
filters: @query.filters,
group_by: @query.group_by,
column_names: @query.column_names,
totalable_names: @query.totalable_names,
sort_criteria: params[:sort])
elsif session_data.present?
@query.sort_criteria = session_data[:sort_criteria]
end
end
end

def query_statement_invalid(exception)
Rails.logger.error "Query::StatementInvalid: #{exception.message}"
session.delete additionals_query_session_key
render_error l(:error_query_statement_invalid)
end

private

def additionals_query_session_key
:"#{queried_class_name}_query"
end

def additionals_load_query_id(query_class, session_key, query_id, user_filter: nil, search_string: nil)
scope = query_class.where project_id: nil
scope = scope.or query_class.where(project_id: @project) if @project
@query = scope.find query_id
raise ::Unauthorized unless @query.visible?

@query.project = @project
@query.user_filter = user_filter if user_filter
@query.search_string = search_string if search_string
session[session_key] = { id: @query.id, project_id: @query.project_id }

@query.sort_criteria = params[:sort] if params[:sort].present?
# we have to write cache for sort order
Rails.cache.write(additionals_query_cache_key,
filters: @query.filters,
group_by: @query.group_by,
column_names: @query.column_names,
totalable_names: @query.totalable_names,
sort_criteria: @query.sort_criteria)
end

def additionals_query_cache_key
project_id = @project ? @project.id : 0
"#{queried_class_name}_query_data_#{session.id}_#{project_id}"
end
end
8 changes: 0 additions & 8 deletions app/controllers/dashboards_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ class DashboardsController < ApplicationController

accept_api_auth :index, :show, :create, :update, :destroy

rescue_from Query::StatementInvalid, with: :query_statement_invalid

helper :queries
helper :issues
helper :activities
Expand Down Expand Up @@ -139,12 +137,6 @@ def destroy
end
end

def query_statement_invalid(exception)
Rails.logger.error "Query::StatementInvalid: #{exception.message}"
session.delete additionals_query_session_key('dashboard')
render_error l(:error_query_statement_invalid)
end

def update_layout_setting
block_settings = params[:settings] || {}

Expand Down
97 changes: 0 additions & 97 deletions app/helpers/additionals_queries_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,94 +17,6 @@ def render_live_search_info(entries:, count: nil)
end
end

def additionals_query_session_key(object_type)
:"#{object_type}_query"
end

def additionals_retrieve_query(object_type, user_filter: nil, search_string: nil)
session_key = additionals_query_session_key object_type
query_class = Object.const_get :"#{object_type.camelcase}Query"
if params[:query_id].present?
additionals_load_query_id(query_class,
session_key,
params[:query_id],
object_type,
user_filter:,
search_string:)
elsif api_request? ||
params[:set_filter] ||
session[session_key].nil? ||
session[session_key][:project_id] != (@project ? @project.id : nil)
# Give it a name, required to be valid
@query = query_class.new name: '_', project: @project
@query.project = @project
@query.user_filter = user_filter if user_filter
@query.search_string = search_string if search_string
@query.build_from_params params
session[session_key] = { project_id: @query.project_id }
# session has a limit to 4k, we have to use a cache for it for larger data
Rails.cache.write(additionals_query_cache_key(object_type),
filters: @query.filters,
group_by: @query.group_by,
column_names: @query.column_names,
totalable_names: @query.totalable_names,
sort_criteria: params[:sort].presence || @query.sort_criteria.to_a)
else
# retrieve from session
@query = query_class.find_by id: session[session_key][:id] if session[session_key][:id]
session_data = Rails.cache.read additionals_query_cache_key(object_type)
@query ||= query_class.new(name: '_',
project: @project,
filters: session_data.nil? ? nil : session_data[:filters],
group_by: session_data.nil? ? nil : session_data[:group_by],
column_names: session_data.nil? ? nil : session_data[:column_names],
totalable_names: session_data.nil? ? nil : session_data[:totalable_names],
sort_criteria: params[:sort].presence || (session_data.nil? ? nil : session_data[:sort_criteria]))
@query.project = @project
@query.user_filter = user_filter if user_filter
@query.display_type = params[:display_type] if params[:display_type]

if params[:sort].present?
@query.sort_criteria = params[:sort]
# we have to write cache for sort order
Rails.cache.write(additionals_query_cache_key(object_type),
filters: @query.filters,
group_by: @query.group_by,
column_names: @query.column_names,
totalable_names: @query.totalable_names,
sort_criteria: params[:sort])
elsif session_data.present?
@query.sort_criteria = session_data[:sort_criteria]
end
end
end

def additionals_load_query_id(query_class, session_key, query_id, object_type, user_filter: nil, search_string: nil)
scope = query_class.where project_id: nil
scope = scope.or query_class.where(project_id: @project) if @project
@query = scope.find query_id
raise ::Unauthorized unless @query.visible?

@query.project = @project
@query.user_filter = user_filter if user_filter
@query.search_string = search_string if search_string
session[session_key] = { id: @query.id, project_id: @query.project_id }

@query.sort_criteria = params[:sort] if params[:sort].present?
# we have to write cache for sort order
Rails.cache.write(additionals_query_cache_key(object_type),
filters: @query.filters,
group_by: @query.group_by,
column_names: @query.column_names,
totalable_names: @query.totalable_names,
sort_criteria: @query.sort_criteria)
end

def additionals_query_cache_key(object_type)
project_id = @project ? @project.id : 0
"#{object_type}_query_data_#{session.id}_#{project_id}"
end

def render_grouped_users_with_select2(users, search_term: nil, with_me: true, with_ano: false, me_value: 'me')
@users = { active: [], groups: [], registered: [], locked: [] }

Expand Down Expand Up @@ -353,13 +265,4 @@ def build_search_query_term(params)
def link_to_nonzero(value, path)
value.zero? ? value : link_to(value, path)
end

# NOTE: copy of Redmine 5.1
# TODO: this method can be removed, if Redmine 5.0 is not supported anymore
def filename_for_export(query, default_name)
query_name = params[:query_name].presence || query.name
query_name = default_name if query_name == '_' || query_name.blank?
# Convert file names using the same rules as Wiki titles
filename_for_content_disposition(Wiki.titleize(query_name).downcase)
end
end
1 change: 0 additions & 1 deletion config/locales/cs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ cs:
emoji_support_info_html: 'Převod emoji do textu. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: "Stav vydání nelze změnit"
error_issues_could_not_be_assigned_to_me: "Problém se mi nepodařilo přiřadit"
error_query_statement_invalid: "Při provádění dotazu došlo k chybě a bylo zaznamenáno. Nahlaste tuto chybu administrátorovi Redmine."
errors_no_or_invalid_arguments: "Žádné nebo neplatné argumenty"
field_always_expose: "Vždy zobrazit název palubní desky"
field_color: Barva
Expand Down
1 change: 0 additions & 1 deletion config/locales/de.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ de:
emoji_support_info_html: 'Emojis im Text konvertieren. Aktivere diese Option, wenn :heart:, :+1: etc in Emojis konvertiert werden sollen. Im <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> können die zur Verfügung stehenden Emoji-Codes eingesetzt werden.'
error_issue_status_could_not_changed: Der Ticket-Status konnte nicht geändert werden
error_issues_could_not_be_assigned_to_me: Das Ticket konnte nicht mir zugeordnet werden
error_query_statement_invalid: Beim Ausführen der Abfrage ist ein Fehler aufgetreten und wurde protokolliert. Bitte melden Sie diesen Fehler Ihrem Redmine-Administrator.
errors_no_or_invalid_arguments: Kein oder ungültiger Parameter
field_always_expose: Dashboard Name immer anzeigen
field_color: Farbe
Expand Down
1 change: 0 additions & 1 deletion config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ en:
emoji_support_info_html: 'Convert emojis in text. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: Issue state could not be changed
error_issues_could_not_be_assigned_to_me: Issue could not be assigned to me
error_query_statement_invalid: An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator.
errors_no_or_invalid_arguments: No or invalid arguments
field_always_expose: Always show dashboard name
field_color: Color
Expand Down
1 change: 0 additions & 1 deletion config/locales/es.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ es:
emoji_support_info_html: 'Convertir emojis en texto. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: El estado de la petición no puede ser modificado
error_issues_could_not_be_assigned_to_me: La petición no puede ser asignada a mi mismo
error_query_statement_invalid: Ocurrió un error ejecutando la consulta y fue registrado. Por favor informe este error al administrador de Redmine.
errors_no_or_invalid_arguments: Parámetros inválidos
field_always_expose: "Mostrar siempre el nombre del salpicadero"
field_color: Color
Expand Down
1 change: 0 additions & 1 deletion config/locales/fr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ fr:
emoji_support_info_html: 'Convertir les emojis en texte. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: "L'état de la tâche n'a pas pu être modifié"
error_issues_could_not_be_assigned_to_me: "La tâche n'a pas pu m'être affectée"
error_query_statement_invalid: "Une erreur s'est produite lors de l'exécution de la requête et a été enregistrée. Veuillez signaler cette erreur à votre administrateur Redmine."
errors_no_or_invalid_arguments: "Pas d'arguments ou arguments invalides"
field_always_expose: "Toujours afficher le nom du tableau de bord"
field_color: Couleur
Expand Down
1 change: 0 additions & 1 deletion config/locales/it.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ it:
emoji_support_info_html: 'Convertire emoji in testo. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: Issue state could not be changed
error_issues_could_not_be_assigned_to_me: Issue could not assigned to me
error_query_statement_invalid: An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator.
errors_no_or_invalid_arguments: No o non valido argomenti
field_always_expose: "Mostra sempre il nome del portale"
field_color: Colore
Expand Down
1 change: 0 additions & 1 deletion config/locales/ja.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ ja:
emoji_support_info_html: '絵文字をテキストに変換する. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: "問題の状態を変更できませんでした"
error_issues_could_not_be_assigned_to_me: "問題を自分に割り当てることができませんでした"
error_query_statement_invalid: "クエリの実行中にエラーが発生し、ログに記録されました。このエラーをRedmine管理者に報告してください。"
errors_no_or_invalid_arguments: "引数がない、または無効な引数"
field_always_expose: "ダッシュボード名を常に表示する"
field_color: "カラー"
Expand Down
1 change: 0 additions & 1 deletion config/locales/ko.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ ko:
emoji_support_info_html: 'Convert emojis in text. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: "문제 상태를 변경할 수 없습니다"
error_issues_could_not_be_assigned_to_me: "나에게 문제를 할당 할 수 없습니다"
error_query_statement_invalid: "쿼리를 실행하는 동안 오류가 발생하여 기록되었습니다. 이 오류를 Redmine 관리자에게보고하십시오."
errors_no_or_invalid_arguments: "인수가 없거나 유효하지 않습니다"
field_always_expose: "항상 대시보드 이름 표시"
field_color: 색깔
Expand Down
1 change: 0 additions & 1 deletion config/locales/pl.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ pl:
emoji_support_info_html: 'Konwertuj emojis na tekst. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: "Stan Issue nie mógł zostać zmieniony."
error_issues_could_not_be_assigned_to_me: "Issue nie mógł być mi przypisany"
error_query_statement_invalid: "Wystąpił błąd podczas wykonywania zapytania i został zarejestrowany. Proszę zgłosić ten błąd administratorowi Redmine."
errors_no_or_invalid_arguments: "Brak lub nieważne argumenty"
field_always_expose: "Zawsze pokazuj nazwę pulpitu"
field_color: Kolor
Expand Down
1 change: 0 additions & 1 deletion config/locales/pt-BR.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ pt-BR:
emoji_support_info_html: 'Converta emojis em texto. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: "O estado da tarefa não poderia ser alterado"
error_issues_could_not_be_assigned_to_me: "A tarefa não poderia ser me atribuída"
error_query_statement_invalid: "Ocorreu um erro durante a execução da consulta e foi registrado. Favor reportar este erro ao seu administrador Redmine."
errors_no_or_invalid_arguments: "Nenhum argumento ou argumentos inválidos"
field_always_expose: "Mostrar sempre o nome do painel de bordo"
field_color: "Cor"
Expand Down
1 change: 0 additions & 1 deletion config/locales/ru.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ ru:
emoji_support_info_html: 'Преобразование эмодзи в текст Поддержка. Activate this option if :heart:, :+1: etc are to be converted to emojis. In the <a href="https://www.webfx.com/tools/emoji-cheat-sheet/" class="external">Emoji cheat sheet</a> the available emoji codes can be used.'
error_issue_status_could_not_changed: "Состояние задач не может быть изменено"
error_issues_could_not_be_assigned_to_me: "Задача не могла быть поручена мне."
error_query_statement_invalid: "Во время выполнения запроса возникла ошибка, которая была зарегистрирована в журнале. Пожалуйста, сообщите об этой ошибке своему администратору Redmine."
errors_no_or_invalid_arguments: "Нет или недействительные аргументы"
field_always_expose: "Всегда показать название приборной панели"
field_color: Color
Expand Down
Loading

0 comments on commit 7f857ab

Please sign in to comment.