renox_admin/resource.rs
1//! What an app declares for each model in the panel: [`AdminResource`],
2//! with its [`AdminAction`]s and [`Filter`]s.
3
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::Arc;
8
9use renox::db::{Model, Query};
10use renox::grid::{Column, Grid};
11use renox::prelude::*;
12use serde::Serialize;
13use serde::de::DeserializeOwned;
14
15use crate::{Entry, Field};
16
17/// A boxed future that can be sent between threads, as an action returns.
18pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
19
20/// A model in the admin panel (Filament's resources), declared once: the
21/// grid's columns, the form's fields, its filters and actions, and who may
22/// do what (its [`Policy`]).
23///
24/// ```
25/// use renox::grid::Column;
26/// use renox::prelude::*;
27/// use renox_admin::{AdminResource, Field};
28/// use serde::{Deserialize, Serialize};
29///
30/// #[derive(Model, Serialize, Default, Clone)]
31/// struct Product { id: i64, name: String, price: i64, active: bool }
32///
33/// impl Policy for Product {
34/// fn allows(&self, user: &User, ability: &str) -> bool {
35/// // Everyone in the panel looks; only managers change things.
36/// matches!(ability, "viewAny" | "view") || user.has_role("manager")
37/// }
38/// }
39///
40/// #[derive(Deserialize, Serialize, Validate)]
41/// struct ProductForm {
42/// #[validate(required, max = 100)]
43/// name: String,
44/// #[validate(required, min = 0)]
45/// price: i64,
46/// active: bool,
47/// }
48///
49/// struct Products;
50///
51/// impl AdminResource for Products {
52/// type Model = Product;
53/// type Form = ProductForm;
54///
55/// fn label(&self) -> &str { "Product" }
56/// fn plural_label(&self) -> &str { "Products" }
57///
58/// fn columns(&self) -> Vec<Column> {
59/// vec![
60/// Column::text("name", "Name").searchable(),
61/// Column::money("price", "Price"),
62/// Column::bool("active", "Active"),
63/// ]
64/// }
65///
66/// fn fields(&self) -> Vec<Field> {
67/// vec![
68/// Field::text("name", "Name").required(),
69/// Field::money("price", "Price").required(),
70/// Field::toggle("active", "Active").default_value(true),
71/// ]
72/// }
73///
74/// fn fill(&self, product: &mut Product, form: ProductForm) {
75/// product.name = form.name;
76/// product.price = form.price;
77/// product.active = form.active;
78/// }
79/// }
80/// ```
81pub trait AdminResource: Send + Sync + 'static {
82 /// The model the resource manages. `Default` gives the record a create
83 /// page starts from, and the one list-level abilities are asked about.
84 type Model: Model + Policy + Serialize + Default + Send + Sync;
85
86 /// The form of the create and edit pages, checked with its own rules
87 /// (`Valid<T>`). `Serialize` refills it after [`rules`](Self::rules)
88 /// fails (passwords aren't refilled).
89 type Form: DeserializeOwned + Validate + Serialize + Send + 'static;
90
91 /// One record's name: "Product".
92 fn label(&self) -> &str;
93
94 /// Several records' name, in the navigation and the list's title:
95 /// "Products".
96 fn plural_label(&self) -> &str;
97
98 /// What a record's view and edit pages call it: "Product #7" by
99 /// default; its name reads better (`product.name.clone()`).
100 fn record_title(&self, record: &Self::Model) -> String {
101 format!("{} #{}", self.label(), record.id())
102 }
103
104 /// The resource's part of the address and of the route names
105 /// (`/admin/products`, `admin.products.index`): letters, digits, `_`
106 /// and `-`. The model's table by default.
107 fn slug(&self) -> &str {
108 Self::Model::TABLE
109 }
110
111 /// A heading the navigation puts the resource under ("Shop").
112 fn navigation_group(&self) -> Option<&str> {
113 None
114 }
115
116 /// The list's columns, left to right (`renox::grid`). Make some
117 /// `.searchable()` for the list's search box.
118 fn columns(&self) -> Vec<Column>;
119
120 /// The create and edit pages' fields, in order.
121 fn fields(&self) -> Vec<Field>;
122
123 /// Copies a valid form into the record, before it is saved (a new
124 /// record starts from `Default`).
125 fn fill(&self, record: &mut Self::Model, form: Self::Form);
126
127 /// Rules that need the record being edited (`None` while creating),
128 /// checked after the form's own, e.g. a unique value that may stay the
129 /// record's own: `v.field("sku", &form.sku).unique("products", "sku")`
130 /// followed by `.ignore(record.id)` when there is one.
131 fn rules(&self, form: &Self::Form, record: Option<&Self::Model>, v: &mut Validator) {
132 let _ = (form, record, v);
133 }
134
135 /// The details of a record's view page. Without any, the resource has
136 /// no view page and its rows open the edit page. By default, an entry
137 /// per column ([`Entry::from_column`]).
138 fn entries(&self) -> Vec<Entry> {
139 self.columns()
140 .iter()
141 .filter_map(Entry::from_column)
142 .collect()
143 }
144
145 /// Named filters over the list, shown as tabs above it ("Active",
146 /// "Low stock"); the grid's columns filter on their own too.
147 fn filters(&self) -> Vec<Filter<Self::Model>> {
148 Vec::new()
149 }
150
151 /// The resource's own actions on selected rows (and, with
152 /// [`AdminAction::row`], on one row).
153 fn actions(&self) -> Vec<AdminAction<Self::Model>> {
154 Vec::new()
155 }
156
157 /// Every query the panel runs for this resource starts here: the
158 /// model's query (with its default scope) by default. Narrow it to
159 /// what the panel may ever show.
160 fn query(&self) -> Query<Self::Model> {
161 Self::Model::query()
162 }
163
164 /// Changes the list's grid after the panel built it from the columns,
165 /// e.g. `grid.sort_by("name").per_page(50).groups(&["status"])`.
166 fn grid(&self, grid: Grid) -> Grid {
167 grid
168 }
169
170 /// Whether `user` may do `ability` (`viewAny`, `view`, `create`,
171 /// `update`, `delete`, `deleteAny`, `restore`, `restoreAny`,
172 /// `forceDelete`, `forceDeleteAny`, or an action's own) on `record`.
173 /// By default, the model's [`Policy`] after `App::gate_before`; when
174 /// there's no record (the list, the create page, what the list
175 /// offers), the policy is asked about a blank record
176 /// (`Self::Model::default()`).
177 fn allows(&self, user: &AuthUser, ability: &str, record: Option<&Self::Model>) -> bool {
178 match record {
179 Some(record) => user.can(ability, record),
180 None => user.can(ability, &Self::Model::default()),
181 }
182 }
183}
184
185/// What an action's code gets besides the records.
186#[derive(Clone)]
187#[non_exhaustive]
188pub struct ActionContext {
189 /// The app's state, e.g. its database (`state.db`).
190 pub state: AppState,
191 /// Who chose the action.
192 pub user: AuthUser,
193}
194
195type Run<M> = Arc<dyn Fn(Vec<M>, ActionContext) -> BoxFuture<'static, Result<Toast>> + Send + Sync>;
196
197/// An action of a resource's list (Filament's bulk actions): a button over
198/// the selected rows that runs `run` with their records and shows the
199/// toast it returns. With [`row`](Self::row), each row's menu has it too.
200///
201/// ```
202/// # use renox::prelude::*;
203/// use renox_admin::AdminAction;
204/// # #[derive(Model, serde::Serialize, Default, Clone)] struct Product { id: i64, active: bool }
205///
206/// let deactivate = AdminAction::new("deactivate", "Deactivate", |products: Vec<Product>, cx| async move {
207/// let ids: Vec<i64> = products.iter().map(|p| p.id).collect();
208/// let n = Product::query().where_in("id", ids).update(&cx.state.db, &[("active", &false)]).await?;
209/// Ok(Toast::success(format!("{n} products deactivated.")))
210/// })
211/// .confirm("Deactivate the selected products?")
212/// .row();
213/// # let _ = deactivate;
214/// ```
215///
216/// Every record must pass [`AdminResource::allows`] for the action's
217/// ability (`update` by default), or nothing runs (403).
218pub struct AdminAction<M> {
219 key: String,
220 label: String,
221 ability: String,
222 confirm: Option<String>,
223 danger: bool,
224 bulk: bool,
225 row: bool,
226 run: Run<M>,
227}
228
229impl<M> Clone for AdminAction<M> {
230 fn clone(&self) -> Self {
231 Self {
232 key: self.key.clone(),
233 label: self.label.clone(),
234 ability: self.ability.clone(),
235 confirm: self.confirm.clone(),
236 danger: self.danger,
237 bulk: self.bulk,
238 row: self.row,
239 run: self.run.clone(),
240 }
241 }
242}
243
244impl<M> fmt::Debug for AdminAction<M> {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246 f.debug_struct("AdminAction")
247 .field("key", &self.key)
248 .field("label", &self.label)
249 .field("ability", &self.ability)
250 .finish_non_exhaustive()
251 }
252}
253
254impl<M: Send + 'static> AdminAction<M> {
255 /// An action named `key` (letters, digits, `_` and `-`; part of its
256 /// address), shown as `label`, that runs `run`.
257 pub fn new<F, Fut>(key: &str, label: &str, run: F) -> Self
258 where
259 F: Fn(Vec<M>, ActionContext) -> Fut + Send + Sync + 'static,
260 Fut: Future<Output = Result<Toast>> + Send + 'static,
261 {
262 Self {
263 key: key.to_owned(),
264 label: label.to_owned(),
265 ability: "update".into(),
266 confirm: None,
267 danger: false,
268 bulk: true,
269 row: false,
270 run: Arc::new(move |records, cx| Box::pin(run(records, cx))),
271 }
272 }
273
274 /// The ability each record must allow (`update` by default).
275 pub fn ability(mut self, ability: &str) -> Self {
276 self.ability = ability.to_owned();
277 self
278 }
279
280 /// Asks first, in a dialog with this question.
281 pub fn confirm(mut self, question: &str) -> Self {
282 self.confirm = Some(question.to_owned());
283 self
284 }
285
286 /// Shown in red, for actions that can't be undone.
287 pub fn danger(mut self) -> Self {
288 self.danger = true;
289 self
290 }
291
292 /// Also in each row's menu, for that row alone.
293 pub fn row(mut self) -> Self {
294 self.row = true;
295 self
296 }
297
298 /// Only in each row's menu, not over the selection.
299 pub fn row_only(mut self) -> Self {
300 self.row = true;
301 self.bulk = false;
302 self
303 }
304
305 pub(crate) fn key(&self) -> &str {
306 &self.key
307 }
308
309 pub(crate) fn label(&self) -> &str {
310 &self.label
311 }
312
313 pub(crate) fn ability_name(&self) -> &str {
314 &self.ability
315 }
316
317 pub(crate) fn question(&self) -> Option<&str> {
318 self.confirm.as_deref()
319 }
320
321 pub(crate) fn is_danger(&self) -> bool {
322 self.danger
323 }
324
325 pub(crate) fn on_bulk(&self) -> bool {
326 self.bulk
327 }
328
329 pub(crate) fn on_row(&self) -> bool {
330 self.row
331 }
332
333 pub(crate) fn run(
334 &self,
335 records: Vec<M>,
336 cx: ActionContext,
337 ) -> BoxFuture<'static, Result<Toast>> {
338 (self.run)(records, cx)
339 }
340}
341
342type Scope<M> = Arc<dyn Fn(Query<M>) -> Query<M> + Send + Sync>;
343
344/// A named filter over a resource's list (Filament's tabs and preset
345/// filters), chosen with `?filter=key`.
346///
347/// ```
348/// # use renox::prelude::*;
349/// use renox_admin::Filter;
350/// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64, active: bool, stock: i64 }
351///
352/// let filters = vec![
353/// Filter::new("active", "Active", |q| q.where_eq("active", true)),
354/// Filter::new("low", "Low stock", |q| q.where_op("stock", "<", 5)),
355/// ];
356/// # let _: Vec<Filter<Product>> = filters;
357/// ```
358pub struct Filter<M> {
359 key: String,
360 label: String,
361 scope: Scope<M>,
362}
363
364impl<M> Clone for Filter<M> {
365 fn clone(&self) -> Self {
366 Self {
367 key: self.key.clone(),
368 label: self.label.clone(),
369 scope: self.scope.clone(),
370 }
371 }
372}
373
374impl<M> fmt::Debug for Filter<M> {
375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376 f.debug_struct("Filter")
377 .field("key", &self.key)
378 .field("label", &self.label)
379 .finish_non_exhaustive()
380 }
381}
382
383impl<M> Filter<M> {
384 /// A filter named `key` (its value in `?filter=`), shown as `label`,
385 /// that narrows the list's query with `scope`.
386 pub fn new(
387 key: &str,
388 label: &str,
389 scope: impl Fn(Query<M>) -> Query<M> + Send + Sync + 'static,
390 ) -> Self {
391 Self {
392 key: key.to_owned(),
393 label: label.to_owned(),
394 scope: Arc::new(scope),
395 }
396 }
397
398 pub(crate) fn key(&self) -> &str {
399 &self.key
400 }
401
402 pub(crate) fn label(&self) -> &str {
403 &self.label
404 }
405
406 pub(crate) fn apply(&self, query: Query<M>) -> Query<M> {
407 (self.scope)(query)
408 }
409}