Skip to main content

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, RelationManager};
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    /// Whether the panel offers a create page and a "New" button. Return
158    /// `false` for a resource that is only edited (a settings row, a
159    /// record other code creates): the create address answers 404.
160    fn creatable(&self) -> bool {
161        true
162    }
163
164    /// Whether records can be deleted from the panel (the delete buttons,
165    /// the bulk delete, the trash and its restore). Return `false` for an
166    /// edit-only resource: those addresses answer 404.
167    fn deletable(&self) -> bool {
168        true
169    }
170
171    /// Child rows managed from a record's own pages (Filament's relation
172    /// managers): its variants, photos or tags, each a tab of the record
173    /// with its own list. See [`RelationManager`].
174    fn relations(&self) -> Vec<RelationManager> {
175        Vec::new()
176    }
177
178    /// Runs after the create or edit page saved a record (Filament's
179    /// `afterSave`), with who saved it and, on an edit, the record as it was
180    /// ([`SaveContext::previous`]): audit an exact price change, refresh
181    /// search keywords. An error answers the request with it, though the
182    /// record is saved by then; do the work in a transaction of your own
183    /// when it must go in with the record.
184    ///
185    /// ```
186    /// # use renox::prelude::*;
187    /// # use renox::grid::Column;
188    /// # use renox_admin::{AdminResource, Field, SaveContext};
189    /// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64, name: String, price: i64 }
190    /// # impl Policy for Product { fn allows(&self, _: &User, _: &str) -> bool { true } }
191    /// # #[derive(serde::Deserialize, serde::Serialize, Validate)] struct ProductForm { #[validate(required)] name: String }
192    /// struct Products;
193    ///
194    /// impl AdminResource for Products {
195    /// #   type Model = Product;
196    /// #   type Form = ProductForm;
197    /// #   fn label(&self) -> &str { "Product" }
198    /// #   fn plural_label(&self) -> &str { "Products" }
199    /// #   fn columns(&self) -> Vec<Column> { vec![] }
200    /// #   fn fields(&self) -> Vec<Field> { vec![] }
201    /// #   fn fill(&self, p: &mut Product, f: ProductForm) { p.name = f.name; }
202    ///     // ...
203    ///     async fn saved(&self, product: &Product, cx: &SaveContext) -> Result {
204    ///         let before = cx.previous.as_ref().and_then(|old| old["price"].as_i64());
205    ///         if before.is_some_and(|before| before != product.price) {
206    ///             // Write the audit entry: who (`cx.user`), which product, from, to.
207    ///             let _ = (&cx.state.db, &cx.user);
208    ///         }
209    ///         Ok(())
210    ///     }
211    /// }
212    /// ```
213    fn saved(&self, record: &Self::Model, cx: &SaveContext) -> impl Future<Output = Result> + Send {
214        let _ = (record, cx);
215        async { Ok(()) }
216    }
217
218    /// Every query the panel runs for this resource starts here: the
219    /// model's query (with its default scope) by default. Narrow it to
220    /// what the panel may ever show.
221    fn query(&self) -> Query<Self::Model> {
222        Self::Model::query()
223    }
224
225    /// Changes the list's grid after the panel built it from the columns,
226    /// e.g. `grid.sort_by("name").per_page(50).groups(&["status"])`.
227    fn grid(&self, grid: Grid) -> Grid {
228        grid
229    }
230
231    /// Whether `user` may do `ability` (`viewAny`, `view`, `create`,
232    /// `update`, `delete`, `deleteAny`, `restore`, `restoreAny`,
233    /// `forceDelete`, `forceDeleteAny`, or an action's own) on `record`.
234    /// By default, the model's [`Policy`] after `App::gate_before`; when
235    /// there's no record (the list, the create page, what the list
236    /// offers), the policy is asked about a blank record
237    /// (`Self::Model::default()`).
238    fn allows(&self, user: &AuthUser, ability: &str, record: Option<&Self::Model>) -> bool {
239        match record {
240            Some(record) => user.can(ability, record),
241            None => user.can(ability, &Self::Model::default()),
242        }
243    }
244}
245
246/// What an action's code gets besides the records.
247#[derive(Clone)]
248#[non_exhaustive]
249pub struct ActionContext {
250    /// The app's state, e.g. its database (`state.db`).
251    pub state: AppState,
252    /// Who chose the action.
253    pub user: AuthUser,
254    /// What the user typed in the action's form ([`AdminAction::form`]);
255    /// empty for an action without one.
256    pub input: ActionInput,
257}
258
259/// What the user typed into an action's form, already checked against the
260/// form's fields ([`AdminAction::form`]). Money fields are in the currency's
261/// smallest unit, toggles are `true` or `false`, and a field left empty is
262/// the empty text.
263///
264/// ```
265/// # use renox_admin::ActionInput;
266/// # fn demo(input: &ActionInput) {
267/// let percent: f64 = input.parse("percent").unwrap_or(0.0);
268/// let reason = input.text("reason");
269/// let notify = input.bool("notify");
270/// # let _ = (percent, reason, notify); }
271/// ```
272#[derive(Debug, Clone, Default)]
273pub struct ActionInput {
274    values: Vec<(String, String)>,
275}
276
277impl ActionInput {
278    pub(crate) fn new(values: Vec<(String, String)>) -> Self {
279        Self { values }
280    }
281
282    /// The value of field `name`, if the form had one.
283    pub fn get(&self, name: &str) -> Option<&str> {
284        self.values
285            .iter()
286            .find(|(key, _)| key == name)
287            .map(|(_, value)| value.as_str())
288    }
289
290    /// The value of field `name`, or `""`.
291    pub fn text(&self, name: &str) -> &str {
292        self.get(name).unwrap_or("")
293    }
294
295    /// The value of field `name` read as a `T` (a number, a date…), or
296    /// `None` when it is empty or doesn't read as one.
297    pub fn parse<T: std::str::FromStr>(&self, name: &str) -> Option<T> {
298        self.get(name)?.trim().parse().ok()
299    }
300
301    /// Whether the checkbox or toggle `name` was on.
302    pub fn bool(&self, name: &str) -> bool {
303        matches!(self.get(name), Some("true" | "on" | "1"))
304    }
305
306    /// Every field's name and value, in the form's order.
307    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
308        self.values.iter().map(|(k, v)| (k.as_str(), v.as_str()))
309    }
310}
311
312/// What a resource's [`saved`](AdminResource::saved) hook gets besides the
313/// record.
314#[derive(Clone)]
315#[non_exhaustive]
316pub struct SaveContext {
317    /// The app's state, e.g. its database (`state.db`).
318    pub state: AppState,
319    /// Who saved the record.
320    pub user: AuthUser,
321    /// The record was just created (the create page), not edited.
322    pub created: bool,
323    /// On an edit, the record as it was before the form changed it (its
324    /// fields as JSON); `None` for a new record.
325    pub previous: Option<renox::serde_json::Value>,
326}
327
328type Run<M> = Arc<dyn Fn(Vec<M>, ActionContext) -> BoxFuture<'static, Result<Toast>> + Send + Sync>;
329
330/// An action of a resource's list (Filament's bulk actions): a button over
331/// the selected rows that runs `run` with their records and shows the
332/// toast it returns. With [`row`](Self::row), each row's menu has it too.
333///
334/// ```
335/// # use renox::prelude::*;
336/// use renox_admin::AdminAction;
337/// # #[derive(Model, serde::Serialize, Default, Clone)] struct Product { id: i64, active: bool }
338///
339/// let deactivate = AdminAction::new("deactivate", "Deactivate", |products: Vec<Product>, cx| async move {
340///     let ids: Vec<i64> = products.iter().map(|p| p.id).collect();
341///     let n = Product::query().where_in("id", ids).update(&cx.state.db, &[("active", &false)]).await?;
342///     Ok(Toast::success(format!("{n} products deactivated.")))
343/// })
344/// .confirm("Deactivate the selected products?")
345/// .row();
346/// # let _ = deactivate;
347/// ```
348///
349/// Every record must pass [`AdminResource::allows`] for the action's
350/// ability (`update` by default), or nothing runs (403).
351pub struct AdminAction<M> {
352    key: String,
353    label: String,
354    ability: String,
355    confirm: Option<String>,
356    danger: bool,
357    bulk: bool,
358    row: bool,
359    form: Vec<Field>,
360    description: Option<String>,
361    submit: Option<String>,
362    run: Run<M>,
363}
364
365impl<M> Clone for AdminAction<M> {
366    fn clone(&self) -> Self {
367        Self {
368            key: self.key.clone(),
369            label: self.label.clone(),
370            ability: self.ability.clone(),
371            confirm: self.confirm.clone(),
372            danger: self.danger,
373            bulk: self.bulk,
374            row: self.row,
375            form: self.form.clone(),
376            description: self.description.clone(),
377            submit: self.submit.clone(),
378            run: self.run.clone(),
379        }
380    }
381}
382
383impl<M> fmt::Debug for AdminAction<M> {
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        f.debug_struct("AdminAction")
386            .field("key", &self.key)
387            .field("label", &self.label)
388            .field("ability", &self.ability)
389            .finish_non_exhaustive()
390    }
391}
392
393impl<M: Send + 'static> AdminAction<M> {
394    /// An action named `key` (letters, digits, `_` and `-`; part of its
395    /// address), shown as `label`, that runs `run`.
396    pub fn new<F, Fut>(key: &str, label: &str, run: F) -> Self
397    where
398        F: Fn(Vec<M>, ActionContext) -> Fut + Send + Sync + 'static,
399        Fut: Future<Output = Result<Toast>> + Send + 'static,
400    {
401        Self {
402            key: key.to_owned(),
403            label: label.to_owned(),
404            ability: "update".into(),
405            confirm: None,
406            danger: false,
407            bulk: true,
408            row: false,
409            form: Vec::new(),
410            description: None,
411            submit: None,
412            run: Arc::new(move |records, cx| Box::pin(run(records, cx))),
413        }
414    }
415
416    /// The ability each record must allow (`update` by default).
417    pub fn ability(mut self, ability: &str) -> Self {
418        self.ability = ability.to_owned();
419        self
420    }
421
422    /// Asks first, in a dialog with this question.
423    pub fn confirm(mut self, question: &str) -> Self {
424        self.confirm = Some(question.to_owned());
425        self
426    }
427
428    /// Shown in red, for actions that can't be undone.
429    pub fn danger(mut self) -> Self {
430        self.danger = true;
431        self
432    }
433
434    /// Also in each row's menu, for that row alone.
435    pub fn row(mut self) -> Self {
436        self.row = true;
437        self
438    }
439
440    /// Only in each row's menu, not over the selection.
441    pub fn row_only(mut self) -> Self {
442        self.row = true;
443        self.bulk = false;
444        self
445    }
446
447    /// Asks for input first: the button opens a sheet with these fields
448    /// (any [`Field`] except `belongs_to`), and the action runs once they
449    /// are valid, with what was typed in [`ActionContext::input`]. A field
450    /// is checked as far as its declaration goes: `required`, numbers and
451    /// dates that read as such, `min` and `max`, a select's choices.
452    ///
453    /// ```
454    /// # use renox::prelude::*;
455    /// use renox_admin::{AdminAction, Field};
456    /// # #[derive(Model, serde::Serialize, Default, Clone)] struct Product { id: i64, price: i64 }
457    ///
458    /// let reprice = AdminAction::new("reprice", "Change price by %", |products: Vec<Product>, cx| async move {
459    ///     let percent: f64 = cx.input.parse("percent").unwrap_or(0.0);
460    ///     for product in &products {
461    ///         let price = (product.price as f64 * (1.0 + percent / 100.0)).round() as i64;
462    ///         Product::query()
463    ///             .where_eq("id", product.id)
464    ///             .update(&cx.state.db, &[("price", &price)])
465    ///             .await?;
466    ///     }
467    ///     Ok(Toast::success(format!("{} prices changed by {percent} %.", products.len())))
468    /// })
469    /// .form(vec![Field::number("percent", "Percent").required().min(-90).max(500).suffix("%")])
470    /// .description("Every selected product's price changes by this much.")
471    /// .submit_label("Change prices")
472    /// .row();
473    /// # let _ = reprice;
474    /// ```
475    pub fn form(mut self, fields: Vec<Field>) -> Self {
476        self.form = fields;
477        self
478    }
479
480    /// A line under the title of the input sheet ([`form`](Self::form)).
481    pub fn description(mut self, text: &str) -> Self {
482        self.description = Some(text.to_owned());
483        self
484    }
485
486    /// The input sheet's button, instead of the action's label.
487    pub fn submit_label(mut self, label: &str) -> Self {
488        self.submit = Some(label.to_owned());
489        self
490    }
491
492    pub(crate) fn fields(&self) -> &[Field] {
493        &self.form
494    }
495
496    pub(crate) fn describe(&self) -> Option<&str> {
497        self.description.as_deref()
498    }
499
500    pub(crate) fn submit(&self) -> Option<&str> {
501        self.submit.as_deref()
502    }
503
504    pub(crate) fn key(&self) -> &str {
505        &self.key
506    }
507
508    pub(crate) fn label(&self) -> &str {
509        &self.label
510    }
511
512    pub(crate) fn ability_name(&self) -> &str {
513        &self.ability
514    }
515
516    pub(crate) fn question(&self) -> Option<&str> {
517        self.confirm.as_deref()
518    }
519
520    pub(crate) fn is_danger(&self) -> bool {
521        self.danger
522    }
523
524    pub(crate) fn on_bulk(&self) -> bool {
525        self.bulk
526    }
527
528    pub(crate) fn on_row(&self) -> bool {
529        self.row
530    }
531
532    pub(crate) fn run(
533        &self,
534        records: Vec<M>,
535        cx: ActionContext,
536    ) -> BoxFuture<'static, Result<Toast>> {
537        (self.run)(records, cx)
538    }
539}
540
541type Scope<M> = Arc<dyn Fn(Query<M>) -> Query<M> + Send + Sync>;
542
543/// A named filter over a resource's list (Filament's tabs and preset
544/// filters), chosen with `?filter=key`.
545///
546/// ```
547/// # use renox::prelude::*;
548/// use renox_admin::Filter;
549/// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64, active: bool, stock: i64 }
550///
551/// let filters = vec![
552///     Filter::new("active", "Active", |q| q.where_eq("active", true)),
553///     Filter::new("low", "Low stock", |q| q.where_op("stock", "<", 5)),
554/// ];
555/// # let _: Vec<Filter<Product>> = filters;
556/// ```
557pub struct Filter<M> {
558    key: String,
559    label: String,
560    scope: Scope<M>,
561}
562
563impl<M> Clone for Filter<M> {
564    fn clone(&self) -> Self {
565        Self {
566            key: self.key.clone(),
567            label: self.label.clone(),
568            scope: self.scope.clone(),
569        }
570    }
571}
572
573impl<M> fmt::Debug for Filter<M> {
574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575        f.debug_struct("Filter")
576            .field("key", &self.key)
577            .field("label", &self.label)
578            .finish_non_exhaustive()
579    }
580}
581
582impl<M> Filter<M> {
583    /// A filter named `key` (its value in `?filter=`), shown as `label`,
584    /// that narrows the list's query with `scope`.
585    pub fn new(
586        key: &str,
587        label: &str,
588        scope: impl Fn(Query<M>) -> Query<M> + Send + Sync + 'static,
589    ) -> Self {
590        Self {
591            key: key.to_owned(),
592            label: label.to_owned(),
593            scope: Arc::new(scope),
594        }
595    }
596
597    pub(crate) fn key(&self) -> &str {
598        &self.key
599    }
600
601    pub(crate) fn label(&self) -> &str {
602        &self.label
603    }
604
605    pub(crate) fn apply(&self, query: Query<M>) -> Query<M> {
606        (self.scope)(query)
607    }
608}