rails_admin_next 3.0.3 → 4.0.0

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 (59) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +3 -0
  3. data/README.md +20 -2
  4. data/app/assets/stylesheets/rails_admin/skin.css +240 -7
  5. data/app/assets/stylesheets/rails_admin/tokens.css +4 -0
  6. data/app/controllers/rails_admin_next/bulk_deletions_controller.rb +27 -0
  7. data/app/controllers/rails_admin_next/main_controller.rb +34 -5
  8. data/app/helpers/rails_admin_next/application_helper.rb +17 -2
  9. data/app/helpers/rails_admin_next/main_helper.rb +64 -0
  10. data/app/jobs/rails_admin_next/bulk_delete_job.rb +65 -0
  11. data/app/views/layouts/rails_admin_next/_head.html.erb +14 -6
  12. data/app/views/layouts/rails_admin_next/content.html.erb +1 -0
  13. data/app/views/rails_admin_next/bulk_deletions/_banner.html.erb +30 -0
  14. data/app/views/rails_admin_next/main/_batch.html.erb +9 -0
  15. data/app/views/rails_admin_next/main/_history_row.html.erb +32 -0
  16. data/app/views/rails_admin_next/main/_list_row.html.erb +19 -0
  17. data/app/views/rails_admin_next/main/_next_batch.html.erb +21 -0
  18. data/app/views/rails_admin_next/main/_selection_bar.html.erb +30 -0
  19. data/app/views/rails_admin_next/main/bulk_delete.html.erb +26 -6
  20. data/app/views/rails_admin_next/main/export.html.erb +1 -0
  21. data/app/views/rails_admin_next/main/history.html.erb +5 -36
  22. data/app/views/rails_admin_next/main/index.html.erb +28 -57
  23. data/config/importmap.rails_admin.rb +7 -2
  24. data/config/locales/rails_admin_next.en.yml +37 -4
  25. data/config/routes.rb +2 -0
  26. data/docs/UPGRADING.md +194 -1
  27. data/docs/security.md +18 -8
  28. data/lib/rails_admin_next/adapters/active_record.rb +7 -0
  29. data/lib/rails_admin_next/bulk_deletion/progress.rb +70 -0
  30. data/lib/rails_admin_next/bulk_deletion.rb +99 -0
  31. data/lib/rails_admin_next/config/actions/base.rb +7 -0
  32. data/lib/rails_admin_next/config/actions/bulk_delete.rb +94 -31
  33. data/lib/rails_admin_next/config/actions/export.rb +4 -0
  34. data/lib/rails_admin_next/config/actions/history_index.rb +1 -1
  35. data/lib/rails_admin_next/config/actions/history_show.rb +1 -1
  36. data/lib/rails_admin_next/config/actions/index.rb +6 -1
  37. data/lib/rails_admin_next/config/fields/types/action_text.rb +11 -0
  38. data/lib/rails_admin_next/config/sections/list.rb +1 -2
  39. data/lib/rails_admin_next/engine.rb +1 -0
  40. data/lib/rails_admin_next/extensions/paper_trail/auditing_adapter.rb +8 -3
  41. data/lib/rails_admin_next/support/action_text_editor.rb +36 -0
  42. data/lib/rails_admin_next/support/paginated_collection.rb +4 -5
  43. data/lib/rails_admin_next/version.rb +2 -2
  44. data/lib/rails_admin_next.rb +3 -0
  45. data/skills/rails-admin-next/SKILL.md +3 -3
  46. data/src/rails_admin/controllers/alert_controller.js +3 -1
  47. data/src/rails_admin/controllers/bulk_progress_controller.js +53 -0
  48. data/src/rails_admin/controllers/bulk_selection_controller.js +151 -0
  49. data/src/rails_admin/controllers/dropdown_controller.js +7 -5
  50. data/src/rails_admin/controllers/filtering_multiselect_controller.js +4 -0
  51. data/src/rails_admin/controllers/filtering_select_controller.js +4 -0
  52. data/src/rails_admin/controllers/index.js +6 -0
  53. data/src/rails_admin/controllers/infinite_scroll_controller.js +79 -0
  54. data/src/rails_admin/controllers/modal_controller.js +3 -1
  55. data/src/rails_admin/controllers/nested_form_controller.js +3 -2
  56. data/src/rails_admin/controllers/sidescroll_controller.js +41 -10
  57. data/src/rails_admin/interactions.js +4 -12
  58. metadata +23 -4
  59. data/app/views/rails_admin_next/main/_pagination.html.erb +0 -54
data/docs/UPGRADING.md CHANGED
@@ -304,7 +304,8 @@ end
304
304
 
305
305
  Pin `:light` to keep the old always-light rendering. Two deliberate exceptions: the navbar is
306
306
  scheme-locked (`navbar_css_classes` express host intent — `navbar-dark bg-primary` stays a
307
- dark navbar under both schemes), and the Trix (ActionText) editor stays light-only for now.
307
+ dark navbar under both schemes), and the Trix rich-text editor stays light. A Lexxy editor
308
+ follows the scheme (see "Rich text follows the host's editor").
308
309
 
309
310
  ### Token mapping: `--bs-*` → `--ra-*`
310
311
 
@@ -731,6 +732,9 @@ page, is not destroyed, and counts in the "failed to be deleted" message. Before
731
732
  delete honoured only the scope, so a `destroy?` rule that reads the record, such as
732
733
  `!record.locked?`, stopped the single delete but not the bulk one.
733
734
 
735
+ The confirmation of every matching record counts every record in the scope, including the
736
+ ones `destroy?` will refuse; it says those are skipped, and the result reports them as failed.
737
+
734
738
  ## Export includes an association only if its model may be listed
735
739
 
736
740
  With Pundit or ActionPolicy configured, export leaves out an association unless the policy grants
@@ -778,6 +782,28 @@ Every admin page now ends with a small, muted "Made in Tokyo with ❤️ and
778
782
  content. It is not shown inside modals. To hide it, set `config.show_footer = false` in your
779
783
  initializer.
780
784
 
785
+ ## Rich text follows the host's editor
786
+
787
+ The admin now loads the Action Text editor your app's `rich_text_area` renders, Trix or Lexxy,
788
+ on every admin page, and links nothing for the other one. Rich-text fields work with no host
789
+ setup. If your `config/importmap.rails_admin.rb` points the `rails_admin` entrypoint at a module
790
+ that imports `trix` and `@rails/actiontext`, you can drop those imports or keep them: Trix still
791
+ loads once.
792
+
793
+ For Lexxy, add the `lexxy` gem. On Rails 8.1 the admin uses it while its
794
+ `config.lexxy.override_action_text_defaults` is on (the default); on Rails 8.2 it follows
795
+ `config.action_text.editor`. Lexxy takes its colours and fonts from the `--ra-*` tokens and
796
+ follows `color_scheme`. To change one Lexxy variable in the admin, set it in an unlayered rule
797
+ on `body.rails_admin`, not on `:root`:
798
+
799
+ ```css
800
+ body.rails_admin {
801
+ --lexxy-color-canvas: #fffdf5;
802
+ }
803
+ ```
804
+
805
+ Trix stays light in both schemes.
806
+
781
807
  ## STI subclasses use their parent model's policy
782
808
 
783
809
  Both the Pundit and the ActionPolicy adapter used to check an STI subclass with no policy of its
@@ -923,3 +949,170 @@ An auditing adapter may define `auditable?(abstract_model)`. When it answers fal
923
949
  `history_index` and `history_show` actions are hidden for that model. A custom adapter that does
924
950
  not define it keeps the History links on every model, as before. A `visible` block you configure
925
951
  on either history action replaces this check.
952
+
953
+ ## Lists load more rows as you scroll
954
+
955
+ A model's list no longer shows page links. It loads the next batch of rows, `items_per_page`
956
+ at a time, as the reader nears the bottom, with a "Load more" link and a retry link when a
957
+ batch fails. The same applies to a model's history page and a record's history page. If the
958
+ session has ended, the batch's redirect takes the reader to the sign-in page.
959
+
960
+ There is no option to keep numbered pages. `limited_pagination` keeps its meaning: no COUNT.
961
+
962
+ What else changes:
963
+
964
+ - `?page=N` URLs still work and open at that batch: the list starts at page N and loads the
965
+ following batches from there.
966
+ - The "Show all" link is gone. `all=true` still works, so existing URLs and "Export found"
967
+ are unaffected.
968
+ - The record count moves above the table, with a thousands delimiter, in the same
969
+ `div.total-count`. Only the first batch of a list without `limited_pagination` runs a
970
+ COUNT, and a `limited_pagination` list shows no count.
971
+ - Paginated lists now order by primary key (descending) after the sort, so
972
+ a record cannot appear on two pages or on none. A grouped relation is left alone.
973
+ - The `_pagination` partial is removed, with the `admin.pagination.previous`, `next` and
974
+ `truncate` keys and `admin.misc.show_all`. A host view that renders it must drop it.
975
+ - A custom auditing adapter's listing scrolls when it responds to `each`, `current_page` and
976
+ `full_page?` (true when the page is full, so more may follow), as
977
+ `RailsAdminNext::PaginatedCollection` does. A listing without `full_page?` shows its rows
978
+ with no way to load more.
979
+ - The `turbo-rails` floor is now `>= 2.0`, the version the suite runs against.
980
+
981
+ New locale keys, under `admin.pagination`: `end`, `error`, `load_more`, `retry`.
982
+
983
+ ## A selection bar holds the bulk menu
984
+
985
+ Once any row is ticked, a bar pins under the navbar with the number of ticked rows, a "Clear
986
+ selection" button and the bulk actions menu. The menu no longer sits in the contextual tabs
987
+ above the list, so it stays in reach on a long list. Nothing shows while no row is ticked, and
988
+ a list configured with `checkboxes false` has no bar.
989
+
990
+ What else changes:
991
+
992
+ - Each bulk menu link names its action in `data-bulk-action` instead of `data-action`. The
993
+ menu now sits inside the element of the `bulk-selection` Stimulus controller, where
994
+ Stimulus would read `data-action` as an action descriptor. A host script that reads
995
+ `.bulk-link[data-action]` must read `data-bulk-action`.
996
+ - `#bulk_menu` and `#bulk_menu_toggle` keep their ids, but are no longer inside `.nav-tabs`.
997
+ - The select-all checkbox, the row checkboxes and the carrying over of ticks as batches load
998
+ are handled by the `bulk-selection` controller on `#bulk_form`. A host that overrides
999
+ `main/index.html.erb` or `main/_list_row.html.erb` keeps its copy and gets no bar until it
1000
+ copies those views again.
1001
+ - Arrow keys in every dropdown menu skip items hidden with CSS.
1002
+
1003
+ New locale keys, under `admin.misc`: `clear_selection`, `select_all_loaded`,
1004
+ `selected_count`, and `selection_announcements` with `all_loaded`, `cleared` and
1005
+ `rows_selected`.
1006
+
1007
+ ## Bulk actions can act on every matching record
1008
+
1009
+ Once every loaded row is ticked and more rows match, the selection bar offers "Select all N
1010
+ matching". Choosing it hands the bulk action the whole filtered set, not the ticked rows. The
1011
+ menu then shows only the actions that accept it: "Export found" and bulk delete. Their links
1012
+ carry `data-all-matching`.
1013
+
1014
+ A host bulk action opts in with `all_matching?`:
1015
+
1016
+ ```ruby
1017
+ class Archive < RailsAdminNext::Config::Actions::Base
1018
+ RailsAdminNext::Config::Actions.register(self)
1019
+
1020
+ register_instance_option(:bulkable?) { true }
1021
+ register_instance_option(:all_matching?) { true }
1022
+
1023
+ register_instance_option :controller do
1024
+ proc do
1025
+ archivable = ->(record) { @authorization_adapter.nil? || @authorization_adapter.authorized?(:archive, @abstract_model, record) }
1026
+ list_entries(@model_config, :update).select(&archivable).each(&:archive!)
1027
+ redirect_to back_or_index
1028
+ end
1029
+ end
1030
+ end
1031
+ ```
1032
+
1033
+ With `params[:all_matching]` present an opted-in action receives no `params[:bulk_ids]`, and
1034
+ `list_entries` returns the whole filtered set, unpaginated. The server rebuilds that relation
1035
+ from the authorization scope, the scope tab, the query and the filters, so the count in the
1036
+ bar is only for display. `list_entries` narrows by scope alone: both adapters' `query` ignore
1037
+ the action, so an action that must ask a per-record rule checks each record with
1038
+ `authorized?`, as above. An action that has not opted in answers a submit carrying the flag
1039
+ with a redirect and the "No actions were taken" notice. `all_matching?` is false by default.
1040
+
1041
+ New locale keys, under `admin.misc`: `all_matching_selected`,
1042
+ `all_matching_selected_uncounted`, `loaded_selected_count`, `select_all_matches`,
1043
+ `select_all_matches_uncounted`, `select_all_matching`, `select_all_matching_uncounted`.
1044
+
1045
+ ## Bulk delete confirms the exact set it deletes
1046
+
1047
+ Confirming a delete of every matching record shows how many records will be deleted and what
1048
+ selects them: the search query, each filter with its operator and value, and the scope tab, or
1049
+ that it is every record of the model. The count includes records the reader may not delete;
1050
+ with an authorization adapter configured the page says those are skipped and reported as
1051
+ failed. An explicit selection lists its records up to 100 and states the count above that.
1052
+
1053
+ The confirmation carries a SHA-256 digest of the matching records' primary keys. At submit the
1054
+ keys are taken again, and if the set differs in any way, a record gone or a record added,
1055
+ nothing is deleted: the confirmation renders again for the current set, with status 422 and a
1056
+ notice. A record that starts matching after the confirmation is never deleted unconfirmed.
1057
+
1058
+ What else changes:
1059
+
1060
+ - The confirmation form carries its selection in hidden body fields (`bulk_ids[]`, or
1061
+ `all_matching` with the filter params and `confirmed_digest`) instead of the query string,
1062
+ so a few hundred ids no longer overflow the URL. `scope` stays in the action URL.
1063
+ - Records are reloaded through the model's `unscoped`, so a `default_scope` can no longer hide
1064
+ a confirmed record from the delete.
1065
+ - A selection with no records left, or a submit with neither ids nor the flag, redirects with
1066
+ "Nothing was left to delete" instead of "0 … failed to be deleted".
1067
+
1068
+ New locale keys, under `admin.flash`: `bulk_delete_changed`, `bulk_delete_nothing_left`;
1069
+ under `admin.form`: `bulk_delete_count`, `bulk_delete_everything`, `bulk_delete_matching`,
1070
+ `bulk_delete_query`, `bulk_delete_scope`, `bulk_delete_unauthorized_skipped`.
1071
+
1072
+ ## Large bulk deletes run in the background
1073
+
1074
+ A confirmed set larger than the bulk delete action's `background_threshold` (500 by default)
1075
+ is destroyed by `RailsAdminNext::BulkDeleteJob` on the host's ActiveJob adapter, whatever it
1076
+ is, Rails' default `:async` included. The engine now requires `active_job/railtie`, so a host
1077
+ that left it out needs no setup. The reader returns to the list, where a banner shows the
1078
+ records done out of the total, refreshes every two seconds while the tab is visible, and ends with the deleted and
1079
+ failed counts. To keep every delete in the request:
1080
+
1081
+ ```ruby
1082
+ config.actions do
1083
+ bulk_delete do
1084
+ background_threshold Float::INFINITY
1085
+ end
1086
+ end
1087
+ ```
1088
+
1089
+ What a background delete needs and does:
1090
+
1091
+ - **Authorization at submit.** Pundit and ActionPolicy need the live controller, so the
1092
+ request asks `destroy?` of every confirmed record before enqueuing, counts the refusals as
1093
+ failed and enqueues only the rest. When every record is refused nothing is enqueued. That
1094
+ pass runs inside one request, so a set larger than `authorization_limit` (10,000 by default)
1095
+ is refused before its confirmation, and nothing is deleted. Raise it, or lift it with
1096
+ `authorization_limit Float::INFINITY`, if your policies are cheap and your request timeout
1097
+ allows.
1098
+ - **Slices.** The keys go out in jobs of about 32 KB of arguments each, so a backend that
1099
+ stores arguments in a `TEXT` column (Solid Queue on MySQL) never overflows it. A very large
1100
+ set runs as several jobs, in parallel on a multi-threaded adapter.
1101
+ - **Progress in `Rails.cache`.** A `NullStore` keeps nothing: the jobs still run, and the
1102
+ reader sees a notice that the records are being deleted in the background instead of a
1103
+ banner. The web and job processes must share the cache, or the banner reports the progress
1104
+ as unavailable after five minutes. Entries expire after a day.
1105
+ - **A stopped delete says so.** A slice that raises, or that goes quiet for five minutes, as
1106
+ an `:async` job does when the server restarts, turns the banner into a stopped report with
1107
+ the counts so far and a link to the filtered list, where the remaining records can be
1108
+ deleted again.
1109
+ - **Auditing.** PaperTrail versions name the submitting user. A custom auditing adapter's
1110
+ `delete_object` runs inside the job and receives the submitting user from it. The job
1111
+ evaluates `audit_with` with no controller, so a custom adapter must not read request state
1112
+ (`request`, `params`, `session`); its third argument is the user. The job finds a record
1113
+ user again by its GlobalID, and passes `nil` once that user has been deleted. Any other
1114
+ user object must be one ActiveJob can serialize, or a large delete raises
1115
+ `ActiveJob::SerializationError` before anything is deleted.
1116
+
1117
+ New locale keys, under `admin.bulk_deletion`: `finished`, `gone`, `remaining`, `running`,
1118
+ `stopped`, `unavailable`; under `admin.flash`: `bulk_delete_background`, `bulk_delete_too_many`.
data/docs/security.md CHANGED
@@ -25,6 +25,11 @@ destructive-action controls itself; a few things are left for the host to opt in
25
25
  check rather than listing or allowing anything; `user` cannot be replaced through `context:`.
26
26
  - **Destructive actions.** `delete` and `bulk_delete` render a confirmation page and additionally
27
27
  carry `data-turbo-confirm` on the destructive submit (Turbo's confirmation, not `@rails/ujs`).
28
+ A bulk delete of every matching record binds its confirmation to a SHA-256 digest of the
29
+ matching primary keys: if the set differs at submit, nothing is deleted and the confirmation is
30
+ shown again, so a record that starts matching afterwards is never deleted unconfirmed. A
31
+ background delete asks `destroy?` of each record in the request, before any job runs, and its
32
+ progress endpoint answers only the ids in the caller's session.
28
33
  - **Mass assignment.** Submitted attributes are sliced to the model config's `visible_fields`
29
34
  before `permit!`, at the top level and at every nested depth, regardless of the submitted
30
35
  nested-attributes cardinality (hash or array). At nested depth the slice also drops the child's
@@ -63,17 +68,22 @@ RailsAdminNext.config do |config|
63
68
  end
64
69
  ```
65
70
 
66
- > **Note on `style-src`.** The admin still renders five inline `style="…"` attributes, which a CSP
71
+ > **Note on `style-src`.** The admin still renders inline `style="…"` attributes, which a CSP
67
72
  > nonce cannot cover (nonces apply to `<script>`/`<style>` elements, not style attributes), so a
68
73
  > `style-src` directive needs `:unsafe_inline` for now. The engine's own `<style>` element (the
69
74
  > index column-width block) is nonced. The remaining attributes:
70
75
  >
71
- > - the `#loading` badge's positioning in the layout, and the delete-notice `<li>` spacing —
76
+ > - the `#loading` badge's positioning in the layout, the delete-notice `<li>` spacing, the
77
+ > polymorphic association select's float and the filtering multiselect's "new" link margin:
72
78
  > static values, removable by moving them into the stylesheet;
73
- > - the file-upload delete toggle's initial `display:none` — conditional initial state, removable
74
- > by switching to the `hidden` attribute;
75
- > - the dashboard's `.progress` margin (static) and each progress bar's `width: N%` (a per-row
76
- > dynamic value — the one that genuinely resists removal; it would need the nonced-`<style>`
77
- > route or a native `<progress>` element).
79
+ > - `display:none` on the `#loading` badge, on the form builder's legend for the default
80
+ > fieldset, on the file-upload delete toggle and its checkbox, and on the multiple-file-upload
81
+ > keep and delete checkboxes: hidden or conditional initial state, removable by switching to the
82
+ > `hidden` attribute. The badge and the delete toggle are shown by script setting
83
+ > `style.display = ""`, which cannot undo `hidden`, so that script must toggle `hidden` instead;
84
+ > - the dashboard's `.progress` margin (static);
85
+ > - two per-record dynamic values that genuinely resist removal: each dashboard progress bar's
86
+ > `width: N%` (it would need the nonced-`<style>` route or a native `<progress>` element) and
87
+ > the color field's `color:` on its displayed value.
78
88
  >
79
- > Once those five are reauthored, `:unsafe_inline` can be dropped.
89
+ > Once those are reauthored, `:unsafe_inline` can be dropped.
@@ -166,8 +166,15 @@ module RailsAdminNext
166
166
  # Offset-mode pagination over the (already ordered/filtered) relation.
167
167
  # geared_pagination runs the real LIMIT/OFFSET/COUNT; the returned
168
168
  # PaginatedCollection is the thin view-facing wrapper.
169
+ #
170
+ # The primary key breaks ties in the sort, so a record cannot sit on two
171
+ # pages or on none. Only paginated relations get it: export batches by
172
+ # primary key when the sort is a single order. A grouped relation is left
173
+ # alone, since ordering by a column outside the GROUP BY is an error on
174
+ # PostgreSQL.
169
175
  def paginate_scope(scope, page, per)
170
176
  per = [per.to_i, 1].max
177
+ scope = scope.order(Array(scope.primary_key).index_with(:desc)) if scope.primary_key && scope.group_values.empty?
171
178
  recordset = GearedPagination::Recordset.new(scope, per_page: per)
172
179
  RailsAdminNext::PaginatedCollection.from_recordset(recordset, page, per)
173
180
  end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsAdminNext
4
+ class BulkDeletion
5
+ # A background delete's progress in Rails.cache: one meta entry the request writes, and one
6
+ # entry per slice that only that slice's job writes, so parallel slices never race.
7
+ module Progress
8
+ NAMESPACE = "rails_admin_next/bulk_deletions"
9
+ EXPIRES_IN = 1.day
10
+ # A slice that has written and then stays quiet this long has died with its process. Before
11
+ # any slice writes, the same wait tells a long queue apart from a cache the jobs do not share.
12
+ QUIET_LIMIT = 5.minutes
13
+ SESSION_KEY = :rails_admin_next_bulk_deletions
14
+
15
+ Summary = Data.define(:state, :model_name, :total, :done, :deleted, :failed, :gone, :list_path) do
16
+ def self.unavailable = new(state: :unavailable, model_name: nil, total: 0, done: 0, deleted: 0, failed: 0, gone: 0, list_path: nil)
17
+
18
+ def terminal? = state != :running
19
+ end
20
+
21
+ module_function
22
+
23
+ # Decided by class: Rails wraps each request in a local cache, so a NullStore reads its own
24
+ # write back within the request that wrote it.
25
+ def working_cache?
26
+ !Rails.cache.is_a?(ActiveSupport::Cache::NullStore)
27
+ end
28
+
29
+ def start(model_name:, total:, refused:, slices:, list_path:)
30
+ id = SecureRandom.uuid
31
+ Rails.cache.write(key(id), {model_name:, total:, refused:, slices:, list_path:, started_at: Time.current}, expires_in: EXPIRES_IN)
32
+ id
33
+ end
34
+
35
+ def write_slice(id, index, counts, state:)
36
+ Rails.cache.write(key(id, index), {**counts.to_h, state:, written_at: Time.current}, expires_in: EXPIRES_IN)
37
+ end
38
+
39
+ def slice_counts(id, index)
40
+ entry = Rails.cache.read(key(id, index))
41
+ Counts.new(**entry.slice(:deleted, :failed, :gone)) if entry
42
+ end
43
+
44
+ def summary(id)
45
+ meta = Rails.cache.read(key(id))
46
+ return Summary.unavailable unless meta
47
+
48
+ entries = Rails.cache.read_multi(*Array.new(meta[:slices]) { key(id, it) }).values
49
+ sum = ->(field) { entries.sum { it[field] } }
50
+ Summary.new(state: state(meta, entries), model_name: meta[:model_name], total: meta[:total],
51
+ done: meta[:refused] + sum.call(:deleted) + sum.call(:failed) + sum.call(:gone),
52
+ deleted: sum.call(:deleted), failed: meta[:refused] + sum.call(:failed), gone: sum.call(:gone), list_path: meta[:list_path])
53
+ end
54
+
55
+ def key(id, index = nil)
56
+ [NAMESPACE, id, index].compact.join("/")
57
+ end
58
+
59
+ # A slice with no entry yet is queued, not stalled.
60
+ def state(meta, entries)
61
+ quiet = ->(time) { time < QUIET_LIMIT.ago }
62
+ return :unavailable if entries.empty? && quiet.call(meta[:started_at])
63
+ return :finished if entries.size == meta[:slices] && entries.all? { it[:state] == :finished }
64
+ return :stopped if entries.any? { it[:state] == :errored || (it[:state] != :finished && quiet.call(it[:written_at])) }
65
+
66
+ :running
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module RailsAdminNext
6
+ # The record walk behind a bulk delete, run by the request and by the background job alike.
7
+ # The confirmed keys come from the reader's list relation; records reload through `unscoped`,
8
+ # so a default_scope can neither hide nor reorder a confirmed record.
9
+ class BulkDeletion
10
+ CHUNK_SIZE = 1_000
11
+
12
+ Counts = Struct.new(:deleted, :failed, :gone) do
13
+ def self.zero = new(deleted: 0, failed: 0, gone: 0)
14
+
15
+ def done = deleted + failed + gone
16
+ end
17
+
18
+ # A filter on a has_many association eager-loads a join that repeats a record once per
19
+ # matching associated row, so the keys are of distinct records.
20
+ def self.keys(relation)
21
+ model = relation.model
22
+ keys = relation.unscope(:order)
23
+ keys = keys.eager_loading? ? keys.distinct : keys.unscope(:includes)
24
+ keys.pluck(*Array(model.primary_key).map { model.arel_table[it] }).sort.reverse
25
+ end
26
+
27
+ # JSON keeps the serialization unambiguous: [1, 23] and [12, 3] digest differently.
28
+ def self.digest(abstract_model, keys)
29
+ Digest::SHA256.hexdigest(JSON.generate(keys.map { abstract_model.format_id(it).to_s }.sort))
30
+ end
31
+
32
+ # Job arguments land in a backend's TEXT column (64 KB on MySQL for Solid Queue), so each
33
+ # slice stays well under it.
34
+ SLICE_BYTES = 32_768
35
+
36
+ def self.slices(keys)
37
+ bytes = 0
38
+ keys.each_with_object([[]]) do |key, slices|
39
+ size = JSON.generate(key).bytesize + 1
40
+ if slices.last.any? && bytes + size > SLICE_BYTES
41
+ slices << []
42
+ bytes = 0
43
+ end
44
+ slices.last << key
45
+ bytes += size
46
+ end
47
+ end
48
+
49
+ def initialize(abstract_model, keys)
50
+ @model = abstract_model.model
51
+ @keys = keys
52
+ end
53
+
54
+ # Walks the keys after the ones `start` already counted, so a retried walk keeps an earlier
55
+ # attempt's counts instead of finding its records gone.
56
+ def destroy(authorize: nil, audit: nil, progress: nil, start: Counts.zero)
57
+ counts = start.dup
58
+ each_record(@keys.drop(counts.done)) do |_key, record|
59
+ if record.nil?
60
+ counts.gone += 1
61
+ elsif destroyed?(record, authorize)
62
+ audit&.call(record)
63
+ counts.deleted += 1
64
+ else
65
+ counts.failed += 1
66
+ end
67
+ progress&.call(counts)
68
+ end
69
+ counts
70
+ end
71
+
72
+ # The keys a background delete may hand to its jobs, and how many the reader may not
73
+ # delete. A key whose record is gone stays, so the job counts it as already gone.
74
+ def authorized_keys(authorize)
75
+ kept = []
76
+ refused = 0
77
+ each_record(@keys) { |key, record| (record.nil? || authorize.call(record)) ? kept << key : refused += 1 }
78
+ [kept, refused]
79
+ end
80
+
81
+ private
82
+
83
+ def each_record(keys)
84
+ keys.each_slice(CHUNK_SIZE) do |chunk|
85
+ records = @model.unscoped.where(@model.primary_key => chunk).index_by(&:id)
86
+ chunk.each { yield it, records[it] }
87
+ end
88
+ end
89
+
90
+ def destroyed?(record, authorize)
91
+ return false if authorize && !authorize.call(record)
92
+
93
+ record.destroy
94
+ record.destroyed?
95
+ rescue ActiveRecord::DeleteRestrictionError, ActiveRecord::InvalidForeignKey, ActiveRecord::RecordNotDestroyed
96
+ false
97
+ end
98
+ end
99
+ end
@@ -104,6 +104,13 @@ module RailsAdminNext
104
104
  false
105
105
  end
106
106
 
107
+ # Bulk actions only. When true, a submit carrying params[:all_matching] acts on every record the
108
+ # current filter matches: params[:bulk_ids] is absent and list_entries returns the whole filtered set
109
+ # unpaginated. When false, such a submit through the bulk menu is refused as a cancel.
110
+ register_instance_option :all_matching? do
111
+ false
112
+ end
113
+
107
114
  # View partial name (called in default :controller block)
108
115
  register_instance_option :template_name do
109
116
  key.to_sym
@@ -14,57 +14,120 @@ module RailsAdminNext
14
14
  %i[post delete]
15
15
  end
16
16
 
17
+ # Above this many records an explicit selection's confirmation states the count instead of
18
+ # listing each one.
19
+ LIST_LIMIT = 100
20
+
17
21
  register_instance_option :controller do
18
22
  proc do
19
23
  destroyable = ->(object) { @authorization_adapter.nil? || @authorization_adapter.authorized?(@action.authorization_key, @abstract_model, object) }
24
+ labelled = ->(count) { pluralize(count, @model_config.label, plural: @model_config.label_plural) }
25
+ nothing_left = -> { redirect_to back_or_index, notice: t("admin.flash.bulk_delete_nothing_left") }
26
+ # A background delete authorizes every record inside the request, so a set past the
27
+ # limit would time out there; it is refused before anything is confirmed or enqueued.
28
+ too_many_to_authorize = ->(keys) { @authorization_adapter && keys.size > @action.background_threshold && keys.size > @action.authorization_limit }
29
+ refuse_too_many = lambda do |keys|
30
+ flash[:error] = t("admin.flash.bulk_delete_too_many", name: labelled.call(keys.size), limit: @action.authorization_limit.to_fs(:delimited))
31
+ redirect_to back_or_index
32
+ end
33
+ # An all-matching confirmation names its set by digest, so a set that changed before
34
+ # the submit is confirmed again rather than deleted.
35
+ confirm_all_matching = lambda do |keys, status: :ok|
36
+ @count = keys.size
37
+ @confirmed_digest = RailsAdminNext::BulkDeletion.digest(@abstract_model, keys)
38
+ render @action.template_name, status:
39
+ end
20
40
 
21
41
  if request.post? # BULK DELETE
22
- @objects = list_entries(@model_config, :destroy).select(&destroyable)
42
+ if all_matching?
43
+ keys = RailsAdminNext::BulkDeletion.keys(list_entries(@model_config, :destroy))
44
+ next nothing_left.call if keys.empty?
45
+ next refuse_too_many.call(keys) if too_many_to_authorize.call(keys)
23
46
 
24
- if @objects.blank?
25
- flash[:error] = t("admin.flash.error", name: pluralize(0, @model_config.label, plural: @model_config.label_plural), action: t("admin.actions.delete.done"))
26
- redirect_to index_path
47
+ confirm_all_matching.call(keys)
27
48
  else
49
+ @objects = list_entries(@model_config, :destroy).select(&destroyable)
50
+ next nothing_left.call if @objects.empty?
51
+
52
+ @count = @objects.size if @objects.size > LIST_LIMIT
28
53
  render @action.template_name
29
54
  end
30
55
 
31
56
  elsif request.delete? # BULK DESTROY
57
+ # Neither flag nor ids selects nothing: the list relation would otherwise widen to
58
+ # the first page, or with params[:all] to every record.
59
+ next nothing_left.call unless all_matching? || params[:bulk_ids].present?
32
60
 
33
- destroyed = nil
34
- not_destroyed = nil
35
-
36
- unless params[:bulk_ids].blank?
37
- @objects = list_entries(@model_config, :destroy)
38
- unless @objects.blank?
39
- # Rescue per record: dependent: :restrict_with_exception raises, and an
40
- # escaping raise would abandon every record behind it in the batch.
41
- # Audit inside the loop so any other raise still leaves a history row
42
- # for each record already destroyed.
43
- destroyed, not_destroyed = Array.wrap(@objects).partition do |object|
44
- next false unless destroyable.call(object)
45
-
46
- object.destroy
47
- next false unless object.destroyed?
48
-
49
- @auditing_adapter&.delete_object(object, @abstract_model, _current_user)
50
- true
51
- rescue ActiveRecord::DeleteRestrictionError
52
- false
53
- end
54
- end
61
+ keys = RailsAdminNext::BulkDeletion.keys(list_entries(@model_config, :destroy))
62
+ next nothing_left.call if keys.empty?
63
+
64
+ if all_matching? && RailsAdminNext::BulkDeletion.digest(@abstract_model, keys) != params[:confirmed_digest]
65
+ flash.now[:notice] = t("admin.flash.bulk_delete_changed")
66
+ next confirm_all_matching.call(keys, status: :unprocessable_content)
55
67
  end
68
+ next refuse_too_many.call(keys) if too_many_to_authorize.call(keys)
56
69
 
57
- if destroyed.nil?
58
- flash[:error] = t("admin.flash.error", name: pluralize(0, @model_config.label, plural: @model_config.label_plural), action: t("admin.actions.delete.done"))
59
- else
60
- flash[:success] = t("admin.flash.successful", name: pluralize(destroyed.count, @model_config.label, plural: @model_config.label_plural), action: t("admin.actions.delete.done")) unless destroyed.empty?
61
- flash[:error] = t("admin.flash.error", name: pluralize(not_destroyed.count, @model_config.label, plural: @model_config.label_plural), action: t("admin.actions.delete.done")) unless not_destroyed.empty?
70
+ if keys.size > @action.background_threshold
71
+ deletion = RailsAdminNext::BulkDeletion.new(@abstract_model, keys)
72
+ kept, refused = @authorization_adapter ? deletion.authorized_keys(destroyable) : [keys, 0]
73
+ if kept.empty?
74
+ flash[:error] = t("admin.flash.error", name: labelled.call(refused), action: t("admin.actions.delete.done"))
75
+ next redirect_to back_or_index
76
+ end
77
+
78
+ slices = RailsAdminNext::BulkDeletion.slices(kept)
79
+ list_path = index_path(request.params.slice("query", "f", "scope", "sort", "sort_reverse")) if all_matching?
80
+ progress_id = RailsAdminNext::BulkDeletion::Progress.start(model_name: @abstract_model.model_name, total: keys.size, refused:, slices: slices.size, list_path:)
81
+ whodunnit = ::PaperTrail.request.whodunnit if defined?(::PaperTrail)
82
+ # A record goes as its GlobalID string, which the job locates itself, so a user
83
+ # deleted before a slice runs cannot fail that slice's argument deserialization.
84
+ submitter = _current_user.respond_to?(:to_global_id) ? _current_user.to_global_id.to_s : _current_user
85
+ jobs = slices.each_with_index.map { |slice, index| RailsAdminNext::BulkDeleteJob.new(@abstract_model.model_name, slice, progress_id, index, whodunnit, submitter) }
86
+ ActiveJob.perform_all_later(jobs)
87
+ # perform_all_later swallows a refused enqueue, and a slice that never runs never
88
+ # writes its entry, so the banner would wait on it until the meta entry expires.
89
+ jobs.each_with_index.reject { |job, _| job.successfully_enqueued? }.each do |_, index|
90
+ RailsAdminNext::BulkDeletion::Progress.write_slice(progress_id, index, RailsAdminNext::BulkDeletion::Counts.zero, state: :errored)
91
+ end
92
+
93
+ if RailsAdminNext::BulkDeletion::Progress.working_cache?
94
+ session[RailsAdminNext::BulkDeletion::Progress::SESSION_KEY] = [*session[RailsAdminNext::BulkDeletion::Progress::SESSION_KEY], progress_id]
95
+ else
96
+ flash[:notice] = t("admin.flash.bulk_delete_background", name: labelled.call(keys.size))
97
+ end
98
+ next redirect_to back_or_index
62
99
  end
100
+
101
+ # Audited inside the walk, so an error that escapes it still leaves a history row
102
+ # for each record already destroyed.
103
+ audit = ->(object) { @auditing_adapter&.delete_object(object, @abstract_model, _current_user) }
104
+ counts = RailsAdminNext::BulkDeletion.new(@abstract_model, keys).destroy(authorize: destroyable, audit:)
105
+
106
+ next nothing_left.call if counts.deleted.zero? && counts.failed.zero?
107
+
108
+ flash[:success] = t("admin.flash.successful", name: labelled.call(counts.deleted), action: t("admin.actions.delete.done")) unless counts.deleted.zero?
109
+ flash[:error] = t("admin.flash.error", name: labelled.call(counts.failed), action: t("admin.actions.delete.done")) unless counts.failed.zero?
63
110
  redirect_to back_or_index
64
111
  end
65
112
  end
66
113
  end
67
114
 
115
+ register_instance_option :all_matching? do
116
+ true
117
+ end
118
+
119
+ # A larger confirmed set is destroyed by background jobs; Float::INFINITY keeps every
120
+ # delete in the request.
121
+ register_instance_option :background_threshold do
122
+ 500
123
+ end
124
+
125
+ # The most records a background delete authorizes one by one in the request when the
126
+ # host has an authorization adapter; Float::INFINITY lifts the cap.
127
+ register_instance_option :authorization_limit do
128
+ 10_000
129
+ end
130
+
68
131
  register_instance_option :authorization_key do
69
132
  :destroy
70
133
  end
@@ -35,6 +35,10 @@ module RailsAdminNext
35
35
  end
36
36
  end
37
37
 
38
+ register_instance_option :all_matching? do
39
+ true
40
+ end
41
+
38
42
  register_instance_option :bulkable? do
39
43
  true
40
44
  end
@@ -33,7 +33,7 @@ module RailsAdminNext
33
33
  @auditing_adapter&.listing_for_model(*listing)
34
34
  end || []
35
35
 
36
- render @action.template_name
36
+ render_history
37
37
  end
38
38
  end
39
39
 
@@ -27,7 +27,7 @@ module RailsAdminNext
27
27
  @general = false
28
28
  @history = @auditing_adapter&.listing_for_object(@abstract_model, @object, params[:query], params[:sort], params[:sort_reverse], params[:all], params[:page]) || []
29
29
 
30
- render @action.template_name
30
+ render_history
31
31
  end
32
32
  end
33
33