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 renox::state_machine::{Available, MachineInfo, Outcome, StateMachine, TransitionError};
13use serde::Serialize;
14use serde::de::DeserializeOwned;
15
16use crate::{Entry, Field, RelationManager};
17
18/// A boxed future that can be sent between threads, as an action returns.
19pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
20
21/// A model in the admin panel (Filament's resources), declared once: the
22/// grid's columns, the form's fields, its filters and actions, and who may
23/// do what (its [`Policy`]).
24///
25/// ```
26/// use renox::grid::Column;
27/// use renox::prelude::*;
28/// use renox_admin::{AdminResource, Field};
29/// use serde::{Deserialize, Serialize};
30///
31/// #[derive(Model, Serialize, Default, Clone)]
32/// struct Product { id: i64, name: String, price: i64, active: bool }
33///
34/// impl Policy for Product {
35/// fn allows(&self, user: &User, ability: &str) -> bool {
36/// // Everyone in the panel looks; only managers change things.
37/// matches!(ability, "viewAny" | "view") || user.has_role("manager")
38/// }
39/// }
40///
41/// #[derive(Deserialize, Serialize, Validate)]
42/// struct ProductForm {
43/// #[validate(required, max = 100)]
44/// name: String,
45/// #[validate(required, min = 0)]
46/// price: i64,
47/// active: bool,
48/// }
49///
50/// struct Products;
51///
52/// impl AdminResource for Products {
53/// type Model = Product;
54/// type Form = ProductForm;
55///
56/// fn label(&self) -> &str { "Product" }
57/// fn plural_label(&self) -> &str { "Products" }
58///
59/// fn columns(&self) -> Vec<Column> {
60/// vec![
61/// Column::text("name", "Name").searchable(),
62/// Column::money("price", "Price"),
63/// Column::bool("active", "Active"),
64/// ]
65/// }
66///
67/// fn fields(&self) -> Vec<Field> {
68/// vec![
69/// Field::text("name", "Name").required(),
70/// Field::money("price", "Price").required(),
71/// Field::toggle("active", "Active").default_value(true),
72/// ]
73/// }
74///
75/// fn fill(&self, product: &mut Product, form: ProductForm) {
76/// product.name = form.name;
77/// product.price = form.price;
78/// product.active = form.active;
79/// }
80/// }
81/// ```
82pub trait AdminResource: Send + Sync + 'static {
83 /// The model the resource manages. `Default` gives the record a create
84 /// page starts from, and the one list-level abilities are asked about.
85 type Model: Model + Policy + Serialize + Default + Send + Sync;
86
87 /// The form of the create and edit pages, checked with its own rules
88 /// (`Valid<T>`). `Serialize` refills it after [`rules`](Self::rules)
89 /// fails (passwords aren't refilled).
90 type Form: DeserializeOwned + Validate + Serialize + Send + 'static;
91
92 /// One record's name: "Product".
93 fn label(&self) -> &str;
94
95 /// Several records' name, in the navigation and the list's title:
96 /// "Products".
97 fn plural_label(&self) -> &str;
98
99 /// What a record's view and edit pages call it: "Product #7" by
100 /// default; its name reads better (`product.name.clone()`).
101 fn record_title(&self, record: &Self::Model) -> String {
102 format!("{} #{}", self.label(), record.id())
103 }
104
105 /// The resource's part of the address and of the route names
106 /// (`/admin/products`, `admin.products.index`): letters, digits, `_`
107 /// and `-`. The model's table by default.
108 fn slug(&self) -> &str {
109 Self::Model::TABLE
110 }
111
112 /// A heading the navigation puts the resource under ("Shop").
113 fn navigation_group(&self) -> Option<&str> {
114 None
115 }
116
117 /// The list's columns, left to right (`renox::grid`). Make some
118 /// `.searchable()` for the list's search box.
119 fn columns(&self) -> Vec<Column>;
120
121 /// The create and edit pages' fields, in order.
122 fn fields(&self) -> Vec<Field>;
123
124 /// Copies a valid form into the record, before it is saved (a new
125 /// record starts from `Default`).
126 fn fill(&self, record: &mut Self::Model, form: Self::Form);
127
128 /// Rules that need the record being edited (`None` while creating),
129 /// checked after the form's own, e.g. a unique value that may stay the
130 /// record's own: `v.field("sku", &form.sku).unique("products", "sku")`
131 /// followed by `.ignore(record.id)` when there is one.
132 fn rules(&self, form: &Self::Form, record: Option<&Self::Model>, v: &mut Validator) {
133 let _ = (form, record, v);
134 }
135
136 /// The details of a record's view page. Without any, the resource has
137 /// no view page and its rows open the edit page. By default, an entry
138 /// per column ([`Entry::from_column`]).
139 fn entries(&self) -> Vec<Entry> {
140 self.columns()
141 .iter()
142 .filter_map(Entry::from_column)
143 .collect()
144 }
145
146 /// Named filters over the list, shown as tabs above it ("Active",
147 /// "Low stock"); the grid's columns filter on their own too.
148 fn filters(&self) -> Vec<Filter<Self::Model>> {
149 Vec::new()
150 }
151
152 /// The resource's own actions on selected rows (and, with
153 /// [`AdminAction::row`], on one row).
154 fn actions(&self) -> Vec<AdminAction<Self::Model>> {
155 Vec::new()
156 }
157
158 /// Whether the panel offers a create page and a "New" button. Return
159 /// `false` for a resource that is only edited (a settings row, a
160 /// record other code creates): the create address answers 404.
161 fn creatable(&self) -> bool {
162 true
163 }
164
165 /// Whether records can be deleted from the panel (the delete buttons,
166 /// the bulk delete, the trash and its restore). Return `false` for an
167 /// edit-only resource: those addresses answer 404.
168 fn deletable(&self) -> bool {
169 true
170 }
171
172 /// Child rows managed from a record's own pages (Filament's relation
173 /// managers): its variants, photos or tags, each a tab of the record
174 /// with its own list. See [`RelationManager`].
175 fn relations(&self) -> Vec<RelationManager> {
176 Vec::new()
177 }
178
179 /// Runs after the create or edit page saved a record (Filament's
180 /// `afterSave`), with who saved it and, on an edit, the record as it was
181 /// ([`SaveContext::previous`]): audit an exact price change, refresh
182 /// search keywords. An error answers the request with it, though the
183 /// record is saved by then; do the work in a transaction of your own
184 /// when it must go in with the record.
185 ///
186 /// ```
187 /// # use renox::prelude::*;
188 /// # use renox::grid::Column;
189 /// # use renox_admin::{AdminResource, Field, SaveContext};
190 /// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64, name: String, price: i64 }
191 /// # impl Policy for Product { fn allows(&self, _: &User, _: &str) -> bool { true } }
192 /// # #[derive(serde::Deserialize, serde::Serialize, Validate)] struct ProductForm { #[validate(required)] name: String }
193 /// struct Products;
194 ///
195 /// impl AdminResource for Products {
196 /// # type Model = Product;
197 /// # type Form = ProductForm;
198 /// # fn label(&self) -> &str { "Product" }
199 /// # fn plural_label(&self) -> &str { "Products" }
200 /// # fn columns(&self) -> Vec<Column> { vec![] }
201 /// # fn fields(&self) -> Vec<Field> { vec![] }
202 /// # fn fill(&self, p: &mut Product, f: ProductForm) { p.name = f.name; }
203 /// // ...
204 /// async fn saved(&self, product: &Product, cx: &SaveContext) -> Result {
205 /// let before = cx.previous.as_ref().and_then(|old| old["price"].as_i64());
206 /// if before.is_some_and(|before| before != product.price) {
207 /// // Write the audit entry: who (`cx.user`), which product, from, to.
208 /// let _ = (&cx.state.db, &cx.user);
209 /// }
210 /// Ok(())
211 /// }
212 /// }
213 /// ```
214 fn saved(&self, record: &Self::Model, cx: &SaveContext) -> impl Future<Output = Result> + Send {
215 let _ = (record, cx);
216 async { Ok(()) }
217 }
218
219 /// The model's state machine, for a read-only diagram on the view page:
220 /// `Some(renox::state_machine::info_of::<Order>())`. Pair it with
221 /// [`available_transitions`](Self::available_transitions) for the buttons
222 /// and [`AdminAction::transitions`] for what they run. `None` by default.
223 fn state_machine(&self) -> Option<MachineInfo> {
224 None
225 }
226
227 /// The transitions `user` may run on `record` now, shown as buttons on
228 /// its view page (each posts to the action of the same name, see
229 /// [`AdminAction::transitions`]). For a state machine model, return
230 /// `record.available(user, db).await`. None by default.
231 fn available_transitions(
232 &self,
233 record: &Self::Model,
234 user: &AuthUser,
235 db: &Db,
236 ) -> impl Future<Output = Result<Vec<Available>>> + Send {
237 let _ = (record, user, db);
238 async { Ok(Vec::new()) }
239 }
240
241 /// Every query the panel runs for this resource starts here: the
242 /// model's query (with its default scope) by default. Narrow it to
243 /// what the panel may ever show.
244 fn query(&self) -> Query<Self::Model> {
245 Self::Model::query()
246 }
247
248 /// Changes the list's grid after the panel built it from the columns,
249 /// e.g. `grid.sort_by("name").per_page(50).groups(&["status"])`.
250 fn grid(&self, grid: Grid) -> Grid {
251 grid
252 }
253
254 /// Whether `user` may do `ability` (`viewAny`, `view`, `create`,
255 /// `update`, `delete`, `deleteAny`, `restore`, `restoreAny`,
256 /// `forceDelete`, `forceDeleteAny`, or an action's own) on `record`.
257 /// By default, the model's [`Policy`] after `App::gate_before`; when
258 /// there's no record (the list, the create page, what the list
259 /// offers), the policy is asked about a blank record
260 /// (`Self::Model::default()`).
261 fn allows(&self, user: &AuthUser, ability: &str, record: Option<&Self::Model>) -> bool {
262 match record {
263 Some(record) => user.can(ability, record),
264 None => user.can(ability, &Self::Model::default()),
265 }
266 }
267}
268
269/// What an action's code gets besides the records.
270#[derive(Clone)]
271#[non_exhaustive]
272pub struct ActionContext {
273 /// The app's state, e.g. its database (`state.db`).
274 pub state: AppState,
275 /// Who chose the action.
276 pub user: AuthUser,
277 /// What the user typed in the action's form ([`AdminAction::form`]);
278 /// empty for an action without one.
279 pub input: ActionInput,
280}
281
282/// What the user typed into an action's form, already checked against the
283/// form's fields ([`AdminAction::form`]). Money fields are in the currency's
284/// smallest unit, toggles are `true` or `false`, and a field left empty is
285/// the empty text.
286///
287/// ```
288/// # use renox_admin::ActionInput;
289/// # fn demo(input: &ActionInput) {
290/// let percent: f64 = input.parse("percent").unwrap_or(0.0);
291/// let reason = input.text("reason");
292/// let notify = input.bool("notify");
293/// # let _ = (percent, reason, notify); }
294/// ```
295#[derive(Debug, Clone, Default)]
296pub struct ActionInput {
297 values: Vec<(String, String)>,
298}
299
300impl ActionInput {
301 pub(crate) fn new(values: Vec<(String, String)>) -> Self {
302 Self { values }
303 }
304
305 /// The value of field `name`, if the form had one.
306 pub fn get(&self, name: &str) -> Option<&str> {
307 self.values
308 .iter()
309 .find(|(key, _)| key == name)
310 .map(|(_, value)| value.as_str())
311 }
312
313 /// The value of field `name`, or `""`.
314 pub fn text(&self, name: &str) -> &str {
315 self.get(name).unwrap_or("")
316 }
317
318 /// The value of field `name` read as a `T` (a number, a dateā¦), or
319 /// `None` when it is empty or doesn't read as one.
320 pub fn parse<T: std::str::FromStr>(&self, name: &str) -> Option<T> {
321 self.get(name)?.trim().parse().ok()
322 }
323
324 /// Whether the checkbox or toggle `name` was on.
325 pub fn bool(&self, name: &str) -> bool {
326 matches!(self.get(name), Some("true" | "on" | "1"))
327 }
328
329 /// Every field's name and value, in the form's order.
330 pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
331 self.values.iter().map(|(k, v)| (k.as_str(), v.as_str()))
332 }
333}
334
335/// What a resource's [`saved`](AdminResource::saved) hook gets besides the
336/// record.
337#[derive(Clone)]
338#[non_exhaustive]
339pub struct SaveContext {
340 /// The app's state, e.g. its database (`state.db`).
341 pub state: AppState,
342 /// Who saved the record.
343 pub user: AuthUser,
344 /// The record was just created (the create page), not edited.
345 pub created: bool,
346 /// On an edit, the record as it was before the form changed it (its
347 /// fields as JSON); `None` for a new record.
348 pub previous: Option<renox::serde_json::Value>,
349}
350
351type Run<M> = Arc<dyn Fn(Vec<M>, ActionContext) -> BoxFuture<'static, Result<Toast>> + Send + Sync>;
352
353/// An action of a resource's list (Filament's bulk actions): a button over
354/// the selected rows that runs `run` with their records and shows the
355/// toast it returns. With [`row`](Self::row), each row's menu has it too.
356///
357/// ```
358/// # use renox::prelude::*;
359/// use renox_admin::AdminAction;
360/// # #[derive(Model, serde::Serialize, Default, Clone)] struct Product { id: i64, active: bool }
361///
362/// let deactivate = AdminAction::new("deactivate", "Deactivate", |products: Vec<Product>, cx| async move {
363/// let ids: Vec<i64> = products.iter().map(|p| p.id).collect();
364/// let n = Product::query().where_in("id", ids).update(&cx.state.db, &[("active", &false)]).await?;
365/// Ok(Toast::success(format!("{n} products deactivated.")))
366/// })
367/// .confirm("Deactivate the selected products?")
368/// .row();
369/// # let _ = deactivate;
370/// ```
371///
372/// Every record must pass [`AdminResource::allows`] for the action's
373/// ability (`update` by default), or nothing runs (403).
374pub struct AdminAction<M> {
375 key: String,
376 label: String,
377 ability: String,
378 confirm: Option<String>,
379 danger: bool,
380 bulk: bool,
381 row: bool,
382 form: Vec<Field>,
383 description: Option<String>,
384 submit: Option<String>,
385 run: Run<M>,
386}
387
388impl<M> Clone for AdminAction<M> {
389 fn clone(&self) -> Self {
390 Self {
391 key: self.key.clone(),
392 label: self.label.clone(),
393 ability: self.ability.clone(),
394 confirm: self.confirm.clone(),
395 danger: self.danger,
396 bulk: self.bulk,
397 row: self.row,
398 form: self.form.clone(),
399 description: self.description.clone(),
400 submit: self.submit.clone(),
401 run: self.run.clone(),
402 }
403 }
404}
405
406impl<M> fmt::Debug for AdminAction<M> {
407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408 f.debug_struct("AdminAction")
409 .field("key", &self.key)
410 .field("label", &self.label)
411 .field("ability", &self.ability)
412 .finish_non_exhaustive()
413 }
414}
415
416impl<M: Send + 'static> AdminAction<M> {
417 /// An action named `key` (letters, digits, `_` and `-`; part of its
418 /// address), shown as `label`, that runs `run`.
419 pub fn new<F, Fut>(key: &str, label: &str, run: F) -> Self
420 where
421 F: Fn(Vec<M>, ActionContext) -> Fut + Send + Sync + 'static,
422 Fut: Future<Output = Result<Toast>> + Send + 'static,
423 {
424 Self {
425 key: key.to_owned(),
426 label: label.to_owned(),
427 ability: "update".into(),
428 confirm: None,
429 danger: false,
430 bulk: true,
431 row: false,
432 form: Vec::new(),
433 description: None,
434 submit: None,
435 run: Arc::new(move |records, cx| Box::pin(run(records, cx))),
436 }
437 }
438
439 /// The ability each record must allow (`update` by default).
440 pub fn ability(mut self, ability: &str) -> Self {
441 self.ability = ability.to_owned();
442 self
443 }
444
445 /// Asks first, in a dialog with this question.
446 pub fn confirm(mut self, question: &str) -> Self {
447 self.confirm = Some(question.to_owned());
448 self
449 }
450
451 /// Shown in red, for actions that can't be undone.
452 pub fn danger(mut self) -> Self {
453 self.danger = true;
454 self
455 }
456
457 /// Also in each row's menu, for that row alone.
458 pub fn row(mut self) -> Self {
459 self.row = true;
460 self
461 }
462
463 /// Only in each row's menu, not over the selection.
464 pub fn row_only(mut self) -> Self {
465 self.row = true;
466 self.bulk = false;
467 self
468 }
469
470 /// Asks for input first: the button opens a sheet with these fields
471 /// (any [`Field`] except `belongs_to`), and the action runs once they
472 /// are valid, with what was typed in [`ActionContext::input`]. A field
473 /// is checked as far as its declaration goes: `required`, numbers and
474 /// dates that read as such, `min` and `max`, a select's choices.
475 ///
476 /// ```
477 /// # use renox::prelude::*;
478 /// use renox_admin::{AdminAction, Field};
479 /// # #[derive(Model, serde::Serialize, Default, Clone)] struct Product { id: i64, price: i64 }
480 ///
481 /// let reprice = AdminAction::new("reprice", "Change price by %", |products: Vec<Product>, cx| async move {
482 /// let percent: f64 = cx.input.parse("percent").unwrap_or(0.0);
483 /// for product in &products {
484 /// let price = (product.price as f64 * (1.0 + percent / 100.0)).round() as i64;
485 /// Product::query()
486 /// .where_eq("id", product.id)
487 /// .update(&cx.state.db, &[("price", &price)])
488 /// .await?;
489 /// }
490 /// Ok(Toast::success(format!("{} prices changed by {percent} %.", products.len())))
491 /// })
492 /// .form(vec![Field::number("percent", "Percent").required().min(-90).max(500).suffix("%")])
493 /// .description("Every selected product's price changes by this much.")
494 /// .submit_label("Change prices")
495 /// .row();
496 /// # let _ = reprice;
497 /// ```
498 pub fn form(mut self, fields: Vec<Field>) -> Self {
499 self.form = fields;
500 self
501 }
502
503 /// A line under the title of the input sheet ([`form`](Self::form)).
504 pub fn description(mut self, text: &str) -> Self {
505 self.description = Some(text.to_owned());
506 self
507 }
508
509 /// The input sheet's button, instead of the action's label.
510 pub fn submit_label(mut self, label: &str) -> Self {
511 self.submit = Some(label.to_owned());
512 self
513 }
514
515 pub(crate) fn fields(&self) -> &[Field] {
516 &self.form
517 }
518
519 pub(crate) fn describe(&self) -> Option<&str> {
520 self.description.as_deref()
521 }
522
523 pub(crate) fn submit(&self) -> Option<&str> {
524 self.submit.as_deref()
525 }
526
527 pub(crate) fn key(&self) -> &str {
528 &self.key
529 }
530
531 pub(crate) fn label(&self) -> &str {
532 &self.label
533 }
534
535 pub(crate) fn ability_name(&self) -> &str {
536 &self.ability
537 }
538
539 pub(crate) fn question(&self) -> Option<&str> {
540 self.confirm.as_deref()
541 }
542
543 pub(crate) fn is_danger(&self) -> bool {
544 self.danger
545 }
546
547 pub(crate) fn on_bulk(&self) -> bool {
548 self.bulk
549 }
550
551 pub(crate) fn on_row(&self) -> bool {
552 self.row
553 }
554
555 pub(crate) fn run(
556 &self,
557 records: Vec<M>,
558 cx: ActionContext,
559 ) -> BoxFuture<'static, Result<Toast>> {
560 (self.run)(records, cx)
561 }
562}
563
564impl<M: StateMachine + Send + Sync + 'static> AdminAction<M> {
565 /// One row action per transition of `M`'s machine (system transitions
566 /// left out), named like the transition, that runs it as the panel's
567 /// user with the engine's checks: permission, `from` state and guards.
568 /// A transition that needs a reason asks for it in a sheet. Use it as
569 /// the resource's [`actions`](AdminResource::actions).
570 ///
571 /// The view page offers only the ones that are
572 /// [`available`](AdminResource::available_transitions) for the record.
573 pub fn transitions() -> Vec<Self> {
574 renox::state_machine::info_of::<M>()
575 .transitions
576 .into_iter()
577 .filter(|t| !t.system)
578 .map(|t| {
579 let name = t.name.clone();
580 let label = t.label.clone();
581 let mut action = Self::new(&t.name, &t.label, move |records: Vec<M>, cx| {
582 let name = name.clone();
583 let label = label.clone();
584 async move {
585 let reason = cx.input.text("reason").trim().to_owned();
586 let mut pending = false;
587 for record in &records {
588 let mut run = record.transition(&name).by(&cx.user);
589 if !reason.is_empty() {
590 run = run.reason(reason.clone());
591 }
592 match run
593 .run(&cx.state)
594 .await
595 .map_err(TransitionError::into_error)?
596 {
597 Outcome::Done(_) => {}
598 Outcome::Pending(_) => pending = true,
599 }
600 }
601 Ok(Toast::success(if pending {
602 format!("{label}: waiting for approval.")
603 } else {
604 format!("{label}: done.")
605 }))
606 }
607 })
608 .row_only();
609 if t.needs_reason {
610 action = action.form(vec![Field::textarea("reason", "Reason").required()]);
611 }
612 if t.tone.as_deref() == Some("danger") {
613 action = action.danger();
614 }
615 action
616 })
617 .collect()
618 }
619}
620
621type Scope<M> = Arc<dyn Fn(Query<M>) -> Query<M> + Send + Sync>;
622
623/// A named filter over a resource's list (Filament's tabs and preset
624/// filters), chosen with `?filter=key`.
625///
626/// ```
627/// # use renox::prelude::*;
628/// use renox_admin::Filter;
629/// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64, active: bool, stock: i64 }
630///
631/// let filters = vec![
632/// Filter::new("active", "Active", |q| q.where_eq("active", true)),
633/// Filter::new("low", "Low stock", |q| q.where_op("stock", "<", 5)),
634/// ];
635/// # let _: Vec<Filter<Product>> = filters;
636/// ```
637pub struct Filter<M> {
638 key: String,
639 label: String,
640 scope: Scope<M>,
641}
642
643impl<M> Clone for Filter<M> {
644 fn clone(&self) -> Self {
645 Self {
646 key: self.key.clone(),
647 label: self.label.clone(),
648 scope: self.scope.clone(),
649 }
650 }
651}
652
653impl<M> fmt::Debug for Filter<M> {
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 f.debug_struct("Filter")
656 .field("key", &self.key)
657 .field("label", &self.label)
658 .finish_non_exhaustive()
659 }
660}
661
662impl<M> Filter<M> {
663 /// A filter named `key` (its value in `?filter=`), shown as `label`,
664 /// that narrows the list's query with `scope`.
665 pub fn new(
666 key: &str,
667 label: &str,
668 scope: impl Fn(Query<M>) -> Query<M> + Send + Sync + 'static,
669 ) -> Self {
670 Self {
671 key: key.to_owned(),
672 label: label.to_owned(),
673 scope: Arc::new(scope),
674 }
675 }
676
677 pub(crate) fn key(&self) -> &str {
678 &self.key
679 }
680
681 pub(crate) fn label(&self) -> &str {
682 &self.label
683 }
684
685 pub(crate) fn apply(&self, query: Query<M>) -> Query<M> {
686 (self.scope)(query)
687 }
688}