decidim-core 0.31.8 → 0.31.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. checksums.yaml +4 -4
  2. data/app/cells/decidim/address_cell.rb +7 -3
  3. data/app/cells/decidim/card_metadata_cell.rb +3 -1
  4. data/app/cells/decidim/date_range/show.erb +6 -6
  5. data/app/cells/decidim/date_range_cell.rb +7 -2
  6. data/app/commands/decidim/create_follow.rb +3 -7
  7. data/app/commands/decidim/create_omniauth_registration.rb +2 -5
  8. data/app/commands/decidim/create_user_report.rb +1 -1
  9. data/app/commands/decidim/destroy_account.rb +6 -6
  10. data/app/commands/decidim/destroy_ephemeral_user.rb +2 -0
  11. data/app/commands/decidim/invite_user.rb +1 -1
  12. data/app/commands/decidim/multiple_attachments_methods.rb +17 -3
  13. data/app/commands/decidim/update_resources_taxonomies.rb +2 -1
  14. data/app/controllers/concerns/decidim/devise_controllers.rb +2 -0
  15. data/app/controllers/concerns/decidim/direct_upload.rb +12 -6
  16. data/app/controllers/concerns/decidim/impersonate_users.rb +2 -2
  17. data/app/controllers/concerns/decidim/needs_organization.rb +15 -0
  18. data/app/controllers/decidim/amendments_controller.rb +34 -6
  19. data/app/controllers/decidim/application_controller.rb +2 -0
  20. data/app/controllers/decidim/authorization_modals_controller.rb +1 -1
  21. data/app/controllers/decidim/doorkeeper/authorizations_controller.rb +10 -4
  22. data/app/controllers/decidim/doorkeeper/credentials_controller.rb +6 -1
  23. data/app/controllers/decidim/messaging/conversations_controller.rb +1 -1
  24. data/app/controllers/decidim/profiles_controller.rb +1 -1
  25. data/app/helpers/decidim/cells_paginate_helper.rb +0 -5
  26. data/app/helpers/decidim/layout_helper.rb +1 -0
  27. data/app/helpers/decidim/orders_helper.rb +8 -6
  28. data/app/helpers/decidim/paginate_helper.rb +27 -2
  29. data/app/helpers/decidim/url_helper.rb +35 -0
  30. data/app/jobs/decidim/open_data_job.rb +21 -5
  31. data/app/models/decidim/action_log.rb +7 -1
  32. data/app/models/decidim/component.rb +10 -0
  33. data/app/models/decidim/like.rb +1 -1
  34. data/app/packs/src/decidim/datepicker/datepicker_functions.js +20 -7
  35. data/app/packs/src/decidim/datepicker/form_datepicker.js +18 -2
  36. data/app/packs/src/decidim/datepicker/generate_datepicker.js +12 -4
  37. data/app/packs/src/decidim/datepicker/generate_timepicker.js +5 -3
  38. data/app/packs/src/decidim/datepicker/test/date.test.js +8 -0
  39. data/app/packs/stylesheets/decidim/_datepicker.scss +3 -3
  40. data/app/packs/stylesheets/decidim/_spinner.scss +16 -0
  41. data/app/packs/stylesheets/decidim/_tom_select.scss +1 -1
  42. data/app/presenters/decidim/log/base_presenter.rb +10 -1
  43. data/app/services/decidim/action_logger.rb +97 -29
  44. data/app/services/decidim/svg_content_validator.rb +419 -84
  45. data/app/validators/uploader_image_content_validator.rb +6 -2
  46. data/app/views/decidim/manifests/show.json.erb +25 -22
  47. data/app/views/decidim/shared/_results_per_page.html.erb +1 -1
  48. data/config/locales/bg.yml +1 -3
  49. data/config/locales/ca-IT.yml +5 -3
  50. data/config/locales/ca.yml +7 -5
  51. data/config/locales/cs.yml +9 -3
  52. data/config/locales/de.yml +1 -3
  53. data/config/locales/en.yml +5 -3
  54. data/config/locales/es-MX.yml +5 -3
  55. data/config/locales/es-PY.yml +5 -3
  56. data/config/locales/es.yml +7 -5
  57. data/config/locales/eu.yml +10 -8
  58. data/config/locales/fi-plain.yml +2 -2
  59. data/config/locales/fi.yml +2 -2
  60. data/config/locales/fr-CA.yml +5 -3
  61. data/config/locales/fr.yml +5 -3
  62. data/config/locales/gl.yml +0 -1
  63. data/config/locales/it.yml +0 -2
  64. data/config/locales/ja.yml +3 -3
  65. data/config/locales/pl.yml +1 -3
  66. data/config/locales/pt-BR.yml +1 -3
  67. data/config/locales/ro-RO.yml +0 -2
  68. data/config/locales/sk.yml +49 -3
  69. data/config/locales/sv.yml +3 -3
  70. data/config/locales/tr-TR.yml +1 -1
  71. data/db/migrate/20250523104311_move_cta_to_hero_content_block.rb +1 -1
  72. data/db/migrate/20250527122040_move_highlighted_content_banner_settings_to_content_block.rb +3 -0
  73. data/db/migrate/20261007090000_make_user_optional_in_action_logs.rb +12 -0
  74. data/decidim-core.gemspec +1 -1
  75. data/lib/decidim/content_renderers/mention_resource_renderer.rb +6 -3
  76. data/lib/decidim/core/test/factories.rb +2 -2
  77. data/lib/decidim/core/version.rb +1 -1
  78. data/lib/decidim/core.rb +1 -1
  79. data/lib/decidim/maintenance/import_models/scope.rb +2 -1
  80. data/lib/decidim/maintenance/taxonomy_importer.rb +4 -1
  81. data/lib/decidim/view_model.rb +1 -0
  82. data/lib/tasks/decidim_open_data_tasks.rake +7 -0
  83. metadata +18 -10
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ # Helper that sanitizes the parameters used to generate URLs.
5
+ module UrlHelper
6
+ # Rails uses these options to build URLs. Allowing user-controlled values
7
+ # for them can change the generated URL's scheme, host, or path. The
8
+ # `_recall` and `use_route` options are handled before the route set
9
+ # resolves the URL, so they are not part of RESERVED_OPTIONS.
10
+ RESERVED_URL_OPTIONS = (
11
+ ActionDispatch::Routing::RouteSet::RESERVED_OPTIONS + [:path_params, :_recall, :use_route]
12
+ ).freeze
13
+
14
+ # Removes the Rails URL generation options from the given parameters and
15
+ # merges the extra parameters.
16
+ #
17
+ # The extra parameters are trusted values defined by the application, so
18
+ # they take precedence over the request parameters. This allows forcing
19
+ # routing options (such as the controller, the action or the format)
20
+ # without letting a request parameter override them.
21
+ #
22
+ # params - An ActionController::Parameters or a Hash.
23
+ # extra_params - A Hash with extra URL generation options.
24
+ #
25
+ # Returns a HashWithIndifferentAccess without the reserved URL options.
26
+ def decidim_url_params(params, **extra_params)
27
+ Decidim::UrlHelper.sanitize_params(params).merge(extra_params)
28
+ end
29
+
30
+ def self.sanitize_params(params)
31
+ params = params.to_unsafe_h if params.respond_to?(:to_unsafe_h)
32
+ params.with_indifferent_access.except(*RESERVED_URL_OPTIONS)
33
+ end
34
+ end
35
+ end
@@ -5,14 +5,30 @@ module Decidim
5
5
  queue_as :exports
6
6
 
7
7
  def perform(organization, resource = nil)
8
- path = Rails.root.join("tmp/#{organization.open_data_file_path(resource)}")
8
+ path = nil
9
+ organization = Organization.with_attached_open_data_files.find(organization&.id)
10
+
11
+ filename = organization.open_data_file_path(resource)
12
+ tmp_filename = "#{SecureRandom.uuid}-#{filename}"
13
+ path = Rails.root.join("tmp", tmp_filename)
14
+
15
+ Rails.logger.info "[OpenDataJob] Starting export for organization=#{organization.id} resource=#{resource.inspect}"
9
16
 
10
17
  exporter = OpenDataExporter.new(organization, path, resource)
11
- raise "Could not generate Open Data export" unless exporter.export.positive?
18
+ exported_bytes = exporter.export
19
+
20
+ raise "Export produced no data (0 bytes) for resource=#{resource.inspect}" unless exported_bytes.is_a?(Integer) && exported_bytes.positive?
21
+
22
+ File.open(path, "rb") do |file|
23
+ organization.open_data_files.attach(io: file, filename:)
24
+ end
12
25
 
13
- organization.open_data_files.attach(io: File.open(path, "rb"), filename: organization.open_data_file_path(resource))
14
- # Deletes the temporary file file
15
- File.delete(path)
26
+ organization.open_data_files.select { |f| f.blob.filename.to_s == filename }.sort_by(&:created_at)[0...-1].each(&:purge)
27
+ rescue StandardError => e
28
+ Rails.logger.error "[OpenDataJob] Export failed for organization=#{organization&.id} resource=#{resource.inspect}: #{e.message}"
29
+ raise
30
+ ensure
31
+ FileUtils.rm_f(path) if path.present?
16
32
  end
17
33
  end
18
34
  end
@@ -12,7 +12,11 @@ module Decidim
12
12
  foreign_key: :decidim_organization_id,
13
13
  class_name: "Decidim::Organization"
14
14
 
15
- belongs_to :user, class_name: "Decidim::UserBaseEntity"
15
+ # As we need to generate logs that do not have a certain user (see #17282),
16
+ # we need to allow user to be optional.
17
+ belongs_to :user,
18
+ class_name: "Decidim::UserBaseEntity",
19
+ optional: true
16
20
 
17
21
  belongs_to :component,
18
22
  foreign_key: :decidim_component_id,
@@ -198,6 +202,8 @@ module Decidim
198
202
  # Lazy loads the `user` association through BatchLoader, can be used
199
203
  # as a regular object.
200
204
  def user_lazy(cache: true)
205
+ return if user_id.blank? || user_type.blank?
206
+
201
207
  self.class.lazy_relation(user_id, user_type, cache)
202
208
  end
203
209
 
@@ -19,6 +19,16 @@ module Decidim
19
19
 
20
20
  scope :registered_component_manifests, -> { where(manifest_name: Decidim.component_registry.manifests.collect(&:name)) }
21
21
  scope :registered_space_manifests, -> { where(participatory_space_type: Decidim.participatory_space_registry.manifests.collect(&:model_class_name)) }
22
+ scope :for_organization, lambda { |organization:|
23
+ conditions = Decidim.participatory_space_registry.manifests.map do |manifest|
24
+ where(
25
+ participatory_space_type: manifest.model_class_name,
26
+ participatory_space_id: manifest.participatory_spaces.call(organization).reselect(:id)
27
+ )
28
+ end
29
+
30
+ conditions.reduce(:or) || none
31
+ }
22
32
 
23
33
  default_scope { registered_component_manifests.registered_space_manifests.order(arel_table[:weight].asc, arel_table[:manifest_name].asc) }
24
34
 
@@ -12,7 +12,7 @@ module Decidim
12
12
  validates :resource_id, uniqueness: { scope: [:resource_type, :author] }
13
13
  validate :author_and_resource_same_organization
14
14
 
15
- scope :for_listing, -> { order(:decidim_author_type, :decidim_author_id, :created_at) }
15
+ scope :for_listing, -> { order(:created_at, :id) }
16
16
 
17
17
  private
18
18
 
@@ -191,16 +191,29 @@ export const updateTimeValue = (time, hour, minute) => {
191
191
  };
192
192
 
193
193
  export const formatDate = (value, formats) => {
194
- let newValue = value;
195
- const splitValue = value.split(formats.separator);
194
+ const splitValue = value.split(formats.separator).splice(0, 3).map((part) => part.replace(/[^0-9]/g, ""));
196
195
 
197
- if (formats.order === "d-m-y") {
198
- newValue = `${splitValue[1]}/${splitValue[0]}/${splitValue[2]}`;
196
+ // Keep an empty date empty instead of silently defaulting to today
197
+ if (splitValue.every((part) => !part)) {
198
+ return "";
199
+ }
200
+
201
+ let newValue = null;
202
+ if (formats.order === "m-d-y") {
203
+ newValue = [splitValue[0], splitValue[1], splitValue[2]];
199
204
  } else if (formats.order === "y-m-d") {
200
- newValue = `${splitValue[1]}/${splitValue[2]}/${splitValue[0]}`
201
- };
205
+ newValue = [splitValue[1], splitValue[2], splitValue[0]];
206
+ } else {
207
+ // Assuming d-m-y
208
+ newValue = [splitValue[1], splitValue[0], splitValue[2]];
209
+ }
210
+
211
+ // Fill missing parts
212
+ let fallback = new Date();
213
+ fallback = [fallback.getMonth() + 1, fallback.getDate(), fallback.getFullYear()];
214
+ newValue = newValue.map((val, idx) => (val || fallback[idx]));
202
215
 
203
- const date = new Date(newValue)
216
+ const date = new Date(newValue.join("/"))
204
217
 
205
218
  let day = date.getDate();
206
219
  let month = date.getMonth() + 1;
@@ -6,12 +6,28 @@ import { formatInputDate, formatInputTime } from "src/decidim/datepicker/datepic
6
6
  import { getDictionary } from "src/decidim/refactor/moved/i18n";
7
7
 
8
8
  export default function formDatePicker(input) {
9
-
10
9
  const i18nDate = getDictionary("date.formats");
11
10
  const i18nDateHelp = getDictionary("date.formats.help");
12
11
  const i18nTime = getDictionary("time");
13
12
  const i18nTimeHelp = getDictionary("time.formats.help");
14
- const formats = { order: i18nDate.order, separator: i18nDate.separator, time: i18nTime.clock_format || 24 }
13
+ /* eslint-disable dot-location */
14
+ // See: https://docs.ruby-lang.org/en/3.4/strftime_formatting_rdoc.html
15
+ const dateFormat = i18nDate.decidim_short
16
+ // Padding modifiers (removed, not supported by the date picker)
17
+ .replace(/%[0_-]/g, "%")
18
+ // Upcase modifier (removed, not supported by the date picker)
19
+ .replaceAll("%^", "%")
20
+ // Week-based year (converted to regular full year as it is not supported by the date picker)
21
+ .replace(/%[gG]/, "%Y")
22
+ // Shorthand conventions %D, %x, %F
23
+ .replace(/%[Dx]/, "%m/%d/%y")
24
+ .replace("%F", "%Y-%m-%d")
25
+ // VMS date (converted to day-month-year as it is not supported by the date picker)
26
+ .replace("%v", "%d-%m-%Y")
27
+ /* eslint-enable dot-location */
28
+ const dateOrder = dateFormat.replace("%Y", "y").replaceAll("%", "").replace(/[^A-Za-z]/g, "-");
29
+ const dateSeparator = (dateFormat.match(/([^%A-Za-z])/) || ["/"])[0];
30
+ const formats = { order: dateOrder, separator: dateSeparator, time: i18nTime.clock_format || 24 }
15
31
 
16
32
  if (!customElements.get("wc-datepicker")) {
17
33
  defineCustomElements();
@@ -73,8 +73,11 @@ export default function generateDatePicker(input, row, formats) {
73
73
  date.addEventListener("paste", (event) => {
74
74
  event.preventDefault();
75
75
  const value = event.clipboardData.getData("text/plain");
76
- if ((/^[0-9/.-]+$/).test(value)) {
77
- date.value = value.replaceAll(/[/.-]/g, formats.separator);
76
+ // Only the date part is accepted; any text after it is ignored
77
+ const pastedDate = value.match(/^([0-9]+[^0-9]){2}[0-9]+/);
78
+
79
+ if (pastedDate) {
80
+ date.value = pastedDate[0].replaceAll(/[^0-9]/g, formats.separator);
78
81
 
79
82
  if (input.type === "date") {
80
83
  input.value = `${formatDate(date.value, formats)}`;
@@ -88,9 +91,14 @@ export default function generateDatePicker(input, row, formats) {
88
91
  datePickerContainer.style.display = "none";
89
92
  });
90
93
 
91
- date.addEventListener("keyup", () => {
94
+ date.addEventListener("input", () => {
95
+ if (date.value.length === 0) {
96
+ input.value = "";
97
+ return;
98
+ };
99
+
92
100
  if (date.value.length === 10) {
93
- date.value = date.value.replaceAll(/[/.-]/g, formats.separator);
101
+ date.value = date.value.replaceAll(/[^0-9]/g, formats.separator);
94
102
  prevDate = dateToPicker(date.value, formats);
95
103
  if (input.type === "date") {
96
104
  input.value = `${formatDate(date.value, formats)}`;
@@ -1,5 +1,5 @@
1
1
  /* eslint-disable require-jsdoc */
2
- /* eslint max-lines: ["error", 310] */
2
+ /* eslint max-lines: ["error", 320] */
3
3
 
4
4
  import icon from "src/decidim/refactor/moved/icon"
5
5
  import { changeHourDisplay, changeMinuteDisplay, formatDate, hourDisplay, minuteDisplay, formatTime, setHour, setMinute, updateTimeValue, updateInputValue, adjustPickerPosition } from "src/decidim/datepicker/datepicker_functions"
@@ -96,7 +96,8 @@ export default function generateTimePicker(input, row, formats) {
96
96
  periodAm.setAttribute("name", `period_${input.id}`);
97
97
  periodAm.setAttribute("id", `period_am_${input.id}`);
98
98
  periodAm.setAttribute("class", "datepicker__period-am");
99
- const periodAmLabel = document.createElement("span");
99
+ const periodAmLabel = document.createElement("label");
100
+ periodAmLabel.setAttribute("for", `period_am_${input.id}`);
100
101
  periodAmLabel.innerText = "AM"
101
102
 
102
103
  const periodPm = document.createElement("input");
@@ -104,7 +105,8 @@ export default function generateTimePicker(input, row, formats) {
104
105
  periodPm.setAttribute("name", `period_${input.id}`);
105
106
  periodPm.setAttribute("id", `period_pm_${input.id}`);
106
107
  periodPm.setAttribute("class", "datepicker__period-pm");
107
- const periodPmLabel = document.createElement("span");
108
+ const periodPmLabel = document.createElement("label");
109
+ periodPmLabel.setAttribute("for", `period_pm_${input.id}`);
108
110
  periodPmLabel.innerText = "PM"
109
111
 
110
112
  periodColumn.appendChild(periodAm);
@@ -66,6 +66,14 @@ describe("formatDate", () => {
66
66
 
67
67
  expect(result).toEqual("2023-02-01");
68
68
  });
69
+
70
+ it("should keep a blank date empty instead of defaulting to today", () => {
71
+ const formats = { separator: "/", order: "d-m-y" };
72
+
73
+ const result = formatDate("", formats);
74
+
75
+ expect(result).toEqual("");
76
+ });
69
77
  });
70
78
 
71
79
  describe("formatInputDate", () => {
@@ -70,7 +70,7 @@
70
70
  }
71
71
 
72
72
  &__period-column {
73
- @apply w-28 h-8 top-1 right-10 my-2 mx-1 absolute;
73
+ @apply w-28 h-8 top-0 right-6 my-2 mx-1 absolute;
74
74
  }
75
75
 
76
76
  &__calendar-button {
@@ -155,11 +155,11 @@
155
155
  }
156
156
 
157
157
  &__period-am {
158
- @apply ml-1 accent-secondary bg-secondary;
158
+ @apply ml-1 !mt-3 accent-secondary bg-secondary;
159
159
  }
160
160
 
161
161
  &__period-pm {
162
- @apply ml-1;
162
+ @apply ml-1 !mt-3;
163
163
  }
164
164
 
165
165
  &__label-row {
@@ -9,3 +9,19 @@
9
9
  @apply content-[""] sticky top-[50vh] ml-[50%] md:ml-[calc(50%-4rem)] block w-6 h-6 -mt-6 rounded-full animate-spin border-4 border-l-background border-y-background border-r-secondary z-20;
10
10
  }
11
11
  }
12
+
13
+ // Pseudo-elements on table rows generate anonymous table cells, which shift
14
+ // the row content. Render the spinner in the first cell instead.
15
+ tr.spinner-container {
16
+ &::before {
17
+ @apply hidden;
18
+ }
19
+
20
+ td:first-child {
21
+ @apply relative;
22
+
23
+ &::after {
24
+ @apply content-[""] absolute top-1/2 left-1/2 -mt-3 -ml-3 block w-6 h-6 rounded-full animate-spin border-4 border-l-background border-y-background border-r-secondary z-20;
25
+ }
26
+ }
27
+ }
@@ -1,4 +1,4 @@
1
- @use "tom-select/dist/scss/tom-select";
1
+ @use "tom-select/dist/css/tom-select";
2
2
 
3
3
  .ts {
4
4
  &-control {
@@ -205,12 +205,21 @@ module Decidim
205
205
  # Returns a Hash.
206
206
  def i18n_params
207
207
  {
208
- user_name: user_presenter.present,
208
+ user_name: system_action? ? nil : user_presenter.present,
209
209
  resource_name: resource_presenter.try(:present),
210
210
  space_name: space_presenter.present
211
211
  }
212
212
  end
213
213
 
214
+ # Private: Whether the action was performed by the system rather than a
215
+ # user. A deleted user still leaves its reference in the log, so this
216
+ # cannot be based on the loaded `user` association.
217
+ #
218
+ # Returns a Boolean.
219
+ def system_action?
220
+ action_log.user_id.blank? && action_log.user_type.blank?
221
+ end
222
+
214
223
  # Private: Calculates if the diff has to be shown or not.
215
224
  #
216
225
  # Returns a Boolean.
@@ -5,31 +5,65 @@ module Decidim
5
5
  # use this class directly, but rather use `Decidim.traceability` instead.
6
6
  # Check the docs on `Decidim::Traceability` for more info.
7
7
  #
8
- # Usage:
8
+ # @example Log an action performed by a user
9
+ # Decidim::ActionLogger.log(:create, user, new_proposal, version_id, extra_data)
9
10
  #
10
- # ActionLogger.log(:create, user, new_proposal, extra_data)
11
+ # @example Log an action performed by the system
12
+ # Decidim::ActionLogger.log_system(:create, new_proposal, visibility: "public-only")
13
+ #
14
+ # @see Decidim::Traceability
11
15
  class ActionLogger
12
- # Public: Logs the given `action` by the given `user` on the given `resource`.
16
+ # Logs the given `action` by the given `user` on the given `resource`.
13
17
  # Delegates the work to the instance method.
14
18
  #
15
- # action - a String representing the name of the action
16
- # user - the Decidim::User that performed the action
17
- # resource - the resource on which the action was performed
18
- # version_id - the ID of the `PaperTrail::Version` that was created on that action
19
- # resource_extra - a Hash with resource_extra info to be recorded
19
+ # @param action [String, Symbol] the name of the action performed
20
+ # @param user [Decidim::User, Decidim::Api::ApiUser] the user that
21
+ # performed the action
22
+ # @param resource [ActiveRecord::Base] the resource on which the action was
23
+ # performed
24
+ # @param version_id [Integer, nil] the ID of the `PaperTrail::Version` that
25
+ # was created by the action
26
+ # @param resource_extra [Hash] extra information to be recorded in the
27
+ # action log. It may include the `:visibility` key to set the visibility
28
+ # of the action log.
29
+ #
30
+ # @return [Decidim::ActionLog] the newly created action log
20
31
  #
21
- # Returns the newly created `Decidim::ActionLog` resource.
32
+ # @raise [ArgumentError] if `user` is `nil`. Use {.log_system} for actions
33
+ # performed by the system.
22
34
  def self.log(action, user, resource, version_id, resource_extra = {})
23
- new(action, user, resource, version_id, resource_extra).log!
35
+ raise ArgumentError, "ActionLogger.log requires a user. Use ActionLogger.log_system for actions performed by the system." if user.nil?
36
+
37
+ new(action, user, resource, version_id, resource_extra).send(:log!)
38
+ end
39
+
40
+ # Logs the given `action` performed by the system (i.e. without a user) on
41
+ # the given `resource`.
42
+ #
43
+ # @param action [String, Symbol] the name of the action performed
44
+ # @param resource [ActiveRecord::Base] the resource on which the action was
45
+ # performed
46
+ # @param resource_extra [Hash] keyword arguments with extra information to
47
+ # be recorded in the action log. It may include the `:visibility` key to
48
+ # set the visibility of the action log.
49
+ #
50
+ # @return [Decidim::ActionLog] the newly created action log
51
+ def self.log_system(action, resource, **resource_extra)
52
+ new(action, nil, resource, nil, resource_extra).send(:log!)
24
53
  end
25
54
 
26
- # Public: Initializes the instance.
55
+ # Initializes the instance.
27
56
  #
28
- # action - a String representing the name of the action
29
- # user - the Decidim::User that performed the action
30
- # resource - the resource on which the action was performed
31
- # version_id - the ID of the `PaperTrail::Version` that was created on that action
32
- # resource_extra - a Hash with resource_extra info to be recorded
57
+ # @param action [String, Symbol] the name of the action performed
58
+ # @param user [Decidim::User, Decidim::Api::ApiUser, nil] the user that
59
+ # performed the action, or `nil` for actions performed by the system
60
+ # @param resource [ActiveRecord::Base] the resource on which the action was
61
+ # performed
62
+ # @param version_id [Integer, nil] the ID of the `PaperTrail::Version` that
63
+ # was created by the action
64
+ # @param resource_extra [Hash] extra information to be recorded in the
65
+ # action log. It may include the `:visibility` key to set the visibility
66
+ # of the action log, which defaults to `"admin-only"`.
33
67
  def initialize(action, user, resource, version_id = nil, resource_extra = {})
34
68
  @action = action
35
69
  @user = user
@@ -39,14 +73,17 @@ module Decidim
39
73
  @visibility = resource_extra.delete(:visibility).presence || "admin-only"
40
74
  end
41
75
 
42
- # Public: Logs the given `action` by the given `user` on the given
43
- # `resource`.
76
+ private
77
+
78
+ # Logs the given `action` by the given `user` on the given `resource`.
79
+ #
80
+ # @return [Decidim::ActionLog] the newly created action log
44
81
  #
45
- # Returns the newly created `Decidim::ActionLog` resource.
82
+ # @raise [ActiveRecord::RecordInvalid] if the action log is not valid
46
83
  def log!
47
84
  Decidim::ActionLog.create!(
48
- user_id: user.id,
49
- user_type: user.class.name,
85
+ user_id: user&.id,
86
+ user_type: user&.class&.name,
50
87
  organization:,
51
88
  action:,
52
89
  resource:,
@@ -62,44 +99,75 @@ module Decidim
62
99
  )
63
100
  end
64
101
 
65
- private
66
-
102
+ # The values given to the logger when it was initialized.
67
103
  attr_reader :action, :user, :resource, :resource_extra, :version_id, :visibility
68
104
 
105
+ # Finds the organization related to the action log.
106
+ #
107
+ # @return [Decidim::Organization, nil] the organization of the user, the
108
+ # participatory space, or the resource, whichever is found first
69
109
  def organization
70
- user.organization
110
+ user&.organization || participatory_space&.organization || resource.try(:organization)
71
111
  end
72
112
 
113
+ # Finds the component related to the resource.
114
+ #
115
+ # @return [Decidim::Component, nil] the component of the resource, if the
116
+ # resource responds to `component`
73
117
  def component
74
118
  resource.component if resource.respond_to?(:component)
75
119
  end
76
120
 
121
+ # Finds the participatory space related to the resource.
122
+ #
123
+ # @return [ActiveRecord::Base, nil] the participatory space of the
124
+ # component, of the resource, or `nil` if it cannot be found
77
125
  def participatory_space
78
126
  return component.participatory_space if component.respond_to?(:participatory_space)
79
127
 
80
128
  resource.participatory_space if resource.respond_to?(:participatory_space)
81
129
  end
82
130
 
131
+ # Finds the area related to the resource or its participatory space.
132
+ #
133
+ # @return [Decidim::Area, nil] the area of the resource or the
134
+ # participatory space, or `nil` if it cannot be found
83
135
  def area
84
136
  resource.try(:area) || participatory_space.try(:area)
85
137
  end
86
138
 
139
+ # Finds the scope related to the resource or its participatory space.
140
+ #
141
+ # @return [Decidim::Scope, nil] the scope of the resource or the
142
+ # participatory space, or `nil` if it cannot be found
87
143
  def scope
88
144
  resource.try(:scope) || participatory_space.try(:scope)
89
145
  end
90
146
 
147
+ # Finds a human-readable title for the given resource.
148
+ #
149
+ # @param resource [Object, nil] an object that may respond to `title`,
150
+ # `name`, or `subject`
151
+ # @return [String, nil] the title, name, or subject of the resource, or
152
+ # `nil` if none of them is available
91
153
  def title_for(resource)
92
154
  resource.try(:title) || resource.try(:name) || resource.try(:subject)
93
155
  end
94
156
 
157
+ # Finds the manifest name of the participatory space.
158
+ #
159
+ # @return [Symbol, nil] the manifest name of the participatory space, or
160
+ # `nil` if it cannot be found
95
161
  def participatory_space_manifest_name
96
162
  participatory_space.try(:class).try(:participatory_space_manifest).try(:name)
97
163
  end
98
164
 
99
- # Private: Defines some extra data that will be saved in the action log `extra`
165
+ # Defines some extra data that will be saved in the action log `extra`
100
166
  # field.
101
167
  #
102
- # Returns a Hash.
168
+ # @return [Hash] the extra data with information about the component, the
169
+ # participatory space, the resource, and the user, merged with the
170
+ # `resource_extra` information
103
171
  def extra_data
104
172
  {
105
173
  component: {
@@ -114,9 +182,9 @@ module Decidim
114
182
  title: title_for(resource)
115
183
  }.compact,
116
184
  user: {
117
- ip: user.current_sign_in_ip,
118
- name: user.name,
119
- nickname: user.nickname
185
+ ip: user&.current_sign_in_ip,
186
+ name: user&.name,
187
+ nickname: user&.nickname
120
188
  }.compact
121
189
  }.deep_merge(resource_extra)
122
190
  end