use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use renox::db::{Model, Query};
use renox::grid::{Column, Grid};
use renox::prelude::*;
use renox::state_machine::{Available, MachineInfo, Outcome, StateMachine, TransitionError};
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::{Entry, Field, RelationManager};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub trait AdminResource: Send + Sync + 'static {
type Model: Model + Policy + Serialize + Default + Send + Sync;
type Form: DeserializeOwned + Validate + Serialize + Send + 'static;
fn label(&self) -> &str;
fn plural_label(&self) -> &str;
fn record_title(&self, record: &Self::Model) -> String {
format!("{} #{}", self.label(), record.id())
}
fn slug(&self) -> &str {
Self::Model::TABLE
}
fn navigation_group(&self) -> Option<&str> {
None
}
fn columns(&self) -> Vec<Column>;
fn fields(&self) -> Vec<Field>;
fn fill(&self, record: &mut Self::Model, form: Self::Form);
fn rules(&self, form: &Self::Form, record: Option<&Self::Model>, v: &mut Validator) {
let _ = (form, record, v);
}
fn entries(&self) -> Vec<Entry> {
self.columns()
.iter()
.filter_map(Entry::from_column)
.collect()
}
fn filters(&self) -> Vec<Filter<Self::Model>> {
Vec::new()
}
fn actions(&self) -> Vec<AdminAction<Self::Model>> {
Vec::new()
}
fn creatable(&self) -> bool {
true
}
fn deletable(&self) -> bool {
true
}
fn relations(&self) -> Vec<RelationManager> {
Vec::new()
}
fn saved(&self, record: &Self::Model, cx: &SaveContext) -> impl Future<Output = Result> + Send {
let _ = (record, cx);
async { Ok(()) }
}
fn state_machine(&self) -> Option<MachineInfo> {
None
}
fn available_transitions(
&self,
record: &Self::Model,
user: &AuthUser,
db: &Db,
) -> impl Future<Output = Result<Vec<Available>>> + Send {
let _ = (record, user, db);
async { Ok(Vec::new()) }
}
fn query(&self) -> Query<Self::Model> {
Self::Model::query()
}
fn grid(&self, grid: Grid) -> Grid {
grid
}
fn allows(&self, user: &AuthUser, ability: &str, record: Option<&Self::Model>) -> bool {
match record {
Some(record) => user.can(ability, record),
None => user.can(ability, &Self::Model::default()),
}
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct ActionContext {
pub state: AppState,
pub user: AuthUser,
pub input: ActionInput,
}
#[derive(Debug, Clone, Default)]
pub struct ActionInput {
values: Vec<(String, String)>,
}
impl ActionInput {
pub(crate) fn new(values: Vec<(String, String)>) -> Self {
Self { values }
}
pub fn get(&self, name: &str) -> Option<&str> {
self.values
.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value.as_str())
}
pub fn text(&self, name: &str) -> &str {
self.get(name).unwrap_or("")
}
pub fn parse<T: std::str::FromStr>(&self, name: &str) -> Option<T> {
self.get(name)?.trim().parse().ok()
}
pub fn bool(&self, name: &str) -> bool {
matches!(self.get(name), Some("true" | "on" | "1"))
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.values.iter().map(|(k, v)| (k.as_str(), v.as_str()))
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct SaveContext {
pub state: AppState,
pub user: AuthUser,
pub created: bool,
pub previous: Option<renox::serde_json::Value>,
}
type Run<M> = Arc<dyn Fn(Vec<M>, ActionContext) -> BoxFuture<'static, Result<Toast>> + Send + Sync>;
pub struct AdminAction<M> {
key: String,
label: String,
ability: String,
confirm: Option<String>,
danger: bool,
bulk: bool,
row: bool,
form: Vec<Field>,
description: Option<String>,
submit: Option<String>,
run: Run<M>,
}
impl<M> Clone for AdminAction<M> {
fn clone(&self) -> Self {
Self {
key: self.key.clone(),
label: self.label.clone(),
ability: self.ability.clone(),
confirm: self.confirm.clone(),
danger: self.danger,
bulk: self.bulk,
row: self.row,
form: self.form.clone(),
description: self.description.clone(),
submit: self.submit.clone(),
run: self.run.clone(),
}
}
}
impl<M> fmt::Debug for AdminAction<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AdminAction")
.field("key", &self.key)
.field("label", &self.label)
.field("ability", &self.ability)
.finish_non_exhaustive()
}
}
impl<M: Send + 'static> AdminAction<M> {
pub fn new<F, Fut>(key: &str, label: &str, run: F) -> Self
where
F: Fn(Vec<M>, ActionContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Toast>> + Send + 'static,
{
Self {
key: key.to_owned(),
label: label.to_owned(),
ability: "update".into(),
confirm: None,
danger: false,
bulk: true,
row: false,
form: Vec::new(),
description: None,
submit: None,
run: Arc::new(move |records, cx| Box::pin(run(records, cx))),
}
}
pub fn ability(mut self, ability: &str) -> Self {
self.ability = ability.to_owned();
self
}
pub fn confirm(mut self, question: &str) -> Self {
self.confirm = Some(question.to_owned());
self
}
pub fn danger(mut self) -> Self {
self.danger = true;
self
}
pub fn row(mut self) -> Self {
self.row = true;
self
}
pub fn row_only(mut self) -> Self {
self.row = true;
self.bulk = false;
self
}
pub fn form(mut self, fields: Vec<Field>) -> Self {
self.form = fields;
self
}
pub fn description(mut self, text: &str) -> Self {
self.description = Some(text.to_owned());
self
}
pub fn submit_label(mut self, label: &str) -> Self {
self.submit = Some(label.to_owned());
self
}
pub(crate) fn fields(&self) -> &[Field] {
&self.form
}
pub(crate) fn describe(&self) -> Option<&str> {
self.description.as_deref()
}
pub(crate) fn submit(&self) -> Option<&str> {
self.submit.as_deref()
}
pub(crate) fn key(&self) -> &str {
&self.key
}
pub(crate) fn label(&self) -> &str {
&self.label
}
pub(crate) fn ability_name(&self) -> &str {
&self.ability
}
pub(crate) fn question(&self) -> Option<&str> {
self.confirm.as_deref()
}
pub(crate) fn is_danger(&self) -> bool {
self.danger
}
pub(crate) fn on_bulk(&self) -> bool {
self.bulk
}
pub(crate) fn on_row(&self) -> bool {
self.row
}
pub(crate) fn run(
&self,
records: Vec<M>,
cx: ActionContext,
) -> BoxFuture<'static, Result<Toast>> {
(self.run)(records, cx)
}
}
impl<M: StateMachine + Send + Sync + 'static> AdminAction<M> {
pub fn transitions() -> Vec<Self> {
renox::state_machine::info_of::<M>()
.transitions
.into_iter()
.filter(|t| !t.system)
.map(|t| {
let name = t.name.clone();
let label = t.label.clone();
let mut action = Self::new(&t.name, &t.label, move |records: Vec<M>, cx| {
let name = name.clone();
let label = label.clone();
async move {
let reason = cx.input.text("reason").trim().to_owned();
let mut pending = false;
for record in &records {
let mut run = record.transition(&name).by(&cx.user);
if !reason.is_empty() {
run = run.reason(reason.clone());
}
match run
.run(&cx.state)
.await
.map_err(TransitionError::into_error)?
{
Outcome::Done(_) => {}
Outcome::Pending(_) => pending = true,
}
}
Ok(Toast::success(if pending {
format!("{label}: waiting for approval.")
} else {
format!("{label}: done.")
}))
}
})
.row_only();
if t.needs_reason {
action = action.form(vec![Field::textarea("reason", "Reason").required()]);
}
if t.tone.as_deref() == Some("danger") {
action = action.danger();
}
action
})
.collect()
}
}
type Scope<M> = Arc<dyn Fn(Query<M>) -> Query<M> + Send + Sync>;
pub struct Filter<M> {
key: String,
label: String,
scope: Scope<M>,
}
impl<M> Clone for Filter<M> {
fn clone(&self) -> Self {
Self {
key: self.key.clone(),
label: self.label.clone(),
scope: self.scope.clone(),
}
}
}
impl<M> fmt::Debug for Filter<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Filter")
.field("key", &self.key)
.field("label", &self.label)
.finish_non_exhaustive()
}
}
impl<M> Filter<M> {
pub fn new(
key: &str,
label: &str,
scope: impl Fn(Query<M>) -> Query<M> + Send + Sync + 'static,
) -> Self {
Self {
key: key.to_owned(),
label: label.to_owned(),
scope: Arc::new(scope),
}
}
pub(crate) fn key(&self) -> &str {
&self.key
}
pub(crate) fn label(&self) -> &str {
&self.label
}
pub(crate) fn apply(&self, query: Query<M>) -> Query<M> {
(self.scope)(query)
}
}