From 0185150b7baf6765e1fc5a6993cf17f0c454e0b1 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Wed, 26 Feb 2025 15:04:24 +0100 Subject: [PATCH 01/19] WIP --- .../views/resource_index_component.html.erb | 2 + .../avo/views/resource_index_component.rb | 26 +++++++ app/controllers/avo/bulk_update_controller.rb | 70 +++++++++++++++++++ app/helpers/avo/url_helpers.rb | 4 ++ config/routes.rb | 4 ++ 5 files changed, 106 insertions(+) create mode 100644 app/controllers/avo/bulk_update_controller.rb diff --git a/app/components/avo/views/resource_index_component.html.erb b/app/components/avo/views/resource_index_component.html.erb index 9cbe4aa5dc..505de0cb6c 100644 --- a/app/components/avo/views/resource_index_component.html.erb +++ b/app/components/avo/views/resource_index_component.html.erb @@ -49,6 +49,8 @@ <%= render Avo::FiltersComponent.new filters: @filters, resource: @resource, applied_filters: @applied_filters, parent_record: @parent_record %> <%= render partial: "avo/partials/view_toggle_button", locals: { available_view_types: available_view_types, view_type: view_type, turbo_frame: @turbo_frame } %> + + <%= render_bulk_update_button %> <% if has_dynamic_filters? %> diff --git a/app/components/avo/views/resource_index_component.rb b/app/components/avo/views/resource_index_component.rb index cd114e7998..744005df74 100644 --- a/app/components/avo/views/resource_index_component.rb +++ b/app/components/avo/views/resource_index_component.rb @@ -3,6 +3,7 @@ class Avo::Views::ResourceIndexComponent < Avo::ResourceComponent include Avo::ResourcesHelper include Avo::ApplicationHelper + include Avo::Concerns::ChecksShowAuthorization prop :resource prop :resources @@ -33,6 +34,20 @@ def view_type @index_params[:view_type] end + def bulk_edit_path + # Add the `view` param to let Avo know where to redirect back when the user clicks the `Cancel` button. + args = {via_view: "index"} + + if @parent_record.present? + args = { + via_resource_class: parent_resource.class.to_s, + via_record_id: @parent_record.to_param + } + end + + helpers.edit_bulk_update_path(resource: @resource, **args) + end + def available_view_types @index_params[:available_view_types] end @@ -158,6 +173,17 @@ def render_dynamic_filters_button end end + def render_bulk_update_button + a_link helpers.edit_bulk_update_path(resource: @resource), + style: :text, + color: :blue, + icon: "avo/edit", + form_class: "flex flex-col sm:flex-row sm:inline-flex", + data: {} do + "Bulk update" + end + end + def scopes_list Avo::Advanced::Scopes::ListComponent.new( scopes: @scopes, diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb new file mode 100644 index 0000000000..263d35cf23 --- /dev/null +++ b/app/controllers/avo/bulk_update_controller.rb @@ -0,0 +1,70 @@ +module Avo + class BulkUpdateController < ApplicationController + before_action :set_resource_name + before_action :set_resource + before_action :set_query, :set_fields, :verify_authorization, only: [:edit, :update] + + def edit + @prefilled_fields = prefill_fields(@query, @fields) + render layout: false + end + + def update + @resources.each_with_index do |resource, index| + record = @query[index] + @fields.each do |field_name, new_value| + resource.fill_field(record, field_name, new_value) if new_value.present? + end + record.save! + end + + flash[:notice] = I18n.t("avo.bulk_update.success", count: @query.size) + redirect_to resources_path(resource: @resources.first) + end + + private + + def prefill_fields(records, fields) + prefilled = {} + fields.each_key do |field_name| + values = records.map { |record| record.public_send(field_name) } + prefilled[field_name] = (values.uniq.size == 1 ? values.first : nil) + end + prefilled + end + + def set_resources + raise ActionController::RoutingError.new "No route matches" if @query.nil? || @query.empty? + + @resources = @query.map do |record| + resource.new(view: params[:view].presence || action_name.to_s, user: _current_user, params: params, record: record) + end + + set_authorization + end + + def set_query + resource_ids = action_params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] + + @query = decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) + end + + def set_fields + @fields = action_params[:fields].except(:avo_resource_ids, :avo_selected_query) + end + + def action_params + @action_params ||= params.permit(:authenticity_token, :resource_name, :button, :arguments, fields: {}) + end + + def decrypted_query + return if (encrypted_query = action_params[:fields]&.dig(:avo_selected_query)).blank? + + Avo::Services::EncryptionService.decrypt(message: encrypted_query, purpose: :select_all, serializer: Marshal) + end + + def verify_authorization + raise Avo::NotAuthorizedError.new unless @action.authorized? + end + end +end diff --git a/app/helpers/avo/url_helpers.rb b/app/helpers/avo/url_helpers.rb index 97e47b30f1..bd99482d3f 100644 --- a/app/helpers/avo/url_helpers.rb +++ b/app/helpers/avo/url_helpers.rb @@ -44,6 +44,10 @@ def edit_resource_path(resource:, record: nil, resource_id: nil, **args) avo.send :"edit_resources_#{resource.singular_route_key}_path", record || resource_id, **args end + def edit_bulk_update_path(resource:, **args) + avo.send :"edit_bulk_update_path", resource, **args + end + def resource_attach_path(resource, record_id, related_name, related_id = nil) helpers.avo.resources_associations_new_path(resource.singular_route_key, record_id, related_name) end diff --git a/config/routes.rb b/config/routes.rb index 41afeb9569..1d7de1fdc7 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -9,6 +9,10 @@ instance_exec(&Avo.mount_engines) end + get "/bulk_update/edit", to: "bulk_update#edit", as: "edit_bulk_update" + patch "/bulk_update", to: "bulk_update#update", as: "bulk_update" + put "/bulk_update", to: "bulk_update#update" + resources :media_library, only: [:index, :show, :update, :destroy], path: "media-library" get "attach-media", to: "media_library#attach" From 633f97d59be7926d81d533f0a9b4f2180bc42aa9 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Tue, 4 Mar 2025 19:52:00 +0100 Subject: [PATCH 02/19] implement bulk update --- .../views/resource_edit_component.html.erb | 9 +- .../avo/views/resource_edit_component.rb | 20 ++- .../avo/views/resource_index_component.rb | 9 +- app/controllers/avo/base_controller.rb | 1 + app/controllers/avo/bulk_update_controller.rb | 132 +++++++++++++----- app/helpers/avo/url_helpers.rb | 8 +- .../controllers/item_select_all_controller.js | 34 +++++ config/routes.rb | 3 +- lib/avo/resources/base.rb | 1 + spec/dummy/config/locales/avo.en.yml | 3 + 10 files changed, 174 insertions(+), 46 deletions(-) diff --git a/app/components/avo/views/resource_edit_component.html.erb b/app/components/avo/views/resource_edit_component.html.erb index 2836f1d241..0d64ebcded 100644 --- a/app/components/avo/views/resource_edit_component.html.erb +++ b/app/components/avo/views/resource_edit_component.html.erb @@ -9,7 +9,7 @@ **@resource.stimulus_data_attributes } do %> <%= render_cards_component %> - <%= form_with model: @resource.record, + <%= form_with model: model, scope: @resource.form_scope, url: form_url, method: form_method, @@ -23,6 +23,13 @@ }, multipart: true do |form| %> <%= render Avo::ReferrerParamsComponent.new back_path: back_path %> + + <% if @prefilled_fields.present? %> + <% @prefilled_fields.each do |field, value| %> + <%= hidden_field_tag "prefilled[#{field}]", value %> + <% end %> + <% end %> + <%= content_tag :div, class: "space-y-12" do %> <% @resource.get_items.each_with_index do |item, index| %> <%= render Avo::Items::SwitcherComponent.new( diff --git a/app/components/avo/views/resource_edit_component.rb b/app/components/avo/views/resource_edit_component.rb index 9a5c4baccf..0c004a7a2c 100644 --- a/app/components/avo/views/resource_edit_component.rb +++ b/app/components/avo/views/resource_edit_component.rb @@ -9,6 +9,14 @@ class Avo::Views::ResourceEditComponent < Avo::ResourceComponent prop :view, default: Avo::ViewInquirer.new(:edit).freeze prop :display_breadcrumbs, default: true, reader: :public + attr_reader :query + + def initialize(resource:, query: nil, prefilled_fields: nil, **args) + @query = query + @prefilled_fields = prefilled_fields + super(resource: resource, **args) + end + def after_initialize @display_breadcrumbs = @reflection.blank? && display_breadcrumbs end @@ -25,6 +33,8 @@ def back_path return resource_view_path if via_resource? return resources_path if via_index? + return helpers.resources_path(resource: @resource) if params[:controller] == 'avo/bulk_update' + if is_edit? && Avo.configuration.resource_default_view.show? # via resource show or edit page return helpers.resource_path(record: @resource.record, resource: @resource, **keep_referrer_params) end @@ -76,13 +86,19 @@ def is_edit? end def form_method - return :put if is_edit? + return :put if is_edit? && params[:controller] != 'avo/bulk_update' :post end + def model + @resource.record + end + def form_url - if is_edit? + if params[:controller] == 'avo/bulk_update' + helpers.handle_bulk_update_path(resource_name: @resource.name, query: @query) + elsif is_edit? helpers.resource_path( record: @resource.record, resource: @resource diff --git a/app/components/avo/views/resource_index_component.rb b/app/components/avo/views/resource_index_component.rb index 744005df74..aa99e95912 100644 --- a/app/components/avo/views/resource_index_component.rb +++ b/app/components/avo/views/resource_index_component.rb @@ -174,12 +174,11 @@ def render_dynamic_filters_button end def render_bulk_update_button - a_link helpers.edit_bulk_update_path(resource: @resource), - style: :text, - color: :blue, + a_link helpers.edit_bulk_update_path(resource_name: @resource.name, id: 4), + style: :primary, + color: :primary, icon: "avo/edit", - form_class: "flex flex-col sm:flex-row sm:inline-flex", - data: {} do + form_class: "flex flex-col sm:flex-row sm:inline-flex" do "Bulk update" end end diff --git a/app/controllers/avo/base_controller.rb b/app/controllers/avo/base_controller.rb index 916ac0b2d8..315770656a 100644 --- a/app/controllers/avo/base_controller.rb +++ b/app/controllers/avo/base_controller.rb @@ -300,6 +300,7 @@ def cast_nullable(params) end .to_h + params.each do |key, value| nullable_values = nullable_fields[key.to_sym] diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index 263d35cf23..e15f6c8ab5 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -1,29 +1,97 @@ module Avo - class BulkUpdateController < ApplicationController - before_action :set_resource_name - before_action :set_resource - before_action :set_query, :set_fields, :verify_authorization, only: [:edit, :update] + class BulkUpdateController < ResourcesController + before_action :set_query, only: [:edit, :handle] + before_action :set_fields, only: [:edit, :handle] def edit @prefilled_fields = prefill_fields(@query, @fields) - render layout: false + @record = @resource.model_class.new(@prefilled_fields.transform_values { |v| v.nil? ? nil : v }) + + @resource.record = @record + render Avo::Views::ResourceEditComponent.new( + resource: @resource, + query: @query, + prefilled_fields: @prefilled_fields + ) end - def update - @resources.each_with_index do |resource, index| - record = @query[index] - @fields.each do |field_name, new_value| - resource.fill_field(record, field_name, new_value) if new_value.present? - end - record.save! + def handle + if params_to_apply.blank? + flash[:warning] = t("avo.no_changes_made") + redirect_to after_bulk_update_path + end + + updated_count, failed_records = update_records + + if failed_records.empty? + flash[:notice] = t("avo.bulk_update_success", count: updated_count) + else + error_messages = failed_records.flat_map { |fr| fr[:errors] }.uniq + flash[:error] = t("avo.bulk_update_failure", count: failed_records.count, errors: error_messages.join(", ")) end - flash[:notice] = I18n.t("avo.bulk_update.success", count: @query.size) - redirect_to resources_path(resource: @resources.first) + redirect_to after_bulk_update_path end private + def params_to_apply + prefilled_params = params[:prefilled] || {} + + resource_key = @resource_name.downcase.to_sym + current_params = params[resource_key] || {} + + progress_fields = @resource.get_field_definitions + .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } + .map(&:id) + .map(&:to_sym) + + + params_to_apply = current_params.reject do |key, value| + key_sym = key.to_sym + prefilled_value = prefilled_params[key_sym] + + next true if progress_fields.include?(key_sym) && prefilled_value == "" && value.to_s == "50" + + prefilled_value.to_s == value.to_s + end + + params_to_apply + end + + def update_records + updated_count = 0 + failed_records = [] + + @query.each do |record| + begin + params_to_apply.each do |key, value| + begin + record.public_send("#{key}=", value) + rescue => e + puts "Błąd przypisywania pola #{key}: #{e.message}" + end + end + + @resource.fill_record(record, params) + + if record.save + updated_count += 1 + else + failed_records << { record: record, errors: record.errors.full_messages } + end + rescue => e + failed_records << { record: record, errors: [e.message] } + end + end + + return updated_count, failed_records + end + + def after_bulk_update_path + resources_path(resource: @resource) + end + def prefill_fields(records, fields) prefilled = {} fields.each_key do |field_name| @@ -33,38 +101,34 @@ def prefill_fields(records, fields) prefilled end - def set_resources - raise ActionController::RoutingError.new "No route matches" if @query.nil? || @query.empty? - - @resources = @query.map do |record| - resource.new(view: params[:view].presence || action_name.to_s, user: _current_user, params: params, record: record) - end - - set_authorization - end - def set_query - resource_ids = action_params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] - - @query = decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) + if params[:query].present? + @query = @resource.find_record(params[:query], params: params) + else + resource_ids = action_params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] + @query = decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) + end end def set_fields - @fields = action_params[:fields].except(:avo_resource_ids, :avo_selected_query) + if @query.blank? + flash[:error] = "Bulk update cannot be performed without records." + redirect_to after_bulk_update_path + else + @fields = @query.first.attributes.keys.index_with { nil } + end end def action_params - @action_params ||= params.permit(:authenticity_token, :resource_name, :button, :arguments, fields: {}) + @action_params ||= params.permit(:authenticity_token, fields: {}) end def decrypted_query - return if (encrypted_query = action_params[:fields]&.dig(:avo_selected_query)).blank? + encrypted_query = action_params[:fields]&.dig(:avo_selected_query) || params[:query] - Avo::Services::EncryptionService.decrypt(message: encrypted_query, purpose: :select_all, serializer: Marshal) - end + return if encrypted_query.blank? - def verify_authorization - raise Avo::NotAuthorizedError.new unless @action.authorized? + Avo::Services::EncryptionService.decrypt(message: encrypted_query, purpose: :select_all, serializer: Marshal) end end end diff --git a/app/helpers/avo/url_helpers.rb b/app/helpers/avo/url_helpers.rb index bd99482d3f..6d2a9d88df 100644 --- a/app/helpers/avo/url_helpers.rb +++ b/app/helpers/avo/url_helpers.rb @@ -44,8 +44,12 @@ def edit_resource_path(resource:, record: nil, resource_id: nil, **args) avo.send :"edit_resources_#{resource.singular_route_key}_path", record || resource_id, **args end - def edit_bulk_update_path(resource:, **args) - avo.send :"edit_bulk_update_path", resource, **args + def edit_bulk_update_path(resource_name:, id:, **args) + avo.send :"edit_bulk_update_path", resource_name, id, **args + end + + def handle_bulk_update_path(resource_name:, query:, **args) + avo.send :"handle_bulk_update_path", resource_name, query, **args end def resource_attach_path(resource, record_id, related_name, related_id = nil) diff --git a/app/javascript/js/controllers/item_select_all_controller.js b/app/javascript/js/controllers/item_select_all_controller.js index 32164bfacc..e4aa9803ed 100644 --- a/app/javascript/js/controllers/item_select_all_controller.js +++ b/app/javascript/js/controllers/item_select_all_controller.js @@ -71,6 +71,7 @@ export default class extends Controller { } this.updateLinks('resourceIds') + this.updateBulkEditLink('resourceIds') } selectAll(event) { @@ -82,8 +83,10 @@ export default class extends Controller { if (this.selectedAllValue) { this.updateLinks('selectedQuery') + this.updateBulkEditLink('selectedQuery') } else { this.updateLinks('resourceIds') + this.updateBulkEditLink('resourceIds') } } @@ -118,6 +121,37 @@ export default class extends Controller { }) } + updateBulkEditLink(param) { + let resourceIds = '' + let selectedQuery = '' + + if (param === 'resourceIds') { + resourceIds = JSON.parse(this.element.dataset.selectedResources).join(',') + } else if (param === 'selectedQuery') { + selectedQuery = this.element.dataset.itemSelectAllSelectedAllQueryValue + } + + document.querySelectorAll('a[href*="/admin/bulk_update/edit"]').forEach((link) => { + try { + const url = new URL(link.href) + + Array.from(url.searchParams.keys()) + .filter((key) => key.startsWith('fields[')) + .forEach((key) => url.searchParams.delete(key)) + + if (param === 'resourceIds') { + url.searchParams.set('fields[avo_resource_ids]', resourceIds) + } else if (param === 'selectedQuery') { + url.searchParams.set('fields[avo_selected_query]', selectedQuery) + } + + link.href = url.toString() + } catch (error) { + console.error('Error updating link:', link, error) + } + }) + } + resetUnselected() { this.selectedAllValue = false this.unselectedMessageTarget.classList.remove('hidden') diff --git a/config/routes.rb b/config/routes.rb index 1d7de1fdc7..28529343bc 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -10,8 +10,7 @@ end get "/bulk_update/edit", to: "bulk_update#edit", as: "edit_bulk_update" - patch "/bulk_update", to: "bulk_update#update", as: "bulk_update" - put "/bulk_update", to: "bulk_update#update" + post "/bulk_update/handle", to: "bulk_update#handle", as: "handle_bulk_update" resources :media_library, only: [:index, :show, :update, :destroy], path: "media-library" get "attach-media", to: "media_library#attach" diff --git a/lib/avo/resources/base.rb b/lib/avo/resources/base.rb index e24a9e914c..6b305625fe 100644 --- a/lib/avo/resources/base.rb +++ b/lib/avo/resources/base.rb @@ -631,6 +631,7 @@ def entity_loader(entity) end def record_param + return nil if @record.nil? @record_param ||= @record.persisted? ? @record.to_param : nil end diff --git a/spec/dummy/config/locales/avo.en.yml b/spec/dummy/config/locales/avo.en.yml index 5f22ca6f1f..22efeba0a5 100644 --- a/spec/dummy/config/locales/avo.en.yml +++ b/spec/dummy/config/locales/avo.en.yml @@ -20,6 +20,8 @@ en: attachment_class_detached: "%{attachment_class} detached." attachment_failed: "Failed to attach %{attachment_class}" attachment_destroyed: Attachment destroyed + bulk_update_success: "%{count} records were successfully updated." + bulk_update_failure: "Failed to update %{count} records. Errors: %{errors}" cancel: Cancel choose_a_country: Choose a country choose_an_option: Choose an option @@ -68,6 +70,7 @@ en: next_page: Next page no_cancel: No, cancel no_cards_present: No cards present + no_changes_made: No changes were made. no_item_found: No record found no_options_available: No options available no_related_item_found: No related record found From 0f85794ff3ec138a6ea5c0b3c8d7ba8423f7c346 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Wed, 5 Mar 2025 17:26:00 +0100 Subject: [PATCH 03/19] optymalize code --- .../avo/views/resource_edit_component.rb | 4 +- .../controllers/item_select_all_controller.js | 52 +++++++------------ 2 files changed, 22 insertions(+), 34 deletions(-) diff --git a/app/components/avo/views/resource_edit_component.rb b/app/components/avo/views/resource_edit_component.rb index 0c004a7a2c..4f504105a6 100644 --- a/app/components/avo/views/resource_edit_component.rb +++ b/app/components/avo/views/resource_edit_component.rb @@ -26,6 +26,8 @@ def title end def back_path + return helpers.resources_path(resource: @resource) if params[:controller] == 'avo/bulk_update' + # The `return_to` param takes precedence over anything else. return params[:return_to] if params[:return_to].present? @@ -33,8 +35,6 @@ def back_path return resource_view_path if via_resource? return resources_path if via_index? - return helpers.resources_path(resource: @resource) if params[:controller] == 'avo/bulk_update' - if is_edit? && Avo.configuration.resource_default_view.show? # via resource show or edit page return helpers.resource_path(record: @resource.record, resource: @resource, **keep_referrer_params) end diff --git a/app/javascript/js/controllers/item_select_all_controller.js b/app/javascript/js/controllers/item_select_all_controller.js index 77756e7c61..9362e03193 100644 --- a/app/javascript/js/controllers/item_select_all_controller.js +++ b/app/javascript/js/controllers/item_select_all_controller.js @@ -91,39 +91,21 @@ export default class extends Controller { } updateLinks(param) { - let resourceIds = '' - let selectedQuery = '' - - if (param === 'resourceIds') { - resourceIds = JSON.parse(this.element.dataset.selectedResources).join(',') - } else if (param === 'selectedQuery') { - selectedQuery = this.element.dataset.itemSelectAllSelectedAllQueryValue - } - - document.querySelectorAll('[data-target="actions-list"] > a').forEach((link) => { - try { - const url = new URL(link.href) - - Array.from(url.searchParams.keys()) - .filter((key) => key.startsWith('fields[')) - .forEach((key) => url.searchParams.delete(key)) - - if (param === 'resourceIds') { - url.searchParams.set('fields[avo_resource_ids]', resourceIds) - url.searchParams.set('fields[avo_selected_all]', 'false') - } else if (param === 'selectedQuery') { - url.searchParams.set('fields[avo_index_query]', selectedQuery) - url.searchParams.set('fields[avo_selected_all]', 'true') - } - - link.href = url.toString() - } catch (error) { - console.error('Error updating link:', link, error) - } + this.updateActionLinks(param, '[data-target="actions-list"] > a', { + resourceIdsKey: 'fields[avo_resource_ids]', + selectedQueryKey: 'fields[avo_index_query]', + selectedAllKey: 'fields[avo_selected_all]', }) } updateBulkEditLink(param) { + this.updateActionLinks(param, 'a[href*="/admin/bulk_update/edit"]', { + resourceIdsKey: 'fields[avo_resource_ids]', + selectedQueryKey: 'fields[avo_selected_query]', + }) + } + + updateActionLinks(param, selector, keys) { let resourceIds = '' let selectedQuery = '' @@ -133,7 +115,7 @@ export default class extends Controller { selectedQuery = this.element.dataset.itemSelectAllSelectedAllQueryValue } - document.querySelectorAll('a[href*="/admin/bulk_update/edit"]').forEach((link) => { + document.querySelectorAll(selector).forEach((link) => { try { const url = new URL(link.href) @@ -142,9 +124,15 @@ export default class extends Controller { .forEach((key) => url.searchParams.delete(key)) if (param === 'resourceIds') { - url.searchParams.set('fields[avo_resource_ids]', resourceIds) + url.searchParams.set(keys.resourceIdsKey, resourceIds) + if (keys.selectedAllKey) { + url.searchParams.set(keys.selectedAllKey, 'false') + } } else if (param === 'selectedQuery') { - url.searchParams.set('fields[avo_selected_query]', selectedQuery) + url.searchParams.set(keys.selectedQueryKey, selectedQuery) + if (keys.selectedAllKey) { + url.searchParams.set(keys.selectedAllKey, 'true') + } } link.href = url.toString() From fa8c558e82e1ed7f1fda10b3884582d5db820ecf Mon Sep 17 00:00:00 2001 From: Nevelito Date: Mon, 10 Mar 2025 19:41:50 +0100 Subject: [PATCH 04/19] fix standardeb errors --- app/components/avo/views/resource_index_component.rb | 8 ++++---- app/controllers/avo/base_controller.rb | 1 - app/controllers/avo/bulk_update_controller.rb | 9 +++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/app/components/avo/views/resource_index_component.rb b/app/components/avo/views/resource_index_component.rb index 17454be96c..910e7b3cf8 100644 --- a/app/components/avo/views/resource_index_component.rb +++ b/app/components/avo/views/resource_index_component.rb @@ -171,10 +171,10 @@ def render_dynamic_filters_button def render_bulk_update_button a_link helpers.edit_bulk_update_path(resource_name: @resource.name, id: 4), - style: :primary, - color: :primary, - icon: "avo/edit", - form_class: "flex flex-col sm:flex-row sm:inline-flex" do + style: :primary, + color: :primary, + icon: "avo/edit", + form_class: "flex flex-col sm:flex-row sm:inline-flex" do "Bulk update" end end diff --git a/app/controllers/avo/base_controller.rb b/app/controllers/avo/base_controller.rb index 5a458ef0dc..94224ee380 100644 --- a/app/controllers/avo/base_controller.rb +++ b/app/controllers/avo/base_controller.rb @@ -304,7 +304,6 @@ def cast_nullable(params) end .to_h - params.each do |key, value| nullable_values = nullable_fields[key.to_sym] diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index e15f6c8ab5..52eddd206c 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -41,10 +41,11 @@ def params_to_apply resource_key = @resource_name.downcase.to_sym current_params = params[resource_key] || {} - progress_fields = @resource.get_field_definitions - .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } - .map(&:id) - .map(&:to_sym) + progress_fields = @resource + .get_field_definitions + .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } + .map(&:id) + .map(&:to_sym) params_to_apply = current_params.reject do |key, value| From 7a67ccdc72b4c4a9db0455ed227a7c4f4322a26d Mon Sep 17 00:00:00 2001 From: Nevelito Date: Mon, 10 Mar 2025 19:56:35 +0100 Subject: [PATCH 05/19] rubocop changes in bulk update --- .../avo/views/resource_edit_component.rb | 6 +-- app/controllers/avo/bulk_update_controller.rb | 45 ++++++++----------- config/routes.rb | 5 --- 3 files changed, 22 insertions(+), 34 deletions(-) diff --git a/app/components/avo/views/resource_edit_component.rb b/app/components/avo/views/resource_edit_component.rb index 4f504105a6..ef2af01ec8 100644 --- a/app/components/avo/views/resource_edit_component.rb +++ b/app/components/avo/views/resource_edit_component.rb @@ -26,7 +26,7 @@ def title end def back_path - return helpers.resources_path(resource: @resource) if params[:controller] == 'avo/bulk_update' + return helpers.resources_path(resource: @resource) if params[:controller] == "avo/bulk_update" # The `return_to` param takes precedence over anything else. return params[:return_to] if params[:return_to].present? @@ -86,7 +86,7 @@ def is_edit? end def form_method - return :put if is_edit? && params[:controller] != 'avo/bulk_update' + return :put if is_edit? && params[:controller] != "avo/bulk_update" :post end @@ -96,7 +96,7 @@ def model end def form_url - if params[:controller] == 'avo/bulk_update' + if params[:controller] == "avo/bulk_update" helpers.handle_bulk_update_path(resource_name: @resource.name, query: @query) elsif is_edit? helpers.resource_path( diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index 52eddd206c..40842615ce 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -42,13 +42,12 @@ def params_to_apply current_params = params[resource_key] || {} progress_fields = @resource - .get_field_definitions - .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } - .map(&:id) - .map(&:to_sym) + .get_field_definitions + .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } + .map(&:id) + .map(&:to_sym) - - params_to_apply = current_params.reject do |key, value| + current_params.reject do |key, value| key_sym = key.to_sym prefilled_value = prefilled_params[key_sym] @@ -56,8 +55,6 @@ def params_to_apply prefilled_value.to_s == value.to_s end - - params_to_apply end def update_records @@ -65,28 +62,24 @@ def update_records failed_records = [] @query.each do |record| - begin - params_to_apply.each do |key, value| - begin - record.public_send("#{key}=", value) - rescue => e - puts "Błąd przypisywania pola #{key}: #{e.message}" - end - end - - @resource.fill_record(record, params) - - if record.save - updated_count += 1 - else - failed_records << { record: record, errors: record.errors.full_messages } - end + params_to_apply.each do |key, value| + record.public_send(:"#{key}=", value) rescue => e - failed_records << { record: record, errors: [e.message] } + puts "Błąd przypisywania pola #{key}: #{e.message}" + end + + @resource.fill_record(record, params) + + if record.save + updated_count += 1 + else + failed_records << { record: record, errors: record.errors.full_messages } end + rescue => e + failed_records << { record: record, errors: [e.message] } end - return updated_count, failed_records + [updated_count, failed_records] end def after_bulk_update_path diff --git a/config/routes.rb b/config/routes.rb index 28529343bc..8f929ea719 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -4,11 +4,6 @@ get "resources", to: redirect(Avo.configuration.root_path) get "dashboards", to: redirect(Avo.configuration.root_path) - # Mount Avo engines routes by default but leave it configurable in case the user wants to nest these under a scope. - if Avo.configuration.mount_avo_engines - instance_exec(&Avo.mount_engines) - end - get "/bulk_update/edit", to: "bulk_update#edit", as: "edit_bulk_update" post "/bulk_update/handle", to: "bulk_update#handle", as: "handle_bulk_update" From 7d35c4650b623c179697d17639fdd6b17d5bc0d0 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Mon, 10 Mar 2025 20:08:26 +0100 Subject: [PATCH 06/19] fix next rubocop errors --- app/controllers/avo/bulk_update_controller.rb | 12 ++++++------ app/helpers/avo/url_helpers.rb | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index 40842615ce..d29fb40b7d 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -42,10 +42,10 @@ def params_to_apply current_params = params[resource_key] || {} progress_fields = @resource - .get_field_definitions - .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } - .map(&:id) - .map(&:to_sym) + .get_field_definitions + .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } + .map(&:id) + .map(&:to_sym) current_params.reject do |key, value| key_sym = key.to_sym @@ -73,10 +73,10 @@ def update_records if record.save updated_count += 1 else - failed_records << { record: record, errors: record.errors.full_messages } + failed_records << {record: record, errors: record.errors.full_messages} end rescue => e - failed_records << { record: record, errors: [e.message] } + failed_records << {record: record, errors: [e.message]} end [updated_count, failed_records] diff --git a/app/helpers/avo/url_helpers.rb b/app/helpers/avo/url_helpers.rb index 6d2a9d88df..42e5e1709d 100644 --- a/app/helpers/avo/url_helpers.rb +++ b/app/helpers/avo/url_helpers.rb @@ -45,11 +45,11 @@ def edit_resource_path(resource:, record: nil, resource_id: nil, **args) end def edit_bulk_update_path(resource_name:, id:, **args) - avo.send :"edit_bulk_update_path", resource_name, id, **args + avo.send :edit_bulk_update_path, resource_name, id, **args end def handle_bulk_update_path(resource_name:, query:, **args) - avo.send :"handle_bulk_update_path", resource_name, query, **args + avo.send :handle_bulk_update_path, resource_name, query, **args end def resource_attach_path(resource, record_id, related_name, related_id = nil) From ade1422487f0b5fd4452149b56db4a55b735e539 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Mon, 10 Mar 2025 20:55:04 +0100 Subject: [PATCH 07/19] small changes with rubocop and locales --- app/controllers/avo/bulk_update_controller.rb | 2 +- lib/generators/avo/templates/locales/avo.en.yml | 3 +++ spec/dummy/config/locales/avo.en.yml | 3 --- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index d29fb40b7d..1fc2d41674 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -90,7 +90,7 @@ def prefill_fields(records, fields) prefilled = {} fields.each_key do |field_name| values = records.map { |record| record.public_send(field_name) } - prefilled[field_name] = (values.uniq.size == 1 ? values.first : nil) + prefilled[field_name] = values.uniq.size == 1 ? values.first : nil end prefilled end diff --git a/lib/generators/avo/templates/locales/avo.en.yml b/lib/generators/avo/templates/locales/avo.en.yml index b6fa650c94..bd6aa6c938 100644 --- a/lib/generators/avo/templates/locales/avo.en.yml +++ b/lib/generators/avo/templates/locales/avo.en.yml @@ -16,6 +16,8 @@ en: attachment_class_detached: "%{attachment_class} detached." attachment_destroyed: Attachment destroyed attachment_failed: Failed to attach %{attachment_class} + bulk_update_success: "%{count} records were successfully updated." + bulk_update_failure: "Failed to update %{count} records. Errors: %{errors}" cancel: Cancel choose_a_country: Choose a country choose_an_option: Choose an option @@ -70,6 +72,7 @@ en: new: new next_page: Next page no_cancel: No, cancel + no_changes_made: No changes were made. no_cards_present: No cards present no_item_found: No record found no_options_available: No options available diff --git a/spec/dummy/config/locales/avo.en.yml b/spec/dummy/config/locales/avo.en.yml index e1f4143a6b..45d166e75c 100644 --- a/spec/dummy/config/locales/avo.en.yml +++ b/spec/dummy/config/locales/avo.en.yml @@ -20,8 +20,6 @@ en: attachment_class_detached: "%{attachment_class} detached." attachment_failed: "Failed to attach %{attachment_class}" attachment_destroyed: Attachment destroyed - bulk_update_success: "%{count} records were successfully updated." - bulk_update_failure: "Failed to update %{count} records. Errors: %{errors}" cancel: Cancel choose_a_country: Choose a country choose_an_option: Choose an option @@ -72,7 +70,6 @@ en: next_page: Next page no_cancel: No, cancel no_cards_present: No cards present - no_changes_made: No changes were made. no_item_found: No record found no_options_available: No options available no_related_item_found: No related record found From a2be7fb150b92d938ed1fab64da2dd2cc2780d99 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Mon, 10 Mar 2025 21:05:05 +0100 Subject: [PATCH 08/19] small changes --- app/controllers/avo/bulk_update_controller.rb | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index 1fc2d41674..88f870dd42 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -87,12 +87,11 @@ def after_bulk_update_path end def prefill_fields(records, fields) - prefilled = {} - fields.each_key do |field_name| + fields.each_key.with_object({}) do |field_name, prefilled| values = records.map { |record| record.public_send(field_name) } - prefilled[field_name] = values.uniq.size == 1 ? values.first : nil + values.uniq! + prefilled[field_name] = (values.size == 1 ? values.first : nil) end - prefilled end def set_query From 0278fcab03f049db7d22605028522eec8bbcf71a Mon Sep 17 00:00:00 2001 From: Nevelito Date: Mon, 10 Mar 2025 21:11:47 +0100 Subject: [PATCH 09/19] codeclimate fix --- .../controllers/item_select_all_controller.js | 35 +++++++++---------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/app/javascript/js/controllers/item_select_all_controller.js b/app/javascript/js/controllers/item_select_all_controller.js index 9362e03193..0883a212b0 100644 --- a/app/javascript/js/controllers/item_select_all_controller.js +++ b/app/javascript/js/controllers/item_select_all_controller.js @@ -106,13 +106,17 @@ export default class extends Controller { } updateActionLinks(param, selector, keys) { - let resourceIds = '' - let selectedQuery = '' - - if (param === 'resourceIds') { - resourceIds = JSON.parse(this.element.dataset.selectedResources).join(',') - } else if (param === 'selectedQuery') { - selectedQuery = this.element.dataset.itemSelectAllSelectedAllQueryValue + const params = { + resourceIds: { + value: JSON.parse(this.element.dataset.selectedResources).join(','), + selectedAll: 'false', + key: keys.resourceIdsKey, + }, + selectedQuery: { + value: this.element.dataset.itemSelectAllSelectedAllQueryValue, + selectedAll: 'true', + key: keys.selectedQueryKey, + }, } document.querySelectorAll(selector).forEach((link) => { @@ -123,21 +127,16 @@ export default class extends Controller { .filter((key) => key.startsWith('fields[')) .forEach((key) => url.searchParams.delete(key)) - if (param === 'resourceIds') { - url.searchParams.set(keys.resourceIdsKey, resourceIds) - if (keys.selectedAllKey) { - url.searchParams.set(keys.selectedAllKey, 'false') - } - } else if (param === 'selectedQuery') { - url.searchParams.set(keys.selectedQueryKey, selectedQuery) - if (keys.selectedAllKey) { - url.searchParams.set(keys.selectedAllKey, 'true') - } + const current = params[param] + url.searchParams.set(current.key, current.value) + + if (keys.selectedAllKey) { + url.searchParams.set(keys.selectedAllKey, current.selectedAll) } link.href = url.toString() } catch (error) { - console.error('Error updating link:', link, error) + console.error(`Error updating link (${param}):`, link, error) } }) } From 750dd25cedd3836f5c68ffaf9634d958c5af0a6b Mon Sep 17 00:00:00 2001 From: Nevelito Date: Tue, 11 Mar 2025 10:02:30 +0100 Subject: [PATCH 10/19] fix codeclimate bugs --- app/controllers/avo/bulk_update_controller.rb | 83 ++++++++++++------- .../avo/templates/locales/avo.en.yml | 1 + 2 files changed, 55 insertions(+), 29 deletions(-) diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index 88f870dd42..3a819ff711 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -19,6 +19,7 @@ def handle if params_to_apply.blank? flash[:warning] = t("avo.no_changes_made") redirect_to after_bulk_update_path + return end updated_count, failed_records = update_records @@ -37,51 +38,71 @@ def handle def params_to_apply prefilled_params = params[:prefilled] || {} - - resource_key = @resource_name.downcase.to_sym - current_params = params[resource_key] || {} - - progress_fields = @resource - .get_field_definitions - .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } - .map(&:id) - .map(&:to_sym) + current_params = current_resource_params + progress_fields = progress_bar_fields current_params.reject do |key, value| key_sym = key.to_sym prefilled_value = prefilled_params[key_sym] - next true if progress_fields.include?(key_sym) && prefilled_value == "" && value.to_s == "50" - - prefilled_value.to_s == value.to_s + progress_field_with_default?(progress_fields, key_sym, prefilled_value, value) || + prefilled_value.to_s == value.to_s end end + def current_resource_params + resource_key = @resource_name.downcase.to_sym + params[resource_key] || {} + end + + def progress_bar_fields + @resource.get_field_definitions + .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } + .map(&:id) + .map(&:to_sym) + end + + def progress_field_with_default?(progress_fields, key_sym, prefilled_value, value) + progress_fields.include?(key_sym) && prefilled_value == "" && value.to_s == "50" + end + def update_records updated_count = 0 failed_records = [] @query.each do |record| - params_to_apply.each do |key, value| - record.public_send(:"#{key}=", value) - rescue => e - puts "Błąd przypisywania pola #{key}: #{e.message}" - end - - @resource.fill_record(record, params) - + update_record(record, params_to_apply) if record.save updated_count += 1 else - failed_records << {record: record, errors: record.errors.full_messages} + add_failed_record(failed_records, record) end rescue => e - failed_records << {record: record, errors: [e.message]} + add_failed_record(failed_records, record, e.message) end [updated_count, failed_records] end + def update_record(record, params_to_apply) + params_to_apply.each do |key, value| + record.public_send(:"#{key}=", value) + rescue => e + log_field_assignment_error(key, e.message) + end + + @resource.fill_record(record, params) + end + + def log_field_assignment_error(key, error_message) + puts "Błąd przypisywania pola #{key}: #{error_message}" + end + + def add_failed_record(failed_records, record, error_message = nil) + errors = error_message ? [error_message] : record.errors.full_messages + failed_records << { record: record, errors: errors } + end + def after_bulk_update_path resources_path(resource: @resource) end @@ -95,17 +116,21 @@ def prefill_fields(records, fields) end def set_query - if params[:query].present? - @query = @resource.find_record(params[:query], params: params) - else - resource_ids = action_params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] - @query = decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) - end + @query = if params[:query].present? + @resource.find_record(params[:query], params: params) + else + find_records_by_resource_ids + end + end + + def find_records_by_resource_ids + resource_ids = action_params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] + decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) end def set_fields if @query.blank? - flash[:error] = "Bulk update cannot be performed without records." + flash[:error] = I18n.t("avo.bulk_update_no_records") redirect_to after_bulk_update_path else @fields = @query.first.attributes.keys.index_with { nil } diff --git a/lib/generators/avo/templates/locales/avo.en.yml b/lib/generators/avo/templates/locales/avo.en.yml index bd6aa6c938..71dc4cdad9 100644 --- a/lib/generators/avo/templates/locales/avo.en.yml +++ b/lib/generators/avo/templates/locales/avo.en.yml @@ -18,6 +18,7 @@ en: attachment_failed: Failed to attach %{attachment_class} bulk_update_success: "%{count} records were successfully updated." bulk_update_failure: "Failed to update %{count} records. Errors: %{errors}" + bulk_update_no_records: Bulk update cannot be performed without records. cancel: Cancel choose_a_country: Choose a country choose_an_option: Choose an option From ec17628e7cf0f6840c6de5ea59a509248e9f3bb4 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Tue, 11 Mar 2025 10:37:25 +0100 Subject: [PATCH 11/19] fix bugs --- .../avo/views/resource_edit_component.rb | 28 +++++++++-------- app/controllers/avo/bulk_update_controller.rb | 30 ++++++------------- .../controllers/item_select_all_controller.js | 28 +++++++++-------- 3 files changed, 41 insertions(+), 45 deletions(-) diff --git a/app/components/avo/views/resource_edit_component.rb b/app/components/avo/views/resource_edit_component.rb index ef2af01ec8..c23f6e7672 100644 --- a/app/components/avo/views/resource_edit_component.rb +++ b/app/components/avo/views/resource_edit_component.rb @@ -26,20 +26,24 @@ def title end def back_path - return helpers.resources_path(resource: @resource) if params[:controller] == "avo/bulk_update" - - # The `return_to` param takes precedence over anything else. - return params[:return_to] if params[:return_to].present? - - return if via_belongs_to? - return resource_view_path if via_resource? - return resources_path if via_index? - - if is_edit? && Avo.configuration.resource_default_view.show? # via resource show or edit page - return helpers.resource_path(record: @resource.record, resource: @resource, **keep_referrer_params) + path = if params[:controller] == "avo/bulk_update" + helpers.resources_path(resource: @resource) + elsif params[:return_to].present? + # The `return_to` param takes precedence over anything else. + params[:return_to] + elsif via_belongs_to? + nil + elsif via_resource? + resource_view_path + elsif via_index? + resources_path + elsif is_edit? && Avo.configuration.resource_default_view.show? # via resource show or edit page + helpers.resource_path(record: @resource.record, resource: @resource, **keep_referrer_params) + else + resources_path end - resources_path + path end def resources_path diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index 3a819ff711..92b0cd4596 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -57,9 +57,9 @@ def current_resource_params def progress_bar_fields @resource.get_field_definitions - .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } - .map(&:id) - .map(&:to_sym) + .select { |field| field.is_a?(Avo::Fields::ProgressBarField) } + .map(&:id) + .map(&:to_sym) end def progress_field_with_default?(progress_fields, key_sym, prefilled_value, value) @@ -72,13 +72,7 @@ def update_records @query.each do |record| update_record(record, params_to_apply) - if record.save - updated_count += 1 - else - add_failed_record(failed_records, record) - end - rescue => e - add_failed_record(failed_records, record, e.message) + record.save ? updated_count += 1 : add_failed_record(failed_records, record) end [updated_count, failed_records] @@ -87,20 +81,14 @@ def update_records def update_record(record, params_to_apply) params_to_apply.each do |key, value| record.public_send(:"#{key}=", value) - rescue => e - log_field_assignment_error(key, e.message) end @resource.fill_record(record, params) end - def log_field_assignment_error(key, error_message) - puts "Błąd przypisywania pola #{key}: #{error_message}" - end - def add_failed_record(failed_records, record, error_message = nil) errors = error_message ? [error_message] : record.errors.full_messages - failed_records << { record: record, errors: errors } + failed_records << {record: record, errors: errors} end def after_bulk_update_path @@ -117,10 +105,10 @@ def prefill_fields(records, fields) def set_query @query = if params[:query].present? - @resource.find_record(params[:query], params: params) - else - find_records_by_resource_ids - end + @resource.find_record(params[:query], params: params) + else + find_records_by_resource_ids + end end def find_records_by_resource_ids diff --git a/app/javascript/js/controllers/item_select_all_controller.js b/app/javascript/js/controllers/item_select_all_controller.js index 0883a212b0..509390632f 100644 --- a/app/javascript/js/controllers/item_select_all_controller.js +++ b/app/javascript/js/controllers/item_select_all_controller.js @@ -106,18 +106,7 @@ export default class extends Controller { } updateActionLinks(param, selector, keys) { - const params = { - resourceIds: { - value: JSON.parse(this.element.dataset.selectedResources).join(','), - selectedAll: 'false', - key: keys.resourceIdsKey, - }, - selectedQuery: { - value: this.element.dataset.itemSelectAllSelectedAllQueryValue, - selectedAll: 'true', - key: keys.selectedQueryKey, - }, - } + const params = this.setLinkParams(keys) document.querySelectorAll(selector).forEach((link) => { try { @@ -141,6 +130,21 @@ export default class extends Controller { }) } + setLinkParams(keys) { + return { + resourceIds: { + value: JSON.parse(this.element.dataset.selectedResources).join(','), + selectedAll: 'false', + key: keys.resourceIdsKey, + }, + selectedQuery: { + value: this.element.dataset.itemSelectAllSelectedAllQueryValue, + selectedAll: 'true', + key: keys.selectedQueryKey, + }, + } + } + resetUnselected() { this.selectedAllValue = false this.unselectedMessageTarget.classList.remove('hidden') From 3d3b87db25cbac6f6535fb19789cb1f4aa42c466 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Tue, 11 Mar 2025 11:01:12 +0100 Subject: [PATCH 12/19] fix errors --- app/components/avo/views/resource_edit_component.rb | 4 +--- app/controllers/avo/bulk_update_controller.rb | 6 +++++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/app/components/avo/views/resource_edit_component.rb b/app/components/avo/views/resource_edit_component.rb index c23f6e7672..cf5a7aab5a 100644 --- a/app/components/avo/views/resource_edit_component.rb +++ b/app/components/avo/views/resource_edit_component.rb @@ -26,7 +26,7 @@ def title end def back_path - path = if params[:controller] == "avo/bulk_update" + if params[:controller] == "avo/bulk_update" helpers.resources_path(resource: @resource) elsif params[:return_to].present? # The `return_to` param takes precedence over anything else. @@ -42,8 +42,6 @@ def back_path else resources_path end - - path end def resources_path diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index 92b0cd4596..4a6e161d42 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -99,7 +99,11 @@ def prefill_fields(records, fields) fields.each_key.with_object({}) do |field_name, prefilled| values = records.map { |record| record.public_send(field_name) } values.uniq! - prefilled[field_name] = (values.size == 1 ? values.first : nil) + prefilled[field_name] = if values.size == 1 + values.first + else + nil + end end end From 669edcec38f97299cf01ff4c3e44388544820181 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Tue, 11 Mar 2025 11:12:10 +0100 Subject: [PATCH 13/19] fix standardrb errors --- app/controllers/avo/bulk_update_controller.rb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index 4a6e161d42..c7b99d0683 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -99,11 +99,7 @@ def prefill_fields(records, fields) fields.each_key.with_object({}) do |field_name, prefilled| values = records.map { |record| record.public_send(field_name) } values.uniq! - prefilled[field_name] = if values.size == 1 - values.first - else - nil - end + prefilled[field_name] = values.first if values.size == 1 end end From 154b062090ca655f09abd79c344198535c0750d6 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Tue, 11 Mar 2025 19:24:16 +0100 Subject: [PATCH 14/19] add locales --- lib/generators/avo/templates/locales/avo.ar.yml | 4 ++++ lib/generators/avo/templates/locales/avo.de.yml | 4 ++++ lib/generators/avo/templates/locales/avo.en.yml | 2 +- lib/generators/avo/templates/locales/avo.es.yml | 4 ++++ lib/generators/avo/templates/locales/avo.fr.yml | 4 ++++ lib/generators/avo/templates/locales/avo.it.yml | 4 ++++ lib/generators/avo/templates/locales/avo.ja.yml | 4 ++++ lib/generators/avo/templates/locales/avo.nb.yml | 4 ++++ lib/generators/avo/templates/locales/avo.nl.yml | 4 ++++ lib/generators/avo/templates/locales/avo.nn.yml | 4 ++++ lib/generators/avo/templates/locales/avo.pl.yml | 4 ++++ lib/generators/avo/templates/locales/avo.pt-BR.yml | 4 ++++ lib/generators/avo/templates/locales/avo.pt.yml | 4 ++++ lib/generators/avo/templates/locales/avo.ro.yml | 4 ++++ lib/generators/avo/templates/locales/avo.ru.yml | 4 ++++ lib/generators/avo/templates/locales/avo.tr.yml | 4 ++++ lib/generators/avo/templates/locales/avo.uk.yml | 4 ++++ lib/generators/avo/templates/locales/avo.zh.yml | 4 ++++ 18 files changed, 69 insertions(+), 1 deletion(-) diff --git a/lib/generators/avo/templates/locales/avo.ar.yml b/lib/generators/avo/templates/locales/avo.ar.yml index 00c5b43005..dc0c8bc880 100644 --- a/lib/generators/avo/templates/locales/avo.ar.yml +++ b/lib/generators/avo/templates/locales/avo.ar.yml @@ -22,6 +22,9 @@ ar: attachment_class_detached: "%{attachment_class} تم فصل" attachment_destroyed: تم حذف المرفق attachment_failed: فشل في إرفاق %{attachment_class} + bulk_update_success: "تم تحديث %{count} سجل بنجاح." + bulk_update_failure: "فشل في تحديث %{count} سجل. الأخطاء: %{errors}" + bulk_update_no_records: لا يمكن تنفيذ التحديث الجماعي بدون سجلات. cancel: إلغاء choose_a_country: اختر دولة choose_an_option: اختر خيارًا @@ -81,6 +84,7 @@ ar: next_page: الصفحة التالية no_cancel: لا، إلغاء no_cards_present: لا توجد بطاقات + no_changes_made: لم يتم إجراء أي تغييرات. no_item_found: لا يوجد سجلات no_options_available: لا توجد خيارات متاحة no_related_item_found: لم يتم العثور على سجلات متعلقة diff --git a/lib/generators/avo/templates/locales/avo.de.yml b/lib/generators/avo/templates/locales/avo.de.yml index 35ea2ff2c3..46612d0265 100644 --- a/lib/generators/avo/templates/locales/avo.de.yml +++ b/lib/generators/avo/templates/locales/avo.de.yml @@ -16,6 +16,9 @@ de: attachment_class_detached: "%{attachment_class} abgehängt." attachment_destroyed: Anhang gelöscht attachment_failed: "%{attachment_class} konnte nicht angehängt werden" + bulk_update_success: "%{count} Datensätze wurden erfolgreich aktualisiert." + bulk_update_failure: "Fehler beim Aktualisieren von %{count} Datensätzen. Fehler: %{errors}" + bulk_update_no_records: Massenaktualisierung kann nicht ohne Datensätze durchgeführt werden. cancel: Abbrechen choose_a_country: Land auswählen choose_an_option: Option auswählen @@ -71,6 +74,7 @@ de: next_page: Nächste Seite no_cancel: Nein, abbrechen no_cards_present: Keine Karten vorhanden + no_changes_made: Es wurden keine Änderungen vorgenommen. no_item_found: Kein Eintrag gefunden no_options_available: Keine Optionen verfügbar no_related_item_found: Kein zugehöriger Eintrag gefunden diff --git a/lib/generators/avo/templates/locales/avo.en.yml b/lib/generators/avo/templates/locales/avo.en.yml index 71dc4cdad9..8bcac3d710 100644 --- a/lib/generators/avo/templates/locales/avo.en.yml +++ b/lib/generators/avo/templates/locales/avo.en.yml @@ -73,8 +73,8 @@ en: new: new next_page: Next page no_cancel: No, cancel - no_changes_made: No changes were made. no_cards_present: No cards present + no_changes_made: No changes were made. no_item_found: No record found no_options_available: No options available no_related_item_found: No related record found diff --git a/lib/generators/avo/templates/locales/avo.es.yml b/lib/generators/avo/templates/locales/avo.es.yml index 3b26bfa1ef..adae2cf485 100644 --- a/lib/generators/avo/templates/locales/avo.es.yml +++ b/lib/generators/avo/templates/locales/avo.es.yml @@ -18,6 +18,9 @@ es: attachment_class_detached: "%{attachment_class} adjuntado/a." attachment_destroyed: Adjunto eliminado attachment_failed: No se pudo adjuntar %{attachment_class} + bulk_update_success: "%{count} registros se actualizaron correctamente." + bulk_update_failure: "No se pudieron actualizar %{count} registros. Errores: %{errors}" + bulk_update_no_records: No se puede realizar una actualización masiva sin registros. cancel: Cancelar choose_a_country: Elige un país choose_an_option: Elige una opción @@ -73,6 +76,7 @@ es: next_page: Página siguiente no_cancel: No, cancelar no_cards_present: No hay tarjetas + no_changes_made: No se realizaron cambios. no_item_found: No se ha encontrado ningún elemento no_options_available: No hay opciones disponibles no_related_item_found: No se ha encontrado ningún elemento relacionado diff --git a/lib/generators/avo/templates/locales/avo.fr.yml b/lib/generators/avo/templates/locales/avo.fr.yml index 64cf8360c8..5a54ca5d2a 100644 --- a/lib/generators/avo/templates/locales/avo.fr.yml +++ b/lib/generators/avo/templates/locales/avo.fr.yml @@ -18,6 +18,9 @@ fr: attachment_class_detached: "%{attachment_class} détaché." attachment_destroyed: Pièce jointe détruite attachment_failed: Échec de l'ajout de %{attachment_class} + bulk_update_success: "%{count} enregistrements ont été mis à jour avec succès." + bulk_update_failure: "Échec de la mise à jour de %{count} enregistrements. Erreurs : %{errors}" + bulk_update_no_records: La mise à jour en masse ne peut pas être effectuée sans enregistrements. cancel: Annuler choose_a_country: Sélectionnez un pays choose_an_option: Sélectionnez une option @@ -73,6 +76,7 @@ fr: next_page: Page suivante no_cancel: Non, annuler no_cards_present: Aucune carte présente + no_changes_made: Aucune modification n'a été effectuée. no_item_found: Enregistrement non trouvé no_options_available: Aucune option disponible no_related_item_found: Enregistrement connexe introuvable diff --git a/lib/generators/avo/templates/locales/avo.it.yml b/lib/generators/avo/templates/locales/avo.it.yml index 088ab48029..f6e345ddc9 100644 --- a/lib/generators/avo/templates/locales/avo.it.yml +++ b/lib/generators/avo/templates/locales/avo.it.yml @@ -16,6 +16,9 @@ it: attachment_class_detached: "%{attachment_class} staccato." attachment_destroyed: Allegato distrutto attachment_failed: Impossibile allegare %{attachment_class} + bulk_update_success: "%{count} record sono stati aggiornati con successo." + bulk_update_failure: "Impossibile aggiornare %{count} record. Errori: %{errors}" + bulk_update_no_records: L'aggiornamento di massa non può essere eseguito senza record. cancel: Annulla choose_a_country: Scegli un paese choose_an_option: Scegli un'opzione @@ -71,6 +74,7 @@ it: next_page: Pagina successiva no_cancel: No, annulla no_cards_present: Nessuna carta presente + no_changes_made: Non sono state apportate modifiche. no_item_found: Nessun record trovato no_options_available: Nessuna opzione disponibile no_related_item_found: Nessun record correlato trovato diff --git a/lib/generators/avo/templates/locales/avo.ja.yml b/lib/generators/avo/templates/locales/avo.ja.yml index 8b6516a595..365adaf36c 100644 --- a/lib/generators/avo/templates/locales/avo.ja.yml +++ b/lib/generators/avo/templates/locales/avo.ja.yml @@ -18,6 +18,9 @@ ja: attachment_class_detached: "%{attachment_class}をデタッチしました。" attachment_destroyed: アタッチは削除されました attachment_failed: "%{attachment_class}の添付に失敗しました" + bulk_update_success: "%{count} 件のレコードが正常に更新されました。" + bulk_update_failure: "%{count} 件のレコードの更新に失敗しました。エラー: %{errors}" + bulk_update_no_records: レコードなしでは一括更新を実行できません。 cancel: キャンセル choose_a_country: 国を選択 choose_an_option: オプションを選択 @@ -73,6 +76,7 @@ ja: next_page: 次のページ no_cancel: いいえ、キャンセル no_cards_present: カードがありません + no_changes_made: 変更はありませんでした。 no_item_found: レコードが見つかりませんでした no_options_available: 利用可能なオプションがありません no_related_item_found: 関連するレコードが見つかりませんでした diff --git a/lib/generators/avo/templates/locales/avo.nb.yml b/lib/generators/avo/templates/locales/avo.nb.yml index 3b5f59bb02..c64f1d7617 100644 --- a/lib/generators/avo/templates/locales/avo.nb.yml +++ b/lib/generators/avo/templates/locales/avo.nb.yml @@ -18,6 +18,9 @@ nb: attachment_class_detached: "%{attachment_class} fjernet." attachment_destroyed: Vedlett slettet attachment_failed: Kunne ikke legge ved %{attachment_class} + bulk_update_success: "%{count} poster ble oppdatert med hell." + bulk_update_failure: "Kunne ikke oppdatere %{count} poster. Feil: %{errors}" + bulk_update_no_records: Masseoppdatering kan ikke utføres uten poster. cancel: Avbryt choose_a_country: Velg et land choose_an_option: Velg et alternativ @@ -73,6 +76,7 @@ nb: next_page: Neste side no_cancel: Nei, avbryt no_cards_present: Ingen kort til stede + no_changes_made: Det ble ikke gjort noen endringer. no_item_found: Ingen funnet no_options_available: Ingen tilgjengelige alternativer no_related_item_found: Ingen relaterte funnet diff --git a/lib/generators/avo/templates/locales/avo.nl.yml b/lib/generators/avo/templates/locales/avo.nl.yml index dcaf35263c..8a280f818d 100644 --- a/lib/generators/avo/templates/locales/avo.nl.yml +++ b/lib/generators/avo/templates/locales/avo.nl.yml @@ -16,6 +16,9 @@ nl: attachment_class_detached: "%{attachment_class} losgekoppeld." attachment_destroyed: Bijlage verwijderd attachment_failed: Kon %{attachment_class} niet bijvoegen + bulk_update_success: "%{count} records zijn succesvol bijgewerkt." + bulk_update_failure: "Kon %{count} records niet bijwerken. Fouten: %{errors}" + bulk_update_no_records: Bulkupdate kan niet worden uitgevoerd zonder records. cancel: Annuleren choose_a_country: Kies een land choose_an_option: Kies een optie @@ -71,6 +74,7 @@ nl: next_page: Volgende pagina no_cancel: Nee, annuleren no_cards_present: Geen kaarten aanwezig + no_changes_made: Er zijn geen wijzigingen aangebracht. no_item_found: Geen item gevonden no_options_available: Geen opties beschikbaar no_related_item_found: Geen gerelateerd item gevonden diff --git a/lib/generators/avo/templates/locales/avo.nn.yml b/lib/generators/avo/templates/locales/avo.nn.yml index e5b9098427..5e7fd63b92 100644 --- a/lib/generators/avo/templates/locales/avo.nn.yml +++ b/lib/generators/avo/templates/locales/avo.nn.yml @@ -18,6 +18,9 @@ nn: attachment_class_detached: "%{attachment_class} fjerna." attachment_destroyed: Vedlegg sletta attachment_failed: Klarte ikkje å legge ved %{attachment_class} + bulk_update_success: "%{count} postane blei oppdatert med suksess." + bulk_update_failure: "Kunne ikkje oppdatere %{count} postane. Feil: %{errors}" + bulk_update_no_records: Masseoppdatering kan ikkje gjennomførast utan postar. cancel: Avbryt choose_a_country: Vel eit land choose_an_option: Vel eit alternativ @@ -73,6 +76,7 @@ nn: next_page: Neste side no_cancel: Nei, avbryt no_cards_present: Ingen kort til stades + no_changes_made: Det vart ikkje gjort nokon endringar. no_item_found: Fann ingen no_options_available: Ingen tilgjengelege alternativ no_related_item_found: Fann ingen relaterte diff --git a/lib/generators/avo/templates/locales/avo.pl.yml b/lib/generators/avo/templates/locales/avo.pl.yml index 4f3a0189da..6d44a63fc9 100644 --- a/lib/generators/avo/templates/locales/avo.pl.yml +++ b/lib/generators/avo/templates/locales/avo.pl.yml @@ -16,6 +16,9 @@ pl: attachment_class_detached: "%{attachment_class} odłączony." attachment_destroyed: Załącznik usunięty attachment_failed: Nie udało się dołączyć %{attachment_class} + bulk_update_success: "%{count} rekordów zostało pomyślnie zaktualizowanych." + bulk_update_failure: "Nie udało się zaktualizować %{count} rekordów. Błędy: %{errors}" + bulk_update_no_records: Aktualizacja zbiorcza nie może zostać wykonana bez rekordów. cancel: Anuluj choose_a_country: Wybierz kraj choose_an_option: Wybierz opcję @@ -73,6 +76,7 @@ pl: next_page: Następna strona no_cancel: Nie, anuluj no_cards_present: Brak kart + no_changes_made: Nie wprowadzono żadnych zmian. no_item_found: Nie znaleziono rekordu no_options_available: Brak dostępnych opcji no_related_item_found: Nie znaleziono powiązanego rekordu diff --git a/lib/generators/avo/templates/locales/avo.pt-BR.yml b/lib/generators/avo/templates/locales/avo.pt-BR.yml index 82d220bb10..43dd4cb7e9 100644 --- a/lib/generators/avo/templates/locales/avo.pt-BR.yml +++ b/lib/generators/avo/templates/locales/avo.pt-BR.yml @@ -18,6 +18,9 @@ pt-BR: attachment_class_detached: "%{attachment_class} separado." attachment_destroyed: Anexo destruído attachment_failed: Não foi possível anexar %{attachment_class} + bulk_update_success: "%{count} registros foram atualizados com sucesso." + bulk_update_failure: "Falha ao atualizar %{count} registros. Erros: %{errors}" + bulk_update_no_records: A atualização em massa não pode ser realizada sem registros. cancel: Cancelar choose_a_country: Escolha um país choose_an_option: Escolha uma opção @@ -73,6 +76,7 @@ pt-BR: next_page: Próxima página no_cancel: Não, cancelar no_cards_present: Nenhum cartão presente + no_changes_made: Nenhuma alteração foi feita. no_item_found: Nenhum registro encontrado no_options_available: Nenhuma opção disponível no_related_item_found: Nenhum registro relacionado encontrado diff --git a/lib/generators/avo/templates/locales/avo.pt.yml b/lib/generators/avo/templates/locales/avo.pt.yml index bb163a138d..8457f25fde 100644 --- a/lib/generators/avo/templates/locales/avo.pt.yml +++ b/lib/generators/avo/templates/locales/avo.pt.yml @@ -18,6 +18,9 @@ pt: attachment_class_detached: "%{attachment_class} separado." attachment_destroyed: Anexo destruído attachment_failed: Não foi possível anexar %{attachment_class} + bulk_update_success: "%{count} registros foram atualizados com sucesso." + bulk_update_failure: "Falha ao atualizar %{count} registros. Erros: %{errors}" + bulk_update_no_records: Não é possível realizar a atualização em massa sem registros. cancel: Cancelar choose_a_country: Escolha um país choose_an_option: Escolha uma opção @@ -73,6 +76,7 @@ pt: next_page: Próxima página no_cancel: Não, cancelar no_cards_present: Nenhum cartão presente + no_changes_made: Nenhuma alteração foi feita. no_item_found: Nenhum registro encontrado no_options_available: Nenhuma opção disponível no_related_item_found: Nenhum registro relacionado encontrado diff --git a/lib/generators/avo/templates/locales/avo.ro.yml b/lib/generators/avo/templates/locales/avo.ro.yml index 027d0fff1d..b12f54ba47 100644 --- a/lib/generators/avo/templates/locales/avo.ro.yml +++ b/lib/generators/avo/templates/locales/avo.ro.yml @@ -19,6 +19,9 @@ ro: attachment_class_detached: "%{attachment_class} separat." attachment_destroyed: Atașamentul a fost distrus attachment_failed: Nu s-a reușit atașarea %{attachment_class} + bulk_update_success: "%{count} înregistrări au fost actualizate cu succes." + bulk_update_failure: "Nu s-au putut actualiza %{count} înregistrări. Erori: %{errors}" + bulk_update_no_records: Actualizarea în masă nu poate fi efectuată fără înregistrări. cancel: Anulează choose_a_country: Alege o țară choose_an_option: Alege o opțiune @@ -75,6 +78,7 @@ ro: next_page: Pagina următoare no_cancel: Nu, anulează no_cards_present: Nici un card găsit + no_changes_made: Nu s-au făcut modificări. no_item_found: Nici un articol găsit no_options_available: Nicio opțiune disponibilă no_related_item_found: Nici un articol asociat găsit diff --git a/lib/generators/avo/templates/locales/avo.ru.yml b/lib/generators/avo/templates/locales/avo.ru.yml index f939543240..74261d65e2 100644 --- a/lib/generators/avo/templates/locales/avo.ru.yml +++ b/lib/generators/avo/templates/locales/avo.ru.yml @@ -16,6 +16,9 @@ ru: attachment_class_detached: "%{attachment_class} отсоединено." attachment_destroyed: Вложение удалено attachment_failed: Не удалось прикрепить %{attachment_class} + bulk_update_success: "%{count} записей успешно обновлено." + bulk_update_failure: "Не удалось обновить %{count} записей. Ошибки: %{errors}" + bulk_update_no_records: Массовое обновление не может быть выполнено без записей. cancel: Отмена choose_a_country: Выберите страну choose_an_option: Выберите опцию @@ -73,6 +76,7 @@ ru: next_page: Следующая страница no_cancel: Нет, отмена no_cards_present: Нет карточек + no_changes_made: Изменений не было внесено. no_item_found: Запись не найдена no_options_available: Опции недоступны no_related_item_found: Связанная запись не найдена diff --git a/lib/generators/avo/templates/locales/avo.tr.yml b/lib/generators/avo/templates/locales/avo.tr.yml index edfcc498cb..79a918c9df 100644 --- a/lib/generators/avo/templates/locales/avo.tr.yml +++ b/lib/generators/avo/templates/locales/avo.tr.yml @@ -18,6 +18,9 @@ tr: attachment_class_detached: "%{attachment_class} ilişkisi kesildi." attachment_destroyed: Ek silindi attachment_failed: "%{attachment_class} eklenemedi" + bulk_update_success: "%{count} kayıt başarıyla güncellendi." + bulk_update_failure: "%{count} kayıt güncellenemedi. Hatalar: %{errors}" + bulk_update_no_records: Kayıt olmadan toplu güncelleme yapılamaz. cancel: İptal et choose_a_country: Bir ülke seç choose_an_option: Bir seçenek seç @@ -73,6 +76,7 @@ tr: next_page: Sonraki sayfa no_cancel: Hayır, iptal et no_cards_present: Kart yok + no_changes_made: Hiçbir değişiklik yapılmadı. no_item_found: Hiç bulunamadı no_options_available: Seçenek yok no_related_item_found: İlişkili bulunamadı diff --git a/lib/generators/avo/templates/locales/avo.uk.yml b/lib/generators/avo/templates/locales/avo.uk.yml index 4fdc4a0724..4435c470ee 100644 --- a/lib/generators/avo/templates/locales/avo.uk.yml +++ b/lib/generators/avo/templates/locales/avo.uk.yml @@ -16,6 +16,9 @@ uk: attachment_class_detached: "%{attachment_class} відкріплено." attachment_destroyed: Вкладення знищено attachment_failed: Не вдалося прикріпити %{attachment_class} + bulk_update_success: "%{count} записів було успішно оновлено." + bulk_update_failure: "Не вдалося оновити %{count} записів. Помилки: %{errors}" + bulk_update_no_records: Масове оновлення не можна виконати без записів. cancel: Скасувати choose_a_country: Виберіть країну choose_an_option: Виберіть опцію @@ -73,6 +76,7 @@ uk: next_page: Наступна сторінка no_cancel: Ні, скасувати no_cards_present: Немає карток + no_changes_made: Змін не було внесено. no_item_found: Запис не знайдено no_options_available: Немає доступних опцій no_related_item_found: Пов'язані записи не знайдені diff --git a/lib/generators/avo/templates/locales/avo.zh.yml b/lib/generators/avo/templates/locales/avo.zh.yml index 5910022bc0..df599ff096 100644 --- a/lib/generators/avo/templates/locales/avo.zh.yml +++ b/lib/generators/avo/templates/locales/avo.zh.yml @@ -16,6 +16,9 @@ zh: attachment_class_detached: "%{attachment_class} 已分离。" attachment_destroyed: 附件已删除 attachment_failed: 无法附加 %{attachment_class} + bulk_update_success: "%{count} 条记录已成功更新。" + bulk_update_failure: "更新 %{count} 条记录失败。错误:%{errors}" + bulk_update_no_records: 没有记录,无法执行批量更新。 cancel: 取消 choose_a_country: 选择一个国家 choose_an_option: 选择一个选项 @@ -71,6 +74,7 @@ zh: next_page: 下一页 no_cancel: 不,取消 no_cards_present: 没有卡片 + no_changes_made: 未做任何更改。 no_item_found: 找不到记录 no_options_available: 没有可用选项 no_related_item_found: 找不到相关记录 From fd56fe0b0aa2555f5fcaf1c51d723b2c8c6a293c Mon Sep 17 00:00:00 2001 From: Nevelito Date: Tue, 11 Mar 2025 19:33:27 +0100 Subject: [PATCH 15/19] normilize locales --- lib/generators/avo/templates/locales/avo.ar.yml | 4 ++-- lib/generators/avo/templates/locales/avo.de.yml | 4 ++-- lib/generators/avo/templates/locales/avo.en.yml | 4 ++-- lib/generators/avo/templates/locales/avo.es.yml | 4 ++-- lib/generators/avo/templates/locales/avo.fr.yml | 4 ++-- lib/generators/avo/templates/locales/avo.it.yml | 4 ++-- lib/generators/avo/templates/locales/avo.ja.yml | 2 +- lib/generators/avo/templates/locales/avo.nb.yml | 4 ++-- lib/generators/avo/templates/locales/avo.nl.yml | 4 ++-- lib/generators/avo/templates/locales/avo.nn.yml | 4 ++-- lib/generators/avo/templates/locales/avo.pl.yml | 4 ++-- lib/generators/avo/templates/locales/avo.pt-BR.yml | 4 ++-- lib/generators/avo/templates/locales/avo.pt.yml | 4 ++-- lib/generators/avo/templates/locales/avo.ro.yml | 4 ++-- lib/generators/avo/templates/locales/avo.ru.yml | 4 ++-- lib/generators/avo/templates/locales/avo.tr.yml | 2 +- lib/generators/avo/templates/locales/avo.uk.yml | 4 ++-- lib/generators/avo/templates/locales/avo.zh.yml | 4 ++-- 18 files changed, 34 insertions(+), 34 deletions(-) diff --git a/lib/generators/avo/templates/locales/avo.ar.yml b/lib/generators/avo/templates/locales/avo.ar.yml index dc0c8bc880..8937c2c281 100644 --- a/lib/generators/avo/templates/locales/avo.ar.yml +++ b/lib/generators/avo/templates/locales/avo.ar.yml @@ -22,9 +22,9 @@ ar: attachment_class_detached: "%{attachment_class} تم فصل" attachment_destroyed: تم حذف المرفق attachment_failed: فشل في إرفاق %{attachment_class} - bulk_update_success: "تم تحديث %{count} سجل بنجاح." - bulk_update_failure: "فشل في تحديث %{count} سجل. الأخطاء: %{errors}" + bulk_update_failure: 'فشل في تحديث %{count} سجل. الأخطاء: %{errors}' bulk_update_no_records: لا يمكن تنفيذ التحديث الجماعي بدون سجلات. + bulk_update_success: تم تحديث %{count} سجل بنجاح. cancel: إلغاء choose_a_country: اختر دولة choose_an_option: اختر خيارًا diff --git a/lib/generators/avo/templates/locales/avo.de.yml b/lib/generators/avo/templates/locales/avo.de.yml index 46612d0265..52b1cffedd 100644 --- a/lib/generators/avo/templates/locales/avo.de.yml +++ b/lib/generators/avo/templates/locales/avo.de.yml @@ -16,9 +16,9 @@ de: attachment_class_detached: "%{attachment_class} abgehängt." attachment_destroyed: Anhang gelöscht attachment_failed: "%{attachment_class} konnte nicht angehängt werden" - bulk_update_success: "%{count} Datensätze wurden erfolgreich aktualisiert." - bulk_update_failure: "Fehler beim Aktualisieren von %{count} Datensätzen. Fehler: %{errors}" + bulk_update_failure: 'Fehler beim Aktualisieren von %{count} Datensätzen. Fehler: %{errors}' bulk_update_no_records: Massenaktualisierung kann nicht ohne Datensätze durchgeführt werden. + bulk_update_success: "%{count} Datensätze wurden erfolgreich aktualisiert." cancel: Abbrechen choose_a_country: Land auswählen choose_an_option: Option auswählen diff --git a/lib/generators/avo/templates/locales/avo.en.yml b/lib/generators/avo/templates/locales/avo.en.yml index 8bcac3d710..cd8bc1bd97 100644 --- a/lib/generators/avo/templates/locales/avo.en.yml +++ b/lib/generators/avo/templates/locales/avo.en.yml @@ -16,9 +16,9 @@ en: attachment_class_detached: "%{attachment_class} detached." attachment_destroyed: Attachment destroyed attachment_failed: Failed to attach %{attachment_class} - bulk_update_success: "%{count} records were successfully updated." - bulk_update_failure: "Failed to update %{count} records. Errors: %{errors}" + bulk_update_failure: 'Failed to update %{count} records. Errors: %{errors}' bulk_update_no_records: Bulk update cannot be performed without records. + bulk_update_success: "%{count} records were successfully updated." cancel: Cancel choose_a_country: Choose a country choose_an_option: Choose an option diff --git a/lib/generators/avo/templates/locales/avo.es.yml b/lib/generators/avo/templates/locales/avo.es.yml index adae2cf485..d87dc2ee3d 100644 --- a/lib/generators/avo/templates/locales/avo.es.yml +++ b/lib/generators/avo/templates/locales/avo.es.yml @@ -18,9 +18,9 @@ es: attachment_class_detached: "%{attachment_class} adjuntado/a." attachment_destroyed: Adjunto eliminado attachment_failed: No se pudo adjuntar %{attachment_class} - bulk_update_success: "%{count} registros se actualizaron correctamente." - bulk_update_failure: "No se pudieron actualizar %{count} registros. Errores: %{errors}" + bulk_update_failure: 'No se pudieron actualizar %{count} registros. Errores: %{errors}' bulk_update_no_records: No se puede realizar una actualización masiva sin registros. + bulk_update_success: "%{count} registros se actualizaron correctamente." cancel: Cancelar choose_a_country: Elige un país choose_an_option: Elige una opción diff --git a/lib/generators/avo/templates/locales/avo.fr.yml b/lib/generators/avo/templates/locales/avo.fr.yml index 5a54ca5d2a..c420e2c13f 100644 --- a/lib/generators/avo/templates/locales/avo.fr.yml +++ b/lib/generators/avo/templates/locales/avo.fr.yml @@ -18,9 +18,9 @@ fr: attachment_class_detached: "%{attachment_class} détaché." attachment_destroyed: Pièce jointe détruite attachment_failed: Échec de l'ajout de %{attachment_class} - bulk_update_success: "%{count} enregistrements ont été mis à jour avec succès." - bulk_update_failure: "Échec de la mise à jour de %{count} enregistrements. Erreurs : %{errors}" + bulk_update_failure: 'Échec de la mise à jour de %{count} enregistrements. Erreurs : %{errors}' bulk_update_no_records: La mise à jour en masse ne peut pas être effectuée sans enregistrements. + bulk_update_success: "%{count} enregistrements ont été mis à jour avec succès." cancel: Annuler choose_a_country: Sélectionnez un pays choose_an_option: Sélectionnez une option diff --git a/lib/generators/avo/templates/locales/avo.it.yml b/lib/generators/avo/templates/locales/avo.it.yml index f6e345ddc9..a67ec887a2 100644 --- a/lib/generators/avo/templates/locales/avo.it.yml +++ b/lib/generators/avo/templates/locales/avo.it.yml @@ -16,9 +16,9 @@ it: attachment_class_detached: "%{attachment_class} staccato." attachment_destroyed: Allegato distrutto attachment_failed: Impossibile allegare %{attachment_class} - bulk_update_success: "%{count} record sono stati aggiornati con successo." - bulk_update_failure: "Impossibile aggiornare %{count} record. Errori: %{errors}" + bulk_update_failure: 'Impossibile aggiornare %{count} record. Errori: %{errors}' bulk_update_no_records: L'aggiornamento di massa non può essere eseguito senza record. + bulk_update_success: "%{count} record sono stati aggiornati con successo." cancel: Annulla choose_a_country: Scegli un paese choose_an_option: Scegli un'opzione diff --git a/lib/generators/avo/templates/locales/avo.ja.yml b/lib/generators/avo/templates/locales/avo.ja.yml index 365adaf36c..e27ebbc556 100644 --- a/lib/generators/avo/templates/locales/avo.ja.yml +++ b/lib/generators/avo/templates/locales/avo.ja.yml @@ -18,9 +18,9 @@ ja: attachment_class_detached: "%{attachment_class}をデタッチしました。" attachment_destroyed: アタッチは削除されました attachment_failed: "%{attachment_class}の添付に失敗しました" - bulk_update_success: "%{count} 件のレコードが正常に更新されました。" bulk_update_failure: "%{count} 件のレコードの更新に失敗しました。エラー: %{errors}" bulk_update_no_records: レコードなしでは一括更新を実行できません。 + bulk_update_success: "%{count} 件のレコードが正常に更新されました。" cancel: キャンセル choose_a_country: 国を選択 choose_an_option: オプションを選択 diff --git a/lib/generators/avo/templates/locales/avo.nb.yml b/lib/generators/avo/templates/locales/avo.nb.yml index c64f1d7617..6a61cd4b84 100644 --- a/lib/generators/avo/templates/locales/avo.nb.yml +++ b/lib/generators/avo/templates/locales/avo.nb.yml @@ -18,9 +18,9 @@ nb: attachment_class_detached: "%{attachment_class} fjernet." attachment_destroyed: Vedlett slettet attachment_failed: Kunne ikke legge ved %{attachment_class} - bulk_update_success: "%{count} poster ble oppdatert med hell." - bulk_update_failure: "Kunne ikke oppdatere %{count} poster. Feil: %{errors}" + bulk_update_failure: 'Kunne ikke oppdatere %{count} poster. Feil: %{errors}' bulk_update_no_records: Masseoppdatering kan ikke utføres uten poster. + bulk_update_success: "%{count} poster ble oppdatert med hell." cancel: Avbryt choose_a_country: Velg et land choose_an_option: Velg et alternativ diff --git a/lib/generators/avo/templates/locales/avo.nl.yml b/lib/generators/avo/templates/locales/avo.nl.yml index 8a280f818d..1bf09488ba 100644 --- a/lib/generators/avo/templates/locales/avo.nl.yml +++ b/lib/generators/avo/templates/locales/avo.nl.yml @@ -16,9 +16,9 @@ nl: attachment_class_detached: "%{attachment_class} losgekoppeld." attachment_destroyed: Bijlage verwijderd attachment_failed: Kon %{attachment_class} niet bijvoegen - bulk_update_success: "%{count} records zijn succesvol bijgewerkt." - bulk_update_failure: "Kon %{count} records niet bijwerken. Fouten: %{errors}" + bulk_update_failure: 'Kon %{count} records niet bijwerken. Fouten: %{errors}' bulk_update_no_records: Bulkupdate kan niet worden uitgevoerd zonder records. + bulk_update_success: "%{count} records zijn succesvol bijgewerkt." cancel: Annuleren choose_a_country: Kies een land choose_an_option: Kies een optie diff --git a/lib/generators/avo/templates/locales/avo.nn.yml b/lib/generators/avo/templates/locales/avo.nn.yml index 5e7fd63b92..436b25615a 100644 --- a/lib/generators/avo/templates/locales/avo.nn.yml +++ b/lib/generators/avo/templates/locales/avo.nn.yml @@ -18,9 +18,9 @@ nn: attachment_class_detached: "%{attachment_class} fjerna." attachment_destroyed: Vedlegg sletta attachment_failed: Klarte ikkje å legge ved %{attachment_class} - bulk_update_success: "%{count} postane blei oppdatert med suksess." - bulk_update_failure: "Kunne ikkje oppdatere %{count} postane. Feil: %{errors}" + bulk_update_failure: 'Kunne ikkje oppdatere %{count} postane. Feil: %{errors}' bulk_update_no_records: Masseoppdatering kan ikkje gjennomførast utan postar. + bulk_update_success: "%{count} postane blei oppdatert med suksess." cancel: Avbryt choose_a_country: Vel eit land choose_an_option: Vel eit alternativ diff --git a/lib/generators/avo/templates/locales/avo.pl.yml b/lib/generators/avo/templates/locales/avo.pl.yml index 6d44a63fc9..05b48e71aa 100644 --- a/lib/generators/avo/templates/locales/avo.pl.yml +++ b/lib/generators/avo/templates/locales/avo.pl.yml @@ -16,9 +16,9 @@ pl: attachment_class_detached: "%{attachment_class} odłączony." attachment_destroyed: Załącznik usunięty attachment_failed: Nie udało się dołączyć %{attachment_class} - bulk_update_success: "%{count} rekordów zostało pomyślnie zaktualizowanych." - bulk_update_failure: "Nie udało się zaktualizować %{count} rekordów. Błędy: %{errors}" + bulk_update_failure: 'Nie udało się zaktualizować %{count} rekordów. Błędy: %{errors}' bulk_update_no_records: Aktualizacja zbiorcza nie może zostać wykonana bez rekordów. + bulk_update_success: "%{count} rekordów zostało pomyślnie zaktualizowanych." cancel: Anuluj choose_a_country: Wybierz kraj choose_an_option: Wybierz opcję diff --git a/lib/generators/avo/templates/locales/avo.pt-BR.yml b/lib/generators/avo/templates/locales/avo.pt-BR.yml index 43dd4cb7e9..1d85240187 100644 --- a/lib/generators/avo/templates/locales/avo.pt-BR.yml +++ b/lib/generators/avo/templates/locales/avo.pt-BR.yml @@ -18,9 +18,9 @@ pt-BR: attachment_class_detached: "%{attachment_class} separado." attachment_destroyed: Anexo destruído attachment_failed: Não foi possível anexar %{attachment_class} - bulk_update_success: "%{count} registros foram atualizados com sucesso." - bulk_update_failure: "Falha ao atualizar %{count} registros. Erros: %{errors}" + bulk_update_failure: 'Falha ao atualizar %{count} registros. Erros: %{errors}' bulk_update_no_records: A atualização em massa não pode ser realizada sem registros. + bulk_update_success: "%{count} registros foram atualizados com sucesso." cancel: Cancelar choose_a_country: Escolha um país choose_an_option: Escolha uma opção diff --git a/lib/generators/avo/templates/locales/avo.pt.yml b/lib/generators/avo/templates/locales/avo.pt.yml index 8457f25fde..a88a449008 100644 --- a/lib/generators/avo/templates/locales/avo.pt.yml +++ b/lib/generators/avo/templates/locales/avo.pt.yml @@ -18,9 +18,9 @@ pt: attachment_class_detached: "%{attachment_class} separado." attachment_destroyed: Anexo destruído attachment_failed: Não foi possível anexar %{attachment_class} - bulk_update_success: "%{count} registros foram atualizados com sucesso." - bulk_update_failure: "Falha ao atualizar %{count} registros. Erros: %{errors}" + bulk_update_failure: 'Falha ao atualizar %{count} registros. Erros: %{errors}' bulk_update_no_records: Não é possível realizar a atualização em massa sem registros. + bulk_update_success: "%{count} registros foram atualizados com sucesso." cancel: Cancelar choose_a_country: Escolha um país choose_an_option: Escolha uma opção diff --git a/lib/generators/avo/templates/locales/avo.ro.yml b/lib/generators/avo/templates/locales/avo.ro.yml index b12f54ba47..2cef4b861b 100644 --- a/lib/generators/avo/templates/locales/avo.ro.yml +++ b/lib/generators/avo/templates/locales/avo.ro.yml @@ -19,9 +19,9 @@ ro: attachment_class_detached: "%{attachment_class} separat." attachment_destroyed: Atașamentul a fost distrus attachment_failed: Nu s-a reușit atașarea %{attachment_class} - bulk_update_success: "%{count} înregistrări au fost actualizate cu succes." - bulk_update_failure: "Nu s-au putut actualiza %{count} înregistrări. Erori: %{errors}" + bulk_update_failure: 'Nu s-au putut actualiza %{count} înregistrări. Erori: %{errors}' bulk_update_no_records: Actualizarea în masă nu poate fi efectuată fără înregistrări. + bulk_update_success: "%{count} înregistrări au fost actualizate cu succes." cancel: Anulează choose_a_country: Alege o țară choose_an_option: Alege o opțiune diff --git a/lib/generators/avo/templates/locales/avo.ru.yml b/lib/generators/avo/templates/locales/avo.ru.yml index 74261d65e2..179a517438 100644 --- a/lib/generators/avo/templates/locales/avo.ru.yml +++ b/lib/generators/avo/templates/locales/avo.ru.yml @@ -16,9 +16,9 @@ ru: attachment_class_detached: "%{attachment_class} отсоединено." attachment_destroyed: Вложение удалено attachment_failed: Не удалось прикрепить %{attachment_class} - bulk_update_success: "%{count} записей успешно обновлено." - bulk_update_failure: "Не удалось обновить %{count} записей. Ошибки: %{errors}" + bulk_update_failure: 'Не удалось обновить %{count} записей. Ошибки: %{errors}' bulk_update_no_records: Массовое обновление не может быть выполнено без записей. + bulk_update_success: "%{count} записей успешно обновлено." cancel: Отмена choose_a_country: Выберите страну choose_an_option: Выберите опцию diff --git a/lib/generators/avo/templates/locales/avo.tr.yml b/lib/generators/avo/templates/locales/avo.tr.yml index 79a918c9df..cc69f4c754 100644 --- a/lib/generators/avo/templates/locales/avo.tr.yml +++ b/lib/generators/avo/templates/locales/avo.tr.yml @@ -18,9 +18,9 @@ tr: attachment_class_detached: "%{attachment_class} ilişkisi kesildi." attachment_destroyed: Ek silindi attachment_failed: "%{attachment_class} eklenemedi" - bulk_update_success: "%{count} kayıt başarıyla güncellendi." bulk_update_failure: "%{count} kayıt güncellenemedi. Hatalar: %{errors}" bulk_update_no_records: Kayıt olmadan toplu güncelleme yapılamaz. + bulk_update_success: "%{count} kayıt başarıyla güncellendi." cancel: İptal et choose_a_country: Bir ülke seç choose_an_option: Bir seçenek seç diff --git a/lib/generators/avo/templates/locales/avo.uk.yml b/lib/generators/avo/templates/locales/avo.uk.yml index 4435c470ee..a11c2e929a 100644 --- a/lib/generators/avo/templates/locales/avo.uk.yml +++ b/lib/generators/avo/templates/locales/avo.uk.yml @@ -16,9 +16,9 @@ uk: attachment_class_detached: "%{attachment_class} відкріплено." attachment_destroyed: Вкладення знищено attachment_failed: Не вдалося прикріпити %{attachment_class} - bulk_update_success: "%{count} записів було успішно оновлено." - bulk_update_failure: "Не вдалося оновити %{count} записів. Помилки: %{errors}" + bulk_update_failure: 'Не вдалося оновити %{count} записів. Помилки: %{errors}' bulk_update_no_records: Масове оновлення не можна виконати без записів. + bulk_update_success: "%{count} записів було успішно оновлено." cancel: Скасувати choose_a_country: Виберіть країну choose_an_option: Виберіть опцію diff --git a/lib/generators/avo/templates/locales/avo.zh.yml b/lib/generators/avo/templates/locales/avo.zh.yml index df599ff096..1b3c5112b9 100644 --- a/lib/generators/avo/templates/locales/avo.zh.yml +++ b/lib/generators/avo/templates/locales/avo.zh.yml @@ -16,9 +16,9 @@ zh: attachment_class_detached: "%{attachment_class} 已分离。" attachment_destroyed: 附件已删除 attachment_failed: 无法附加 %{attachment_class} - bulk_update_success: "%{count} 条记录已成功更新。" - bulk_update_failure: "更新 %{count} 条记录失败。错误:%{errors}" + bulk_update_failure: 更新 %{count} 条记录失败。错误:%{errors} bulk_update_no_records: 没有记录,无法执行批量更新。 + bulk_update_success: "%{count} 条记录已成功更新。" cancel: 取消 choose_a_country: 选择一个国家 choose_an_option: 选择一个选项 From 182c52234ff0c3d706780f299bc7e0b4958dbea3 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Wed, 12 Mar 2025 18:34:06 +0100 Subject: [PATCH 16/19] changes locales, add specs, optymalize code --- .../avo/views/resource_index_component.rb | 4 +- app/controllers/avo/base_controller.rb | 16 +++- app/controllers/avo/bulk_update_controller.rb | 95 ++++++++----------- .../avo/templates/locales/avo.ar.yml | 7 +- .../avo/templates/locales/avo.de.yml | 9 +- .../avo/templates/locales/avo.en.yml | 7 +- .../avo/templates/locales/avo.es.yml | 9 +- .../avo/templates/locales/avo.fr.yml | 7 +- .../avo/templates/locales/avo.it.yml | 7 +- .../avo/templates/locales/avo.ja.yml | 9 +- .../avo/templates/locales/avo.nb.yml | 9 +- .../avo/templates/locales/avo.nl.yml | 9 +- .../avo/templates/locales/avo.nn.yml | 9 +- .../avo/templates/locales/avo.pl.yml | 7 +- .../avo/templates/locales/avo.pt-BR.yml | 7 +- .../avo/templates/locales/avo.pt.yml | 9 +- .../avo/templates/locales/avo.ro.yml | 7 +- .../avo/templates/locales/avo.ru.yml | 7 +- .../avo/templates/locales/avo.tr.yml | 9 +- .../avo/templates/locales/avo.uk.yml | 9 +- .../avo/templates/locales/avo.zh.yml | 9 +- spec/system/avo/bulk_update_spec.rb | 84 ++++++++++++++++ 22 files changed, 220 insertions(+), 125 deletions(-) create mode 100644 spec/system/avo/bulk_update_spec.rb diff --git a/app/components/avo/views/resource_index_component.rb b/app/components/avo/views/resource_index_component.rb index 910e7b3cf8..559dbcf45c 100644 --- a/app/components/avo/views/resource_index_component.rb +++ b/app/components/avo/views/resource_index_component.rb @@ -170,12 +170,12 @@ def render_dynamic_filters_button end def render_bulk_update_button - a_link helpers.edit_bulk_update_path(resource_name: @resource.name, id: 4), + a_link helpers.edit_bulk_update_path(resource_name: @resource.name), style: :primary, color: :primary, icon: "avo/edit", form_class: "flex flex-col sm:flex-row sm:inline-flex" do - "Bulk update" + I18n.t("avo.bulk_update") end end diff --git a/app/controllers/avo/base_controller.rb b/app/controllers/avo/base_controller.rb index 94224ee380..20ce127b80 100644 --- a/app/controllers/avo/base_controller.rb +++ b/app/controllers/avo/base_controller.rb @@ -7,7 +7,7 @@ class BaseController < ApplicationController before_action :set_resource_name before_action :set_resource before_action :set_applied_filters, only: :index - before_action :set_record, only: [:show, :edit, :destroy, :update, :preview] + before_action :set_record, only: [:show, :edit, :destroy, :update, :preview], if: -> { controller_name != "bulk_update" } before_action :set_record_to_fill, only: [:new, :edit, :create, :update] before_action :detect_fields before_action :set_edit_title_and_breadcrumbs, only: [:edit, :update] @@ -416,8 +416,10 @@ def filters_to_be_applied end def set_edit_title_and_breadcrumbs - @resource = @resource.hydrate(record: @record, view: Avo::ViewInquirer.new(:edit), user: _current_user) - @page_title = @resource.default_panel_name.to_s + if params[:controller] != "avo/bulk_update" + @resource = @resource.hydrate(record: @record, view: Avo::ViewInquirer.new(:edit), user: _current_user) + @page_title = @resource.default_panel_name.to_s + end last_crumb_args = {} # If we're accessing this resource via another resource add the parent to the breadcrumbs. @@ -438,8 +440,12 @@ def set_edit_title_and_breadcrumbs add_breadcrumb @resource.plural_name.humanize, resources_path(resource: @resource) end - add_breadcrumb @resource.record_title, resource_path(record: @resource.record, resource: @resource, **last_crumb_args) - add_breadcrumb t("avo.edit").humanize + if params[:controller] != "avo/bulk_update" + add_breadcrumb @resource.record_title, resource_path(record: @resource.record, resource: @resource, **last_crumb_args) if params[:controller] != "avo/bulk_update" + add_breadcrumb t("avo.edit").humanize + else + add_breadcrumb t("avo.bulk_edit") + end end def create_success_action diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index c7b99d0683..6b33012804 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -16,19 +16,12 @@ def edit end def handle - if params_to_apply.blank? - flash[:warning] = t("avo.no_changes_made") - redirect_to after_bulk_update_path - return - end - - updated_count, failed_records = update_records + saved = save_records - if failed_records.empty? - flash[:notice] = t("avo.bulk_update_success", count: updated_count) + if saved + flash[:notice] = t("avo.bulk_update_success") else - error_messages = failed_records.flat_map { |fr| fr[:errors] }.uniq - flash[:error] = t("avo.bulk_update_failure", count: failed_records.count, errors: error_messages.join(", ")) + flash[:error] = t("avo.bulk_update_failure") end redirect_to after_bulk_update_path @@ -36,6 +29,33 @@ def handle private + def update_records + params = params_to_apply + + @query.each do |record| + @resource.fill_record(record, params) + end + end + + def save_records + update_records + + all_saved = true + + ActiveRecord::Base.transaction do + @query.each do |record| + @record = record + save_record + end + rescue ActiveRecord::RecordInvalid => e + all_saved = false + puts "Failed to save #{record.id}: #{e.message}" + raise ActiveRecord::Rollback + end + + all_saved + end + def params_to_apply prefilled_params = params[:prefilled] || {} current_params = current_resource_params @@ -43,10 +63,10 @@ def params_to_apply current_params.reject do |key, value| key_sym = key.to_sym + prefilled_value = prefilled_params[key_sym] - progress_field_with_default?(progress_fields, key_sym, prefilled_value, value) || - prefilled_value.to_s == value.to_s + progress_field_with_default?(progress_fields, key_sym, prefilled_value, value) || prefilled_value.to_s == value.to_s end end @@ -63,36 +83,7 @@ def progress_bar_fields end def progress_field_with_default?(progress_fields, key_sym, prefilled_value, value) - progress_fields.include?(key_sym) && prefilled_value == "" && value.to_s == "50" - end - - def update_records - updated_count = 0 - failed_records = [] - - @query.each do |record| - update_record(record, params_to_apply) - record.save ? updated_count += 1 : add_failed_record(failed_records, record) - end - - [updated_count, failed_records] - end - - def update_record(record, params_to_apply) - params_to_apply.each do |key, value| - record.public_send(:"#{key}=", value) - end - - @resource.fill_record(record, params) - end - - def add_failed_record(failed_records, record, error_message = nil) - errors = error_message ? [error_message] : record.errors.full_messages - failed_records << {record: record, errors: errors} - end - - def after_bulk_update_path - resources_path(resource: @resource) + progress_fields.include?(key_sym) && prefilled_value == nil && value.to_s == "50" end def prefill_fields(records, fields) @@ -107,15 +98,11 @@ def set_query @query = if params[:query].present? @resource.find_record(params[:query], params: params) else - find_records_by_resource_ids + resource_ids = params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] + decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) end end - def find_records_by_resource_ids - resource_ids = action_params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] - decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) - end - def set_fields if @query.blank? flash[:error] = I18n.t("avo.bulk_update_no_records") @@ -125,16 +112,16 @@ def set_fields end end - def action_params - @action_params ||= params.permit(:authenticity_token, fields: {}) - end - def decrypted_query - encrypted_query = action_params[:fields]&.dig(:avo_selected_query) || params[:query] + encrypted_query = params[:fields]&.dig(:avo_selected_query) || params[:query] return if encrypted_query.blank? Avo::Services::EncryptionService.decrypt(message: encrypted_query, purpose: :select_all, serializer: Marshal) end + + def after_bulk_update_path + resources_path(resource: @resource) + end end end diff --git a/lib/generators/avo/templates/locales/avo.ar.yml b/lib/generators/avo/templates/locales/avo.ar.yml index 8937c2c281..717ea7f189 100644 --- a/lib/generators/avo/templates/locales/avo.ar.yml +++ b/lib/generators/avo/templates/locales/avo.ar.yml @@ -22,9 +22,11 @@ ar: attachment_class_detached: "%{attachment_class} تم فصل" attachment_destroyed: تم حذف المرفق attachment_failed: فشل في إرفاق %{attachment_class} - bulk_update_failure: 'فشل في تحديث %{count} سجل. الأخطاء: %{errors}' + bulk_edit: تحرير جماعي + bulk_update: تحديث جماعي + bulk_update_failure: فشل في تحديث السجلات. bulk_update_no_records: لا يمكن تنفيذ التحديث الجماعي بدون سجلات. - bulk_update_success: تم تحديث %{count} سجل بنجاح. + bulk_update_success: تم تنفيذ العملية الجماعية بنجاح. cancel: إلغاء choose_a_country: اختر دولة choose_an_option: اختر خيارًا @@ -84,7 +86,6 @@ ar: next_page: الصفحة التالية no_cancel: لا، إلغاء no_cards_present: لا توجد بطاقات - no_changes_made: لم يتم إجراء أي تغييرات. no_item_found: لا يوجد سجلات no_options_available: لا توجد خيارات متاحة no_related_item_found: لم يتم العثور على سجلات متعلقة diff --git a/lib/generators/avo/templates/locales/avo.de.yml b/lib/generators/avo/templates/locales/avo.de.yml index 52b1cffedd..0a30da9273 100644 --- a/lib/generators/avo/templates/locales/avo.de.yml +++ b/lib/generators/avo/templates/locales/avo.de.yml @@ -16,9 +16,11 @@ de: attachment_class_detached: "%{attachment_class} abgehängt." attachment_destroyed: Anhang gelöscht attachment_failed: "%{attachment_class} konnte nicht angehängt werden" - bulk_update_failure: 'Fehler beim Aktualisieren von %{count} Datensätzen. Fehler: %{errors}' - bulk_update_no_records: Massenaktualisierung kann nicht ohne Datensätze durchgeführt werden. - bulk_update_success: "%{count} Datensätze wurden erfolgreich aktualisiert." + bulk_edit: Massenbearbeitung + bulk_update: Massenaktualisierung + bulk_update_failure: Aktualisierung der Datensätze fehlgeschlagen. + bulk_update_no_records: Bulk-Aktualisierung kann ohne Datensätze nicht durchgeführt werden. + bulk_update_success: Massenaktion erfolgreich ausgeführt. cancel: Abbrechen choose_a_country: Land auswählen choose_an_option: Option auswählen @@ -74,7 +76,6 @@ de: next_page: Nächste Seite no_cancel: Nein, abbrechen no_cards_present: Keine Karten vorhanden - no_changes_made: Es wurden keine Änderungen vorgenommen. no_item_found: Kein Eintrag gefunden no_options_available: Keine Optionen verfügbar no_related_item_found: Kein zugehöriger Eintrag gefunden diff --git a/lib/generators/avo/templates/locales/avo.en.yml b/lib/generators/avo/templates/locales/avo.en.yml index cd8bc1bd97..eff925f26d 100644 --- a/lib/generators/avo/templates/locales/avo.en.yml +++ b/lib/generators/avo/templates/locales/avo.en.yml @@ -16,9 +16,11 @@ en: attachment_class_detached: "%{attachment_class} detached." attachment_destroyed: Attachment destroyed attachment_failed: Failed to attach %{attachment_class} - bulk_update_failure: 'Failed to update %{count} records. Errors: %{errors}' + bulk_edit: Bulk edit + bulk_update: Bulk update + bulk_update_failure: Failed to update records. bulk_update_no_records: Bulk update cannot be performed without records. - bulk_update_success: "%{count} records were successfully updated." + bulk_update_success: Bulk action run successfully. cancel: Cancel choose_a_country: Choose a country choose_an_option: Choose an option @@ -74,7 +76,6 @@ en: next_page: Next page no_cancel: No, cancel no_cards_present: No cards present - no_changes_made: No changes were made. no_item_found: No record found no_options_available: No options available no_related_item_found: No related record found diff --git a/lib/generators/avo/templates/locales/avo.es.yml b/lib/generators/avo/templates/locales/avo.es.yml index d87dc2ee3d..4d1abeebb2 100644 --- a/lib/generators/avo/templates/locales/avo.es.yml +++ b/lib/generators/avo/templates/locales/avo.es.yml @@ -18,9 +18,11 @@ es: attachment_class_detached: "%{attachment_class} adjuntado/a." attachment_destroyed: Adjunto eliminado attachment_failed: No se pudo adjuntar %{attachment_class} - bulk_update_failure: 'No se pudieron actualizar %{count} registros. Errores: %{errors}' - bulk_update_no_records: No se puede realizar una actualización masiva sin registros. - bulk_update_success: "%{count} registros se actualizaron correctamente." + bulk_edit: Edición masiva + bulk_update: Actualización masiva + bulk_update_failure: Error al actualizar los registros. + bulk_update_no_records: La actualización masiva no se puede realizar sin registros. + bulk_update_success: Acción masiva ejecutada con éxito. cancel: Cancelar choose_a_country: Elige un país choose_an_option: Elige una opción @@ -76,7 +78,6 @@ es: next_page: Página siguiente no_cancel: No, cancelar no_cards_present: No hay tarjetas - no_changes_made: No se realizaron cambios. no_item_found: No se ha encontrado ningún elemento no_options_available: No hay opciones disponibles no_related_item_found: No se ha encontrado ningún elemento relacionado diff --git a/lib/generators/avo/templates/locales/avo.fr.yml b/lib/generators/avo/templates/locales/avo.fr.yml index c420e2c13f..d03e05b121 100644 --- a/lib/generators/avo/templates/locales/avo.fr.yml +++ b/lib/generators/avo/templates/locales/avo.fr.yml @@ -18,9 +18,11 @@ fr: attachment_class_detached: "%{attachment_class} détaché." attachment_destroyed: Pièce jointe détruite attachment_failed: Échec de l'ajout de %{attachment_class} - bulk_update_failure: 'Échec de la mise à jour de %{count} enregistrements. Erreurs : %{errors}' + bulk_edit: Modification en masse + bulk_update: Mise à jour en masse + bulk_update_failure: Échec de la mise à jour des enregistrements. bulk_update_no_records: La mise à jour en masse ne peut pas être effectuée sans enregistrements. - bulk_update_success: "%{count} enregistrements ont été mis à jour avec succès." + bulk_update_success: Action en masse exécutée avec succès. cancel: Annuler choose_a_country: Sélectionnez un pays choose_an_option: Sélectionnez une option @@ -76,7 +78,6 @@ fr: next_page: Page suivante no_cancel: Non, annuler no_cards_present: Aucune carte présente - no_changes_made: Aucune modification n'a été effectuée. no_item_found: Enregistrement non trouvé no_options_available: Aucune option disponible no_related_item_found: Enregistrement connexe introuvable diff --git a/lib/generators/avo/templates/locales/avo.it.yml b/lib/generators/avo/templates/locales/avo.it.yml index a67ec887a2..6473e21695 100644 --- a/lib/generators/avo/templates/locales/avo.it.yml +++ b/lib/generators/avo/templates/locales/avo.it.yml @@ -16,9 +16,11 @@ it: attachment_class_detached: "%{attachment_class} staccato." attachment_destroyed: Allegato distrutto attachment_failed: Impossibile allegare %{attachment_class} - bulk_update_failure: 'Impossibile aggiornare %{count} record. Errori: %{errors}' + bulk_edit: Modifica di massa + bulk_update: Aggiornamento di massa + bulk_update_failure: Aggiornamento dei record fallito. bulk_update_no_records: L'aggiornamento di massa non può essere eseguito senza record. - bulk_update_success: "%{count} record sono stati aggiornati con successo." + bulk_update_success: Azione di massa eseguita con successo. cancel: Annulla choose_a_country: Scegli un paese choose_an_option: Scegli un'opzione @@ -74,7 +76,6 @@ it: next_page: Pagina successiva no_cancel: No, annulla no_cards_present: Nessuna carta presente - no_changes_made: Non sono state apportate modifiche. no_item_found: Nessun record trovato no_options_available: Nessuna opzione disponibile no_related_item_found: Nessun record correlato trovato diff --git a/lib/generators/avo/templates/locales/avo.ja.yml b/lib/generators/avo/templates/locales/avo.ja.yml index e27ebbc556..6fb27be7c7 100644 --- a/lib/generators/avo/templates/locales/avo.ja.yml +++ b/lib/generators/avo/templates/locales/avo.ja.yml @@ -18,9 +18,11 @@ ja: attachment_class_detached: "%{attachment_class}をデタッチしました。" attachment_destroyed: アタッチは削除されました attachment_failed: "%{attachment_class}の添付に失敗しました" - bulk_update_failure: "%{count} 件のレコードの更新に失敗しました。エラー: %{errors}" - bulk_update_no_records: レコードなしでは一括更新を実行できません。 - bulk_update_success: "%{count} 件のレコードが正常に更新されました。" + bulk_edit: 一括編集 + bulk_update: 一括更新 + bulk_update_failure: レコードの更新に失敗しました。 + bulk_update_no_records: レコードがない場合、バルク更新を実行できません。 + bulk_update_success: 一括処理が正常に実行されました。 cancel: キャンセル choose_a_country: 国を選択 choose_an_option: オプションを選択 @@ -76,7 +78,6 @@ ja: next_page: 次のページ no_cancel: いいえ、キャンセル no_cards_present: カードがありません - no_changes_made: 変更はありませんでした。 no_item_found: レコードが見つかりませんでした no_options_available: 利用可能なオプションがありません no_related_item_found: 関連するレコードが見つかりませんでした diff --git a/lib/generators/avo/templates/locales/avo.nb.yml b/lib/generators/avo/templates/locales/avo.nb.yml index 6a61cd4b84..6a25a11d47 100644 --- a/lib/generators/avo/templates/locales/avo.nb.yml +++ b/lib/generators/avo/templates/locales/avo.nb.yml @@ -18,9 +18,11 @@ nb: attachment_class_detached: "%{attachment_class} fjernet." attachment_destroyed: Vedlett slettet attachment_failed: Kunne ikke legge ved %{attachment_class} - bulk_update_failure: 'Kunne ikke oppdatere %{count} poster. Feil: %{errors}' - bulk_update_no_records: Masseoppdatering kan ikke utføres uten poster. - bulk_update_success: "%{count} poster ble oppdatert med hell." + bulk_edit: Masse redigering + bulk_update: Masseoppdatering + bulk_update_failure: Feil ved oppdatering av poster. + bulk_update_no_records: Bulkoppdatering kan ikke utføres uten poster. + bulk_update_success: Massehandling utført med suksess. cancel: Avbryt choose_a_country: Velg et land choose_an_option: Velg et alternativ @@ -76,7 +78,6 @@ nb: next_page: Neste side no_cancel: Nei, avbryt no_cards_present: Ingen kort til stede - no_changes_made: Det ble ikke gjort noen endringer. no_item_found: Ingen funnet no_options_available: Ingen tilgjengelige alternativer no_related_item_found: Ingen relaterte funnet diff --git a/lib/generators/avo/templates/locales/avo.nl.yml b/lib/generators/avo/templates/locales/avo.nl.yml index 1bf09488ba..23164a5644 100644 --- a/lib/generators/avo/templates/locales/avo.nl.yml +++ b/lib/generators/avo/templates/locales/avo.nl.yml @@ -16,9 +16,11 @@ nl: attachment_class_detached: "%{attachment_class} losgekoppeld." attachment_destroyed: Bijlage verwijderd attachment_failed: Kon %{attachment_class} niet bijvoegen - bulk_update_failure: 'Kon %{count} records niet bijwerken. Fouten: %{errors}' - bulk_update_no_records: Bulkupdate kan niet worden uitgevoerd zonder records. - bulk_update_success: "%{count} records zijn succesvol bijgewerkt." + bulk_edit: Massabewerking + bulk_update: Massaupdate + bulk_update_failure: Fout bij het bijwerken van records. + bulk_update_no_records: Bulk update kan niet worden uitgevoerd zonder records. + bulk_update_success: Massactie succesvol uitgevoerd. cancel: Annuleren choose_a_country: Kies een land choose_an_option: Kies een optie @@ -74,7 +76,6 @@ nl: next_page: Volgende pagina no_cancel: Nee, annuleren no_cards_present: Geen kaarten aanwezig - no_changes_made: Er zijn geen wijzigingen aangebracht. no_item_found: Geen item gevonden no_options_available: Geen opties beschikbaar no_related_item_found: Geen gerelateerd item gevonden diff --git a/lib/generators/avo/templates/locales/avo.nn.yml b/lib/generators/avo/templates/locales/avo.nn.yml index 436b25615a..a66492e1cc 100644 --- a/lib/generators/avo/templates/locales/avo.nn.yml +++ b/lib/generators/avo/templates/locales/avo.nn.yml @@ -18,9 +18,11 @@ nn: attachment_class_detached: "%{attachment_class} fjerna." attachment_destroyed: Vedlegg sletta attachment_failed: Klarte ikkje å legge ved %{attachment_class} - bulk_update_failure: 'Kunne ikkje oppdatere %{count} postane. Feil: %{errors}' - bulk_update_no_records: Masseoppdatering kan ikkje gjennomførast utan postar. - bulk_update_success: "%{count} postane blei oppdatert med suksess." + bulk_edit: Masseredigering + bulk_update: Masseoppdatering + bulk_update_failure: Feil ved oppdatering av poster. + bulk_update_no_records: Bulk update kan ikke utføres uten poster. + bulk_update_success: Massehandling utført med suksess. cancel: Avbryt choose_a_country: Vel eit land choose_an_option: Vel eit alternativ @@ -76,7 +78,6 @@ nn: next_page: Neste side no_cancel: Nei, avbryt no_cards_present: Ingen kort til stades - no_changes_made: Det vart ikkje gjort nokon endringar. no_item_found: Fann ingen no_options_available: Ingen tilgjengelege alternativ no_related_item_found: Fann ingen relaterte diff --git a/lib/generators/avo/templates/locales/avo.pl.yml b/lib/generators/avo/templates/locales/avo.pl.yml index 05b48e71aa..3dcf95b23c 100644 --- a/lib/generators/avo/templates/locales/avo.pl.yml +++ b/lib/generators/avo/templates/locales/avo.pl.yml @@ -16,9 +16,11 @@ pl: attachment_class_detached: "%{attachment_class} odłączony." attachment_destroyed: Załącznik usunięty attachment_failed: Nie udało się dołączyć %{attachment_class} - bulk_update_failure: 'Nie udało się zaktualizować %{count} rekordów. Błędy: %{errors}' + bulk_edit: Edycja zbiorcza + bulk_update: Aktualizacja zbiorcza + bulk_update_failure: Nie udało się zaktualizować rekordów. bulk_update_no_records: Aktualizacja zbiorcza nie może zostać wykonana bez rekordów. - bulk_update_success: "%{count} rekordów zostało pomyślnie zaktualizowanych." + bulk_update_success: Akcja zbiorcza zakończona sukcesem. cancel: Anuluj choose_a_country: Wybierz kraj choose_an_option: Wybierz opcję @@ -76,7 +78,6 @@ pl: next_page: Następna strona no_cancel: Nie, anuluj no_cards_present: Brak kart - no_changes_made: Nie wprowadzono żadnych zmian. no_item_found: Nie znaleziono rekordu no_options_available: Brak dostępnych opcji no_related_item_found: Nie znaleziono powiązanego rekordu diff --git a/lib/generators/avo/templates/locales/avo.pt-BR.yml b/lib/generators/avo/templates/locales/avo.pt-BR.yml index 1d85240187..c44153cc87 100644 --- a/lib/generators/avo/templates/locales/avo.pt-BR.yml +++ b/lib/generators/avo/templates/locales/avo.pt-BR.yml @@ -18,9 +18,11 @@ pt-BR: attachment_class_detached: "%{attachment_class} separado." attachment_destroyed: Anexo destruído attachment_failed: Não foi possível anexar %{attachment_class} - bulk_update_failure: 'Falha ao atualizar %{count} registros. Erros: %{errors}' + bulk_edit: Edição em massa + bulk_update: Atualização em massa + bulk_update_failure: Falha ao atualizar os registros. bulk_update_no_records: A atualização em massa não pode ser realizada sem registros. - bulk_update_success: "%{count} registros foram atualizados com sucesso." + bulk_update_success: Ação em massa executada com sucesso. cancel: Cancelar choose_a_country: Escolha um país choose_an_option: Escolha uma opção @@ -76,7 +78,6 @@ pt-BR: next_page: Próxima página no_cancel: Não, cancelar no_cards_present: Nenhum cartão presente - no_changes_made: Nenhuma alteração foi feita. no_item_found: Nenhum registro encontrado no_options_available: Nenhuma opção disponível no_related_item_found: Nenhum registro relacionado encontrado diff --git a/lib/generators/avo/templates/locales/avo.pt.yml b/lib/generators/avo/templates/locales/avo.pt.yml index a88a449008..4660fce715 100644 --- a/lib/generators/avo/templates/locales/avo.pt.yml +++ b/lib/generators/avo/templates/locales/avo.pt.yml @@ -18,9 +18,11 @@ pt: attachment_class_detached: "%{attachment_class} separado." attachment_destroyed: Anexo destruído attachment_failed: Não foi possível anexar %{attachment_class} - bulk_update_failure: 'Falha ao atualizar %{count} registros. Erros: %{errors}' - bulk_update_no_records: Não é possível realizar a atualização em massa sem registros. - bulk_update_success: "%{count} registros foram atualizados com sucesso." + bulk_edit: Edição em massa + bulk_update: Atualização em massa + bulk_update_failure: Falha ao atualizar os registros. + bulk_update_no_records: A atualização em massa não pode ser realizada sem registros. + bulk_update_success: Ação em massa executada com sucesso. cancel: Cancelar choose_a_country: Escolha um país choose_an_option: Escolha uma opção @@ -76,7 +78,6 @@ pt: next_page: Próxima página no_cancel: Não, cancelar no_cards_present: Nenhum cartão presente - no_changes_made: Nenhuma alteração foi feita. no_item_found: Nenhum registro encontrado no_options_available: Nenhuma opção disponível no_related_item_found: Nenhum registro relacionado encontrado diff --git a/lib/generators/avo/templates/locales/avo.ro.yml b/lib/generators/avo/templates/locales/avo.ro.yml index 2cef4b861b..350af3a3ba 100644 --- a/lib/generators/avo/templates/locales/avo.ro.yml +++ b/lib/generators/avo/templates/locales/avo.ro.yml @@ -19,9 +19,11 @@ ro: attachment_class_detached: "%{attachment_class} separat." attachment_destroyed: Atașamentul a fost distrus attachment_failed: Nu s-a reușit atașarea %{attachment_class} - bulk_update_failure: 'Nu s-au putut actualiza %{count} înregistrări. Erori: %{errors}' + bulk_edit: Editare în masă + bulk_update: Actualizare în masă + bulk_update_failure: Actualizarea înregistrărilor a eșuat. bulk_update_no_records: Actualizarea în masă nu poate fi efectuată fără înregistrări. - bulk_update_success: "%{count} înregistrări au fost actualizate cu succes." + bulk_update_success: Acțiune în masă executată cu succes. cancel: Anulează choose_a_country: Alege o țară choose_an_option: Alege o opțiune @@ -78,7 +80,6 @@ ro: next_page: Pagina următoare no_cancel: Nu, anulează no_cards_present: Nici un card găsit - no_changes_made: Nu s-au făcut modificări. no_item_found: Nici un articol găsit no_options_available: Nicio opțiune disponibilă no_related_item_found: Nici un articol asociat găsit diff --git a/lib/generators/avo/templates/locales/avo.ru.yml b/lib/generators/avo/templates/locales/avo.ru.yml index 179a517438..e42c2961d5 100644 --- a/lib/generators/avo/templates/locales/avo.ru.yml +++ b/lib/generators/avo/templates/locales/avo.ru.yml @@ -16,9 +16,11 @@ ru: attachment_class_detached: "%{attachment_class} отсоединено." attachment_destroyed: Вложение удалено attachment_failed: Не удалось прикрепить %{attachment_class} - bulk_update_failure: 'Не удалось обновить %{count} записей. Ошибки: %{errors}' + bulk_edit: Массовое редактирование + bulk_update: Массовое обновление + bulk_update_failure: Не удалось обновить записи. bulk_update_no_records: Массовое обновление не может быть выполнено без записей. - bulk_update_success: "%{count} записей успешно обновлено." + bulk_update_success: Массовое действие выполнено успешно. cancel: Отмена choose_a_country: Выберите страну choose_an_option: Выберите опцию @@ -76,7 +78,6 @@ ru: next_page: Следующая страница no_cancel: Нет, отмена no_cards_present: Нет карточек - no_changes_made: Изменений не было внесено. no_item_found: Запись не найдена no_options_available: Опции недоступны no_related_item_found: Связанная запись не найдена diff --git a/lib/generators/avo/templates/locales/avo.tr.yml b/lib/generators/avo/templates/locales/avo.tr.yml index cc69f4c754..7bf94d4738 100644 --- a/lib/generators/avo/templates/locales/avo.tr.yml +++ b/lib/generators/avo/templates/locales/avo.tr.yml @@ -18,9 +18,11 @@ tr: attachment_class_detached: "%{attachment_class} ilişkisi kesildi." attachment_destroyed: Ek silindi attachment_failed: "%{attachment_class} eklenemedi" - bulk_update_failure: "%{count} kayıt güncellenemedi. Hatalar: %{errors}" - bulk_update_no_records: Kayıt olmadan toplu güncelleme yapılamaz. - bulk_update_success: "%{count} kayıt başarıyla güncellendi." + bulk_edit: Toplu düzenleme + bulk_update: Toplu güncelleme + bulk_update_failure: Kayıtlar güncellenemedi. + bulk_update_no_records: Kayıtlar olmadan toplu güncelleme yapılamaz. + bulk_update_success: Toplu işlem başarıyla tamamlandı. cancel: İptal et choose_a_country: Bir ülke seç choose_an_option: Bir seçenek seç @@ -76,7 +78,6 @@ tr: next_page: Sonraki sayfa no_cancel: Hayır, iptal et no_cards_present: Kart yok - no_changes_made: Hiçbir değişiklik yapılmadı. no_item_found: Hiç bulunamadı no_options_available: Seçenek yok no_related_item_found: İlişkili bulunamadı diff --git a/lib/generators/avo/templates/locales/avo.uk.yml b/lib/generators/avo/templates/locales/avo.uk.yml index a11c2e929a..2817a72c3c 100644 --- a/lib/generators/avo/templates/locales/avo.uk.yml +++ b/lib/generators/avo/templates/locales/avo.uk.yml @@ -16,9 +16,11 @@ uk: attachment_class_detached: "%{attachment_class} відкріплено." attachment_destroyed: Вкладення знищено attachment_failed: Не вдалося прикріпити %{attachment_class} - bulk_update_failure: 'Не вдалося оновити %{count} записів. Помилки: %{errors}' - bulk_update_no_records: Масове оновлення не можна виконати без записів. - bulk_update_success: "%{count} записів було успішно оновлено." + bulk_edit: Масове редагування + bulk_update: Масове оновлення + bulk_update_failure: Не вдалося оновити записи. + bulk_update_no_records: Неможливо виконати масове оновлення без записів. + bulk_update_success: Масова дія успішно виконана. cancel: Скасувати choose_a_country: Виберіть країну choose_an_option: Виберіть опцію @@ -76,7 +78,6 @@ uk: next_page: Наступна сторінка no_cancel: Ні, скасувати no_cards_present: Немає карток - no_changes_made: Змін не було внесено. no_item_found: Запис не знайдено no_options_available: Немає доступних опцій no_related_item_found: Пов'язані записи не знайдені diff --git a/lib/generators/avo/templates/locales/avo.zh.yml b/lib/generators/avo/templates/locales/avo.zh.yml index 1b3c5112b9..9afc68df19 100644 --- a/lib/generators/avo/templates/locales/avo.zh.yml +++ b/lib/generators/avo/templates/locales/avo.zh.yml @@ -16,9 +16,11 @@ zh: attachment_class_detached: "%{attachment_class} 已分离。" attachment_destroyed: 附件已删除 attachment_failed: 无法附加 %{attachment_class} - bulk_update_failure: 更新 %{count} 条记录失败。错误:%{errors} - bulk_update_no_records: 没有记录,无法执行批量更新。 - bulk_update_success: "%{count} 条记录已成功更新。" + bulk_edit: 批量编辑 + bulk_update: 批量更新 + bulk_update_failure: 更新记录失败。 + bulk_update_no_records: 无法在没有记录的情况下执行批量更新。 + bulk_update_success: 批量操作成功执行。 cancel: 取消 choose_a_country: 选择一个国家 choose_an_option: 选择一个选项 @@ -74,7 +76,6 @@ zh: next_page: 下一页 no_cancel: 不,取消 no_cards_present: 没有卡片 - no_changes_made: 未做任何更改。 no_item_found: 找不到记录 no_options_available: 没有可用选项 no_related_item_found: 找不到相关记录 diff --git a/spec/system/avo/bulk_update_spec.rb b/spec/system/avo/bulk_update_spec.rb new file mode 100644 index 0000000000..d5eaee2400 --- /dev/null +++ b/spec/system/avo/bulk_update_spec.rb @@ -0,0 +1,84 @@ +require "rails_helper" + +RSpec.describe "Actions", type: :system do + let!(:user) { create :user } + let!(:project) { create :project } + let!(:second_project) { create :project } + + describe "check visibility" do + context "index" do + it "finds a button on index" do + visit "/admin/resources/projects" + expect(page).to have_link("Bulk update") + end + end + end + + describe "check redirect functionality" do + context "with selected records" do + it "redirects to edit form page" do + visit "/admin/resources/projects" + + check_and_select_projects + + find("a", text: "Bulk update").click + + expect(page).to have_current_path("/admin/bulk_update/edit", ignore_query: true) + expect(page).to have_button("Save") + end + end + + context "with no selected records" do + it "does not redirect to edit form page" do + visit "/admin/resources/projects" + find("a", text: "Bulk update").click + + expect(page).to have_current_path("/admin/resources/projects") + expect(page).to have_text "Bulk update cannot be performed without records." + end + end + end + + describe "check bulk update" do + before do + visit "/admin/resources/projects" + check_and_select_projects + find("a", text: "Bulk update").click + end + + context "with no changes in form" do + it "works correctly" do + find("button", text: "Save").click + + expect(page).to have_text "Bulk action run successfully." + end + end + + context "with valid params" do + it "works correctly" do + fill_in "project_name", with: "Test" + select "Virgin Islands, U.S.", from: "project_country" + find("button", text: "Save").click + + project.reload + second_project.reload + + expect(page).to have_current_path("/admin/resources/projects") + expect(page).to have_text "Bulk action run successfully." + expect(project.name).to eq "Test" + expect(second_project.country).to eq "VI" + end + end + end + + private + + def check_and_select_projects + checkboxes = all('input[type="checkbox"][name="Select item"]') + checkboxes[0].click + checkboxes[1].click + + expect(checkboxes[0].checked?).to be true + expect(checkboxes[1].checked?).to be true + end +end From c8f635aba0b951bb13b273284d2ab94ca821599b Mon Sep 17 00:00:00 2001 From: Nevelito Date: Wed, 12 Mar 2025 18:41:16 +0100 Subject: [PATCH 17/19] fix bugs --- app/controllers/avo/base_controller.rb | 64 ++++++++++++------- app/controllers/avo/bulk_update_controller.rb | 10 ++- 2 files changed, 49 insertions(+), 25 deletions(-) diff --git a/app/controllers/avo/base_controller.rb b/app/controllers/avo/base_controller.rb index 20ce127b80..f45e3145d3 100644 --- a/app/controllers/avo/base_controller.rb +++ b/app/controllers/avo/base_controller.rb @@ -417,37 +417,57 @@ def filters_to_be_applied def set_edit_title_and_breadcrumbs if params[:controller] != "avo/bulk_update" - @resource = @resource.hydrate(record: @record, view: Avo::ViewInquirer.new(:edit), user: _current_user) - @page_title = @resource.default_panel_name.to_s + set_resource_and_title end - last_crumb_args = {} - # If we're accessing this resource via another resource add the parent to the breadcrumbs. - if params[:via_resource_class].present? && params[:via_record_id].present? - via_resource = Avo.resource_manager.get_resource(params[:via_resource_class]) - via_record = via_resource.find_record params[:via_record_id], params: params - via_resource = via_resource.new record: via_record + add_breadcrumbs_based_on_resource - add_breadcrumb via_resource.plural_name, resources_path(resource: @resource) - add_breadcrumb via_resource.record_title, resource_path(record: via_record, resource: via_resource) + add_bulk_edit_breadcrumb if params[:controller] == "avo/bulk_update" + end - last_crumb_args = { - via_resource_class: params[:via_resource_class], - via_record_id: params[:via_record_id] - } - add_breadcrumb @resource.plural_name.humanize - else - add_breadcrumb @resource.plural_name.humanize, resources_path(resource: @resource) - end + private - if params[:controller] != "avo/bulk_update" - add_breadcrumb @resource.record_title, resource_path(record: @resource.record, resource: @resource, **last_crumb_args) if params[:controller] != "avo/bulk_update" - add_breadcrumb t("avo.edit").humanize + def set_resource_and_title + @resource = @resource.hydrate(record: @record, view: Avo::ViewInquirer.new(:edit), user: _current_user) + @page_title = @resource.default_panel_name.to_s + end + + def add_breadcrumbs_based_on_resource + if params[:via_resource_class].present? && params[:via_record_id].present? + add_parent_resource_breadcrumbs else - add_breadcrumb t("avo.bulk_edit") + add_default_resource_breadcrumb end end + def add_parent_resource_breadcrumbs + via_resource = Avo.resource_manager.get_resource(params[:via_resource_class]) + via_record = via_resource.find_record params[:via_record_id], params: params + via_resource = via_resource.new record: via_record + + add_breadcrumb via_resource.plural_name, resources_path(resource: @resource) + add_breadcrumb via_resource.record_title, resource_path(record: via_record, resource: via_resource) + + add_last_crumb(via_resource) + end + + def add_default_resource_breadcrumb + add_breadcrumb @resource.plural_name.humanize, resources_path(resource: @resource) + add_breadcrumb @resource.record_title, resource_path(record: @resource.record, resource: @resource) + end + + def add_last_crumb(via_resource) + last_crumb_args = { + via_resource_class: params[:via_resource_class], + via_record_id: params[:via_record_id] + } + add_breadcrumb @resource.plural_name.humanize + end + + def add_bulk_edit_breadcrumb + add_breadcrumb t("avo.bulk_edit") + end + def create_success_action return render "close_modal_and_reload_field" if params[:via_belongs_to_resource_class].present? diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index 6b33012804..dd0cfbad02 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -83,7 +83,7 @@ def progress_bar_fields end def progress_field_with_default?(progress_fields, key_sym, prefilled_value, value) - progress_fields.include?(key_sym) && prefilled_value == nil && value.to_s == "50" + progress_fields.include?(key_sym) && prefilled_value.nil? && value.to_s == "50" end def prefill_fields(records, fields) @@ -98,11 +98,15 @@ def set_query @query = if params[:query].present? @resource.find_record(params[:query], params: params) else - resource_ids = params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] - decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) + find_records_by_resource_ids end end + def find_records_by_resource_ids + resource_ids = action_params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] + decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) + end + def set_fields if @query.blank? flash[:error] = I18n.t("avo.bulk_update_no_records") From b7f529bac549fed9f7a224f6925acc0345d02193 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Wed, 12 Mar 2025 18:47:35 +0100 Subject: [PATCH 18/19] fix bugs --- app/controllers/avo/base_controller.rb | 68 +++++++++++--------------- 1 file changed, 28 insertions(+), 40 deletions(-) diff --git a/app/controllers/avo/base_controller.rb b/app/controllers/avo/base_controller.rb index f45e3145d3..7a07848e82 100644 --- a/app/controllers/avo/base_controller.rb +++ b/app/controllers/avo/base_controller.rb @@ -416,56 +416,44 @@ def filters_to_be_applied end def set_edit_title_and_breadcrumbs - if params[:controller] != "avo/bulk_update" - set_resource_and_title - end - - add_breadcrumbs_based_on_resource - - add_bulk_edit_breadcrumb if params[:controller] == "avo/bulk_update" - end + set_resource_and_page_title - private + last_crumb_args = {} + # If we're accessing this resource via another resource add the parent to the breadcrumbs. + if params[:via_resource_class].present? && params[:via_record_id].present? + via_resource = Avo.resource_manager.get_resource(params[:via_resource_class]) + via_record = via_resource.find_record params[:via_record_id], params: params + via_resource = via_resource.new record: via_record - def set_resource_and_title - @resource = @resource.hydrate(record: @record, view: Avo::ViewInquirer.new(:edit), user: _current_user) - @page_title = @resource.default_panel_name.to_s - end + add_breadcrumb via_resource.plural_name, resources_path(resource: @resource) + add_breadcrumb via_resource.record_title, resource_path(record: via_record, resource: via_resource) - def add_breadcrumbs_based_on_resource - if params[:via_resource_class].present? && params[:via_record_id].present? - add_parent_resource_breadcrumbs + last_crumb_args = { + via_resource_class: params[:via_resource_class], + via_record_id: params[:via_record_id] + } + add_breadcrumb @resource.plural_name.humanize else - add_default_resource_breadcrumb + add_breadcrumb @resource.plural_name.humanize, resources_path(resource: @resource) end - end - def add_parent_resource_breadcrumbs - via_resource = Avo.resource_manager.get_resource(params[:via_resource_class]) - via_record = via_resource.find_record params[:via_record_id], params: params - via_resource = via_resource.new record: via_record - - add_breadcrumb via_resource.plural_name, resources_path(resource: @resource) - add_breadcrumb via_resource.record_title, resource_path(record: via_record, resource: via_resource) - - add_last_crumb(via_resource) + help_add_breadcrumb(last_crumb_args) end - def add_default_resource_breadcrumb - add_breadcrumb @resource.plural_name.humanize, resources_path(resource: @resource) - add_breadcrumb @resource.record_title, resource_path(record: @resource.record, resource: @resource) - end - - def add_last_crumb(via_resource) - last_crumb_args = { - via_resource_class: params[:via_resource_class], - via_record_id: params[:via_record_id] - } - add_breadcrumb @resource.plural_name.humanize + def set_resource_and_page_title + if params[:controller] != "avo/bulk_update" + @resource = @resource.hydrate(record: @record, view: Avo::ViewInquirer.new(:edit), user: _current_user) + @page_title = @resource.default_panel_name.to_s + end end - def add_bulk_edit_breadcrumb - add_breadcrumb t("avo.bulk_edit") + def help_add_breadcrumb(last_crumb_args) + if params[:controller] != "avo/bulk_update" + add_breadcrumb @resource.record_title, resource_path(record: @resource.record, resource: @resource, **last_crumb_args) if params[:controller] != "avo/bulk_update" + add_breadcrumb t("avo.edit").humanize + else + add_breadcrumb t("avo.bulk_edit") + end end def create_success_action From aaa324ee9bd6d02015a805609ab684415d7958e9 Mon Sep 17 00:00:00 2001 From: Nevelito Date: Wed, 12 Mar 2025 19:14:32 +0100 Subject: [PATCH 19/19] fix bulk update controller --- app/controllers/avo/bulk_update_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/avo/bulk_update_controller.rb b/app/controllers/avo/bulk_update_controller.rb index dd0cfbad02..3dbcced78a 100644 --- a/app/controllers/avo/bulk_update_controller.rb +++ b/app/controllers/avo/bulk_update_controller.rb @@ -103,7 +103,7 @@ def set_query end def find_records_by_resource_ids - resource_ids = action_params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] + resource_ids = params[:fields]&.dig(:avo_resource_ids)&.split(",") || [] decrypted_query || (resource_ids.any? ? @resource.find_record(resource_ids, params: params) : []) end