♻️ (admin): Reduce pagetop-admin a los ajustes
El panel pasa al núcleo y pagetop-admin se queda con los ajustes guardados en la base de datos: DeclareConfigForms, ConfigForm y la tabla settings. Un campo obligatorio vacío ya no se guarda, y un fallo al guardar se muestra con los mensajes del núcleo.
This commit is contained in:
parent
ab2677be44
commit
824dc4a3ab
15 changed files with 392 additions and 1244 deletions
|
|
@ -1,286 +1,119 @@
|
|||
//! Tipos de acción que `pagetop-admin` expone para que otras extensiones registren
|
||||
//! secciones, páginas, tareas y acciones en el panel de administración.
|
||||
//!
|
||||
//! El flujo de `registry::build()` despacha estas acciones en este orden:
|
||||
//!
|
||||
//! 1. `DeclareAdminSections` - secciones (agrupaciones del sidebar).
|
||||
//! 2. `DeclareAdminPages` - páginas del panel.
|
||||
//! 3. `DeclareAdminTasks` - tareas (pestañas) locales por página.
|
||||
//! 4. `DeclareAdminActions` - acciones locales (botones) por página.
|
||||
//! Acción para declarar páginas de ajustes que `pagetop-admin` pinta y guarda por sí solo.
|
||||
|
||||
use pagetop::prelude::*;
|
||||
|
||||
use crate::registry::{AdminAction, AdminPage, AdminSection, AdminTask};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
// **< Tipo de callbacks >**************************************************************************
|
||||
use crate::settings::SettingsSchema;
|
||||
|
||||
pub type FnSectionBag = fn(&mut SectionBag);
|
||||
pub type FnPageBag = fn(&mut PageBag);
|
||||
pub type FnTaskBag = fn(&mut TaskBag);
|
||||
pub type FnActionBag = fn(&mut ActionBag);
|
||||
// **< ConfigFormPage >*****************************************************************************
|
||||
|
||||
// **< Bolsas de declaración >**********************************************************************
|
||||
|
||||
/// Bolsa de secciones para [`DeclareAdminSections`].
|
||||
pub struct SectionBag {
|
||||
pub(crate) sections: Vec<AdminSection>,
|
||||
}
|
||||
|
||||
impl SectionBag {
|
||||
/// Añade una sección al registro.
|
||||
pub fn add(&mut self, section: AdminSection) {
|
||||
self.sections.push(section);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bolsa de páginas para [`DeclareAdminPages`].
|
||||
pub struct PageBag {
|
||||
pub(crate) pages: Vec<AdminPage>,
|
||||
}
|
||||
|
||||
impl PageBag {
|
||||
/// Añade una página al registro.
|
||||
pub fn add(&mut self, page: AdminPage) {
|
||||
self.pages.push(page);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bolsa de tareas para [`DeclareAdminTasks`].
|
||||
pub struct TaskBag {
|
||||
pub(crate) tasks: Vec<AdminTask>,
|
||||
}
|
||||
|
||||
impl TaskBag {
|
||||
/// Añade una tarea local al registro.
|
||||
pub fn add(&mut self, task: AdminTask) {
|
||||
self.tasks.push(task);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bolsa de acciones locales para [`DeclareAdminActions`].
|
||||
pub struct ActionBag {
|
||||
pub(crate) actions: Vec<AdminAction>,
|
||||
}
|
||||
|
||||
impl ActionBag {
|
||||
/// Añade una acción local al registro.
|
||||
pub fn add(&mut self, action: AdminAction) {
|
||||
self.actions.push(action);
|
||||
}
|
||||
}
|
||||
|
||||
// **< DeclareAdminSections >***********************************************************************
|
||||
|
||||
/// Acción para declarar secciones del panel de administración.
|
||||
/// Página de ajustes del panel: una [`AdminPage`] y el esquema de su formulario.
|
||||
///
|
||||
/// Se despacha durante `registry::build()` (dentro de `initialize()`). El callback
|
||||
/// recibe un [`SectionBag`] y puede llamar a `add()` para registrar secciones.
|
||||
/// `pagetop-admin` la añade al registro del panel como cualquier otra página, monta su ruta y
|
||||
/// responde a su `GET` (el formulario con los valores guardados) y a su `POST` (los guarda en la
|
||||
/// base de datos). La extensión que la declara no registra ninguna ruta.
|
||||
#[derive(Clone)]
|
||||
pub struct ConfigFormPage {
|
||||
/// Página del panel, con su ruta relativa a la raíz del panel.
|
||||
pub page: AdminPage,
|
||||
/// Esquema del formulario.
|
||||
pub schema: SettingsSchema,
|
||||
}
|
||||
|
||||
/// Bolsa de páginas de ajustes para [`DeclareConfigForms`].
|
||||
pub struct ConfigFormBag {
|
||||
forms: Vec<ConfigFormPage>,
|
||||
}
|
||||
|
||||
impl ConfigFormBag {
|
||||
/// Añade una página de ajustes.
|
||||
pub fn add(&mut self, form: ConfigFormPage) {
|
||||
self.forms.push(form);
|
||||
}
|
||||
}
|
||||
|
||||
// **< DeclareConfigForms >*************************************************************************
|
||||
|
||||
/// Tipo de función para declarar páginas de ajustes.
|
||||
pub type FnActionDeclareConfigForms = fn(bag: &mut ConfigFormBag);
|
||||
|
||||
/// Acción para declarar páginas de ajustes que gestiona `pagetop-admin` (ver [`ConfigFormPage`]).
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use pagetop::prelude::*;
|
||||
/// use pagetop_admin::action::{DeclareAdminSections, SectionBag};
|
||||
/// use pagetop_admin::registry::AdminSection;
|
||||
/// use pagetop_admin::prelude::*;
|
||||
///
|
||||
/// fn declare_sections(bag: &mut SectionBag) {
|
||||
/// bag.add(AdminSection {
|
||||
/// key: "tools".to_owned(),
|
||||
/// path: "/admin/tools".to_owned(),
|
||||
/// title: Lc::n("Tools"),
|
||||
/// weight: 60,
|
||||
/// });
|
||||
/// #[derive(Clone, Copy, Debug)]
|
||||
/// enum MyPermission {
|
||||
/// Config,
|
||||
/// }
|
||||
/// // En Extension::actions():
|
||||
/// // DeclareAdminSections::new(declare_sections)
|
||||
/// ```
|
||||
pub struct DeclareAdminSections {
|
||||
f: FnSectionBag,
|
||||
weight: Weight,
|
||||
}
|
||||
|
||||
impl ActionDispatcher for DeclareAdminSections {
|
||||
fn weight(&self) -> Weight {
|
||||
self.weight
|
||||
}
|
||||
}
|
||||
|
||||
impl DeclareAdminSections {
|
||||
pub fn new(f: FnSectionBag) -> Self {
|
||||
DeclareAdminSections { f, weight: 0 }
|
||||
}
|
||||
|
||||
pub fn with_weight(mut self, w: Weight) -> Self {
|
||||
self.weight = w;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch(bag: &mut SectionBag) {
|
||||
dispatch_actions(|action: &Self| (action.f)(bag));
|
||||
}
|
||||
}
|
||||
|
||||
// **< DeclareAdminPages >**************************************************************************
|
||||
|
||||
/// Acción para declarar páginas del panel de administración.
|
||||
///
|
||||
/// Se despacha durante `registry::build()`. El callback recibe un [`PageBag`].
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use pagetop::prelude::*;
|
||||
/// use pagetop_admin::action::{DeclareAdminPages, PageBag};
|
||||
/// use pagetop_admin::registry::{AdminPage, AdminPageKind};
|
||||
///
|
||||
/// struct ExportPermission;
|
||||
///
|
||||
/// impl Permission for ExportPermission {
|
||||
/// impl Permission for MyPermission {
|
||||
/// fn key(&self) -> CowStr {
|
||||
/// "tools:export".into()
|
||||
/// "myapp:config".into()
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn declare_pages(bag: &mut PageBag) {
|
||||
/// bag.add(AdminPage {
|
||||
/// path: "/admin/tools/export".to_owned(),
|
||||
/// section: "tools".to_owned(),
|
||||
/// title: Lc::n("Export"),
|
||||
/// description: Some(Lc::n("Export site data.")),
|
||||
/// weight: 0,
|
||||
/// permission: &ExportPermission,
|
||||
/// kind: AdminPageKind::View,
|
||||
/// fn declare_forms(bag: &mut ConfigFormBag) {
|
||||
/// bag.add(ConfigFormPage {
|
||||
/// page: AdminPage::new("config/myapp", "config", Lc::n("My App"), &MyPermission::Config)
|
||||
/// .with_description(Lc::n("Configure My App.")),
|
||||
/// schema: SettingsSchema::new("myapp.config").with_field(
|
||||
/// SettingField::text("site_name", Lc::n("Site name")).with_required(true),
|
||||
/// ),
|
||||
/// });
|
||||
/// }
|
||||
/// // En Extension::actions():
|
||||
/// // DeclareAdminPages::new(declare_pages)
|
||||
/// // DeclareConfigForms::new(declare_forms)
|
||||
/// ```
|
||||
pub struct DeclareAdminPages {
|
||||
f: FnPageBag,
|
||||
pub struct DeclareConfigForms {
|
||||
f: FnActionDeclareConfigForms,
|
||||
weight: Weight,
|
||||
}
|
||||
|
||||
impl ActionDispatcher for DeclareAdminPages {
|
||||
impl ActionDispatcher for DeclareConfigForms {
|
||||
fn weight(&self) -> Weight {
|
||||
self.weight
|
||||
}
|
||||
}
|
||||
|
||||
impl DeclareAdminPages {
|
||||
pub fn new(f: FnPageBag) -> Self {
|
||||
DeclareAdminPages { f, weight: 0 }
|
||||
impl DeclareConfigForms {
|
||||
/// Registra una nueva acción para declarar páginas de ajustes.
|
||||
pub fn new(f: FnActionDeclareConfigForms) -> Self {
|
||||
DeclareConfigForms { f, weight: 0 }
|
||||
}
|
||||
|
||||
pub fn with_weight(mut self, w: Weight) -> Self {
|
||||
self.weight = w;
|
||||
/// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos.
|
||||
pub fn with_weight(mut self, value: Weight) -> Self {
|
||||
self.weight = value;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch(bag: &mut PageBag) {
|
||||
dispatch_actions(|action: &Self| (action.f)(bag));
|
||||
}
|
||||
}
|
||||
|
||||
// **< DeclareAdminTasks >**************************************************************************
|
||||
// **< Registro de las páginas de ajustes >*********************************************************
|
||||
|
||||
/// Acción para declarar tareas (pestañas) locales en páginas del panel.
|
||||
///
|
||||
/// Se despacha durante `registry::build()`. El callback recibe un [`TaskBag`].
|
||||
/// Cada [`AdminTask`] indica en `parent_path` la página a la que pertenece.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use pagetop::prelude::*;
|
||||
/// use pagetop_admin::action::{DeclareAdminTasks, TaskBag};
|
||||
/// use pagetop_admin::registry::AdminTask;
|
||||
///
|
||||
/// fn declare_tasks(bag: &mut TaskBag) {
|
||||
/// bag.add(AdminTask {
|
||||
/// path: "/admin/tools/export/csv".to_owned(),
|
||||
/// parent_path: "/admin/tools/export".to_owned(),
|
||||
/// title: Lc::n("CSV"),
|
||||
/// weight: 0,
|
||||
/// is_default: true,
|
||||
/// permission: None,
|
||||
/// });
|
||||
/// }
|
||||
/// // En Extension::actions():
|
||||
/// // DeclareAdminTasks::new(declare_tasks)
|
||||
/// ```
|
||||
pub struct DeclareAdminTasks {
|
||||
f: FnTaskBag,
|
||||
weight: Weight,
|
||||
// Esquemas de las páginas de ajustes, por su ruta relativa a la raíz del panel.
|
||||
static CONFIG_FORMS: OnceLock<BTreeMap<String, SettingsSchema>> = OnceLock::new();
|
||||
|
||||
// Añade las páginas de ajustes al registro del panel. `pagetop-admin` lo registra como una acción
|
||||
// `DeclareAdminPages`, así que se ejecuta una sola vez, cuando el núcleo construye el registro.
|
||||
pub(crate) fn declare_config_form_pages(bag: &mut AdminPageBag) {
|
||||
let mut forms = ConfigFormBag { forms: Vec::new() };
|
||||
dispatch_actions(|action: &DeclareConfigForms| (action.f)(&mut forms));
|
||||
let mut schemas = BTreeMap::new();
|
||||
for form in forms.forms {
|
||||
schemas.insert(form.page.path().to_owned(), form.schema);
|
||||
bag.add(form.page);
|
||||
}
|
||||
let _ = CONFIG_FORMS.set(schemas);
|
||||
}
|
||||
|
||||
impl ActionDispatcher for DeclareAdminTasks {
|
||||
fn weight(&self) -> Weight {
|
||||
self.weight
|
||||
}
|
||||
}
|
||||
|
||||
impl DeclareAdminTasks {
|
||||
pub fn new(f: FnTaskBag) -> Self {
|
||||
DeclareAdminTasks { f, weight: 0 }
|
||||
}
|
||||
|
||||
pub fn with_weight(mut self, w: Weight) -> Self {
|
||||
self.weight = w;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch(bag: &mut TaskBag) {
|
||||
dispatch_actions(|action: &Self| (action.f)(bag));
|
||||
}
|
||||
}
|
||||
|
||||
// **< DeclareAdminActions >************************************************************************
|
||||
|
||||
/// Acción para declarar acciones locales (botones de acción) en páginas del panel.
|
||||
///
|
||||
/// Se despacha durante `registry::build()`. El callback recibe un [`ActionBag`].
|
||||
/// Cada [`AdminAction`] indica en `for_path` la página en la que aparece el botón.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use pagetop::prelude::*;
|
||||
/// use pagetop_admin::action::{DeclareAdminActions, ActionBag};
|
||||
/// use pagetop_admin::registry::AdminAction;
|
||||
///
|
||||
/// fn declare_actions(bag: &mut ActionBag) {
|
||||
/// bag.add(AdminAction {
|
||||
/// url: "/admin/tools/export/new".to_owned(),
|
||||
/// for_path: "/admin/tools/export".to_owned(),
|
||||
/// title: Lc::n("Add export"),
|
||||
/// weight: 0,
|
||||
/// });
|
||||
/// }
|
||||
/// // En Extension::actions():
|
||||
/// // DeclareAdminActions::new(declare_actions)
|
||||
/// ```
|
||||
pub struct DeclareAdminActions {
|
||||
f: FnActionBag,
|
||||
weight: Weight,
|
||||
}
|
||||
|
||||
impl ActionDispatcher for DeclareAdminActions {
|
||||
fn weight(&self) -> Weight {
|
||||
self.weight
|
||||
}
|
||||
}
|
||||
|
||||
impl DeclareAdminActions {
|
||||
pub fn new(f: FnActionBag) -> Self {
|
||||
DeclareAdminActions { f, weight: 0 }
|
||||
}
|
||||
|
||||
pub fn with_weight(mut self, w: Weight) -> Self {
|
||||
self.weight = w;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch(bag: &mut ActionBag) {
|
||||
dispatch_actions(|action: &Self| (action.f)(bag));
|
||||
}
|
||||
// Esquemas de las páginas de ajustes, por su ruta relativa a la raíz del panel.
|
||||
pub(crate) fn config_forms() -> &'static BTreeMap<String, SettingsSchema> {
|
||||
static EMPTY: BTreeMap<String, SettingsSchema> = BTreeMap::new();
|
||||
CONFIG_FORMS.get().unwrap_or(&EMPTY)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,5 @@
|
|||
//! Componentes de renderizado del panel de administración.
|
||||
|
||||
mod admin_frame;
|
||||
mod admin_menu;
|
||||
mod config_form;
|
||||
|
||||
pub use admin_frame::AdminFrame;
|
||||
pub use admin_menu::AdminMenu;
|
||||
pub use config_form::ConfigForm;
|
||||
|
|
|
|||
|
|
@ -1,150 +0,0 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use crate::LOCALES_ADMIN;
|
||||
use crate::registry;
|
||||
|
||||
/// Componente de layout principal de una página del panel de administración.
|
||||
///
|
||||
/// Renderiza breadcrumb, encabezado (título + acciones locales), tareas locales (pestañas) y el
|
||||
/// contenido de la página. No incluye ningún menú de navegación: mostrar las secciones del panel
|
||||
/// (el "sidebar" o el "menú superior", según el tema) es responsabilidad del tema que intercepte
|
||||
/// [`CoreTemplates::Admin`](pagetop::core::theme::CoreTemplates::Admin) (por ejemplo
|
||||
/// `pagetop-bootsier`) leyendo directamente [`crate::registry::global()`]. El tema básico de
|
||||
/// PageTop no lo hace, y una página de administración sigue siendo completamente navegable sin él,
|
||||
/// a través del *dashboard* (`/admin`), las páginas de sección y este mismo breadcrumb.
|
||||
///
|
||||
/// ```html
|
||||
/// <nav class="admin-breadcrumb">...</nav>
|
||||
/// <header class="admin-header">
|
||||
/// <h1 class="admin-page-title">Title</h1>
|
||||
/// <ul class="admin-actions-list">...</ul>
|
||||
/// </header>
|
||||
/// <nav class="admin-local-tasks">...</nav>
|
||||
/// <div class="admin-content">...</div>
|
||||
/// ```
|
||||
///
|
||||
/// El contenido son sus propios hijos ([`Children`]), igual que en cualquier otro componente
|
||||
/// contenedor (p. ej. [`Block`](pagetop::base::component::Block)): admite tantos `with_child(...)`
|
||||
/// como haga falta, cada uno renderizado en el ciclo normal de componentes.
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct AdminFrame {
|
||||
/// Devuelve el título de la página.
|
||||
title: Lc,
|
||||
/// Devuelve la lista de componentes hijo de la página.
|
||||
children: Children,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for AdminFrame {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let path = cx
|
||||
.request()
|
||||
.map(|r| r.path().to_string())
|
||||
.unwrap_or_else(|| "/".to_string());
|
||||
|
||||
let breadcrumbs = render_breadcrumbs(cx, &path).await;
|
||||
let local_tasks = render_local_tasks(cx, &path);
|
||||
let local_acts = render_local_actions(cx, &path);
|
||||
let body = self.children().render(cx).await;
|
||||
|
||||
Ok(html! {
|
||||
(breadcrumbs)
|
||||
header class="admin-header" {
|
||||
h1 class="admin-page-title" { (self.title().using(cx)) }
|
||||
(local_acts)
|
||||
}
|
||||
@if !local_tasks.0.is_empty() {
|
||||
nav class="admin-local-tasks" { (local_tasks) }
|
||||
}
|
||||
div class="admin-content" {
|
||||
(body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl AdminFrame {
|
||||
/// Establece el título de la página.
|
||||
pub fn with_title(mut self, title: Lc) -> Self {
|
||||
self.title = title;
|
||||
self
|
||||
}
|
||||
|
||||
/// Añade un componente hijo al contenido de la página.
|
||||
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
|
||||
self.children.alter_child(op.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// **< Breadcrumbs >********************************************************************************
|
||||
|
||||
async fn render_breadcrumbs(cx: &mut Context, current_path: &str) -> Markup {
|
||||
let reg = registry::global();
|
||||
let base = crate::ADMIN_BASE_PATH;
|
||||
|
||||
let home_label = Lc::t("admin-breadcrumb-home", &LOCALES_ADMIN);
|
||||
let mut bc = Breadcrumb::new().with_crumb(breadcrumb::Crumb::new(home_label, base));
|
||||
|
||||
if let Some(page) = reg.pages().get(current_path) {
|
||||
if let Some(section) = reg.sections().get(&page.section) {
|
||||
bc = bc.with_crumb(breadcrumb::Crumb::new(
|
||||
section.title.clone(),
|
||||
section.path.as_str(),
|
||||
));
|
||||
}
|
||||
bc = bc.with_crumb(breadcrumb::Crumb::current(page.title.clone()));
|
||||
} else if let Some(section) = reg.sections().values().find(|s| s.path == current_path) {
|
||||
// La ruta actual es la propia sección (su página de aterrizaje), no una `AdminPage`
|
||||
// registrada dentro de ella.
|
||||
bc = bc.with_crumb(breadcrumb::Crumb::current(section.title.clone()));
|
||||
}
|
||||
|
||||
bc.render(cx).await
|
||||
}
|
||||
|
||||
// **< Tareas locales >*****************************************************************************
|
||||
|
||||
fn render_local_tasks(cx: &Context, current_path: &str) -> Markup {
|
||||
let reg = registry::global();
|
||||
let tasks = reg.tasks_for(current_path);
|
||||
if tasks.is_empty() {
|
||||
return html! {};
|
||||
}
|
||||
html! {
|
||||
ul class="admin-tasks-list" {
|
||||
@for task in tasks {
|
||||
@let is_active = current_path == task.path;
|
||||
li class=(if is_active { "admin-task admin-task-active" } else { "admin-task" }) {
|
||||
a href=(cx.route(task.path.as_str())) { (task.title.using(cx)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// **< Acciones locales >***************************************************************************
|
||||
|
||||
fn render_local_actions(cx: &Context, current_path: &str) -> Markup {
|
||||
let reg = registry::global();
|
||||
let actions = reg.actions_for(current_path);
|
||||
if actions.is_empty() {
|
||||
return html! {};
|
||||
}
|
||||
html! {
|
||||
ul class="admin-actions-list" {
|
||||
@for action in actions {
|
||||
li class="admin-action" {
|
||||
a class="admin-action-link" href=(cx.route(action.url.as_str())) {
|
||||
(action.title.using(cx))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use crate::registry;
|
||||
|
||||
/// Componente que renderiza la barra de navegación del panel de administración.
|
||||
///
|
||||
/// Construye la [`Navbar`] en cada petición a partir de [`registry::admin_navbar()`], ya filtrada
|
||||
/// por el usuario de la petición actual. Pensado para que un tema la registre en su propia región
|
||||
/// de navegación e intercepte `Navbar`/`Nav`/`Dropdown` en
|
||||
/// [`Theme::render_component()`](pagetop::core::theme::Theme::render_component) si quiere darle un
|
||||
/// aspecto propio (p. ej. `pagetop-bootsier` la reconoce automáticamente al ser componentes del
|
||||
/// núcleo); sin intercepción, se renderiza con el marcado por defecto de cada componente.
|
||||
///
|
||||
/// Sólo se renderiza en páginas creadas con
|
||||
/// [`Page::admin()`](pagetop::response::Page::admin) (plantilla
|
||||
/// [`CoreTemplates::Admin`](pagetop::core::theme::CoreTemplates::Admin)). Es necesario comprobarlo
|
||||
/// explícitamente porque, si se registra en una región de propósito general como
|
||||
/// [`CoreRegions::Aside`](pagetop::core::theme::CoreRegions::Aside), se renderizaría también en
|
||||
/// páginas `Standard` si no se autolimitara.
|
||||
#[derive(AutoDefault, Clone, Debug)]
|
||||
pub struct AdminMenu;
|
||||
|
||||
#[async_trait]
|
||||
impl Component for AdminMenu {
|
||||
fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
if !matches!(
|
||||
cx.template().downcast_ref::<CoreTemplates>(),
|
||||
Some(CoreTemplates::Admin)
|
||||
) {
|
||||
return Ok(html! {});
|
||||
}
|
||||
Ok(registry::admin_navbar(cx).render(cx).await)
|
||||
}
|
||||
}
|
||||
|
|
@ -3,35 +3,27 @@ use pagetop::prelude::*;
|
|||
use crate::LOCALES_ADMIN;
|
||||
use crate::settings::{SettingFieldType, SettingsSchema, get_or};
|
||||
|
||||
/// Componente que renderiza un formulario de configuración persistente.
|
||||
/// Formulario de un [`SettingsSchema`], con los valores guardados en la tabla `settings`.
|
||||
///
|
||||
/// Genera campos HTML a partir de un [`SettingsSchema`] y carga los valores
|
||||
/// actuales desde `settings`. El POST es procesado por el handler interno
|
||||
/// `config_form_post`.
|
||||
/// En las páginas declaradas con [`DeclareConfigForms`](crate::action::DeclareConfigForms),
|
||||
/// `pagetop-admin` lo muestra y guarda lo que se envía. En una página propia sólo lo muestra: el
|
||||
/// envío llega a la ruta de la página, o a la de [`with_action_path()`](Self::with_action_path), y
|
||||
/// lo guarda su *handler* (ver [`settings::set()`](crate::settings::set)).
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use pagetop::prelude::*;
|
||||
/// use pagetop_admin::component::{AdminFrame, ConfigForm};
|
||||
/// use pagetop_admin::component::ConfigForm;
|
||||
/// use pagetop_admin::settings::{SettingField, SettingsSchema};
|
||||
///
|
||||
/// async fn settings_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
/// let schema = SettingsSchema::new("myapp.general")
|
||||
/// .with_field(SettingField::text("site_name", "Site name").with_required(true));
|
||||
///
|
||||
/// let title = "General settings";
|
||||
/// let mut form = ConfigForm::with_schema(schema);
|
||||
/// let mut cx = Context::new(request.clone());
|
||||
/// let content = form.render(&mut cx).await;
|
||||
/// .with_field(SettingField::text("site_name", Lc::n("Site name")).with_required(true));
|
||||
///
|
||||
/// Page::admin(request)
|
||||
/// .with_title(Lc::n(title))
|
||||
/// .with_child(
|
||||
/// AdminFrame::new()
|
||||
/// .with_title(Lc::n(title))
|
||||
/// .with_child(Html::with(move |_| content.clone())),
|
||||
/// )
|
||||
/// .with_title(Lc::n("General settings"))
|
||||
/// .with_child(ConfigForm::with_schema(schema))
|
||||
/// .render()
|
||||
/// .await
|
||||
/// }
|
||||
|
|
@ -42,10 +34,6 @@ pub struct ConfigForm {
|
|||
schema: Option<SettingsSchema>,
|
||||
/// Devuelve la ruta de destino del formulario, si se ha personalizado.
|
||||
action_path: Option<Route>,
|
||||
/// Devuelve si el último envío se guardó correctamente.
|
||||
saved: bool,
|
||||
/// Devuelve si el último envío produjo un error al guardar.
|
||||
error: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
|
|
@ -64,22 +52,11 @@ impl Component for ConfigForm {
|
|||
None => cx.route(cx.request().map(|r| r.path()).unwrap_or("/")),
|
||||
};
|
||||
|
||||
let save_label = Lc::t("config-save-label", &LOCALES_ADMIN)
|
||||
.lookup(cx)
|
||||
.unwrap_or_else(|| "Save configuration".into());
|
||||
|
||||
let saved_msg = Lc::t("config-saved-ok", &LOCALES_ADMIN)
|
||||
.lookup(cx)
|
||||
.unwrap_or_else(|| "Configuration saved.".into());
|
||||
|
||||
let error_msg = Lc::t("config-saved-error", &LOCALES_ADMIN)
|
||||
.lookup(cx)
|
||||
.unwrap_or_else(|| "Could not save configuration.".into());
|
||||
|
||||
// Pre-computa los valores de BD para cada campo antes del macro html! (que es síncrono).
|
||||
// Pre-computa los valores de BD para cada campo antes del macro html! (que es síncrono). El
|
||||
// formulario guarda todos los valores como texto (`"42"`, `"true"`), así que se leen como
|
||||
// texto también los de los campos numéricos y las casillas.
|
||||
struct FieldVals {
|
||||
raw_val: String,
|
||||
num_val: String,
|
||||
checked: bool,
|
||||
}
|
||||
let mut prepared: Vec<FieldVals> = Vec::with_capacity(schema.fields().len());
|
||||
|
|
@ -87,27 +64,18 @@ impl Component for ConfigForm {
|
|||
let key = schema.key_for(field.name());
|
||||
let raw_val =
|
||||
get_or::<String>(&key, field.default_value().cloned().unwrap_or_default()).await;
|
||||
let num_val = get_or::<f64>(&key, 0.0).await.to_string();
|
||||
let checked = get_or::<bool>(&key, false).await;
|
||||
prepared.push(FieldVals {
|
||||
raw_val,
|
||||
num_val,
|
||||
checked,
|
||||
});
|
||||
let checked = raw_val == "true";
|
||||
prepared.push(FieldVals { raw_val, checked });
|
||||
}
|
||||
|
||||
Ok(html! {
|
||||
@if *self.saved() {
|
||||
div class="admin-message admin-message-ok" { (&saved_msg) }
|
||||
}
|
||||
@if *self.error() {
|
||||
div class="admin-message admin-message-error" { (&error_msg) }
|
||||
}
|
||||
form class="admin-config-form" method="post" action=(action) {
|
||||
@for (i, field) in schema.fields().iter().enumerate() {
|
||||
@let pf = &prepared[i];
|
||||
div class="admin-form-field" {
|
||||
label class="admin-form-label" for=(field.name()) { (field.label()) }
|
||||
label class="admin-form-label" for=(field.name()) {
|
||||
(field.label().using(cx))
|
||||
}
|
||||
@match field.field_type() {
|
||||
SettingFieldType::Text { max_length } => {
|
||||
@if let Some(max) = max_length {
|
||||
|
|
@ -133,7 +101,7 @@ impl Component for ConfigForm {
|
|||
type="number"
|
||||
id=(field.name())
|
||||
name=(field.name())
|
||||
value=(&pf.num_val)
|
||||
value=(&pf.raw_val)
|
||||
min=(lo)
|
||||
max=(hi)
|
||||
required[*field.required()];
|
||||
|
|
@ -142,7 +110,7 @@ impl Component for ConfigForm {
|
|||
type="number"
|
||||
id=(field.name())
|
||||
name=(field.name())
|
||||
value=(&pf.num_val)
|
||||
value=(&pf.raw_val)
|
||||
min=(lo)
|
||||
required[*field.required()];
|
||||
} @else if let Some(hi) = max {
|
||||
|
|
@ -150,7 +118,7 @@ impl Component for ConfigForm {
|
|||
type="number"
|
||||
id=(field.name())
|
||||
name=(field.name())
|
||||
value=(&pf.num_val)
|
||||
value=(&pf.raw_val)
|
||||
max=(hi)
|
||||
required[*field.required()];
|
||||
} @else {
|
||||
|
|
@ -158,7 +126,7 @@ impl Component for ConfigForm {
|
|||
type="number"
|
||||
id=(field.name())
|
||||
name=(field.name())
|
||||
value=(&pf.num_val)
|
||||
value=(&pf.raw_val)
|
||||
required[*field.required()];
|
||||
}
|
||||
}
|
||||
|
|
@ -178,22 +146,22 @@ impl Component for ConfigForm {
|
|||
{
|
||||
@for (val, label) in options {
|
||||
@if &pf.raw_val == val {
|
||||
option value=(val) selected { (label) }
|
||||
option value=(val) selected { (label.using(cx)) }
|
||||
} @else {
|
||||
option value=(val) { (label) }
|
||||
option value=(val) { (label.using(cx)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@if let Some(help) = field.help_text() {
|
||||
small class="admin-form-help" { (help) }
|
||||
@if !field.help_text().is_none() {
|
||||
small class="admin-form-help" { (field.help_text().using(cx)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
div class="admin-form-actions" {
|
||||
button class="admin-btn admin-btn-primary" type="submit" {
|
||||
(&save_label)
|
||||
(Lc::t("config-save-label", &LOCALES_ADMIN).using(cx))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -212,17 +180,10 @@ impl ConfigForm {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn with_action_path(mut self, v: impl Into<Option<Route>>) -> Self {
|
||||
if let Some(v) = v.into() {
|
||||
self.action_path = Some(v);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
#[builder_skip]
|
||||
pub(crate) fn with_saved(mut self, saved: bool, error: bool) -> Self {
|
||||
self.saved = saved;
|
||||
self.error = error;
|
||||
/// Establece la ruta a la que se envía el formulario, o `None` para enviarlo a la de la
|
||||
/// página.
|
||||
pub fn with_action_path(mut self, path: impl Into<Option<Route>>) -> Self {
|
||||
self.action_path = path.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,212 +3,128 @@ use std::collections::HashMap;
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use crate::LOCALES_ADMIN;
|
||||
use crate::component::{AdminFrame, ConfigForm};
|
||||
use crate::registry::{self, AdminPageKind, AdminSection};
|
||||
use crate::settings;
|
||||
use crate::action::config_forms;
|
||||
use crate::component::ConfigForm;
|
||||
use crate::settings::{self, SettingFieldType, SettingsSchema};
|
||||
|
||||
// **< Dashboard >**********************************************************************************
|
||||
// **< Config form >********************************************************************************
|
||||
|
||||
/// GET /admin - Dashboard de administración: lista todas las secciones disponibles.
|
||||
///
|
||||
/// Devuelve [`ErrorPage::AccessDenied`] si el usuario actual no tiene acceso a ninguna página.
|
||||
pub async fn dashboard(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let cx = Context::new(request.clone());
|
||||
let sections = registry::global().ordered_sections();
|
||||
|
||||
let title = Lc::t("dashboard-title", &LOCALES_ADMIN);
|
||||
let content = render_sections(&cx, §ions)
|
||||
.ok_or_else(|| ErrorPage::AccessDenied(Some(request.clone())))?;
|
||||
|
||||
Page::admin(request)
|
||||
.with_title(title.clone())
|
||||
.with_child(AdminFrame::new().with_title(title).with_child(content))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
// **< Sección >************************************************************************************
|
||||
|
||||
/// GET /admin/{section} - Página de aterrizaje de una sección: lista sus páginas.
|
||||
///
|
||||
/// Sólo se monta (ver `configure_router()` en `lib.rs`) para las secciones cuyo `path` no coincida
|
||||
/// con ninguna [`AdminPage`](crate::registry::AdminPage) registrada explícitamente por una
|
||||
/// extensión; si una extensión reclama esa ruta con su propia página, esa página gana y este
|
||||
/// handler nunca llega a montarse para ella.
|
||||
///
|
||||
/// Devuelve [`ErrorPage::AccessDenied`] si el usuario actual no tiene acceso a ninguna de sus
|
||||
/// páginas.
|
||||
pub async fn section_page(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let path = request.path().to_owned();
|
||||
let reg = registry::global();
|
||||
let section = reg
|
||||
.sections()
|
||||
.values()
|
||||
.find(|s| s.path == path)
|
||||
.ok_or_else(|| ErrorPage::NotFound(Some(request.clone())))?;
|
||||
|
||||
let cx = Context::new(request.clone());
|
||||
let title = section.title.clone();
|
||||
let content = render_sections(&cx, &[section])
|
||||
.ok_or_else(|| ErrorPage::AccessDenied(Some(request.clone())))?;
|
||||
|
||||
Page::admin(request)
|
||||
.with_title(title.clone())
|
||||
.with_child(AdminFrame::new().with_title(title).with_child(content))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
// **< Render compartido >**************************************************************************
|
||||
|
||||
// Rejilla de secciones con sus páginas (título + descripción). La usan tanto `dashboard()` (todas
|
||||
// las secciones) como `section_page()` (una sola), filtrando siempre por permiso del usuario
|
||||
// actual. Devuelve `None` si no queda ninguna sección visible con páginas accesibles.
|
||||
fn render_sections(cx: &Context, candidates: &[&'static AdminSection]) -> Option<Container> {
|
||||
let reg = registry::global();
|
||||
let sections_with_pages: Vec<_> = candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|section| {
|
||||
let pages: Vec<_> = reg
|
||||
.pages_for_section(§ion.key)
|
||||
.into_iter()
|
||||
.filter(|p| p.is_accessible(cx))
|
||||
.collect();
|
||||
(section, pages)
|
||||
})
|
||||
.filter(|(_, pages)| !pages.is_empty())
|
||||
.collect();
|
||||
if sections_with_pages.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut sections = Container::new().with_prop(PropsOp::add_classes("admin-dashboard-sections"));
|
||||
for (section, pages) in sections_with_pages {
|
||||
sections = sections.with_child(
|
||||
Container::new()
|
||||
.with_prop(PropsOp::add_classes("admin-dashboard-section"))
|
||||
.with_child(Html::with(move |cx| {
|
||||
html! {
|
||||
h2 class="admin-dashboard-section-title" {
|
||||
a href=(cx.route(section.path.as_str())) { (section.title.using(cx)) }
|
||||
}
|
||||
ul class="admin-dashboard-section-links" {
|
||||
@for page in &pages {
|
||||
li class="admin-dashboard-link" {
|
||||
a href=(cx.route(page.path.as_str())) {
|
||||
(page.title.using(cx))
|
||||
}
|
||||
@if let Some(description) = &page.description {
|
||||
span class="admin-dashboard-link-desc" {
|
||||
" - " (description.using(cx))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})),
|
||||
);
|
||||
}
|
||||
Some(sections)
|
||||
// Página del registro y esquema de la página de ajustes de la petición.
|
||||
fn config_form_page(
|
||||
request: &HttpRequest,
|
||||
) -> Result<(&'static AdminPage, &'static SettingsSchema), ErrorPage> {
|
||||
let not_found = || ErrorPage::NotFound(Some(request.clone()));
|
||||
let path = strip_admin_path(request.path()).ok_or_else(not_found)?;
|
||||
let page = AdminRegistry::global().page(path).ok_or_else(not_found)?;
|
||||
let schema = config_forms().get(path).ok_or_else(not_found)?;
|
||||
Ok((page, schema))
|
||||
}
|
||||
|
||||
// **< Config form - GET >**************************************************************************
|
||||
|
||||
/// GET de una página [`AdminPageKind::ConfigForm`].
|
||||
///
|
||||
/// Lee el schema del registro y renderiza el formulario con los valores actuales.
|
||||
// GET de una página de ajustes: el formulario con los valores guardados.
|
||||
pub async fn config_form_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let path = request.path().to_owned();
|
||||
let reg = registry::global();
|
||||
let page = reg
|
||||
.pages()
|
||||
.get(&path)
|
||||
.ok_or_else(|| ErrorPage::NotFound(Some(request.clone())))?;
|
||||
|
||||
let AdminPageKind::ConfigForm(ref schema) = page.kind else {
|
||||
return Err(ErrorPage::NotFound(Some(request.clone())));
|
||||
};
|
||||
|
||||
require_permission(&request, page.permission)?;
|
||||
|
||||
let title = page.title.clone();
|
||||
let mut form = ConfigForm::with_schema(schema.clone());
|
||||
let mut cx = Context::new(request.clone());
|
||||
let content = form.render(&mut cx).await;
|
||||
let (page, schema) = config_form_page(&request)?;
|
||||
|
||||
Page::admin(request)
|
||||
.with_title(title.clone())
|
||||
.with_child(
|
||||
AdminFrame::new()
|
||||
.with_title(title)
|
||||
.with_child(Html::with(move |_| content.clone())),
|
||||
)
|
||||
.with_title(page.title().clone())
|
||||
.with_child(ConfigForm::with_schema(schema.clone()))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
// **< Config form - POST >*************************************************************************
|
||||
|
||||
/// POST de una página [`AdminPageKind::ConfigForm`].
|
||||
///
|
||||
/// Valida y persiste los valores en `settings`, luego redirige al GET con
|
||||
/// estado `saved=true`.
|
||||
// POST de una página de ajustes: guarda los valores enviados y vuelve a mostrar el formulario con
|
||||
// un mensaje. Si falta algún campo obligatorio no guarda ninguno.
|
||||
pub async fn config_form_post(
|
||||
request: HttpRequest,
|
||||
web::Form(data): web::Form<HashMap<String, String>>,
|
||||
) -> Result<Markup, ErrorPage> {
|
||||
let path = request.path().to_owned();
|
||||
let reg = registry::global();
|
||||
let page = reg
|
||||
.pages()
|
||||
.get(&path)
|
||||
.ok_or_else(|| ErrorPage::NotFound(Some(request.clone())))?;
|
||||
let (page, schema) = config_form_page(&request)?;
|
||||
let mut admin = Page::admin(request).with_title(page.title().clone());
|
||||
|
||||
let AdminPageKind::ConfigForm(ref schema) = page.kind else {
|
||||
return Err(ErrorPage::NotFound(Some(request.clone())));
|
||||
};
|
||||
|
||||
require_permission(&request, page.permission)?;
|
||||
|
||||
let mut save_error = false;
|
||||
|
||||
for field in schema.fields() {
|
||||
let key = schema.key_for(field.name());
|
||||
|
||||
// Los checkbox HTML sólo envían el campo si están marcados.
|
||||
let raw = match field.field_type() {
|
||||
crate::settings::SettingFieldType::Boolean => data
|
||||
.get(field.name())
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("false")
|
||||
.to_owned(),
|
||||
_ => {
|
||||
let Some(raw) = data.get(field.name()) else {
|
||||
if *field.required() {
|
||||
save_error = true;
|
||||
}
|
||||
continue;
|
||||
};
|
||||
raw.clone()
|
||||
let (level, message) = match submitted_values(schema, &data) {
|
||||
None => (MessageLevel::Error, "config-required"),
|
||||
Some(values) => {
|
||||
let user_id = admin.current_user().id();
|
||||
let mut saved = true;
|
||||
for (key, value) in values {
|
||||
if let Err(error) = settings::set(&key, &value, schema.scope(), user_id).await {
|
||||
trace::error!("Failed to save the setting \"{key}\": {error}");
|
||||
saved = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
if saved {
|
||||
(MessageLevel::Info, "config-saved-ok")
|
||||
} else {
|
||||
(MessageLevel::Error, "config-saved-error")
|
||||
}
|
||||
}
|
||||
};
|
||||
admin.push_message(level, Lc::t(message, &LOCALES_ADMIN));
|
||||
|
||||
settings::set::<String>(&key, &raw, schema.scope(), None).await;
|
||||
}
|
||||
|
||||
let title = page.title.clone();
|
||||
let mut form = ConfigForm::with_schema(schema.clone()).with_saved(!save_error, save_error);
|
||||
let mut cx = Context::new(request.clone());
|
||||
let content = form.render(&mut cx).await;
|
||||
|
||||
Page::admin(request)
|
||||
.with_title(title.clone())
|
||||
.with_child(
|
||||
AdminFrame::new()
|
||||
.with_title(title)
|
||||
.with_child(Html::with(move |_| content.clone())),
|
||||
)
|
||||
admin
|
||||
.with_child(ConfigForm::with_schema(schema.clone()))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
// Clave y valor de cada campo del esquema en el envío, o `None` si falta un campo obligatorio o
|
||||
// llega vacío. Una casilla sin marcar no se envía, así que vale `"false"`.
|
||||
fn submitted_values(
|
||||
schema: &SettingsSchema,
|
||||
data: &HashMap<String, String>,
|
||||
) -> Option<Vec<(String, String)>> {
|
||||
let mut values = Vec::with_capacity(schema.fields().len());
|
||||
for field in schema.fields() {
|
||||
let value = match (field.field_type(), data.get(field.name())) {
|
||||
(SettingFieldType::Boolean, value) => value.map_or("false", String::as_str),
|
||||
(_, Some(value)) if !value.trim().is_empty() => value,
|
||||
(_, _) if *field.required() => return None,
|
||||
(_, value) => value.map_or("", String::as_str),
|
||||
};
|
||||
values.push((schema.key_for(field.name()), value.to_owned()));
|
||||
}
|
||||
Some(values)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::settings::SettingField;
|
||||
|
||||
fn schema() -> SettingsSchema {
|
||||
SettingsSchema::new("garden")
|
||||
.with_field(SettingField::text("name", Lc::n("Name")).with_required(true))
|
||||
.with_field(SettingField::text("notice", Lc::n("Notice")))
|
||||
.with_field(SettingField::boolean("open", Lc::n("Open")))
|
||||
}
|
||||
|
||||
fn data(pairs: &[(&str, &str)]) -> HashMap<String, String> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn values_are_keyed_by_scope_and_an_unchecked_box_is_false() {
|
||||
let values = submitted_values(&schema(), &data(&[("name", "Ours"), ("notice", "")]));
|
||||
assert_eq!(
|
||||
values.unwrap(),
|
||||
[
|
||||
("garden.name".to_owned(), "Ours".to_owned()),
|
||||
("garden.notice".to_owned(), String::new()),
|
||||
("garden.open".to_owned(), "false".to_owned()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_required_field_missing_or_blank_saves_nothing() {
|
||||
assert!(submitted_values(&schema(), &data(&[("notice", "Hi")])).is_none());
|
||||
assert!(submitted_values(&schema(), &data(&[("name", " ")])).is_none());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
<h1>PageTop Admin</h1>
|
||||
|
||||
<p>Panel de administración extensible para <strong>PageTop</strong>.</p>
|
||||
<p>Ajustes guardados en la base de datos para el panel de administración de <strong>PageTop</strong>.</p>
|
||||
|
||||
[](https://docs.rs/pagetop-admin)
|
||||
[](https://crates.io/crates/pagetop-admin)
|
||||
|
|
@ -12,11 +12,8 @@
|
|||
|
||||
</div>
|
||||
|
||||
Añade a una aplicación PageTop un panel de administración en `/admin` que cada extensión amplía con
|
||||
sus propias secciones, páginas, pestañas y botones, declarados con acciones. Trae las secciones
|
||||
habituales (personas, estructura, configuración, informes y ayuda), formularios de configuración
|
||||
que se guardan en la base de datos y un menú de navegación hecho sólo con componentes del núcleo,
|
||||
para que funcione con cualquier tema.
|
||||
Añade al panel de administración de PageTop **ajustes que se guardan en la base de datos** y que un
|
||||
administrador cambia desde el propio panel, con la aplicación en marcha.
|
||||
|
||||
## Sobre PageTop
|
||||
|
||||
|
|
@ -24,6 +21,36 @@ para que funcione con cualquier tema.
|
|||
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
|
||||
configurables, basadas en HTML, CSS y JavaScript.
|
||||
|
||||
## Qué aporta
|
||||
|
||||
- **Páginas de ajustes sin código propio.** Una extensión describe los campos con un
|
||||
[`SettingsSchema`] y declara la página con [`DeclareConfigForms`]. `pagetop-admin` monta su ruta,
|
||||
pinta el formulario con los valores guardados y guarda lo que se envía, salvo que falte algún
|
||||
campo obligatorio o llegue vacío.
|
||||
- **El almacén de los valores.** La tabla `settings`, que crea al arrancar, y las funciones del
|
||||
módulo [`settings`](mod@settings) para leerlos ([`settings::get_or()`] y compañía) y
|
||||
escribirlos desde código.
|
||||
- **El formulario** ([`ConfigForm`]), por si una página propia quiere mostrar el de un esquema.
|
||||
|
||||
## En qué se apoya
|
||||
|
||||
El panel en sí es de PageTop (el módulo [`pagetop::admin`]): su página de inicio, sus secciones, la
|
||||
navegación, las migas de pan y la plantilla de administración ([`Page::admin()`]). Cada página de
|
||||
ajustes es una [`AdminPage`] del núcleo, así que aparece en el panel como cualquier otra, con su
|
||||
sección y su permiso, y se pinta con cualquier tema. Una extensión que sólo añade páginas propias al
|
||||
panel, sin ajustes, no necesita `pagetop-admin`.
|
||||
|
||||
## Cuándo usarlo
|
||||
|
||||
Para valores que decide quien administra el sitio y que cambian con el tiempo: un aviso en la
|
||||
portada, un número de plazas, abrir o cerrar las inscripciones... Lo que fija quien despliega la
|
||||
aplicación (la base de datos, el servidor de correo, los límites) va en los archivos de
|
||||
configuración (ver [`pagetop::config`]), que no se pueden cambiar desde el panel y exigen
|
||||
reiniciar.
|
||||
|
||||
Los valores que envía el formulario se guardan como texto, también los de los campos numéricos y las
|
||||
casillas (`"42"`, `"true"`): se leen como `String` y se convierten al usarlos.
|
||||
|
||||
## Guía rápida
|
||||
|
||||
**Añade la dependencia** a tu `Cargo.toml`:
|
||||
|
|
@ -33,16 +60,15 @@ configurables, basadas en HTML, CSS y JavaScript.
|
|||
pagetop-admin = "..."
|
||||
```
|
||||
|
||||
La configuración se guarda con `pagetop-seaorm`: la aplicación elige el motor de base de datos con
|
||||
su *feature* (`postgres`, `mysql` o `sqlite`) y configura la conexión en la sección `[database]`.
|
||||
Los ajustes se guardan con `pagetop-seaorm`: la aplicación elige el motor de base de datos con su
|
||||
*feature* (`postgres`, `mysql` o `sqlite`) y configura la conexión en la sección `[database]`.
|
||||
|
||||
**Declara la extensión** como dependencia de la tuya (`&pagetop_admin::Admin`) y **añade al panel**
|
||||
tus secciones, páginas o formularios de configuración:
|
||||
**Declara la extensión** como dependencia de la tuya (`&pagetop_admin::Admin`); si no, sus páginas
|
||||
de ajustes no se montan. Después **declara tus páginas de ajustes**, cada una con su permiso:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_admin::prelude::*;
|
||||
use pagetop_admin::settings::{SettingField, SettingsSchema};
|
||||
|
||||
pub struct MyApp;
|
||||
|
||||
|
|
@ -53,25 +79,17 @@ impl Extension for MyApp {
|
|||
}
|
||||
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![
|
||||
DeclareAdminPages::new(declare_pages),
|
||||
]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router.route("/admin/config/myapp", web::get(config_handler))
|
||||
actions![DeclareConfigForms::new(declare_forms)]
|
||||
}
|
||||
}
|
||||
|
||||
fn declare_pages(bag: &mut PageBag) {
|
||||
bag.add(AdminPage {
|
||||
path: "/admin/config/myapp".to_owned(),
|
||||
section: "config".to_owned(),
|
||||
title: Lc::n("My App"),
|
||||
description: Some(Lc::n("Configure My App.")),
|
||||
weight: 0,
|
||||
permission: &MyPermission::Config,
|
||||
kind: AdminPageKind::View,
|
||||
fn declare_forms(bag: &mut ConfigFormBag) {
|
||||
bag.add(ConfigFormPage {
|
||||
page: AdminPage::new("config/myapp", "config", Lc::n("My App"), &MyPermission::Config)
|
||||
.with_description(Lc::n("Name of the site.")),
|
||||
schema: SettingsSchema::new("myapp").with_field(
|
||||
SettingField::text("site_name", Lc::n("Site name")).with_required(true),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -88,30 +106,11 @@ impl Permission for MyPermission {
|
|||
}
|
||||
}
|
||||
|
||||
async fn config_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let schema = SettingsSchema::new("myapp.config")
|
||||
.with_field(SettingField::text("site_name", "Site name").with_required(true));
|
||||
|
||||
let title = "My App configuration";
|
||||
let mut form = ConfigForm::with_schema(schema);
|
||||
let mut cx = Context::new(request.clone());
|
||||
let content = form.render(&mut cx).await;
|
||||
|
||||
Page::admin(request)
|
||||
.with_title(Lc::n(title))
|
||||
.with_child(
|
||||
AdminFrame::new()
|
||||
.with_title(Lc::n(title))
|
||||
.with_child(Html::with(move |_| content.clone())),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
// Los valores se guardan con la clave `<ámbito>.<campo>`.
|
||||
async fn site_name() -> String {
|
||||
pagetop_admin::settings::get_or("myapp.site_name", String::new()).await
|
||||
}
|
||||
```
|
||||
|
||||
Para formularios de configuración enteramente automáticos (GET y POST gestionados por
|
||||
`pagetop-admin`), usa `AdminPageKind::ConfigForm(schema)` en lugar de `View` y no registres la ruta
|
||||
tú mismo.
|
||||
*/
|
||||
|
||||
use pagetop::prelude::*;
|
||||
|
|
@ -119,39 +118,24 @@ use pagetop_seaorm::install_migrations;
|
|||
|
||||
include_locales!(LOCALES_ADMIN);
|
||||
|
||||
/// Ruta raíz del panel de administración. No es configurable: otras piezas del ecosistema (p. ej.
|
||||
/// las rutas de `pagetop-user`, `/admin/user/...`) ya asumen este valor de forma literal. Es
|
||||
/// pública para que otras extensiones enlacen al panel sin repetir la ruta.
|
||||
pub const ADMIN_BASE_PATH: &str = "/admin";
|
||||
|
||||
pub mod action;
|
||||
pub mod component;
|
||||
pub mod error;
|
||||
pub mod registry;
|
||||
pub mod settings;
|
||||
|
||||
pub(crate) mod entity;
|
||||
pub(crate) mod handlers;
|
||||
pub(crate) mod migration;
|
||||
pub(crate) mod seed;
|
||||
|
||||
pub use action::{
|
||||
ActionBag, DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks,
|
||||
PageBag, SectionBag, TaskBag,
|
||||
};
|
||||
pub use component::{AdminFrame, AdminMenu, ConfigForm};
|
||||
pub use registry::{AdminAction, AdminPage, AdminPageKind, AdminSection, AdminTask};
|
||||
pub use action::{ConfigFormBag, ConfigFormPage, DeclareConfigForms};
|
||||
pub use component::ConfigForm;
|
||||
pub use settings::{SettingField, SettingFieldType, SettingsSchema};
|
||||
|
||||
/// Prelude de `pagetop-admin`.
|
||||
pub mod prelude {
|
||||
pub use crate::action::{
|
||||
ActionBag, DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks,
|
||||
PageBag, SectionBag, TaskBag,
|
||||
};
|
||||
pub use crate::component::{AdminFrame, AdminMenu, ConfigForm};
|
||||
pub use crate::action::{ConfigFormBag, ConfigFormPage, DeclareConfigForms};
|
||||
pub use crate::component::ConfigForm;
|
||||
pub use crate::error::AdminError;
|
||||
pub use crate::registry::{AdminAction, AdminPage, AdminPageKind, AdminSection, AdminTask};
|
||||
pub use crate::settings::{SettingField, SettingFieldType, SettingsSchema};
|
||||
}
|
||||
|
||||
|
|
@ -175,42 +159,22 @@ impl Extension for Admin {
|
|||
}
|
||||
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![action::DeclareAdminSections::new(seed::declare_default_sections).with_weight(-99),]
|
||||
actions![pagetop::base::action::admin::DeclareAdminPages::new(
|
||||
action::declare_config_form_pages
|
||||
)]
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
install_migrations!(m20260629_000001_create_settings)?;
|
||||
registry::build();
|
||||
|
||||
// Región neutra del core: cualquier tema puede decidir renderizarla (o no) sin que
|
||||
// `pagetop-admin` dependa de ninguno en concreto (ver `CoreRegions::Aside`).
|
||||
InRegion::Global(&CoreRegions::Aside).add(component::AdminMenu::new());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
let base = ADMIN_BASE_PATH;
|
||||
let reg = registry::global();
|
||||
|
||||
let mut r = router.route(base, web::get(handlers::dashboard));
|
||||
|
||||
// Página de aterrizaje de cada sección, salvo que una extensión ya haya reclamado esa
|
||||
// misma ruta con su propia `AdminPage` (esa página gana y se monta más abajo).
|
||||
for section in reg.sections().values() {
|
||||
if !reg.pages().contains_key(§ion.path) {
|
||||
r = r.route(section.path.as_str(), web::get(handlers::section_page));
|
||||
}
|
||||
}
|
||||
|
||||
for (path, page) in reg.pages() {
|
||||
if let AdminPageKind::ConfigForm(_) = &page.kind {
|
||||
r = r.route(
|
||||
path.as_str(),
|
||||
web::get(handlers::config_form_get).post(handlers::config_form_post),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
r
|
||||
fn configure_router(&self, routes: Routes) -> Routes {
|
||||
action::config_forms().keys().fold(routes, |routes, path| {
|
||||
routes.admin_route(
|
||||
path,
|
||||
web::get(handlers::config_form_get).post(handlers::config_form_post),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,21 +1,8 @@
|
|||
extension_name = PageTop Admin
|
||||
extension_description = Extensible administration panel for PageTop.
|
||||
|
||||
# Dashboard
|
||||
dashboard-title = Administration
|
||||
dashboard-description = Manage your site.
|
||||
|
||||
# Sections
|
||||
section-people = People
|
||||
section-structure = Structure
|
||||
section-config = Configuration
|
||||
section-reports = Reports
|
||||
section-help = Help
|
||||
extension_description = Settings stored in the database for the PageTop administration panel.
|
||||
|
||||
# Config form
|
||||
config-save-label = Save configuration
|
||||
config-saved-ok = Configuration saved.
|
||||
config-saved-error = Could not save configuration.
|
||||
|
||||
# Navigation
|
||||
admin-breadcrumb-home = Administration
|
||||
config-required = Fill in the required fields. Nothing was saved.
|
||||
|
|
|
|||
|
|
@ -1,21 +1,8 @@
|
|||
extension_name = PageTop Admin
|
||||
extension_description = Panel de administración extensible para PageTop.
|
||||
|
||||
# Dashboard
|
||||
dashboard-title = Administración
|
||||
dashboard-description = Gestiona tu sitio.
|
||||
|
||||
# Sections
|
||||
section-people = Personas
|
||||
section-structure = Estructura
|
||||
section-config = Configuración
|
||||
section-reports = Informes
|
||||
section-help = Ayuda
|
||||
extension_description = Ajustes guardados en la base de datos para el panel de administración de PageTop.
|
||||
|
||||
# Config form
|
||||
config-save-label = Guardar configuración
|
||||
config-saved-ok = Configuración guardada.
|
||||
config-saved-error = No se pudo guardar la configuración.
|
||||
|
||||
# Navigation
|
||||
admin-breadcrumb-home = Administración
|
||||
config-required = Rellena los campos obligatorios. No se ha guardado nada.
|
||||
|
|
|
|||
|
|
@ -1,279 +0,0 @@
|
|||
//! Registro global de secciones, páginas, tareas y acciones del panel de administración.
|
||||
//!
|
||||
//! Se construye una única vez durante `Extension::initialize()` y permanece
|
||||
//! inmutable durante la vida de la aplicación.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use pagetop::prelude::*;
|
||||
|
||||
use crate::action::{
|
||||
ActionBag, DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks,
|
||||
PageBag, SectionBag, TaskBag,
|
||||
};
|
||||
use crate::settings::SettingsSchema;
|
||||
|
||||
// **< Tipos del registro >*************************************************************************
|
||||
|
||||
/// Sección del panel de administración (agrupación de páginas en el menú y en el *dashboard*).
|
||||
///
|
||||
/// Una sección no tiene permiso propio: se muestra a quien pueda acceder a alguna de sus páginas, y
|
||||
/// se oculta si no le queda ninguna.
|
||||
#[derive(Clone)]
|
||||
pub struct AdminSection {
|
||||
/// Identificador único de la sección (p. ej. `"config"`).
|
||||
pub key: String,
|
||||
/// Ruta base de la sección (p. ej. `"/admin/config"`).
|
||||
pub path: String,
|
||||
/// Título visible en el sidebar.
|
||||
pub title: Lc,
|
||||
/// Peso para ordenar en el sidebar (menor = antes).
|
||||
pub weight: i32,
|
||||
}
|
||||
|
||||
/// Página del panel de administración.
|
||||
#[derive(Clone)]
|
||||
pub struct AdminPage {
|
||||
/// Ruta exacta de la página (p. ej. `"/admin/config/site"`).
|
||||
pub path: String,
|
||||
/// Clave de la sección a la que pertenece.
|
||||
pub section: String,
|
||||
/// Título visible en el sidebar y encabezado de página.
|
||||
pub title: Lc,
|
||||
/// Descripción breve (para el dashboard y listas de páginas), si tiene una.
|
||||
pub description: Option<Lc>,
|
||||
/// Peso dentro de la sección (menor = antes).
|
||||
pub weight: i32,
|
||||
/// Permiso requerido para acceder. Es obligatorio: cada página declara el suyo, y es también
|
||||
/// el que decide si su sección se muestra.
|
||||
pub permission: PermissionRef,
|
||||
/// Tipo de página y datos asociados.
|
||||
pub kind: AdminPageKind,
|
||||
}
|
||||
|
||||
impl AdminPage {
|
||||
/// Devuelve `true` si el usuario actual puede acceder a esta página.
|
||||
pub fn is_accessible(&self, cx: &Context) -> bool {
|
||||
cx.request()
|
||||
.is_some_and(|request| has_permission(request, self.permission))
|
||||
}
|
||||
}
|
||||
|
||||
/// Variantes de comportamiento de una [`AdminPage`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum AdminPageKind {
|
||||
/// Página genérica cuyo handler se registra externamente.
|
||||
View,
|
||||
/// Formulario de configuración gestionado automáticamente por `pagetop-admin`.
|
||||
ConfigForm(SettingsSchema),
|
||||
}
|
||||
|
||||
/// Tarea (pestaña) local dentro de una página de administración.
|
||||
#[derive(Clone)]
|
||||
pub struct AdminTask {
|
||||
/// Ruta de la tarea.
|
||||
pub path: String,
|
||||
/// Ruta de la página padre.
|
||||
pub parent_path: String,
|
||||
/// Etiqueta de la pestaña.
|
||||
pub title: Lc,
|
||||
/// Peso (menor = primera pestaña).
|
||||
pub weight: i32,
|
||||
/// Si es la tarea por defecto (pestaña activa al entrar a la página padre).
|
||||
pub is_default: bool,
|
||||
/// Permiso requerido (`None` = mismo que la página padre).
|
||||
pub permission: Option<PermissionRef>,
|
||||
}
|
||||
|
||||
/// Acción local (botón de acción) en una página de administración.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AdminAction {
|
||||
/// Ruta de destino de la acción.
|
||||
pub url: String,
|
||||
/// Página en la que aparece el botón.
|
||||
pub for_path: String,
|
||||
/// Etiqueta del botón.
|
||||
pub title: Lc,
|
||||
/// Peso (menor = primero).
|
||||
pub weight: i32,
|
||||
}
|
||||
|
||||
// **< AdminRegistry >******************************************************************************
|
||||
|
||||
/// Registro global del panel de administración, construido una sola vez en `initialize()`.
|
||||
#[derive(Getters)]
|
||||
pub struct AdminRegistry {
|
||||
/// Devuelve las secciones indexadas por clave (`BTreeMap` para orden estable por clave).
|
||||
sections: BTreeMap<String, AdminSection>,
|
||||
/// Devuelve las páginas indexadas por ruta.
|
||||
pages: BTreeMap<String, AdminPage>,
|
||||
/// Devuelve las tareas indexadas por ruta de página padre.
|
||||
tasks: BTreeMap<String, Vec<AdminTask>>,
|
||||
/// Devuelve las acciones indexadas por ruta de página.
|
||||
actions: BTreeMap<String, Vec<AdminAction>>,
|
||||
}
|
||||
|
||||
impl AdminRegistry {
|
||||
fn new() -> Self {
|
||||
AdminRegistry {
|
||||
sections: BTreeMap::new(),
|
||||
pages: BTreeMap::new(),
|
||||
tasks: BTreeMap::new(),
|
||||
actions: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Devuelve las páginas de una sección ordenadas por peso.
|
||||
pub fn pages_for_section(&self, section_key: &str) -> Vec<&AdminPage> {
|
||||
let mut pages: Vec<&AdminPage> = self
|
||||
.pages
|
||||
.values()
|
||||
.filter(|p| p.section == section_key)
|
||||
.collect();
|
||||
pages.sort_by_key(|p| p.weight);
|
||||
pages
|
||||
}
|
||||
|
||||
/// Devuelve las secciones ordenadas por peso.
|
||||
pub fn ordered_sections(&self) -> Vec<&AdminSection> {
|
||||
let mut sections: Vec<&AdminSection> = self.sections.values().collect();
|
||||
sections.sort_by_key(|s| s.weight);
|
||||
sections
|
||||
}
|
||||
|
||||
/// Devuelve las tareas de una página ordenadas por peso.
|
||||
pub fn tasks_for(&self, path: &str) -> Vec<&AdminTask> {
|
||||
let Some(tasks) = self.tasks.get(path) else {
|
||||
return vec![];
|
||||
};
|
||||
let mut t: Vec<&AdminTask> = tasks.iter().collect();
|
||||
t.sort_by_key(|t| t.weight);
|
||||
t
|
||||
}
|
||||
|
||||
/// Devuelve las acciones de una página ordenadas por peso.
|
||||
pub fn actions_for(&self, path: &str) -> Vec<&AdminAction> {
|
||||
let Some(actions) = self.actions.get(path) else {
|
||||
return vec![];
|
||||
};
|
||||
let mut a: Vec<&AdminAction> = actions.iter().collect();
|
||||
a.sort_by_key(|a| a.weight);
|
||||
a
|
||||
}
|
||||
}
|
||||
|
||||
// **< Registro global >****************************************************************************
|
||||
|
||||
static REGISTRY: OnceLock<AdminRegistry> = OnceLock::new();
|
||||
|
||||
/// Construye el registro despachando todas las acciones de declaración.
|
||||
///
|
||||
/// Se llama una sola vez desde `Admin::initialize()`.
|
||||
pub(crate) fn build() {
|
||||
let mut registry = AdminRegistry::new();
|
||||
|
||||
// Secciones
|
||||
let mut section_bag = SectionBag {
|
||||
sections: Vec::new(),
|
||||
};
|
||||
DeclareAdminSections::dispatch(&mut section_bag);
|
||||
for s in section_bag.sections {
|
||||
registry.sections.insert(s.key.clone(), s);
|
||||
}
|
||||
|
||||
// Páginas
|
||||
let mut page_bag = PageBag { pages: Vec::new() };
|
||||
DeclareAdminPages::dispatch(&mut page_bag);
|
||||
for p in page_bag.pages {
|
||||
registry.pages.insert(p.path.clone(), p);
|
||||
}
|
||||
|
||||
// Tareas
|
||||
let mut task_bag = TaskBag { tasks: Vec::new() };
|
||||
DeclareAdminTasks::dispatch(&mut task_bag);
|
||||
for t in task_bag.tasks {
|
||||
registry
|
||||
.tasks
|
||||
.entry(t.parent_path.clone())
|
||||
.or_default()
|
||||
.push(t);
|
||||
}
|
||||
|
||||
// Acciones locales
|
||||
let mut action_bag = ActionBag {
|
||||
actions: Vec::new(),
|
||||
};
|
||||
DeclareAdminActions::dispatch(&mut action_bag);
|
||||
for a in action_bag.actions {
|
||||
registry
|
||||
.actions
|
||||
.entry(a.for_path.clone())
|
||||
.or_default()
|
||||
.push(a);
|
||||
}
|
||||
|
||||
REGISTRY.set(registry).ok();
|
||||
}
|
||||
|
||||
/// Accede al registro global del panel de administración.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Entra en pánico si se llama antes de que `Admin::initialize()` haya completado.
|
||||
pub fn global() -> &'static AdminRegistry {
|
||||
REGISTRY.get().expect("AdminRegistry not initialized")
|
||||
}
|
||||
|
||||
/// Devuelve `true` si el usuario de la petición actual tiene acceso a alguna página del panel, es
|
||||
/// decir, si `/admin` no le devolvería un acceso denegado.
|
||||
///
|
||||
/// Permite a otras extensiones (p. ej. el menú de cuenta de `pagetop-user`) ofrecer el enlace a
|
||||
/// la administración sólo cuando procede.
|
||||
pub fn can_access_admin(cx: &Context) -> bool {
|
||||
let reg = global();
|
||||
reg.ordered_sections().into_iter().any(|section| {
|
||||
reg.pages_for_section(§ion.key)
|
||||
.into_iter()
|
||||
.any(|page| page.is_accessible(cx))
|
||||
})
|
||||
}
|
||||
|
||||
// **< Menú de administración >*********************************************************************
|
||||
|
||||
/// Construye la barra de navegación de administración para el usuario de la petición actual: un
|
||||
/// enlace al *dashboard* seguido de un desplegable por sección visible, con sus páginas accesibles
|
||||
/// dentro.
|
||||
///
|
||||
/// Pensado para que un tema la use como navegación de `CoreTemplates::Admin` -- ver
|
||||
/// [`crate::component::AdminMenu`]. `pagetop-admin` no impone ningún marcado propio: la
|
||||
/// [`Navbar`] resultante se renderiza con su aspecto por defecto salvo que el tema lo intercepte
|
||||
/// en [`Theme::render_component()`](pagetop::core::theme::Theme::render_component). Se construye
|
||||
/// enteramente con componentes del núcleo (`Navbar`/`Nav`/`Dropdown`), sin depender de ningún
|
||||
/// tema concreto.
|
||||
pub fn admin_navbar(cx: &Context) -> Navbar {
|
||||
let reg = global();
|
||||
|
||||
let mut nav = Nav::new().with_item(nav::Item::link(
|
||||
Lc::t("dashboard-title", &crate::LOCALES_ADMIN),
|
||||
crate::ADMIN_BASE_PATH,
|
||||
));
|
||||
|
||||
for section in reg.ordered_sections() {
|
||||
let pages: Vec<_> = reg
|
||||
.pages_for_section(§ion.key)
|
||||
.into_iter()
|
||||
.filter(|p| p.is_accessible(cx))
|
||||
.collect();
|
||||
if pages.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut menu = Dropdown::new().with_title(section.title.clone());
|
||||
for page in pages {
|
||||
menu = menu.with_item(dropdown::Item::link(page.title.clone(), page.path.clone()));
|
||||
}
|
||||
nav = nav.with_item(nav::Item::dropdown(menu));
|
||||
}
|
||||
|
||||
Navbar::simple().with_item(navbar::Item::nav(nav))
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use crate::ADMIN_BASE_PATH;
|
||||
use crate::LOCALES_ADMIN;
|
||||
use crate::action::SectionBag;
|
||||
use crate::registry::AdminSection;
|
||||
|
||||
/// Declara las secciones incorporadas del panel de administración.
|
||||
///
|
||||
/// Se registra en `Admin::actions()` como `DeclareAdminSections::new(declare_default_sections)`
|
||||
/// con peso negativo para ejecutarse antes que las extensiones de terceros.
|
||||
pub(crate) fn declare_default_sections(bag: &mut SectionBag) {
|
||||
let base = ADMIN_BASE_PATH;
|
||||
|
||||
bag.add(AdminSection {
|
||||
key: "people".to_owned(),
|
||||
path: format!("{}/people", base),
|
||||
title: Lc::t("section-people", &LOCALES_ADMIN),
|
||||
weight: 10,
|
||||
});
|
||||
bag.add(AdminSection {
|
||||
key: "structure".to_owned(),
|
||||
path: format!("{}/structure", base),
|
||||
title: Lc::t("section-structure", &LOCALES_ADMIN),
|
||||
weight: 20,
|
||||
});
|
||||
bag.add(AdminSection {
|
||||
key: "config".to_owned(),
|
||||
path: format!("{}/config", base),
|
||||
title: Lc::t("section-config", &LOCALES_ADMIN),
|
||||
weight: 30,
|
||||
});
|
||||
bag.add(AdminSection {
|
||||
key: "reports".to_owned(),
|
||||
path: format!("{}/reports", base),
|
||||
title: Lc::t("section-reports", &LOCALES_ADMIN),
|
||||
weight: 40,
|
||||
});
|
||||
bag.add(AdminSection {
|
||||
key: "help".to_owned(),
|
||||
path: format!("{}/help", base),
|
||||
title: Lc::t("section-help", &LOCALES_ADMIN),
|
||||
weight: 50,
|
||||
});
|
||||
}
|
||||
|
|
@ -25,32 +25,9 @@ pub async fn get_or<T: DeserializeOwned>(key: &str, default: T) -> T {
|
|||
|
||||
/// Escribe un valor en la tabla `settings`.
|
||||
///
|
||||
/// Si la clave no existe se inserta; si existe, se actualiza.
|
||||
pub async fn set<T: Serialize>(key: &str, value: &T, scope: &str, user_id: Option<i32>) {
|
||||
set_async(key, value, scope, user_id).await.ok();
|
||||
}
|
||||
|
||||
/// Elimina una entrada de `settings` por clave.
|
||||
pub async fn delete(key: &str) {
|
||||
delete_async(key).await.ok();
|
||||
}
|
||||
|
||||
/// Devuelve todos los pares `(key, value_json)` de un `scope` dado.
|
||||
pub async fn list_scope(scope: &str) -> Vec<(String, String)> {
|
||||
list_scope_async(scope).await.unwrap_or_default()
|
||||
}
|
||||
|
||||
// **< Implementación asíncrona >*******************************************************************
|
||||
|
||||
async fn get_async<T: DeserializeOwned>(key: &str) -> Result<T, AdminError> {
|
||||
let model = Entity::find_by_id(key)
|
||||
.one(dbconn())
|
||||
.await?
|
||||
.ok_or_else(|| AdminError::NotFound(key.to_owned()))?;
|
||||
Ok(serde_json::from_str(&model.value)?)
|
||||
}
|
||||
|
||||
async fn set_async<T: Serialize>(
|
||||
/// Si la clave no existe se inserta; si existe, se actualiza. Devuelve el error si no se puede
|
||||
/// guardar.
|
||||
pub async fn set<T: Serialize>(
|
||||
key: &str,
|
||||
value: &T,
|
||||
scope: &str,
|
||||
|
|
@ -82,11 +59,27 @@ async fn set_async<T: Serialize>(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete_async(key: &str) -> Result<(), AdminError> {
|
||||
/// Elimina una entrada de `settings` por clave. Devuelve el error si no se puede eliminar.
|
||||
pub async fn delete(key: &str) -> Result<(), AdminError> {
|
||||
Entity::delete_by_id(key).exec(dbconn()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Devuelve todos los pares `(key, value_json)` de un `scope` dado.
|
||||
pub async fn list_scope(scope: &str) -> Vec<(String, String)> {
|
||||
list_scope_async(scope).await.unwrap_or_default()
|
||||
}
|
||||
|
||||
// **< Implementación asíncrona >*******************************************************************
|
||||
|
||||
async fn get_async<T: DeserializeOwned>(key: &str) -> Result<T, AdminError> {
|
||||
let model = Entity::find_by_id(key)
|
||||
.one(dbconn())
|
||||
.await?
|
||||
.ok_or_else(|| AdminError::NotFound(key.to_owned()))?;
|
||||
Ok(serde_json::from_str(&model.value)?)
|
||||
}
|
||||
|
||||
async fn list_scope_async(scope: &str) -> Result<Vec<(String, String)>, AdminError> {
|
||||
let rows = Entity::find()
|
||||
.filter(Column::Scope.eq(scope))
|
||||
|
|
@ -107,7 +100,7 @@ pub enum SettingFieldType {
|
|||
/// Casilla de verificación (booleano).
|
||||
Boolean,
|
||||
/// Lista de opciones `(valor, etiqueta)`.
|
||||
Select { options: Vec<(String, String)> },
|
||||
Select { options: Vec<(String, Lc)> },
|
||||
}
|
||||
|
||||
/// Definición de un campo dentro de un [`SettingsSchema`].
|
||||
|
|
@ -116,70 +109,66 @@ pub struct SettingField {
|
|||
/// Devuelve el nombre del campo (clave dentro del scope, p. ej. `"site_name"`).
|
||||
name: String,
|
||||
/// Devuelve la etiqueta visible en el formulario.
|
||||
label: String,
|
||||
label: Lc,
|
||||
/// Devuelve el tipo de campo.
|
||||
field_type: SettingFieldType,
|
||||
/// Devuelve si el campo es obligatorio.
|
||||
required: bool,
|
||||
/// Devuelve el texto de ayuda opcional bajo el campo.
|
||||
help_text: Option<String>,
|
||||
/// Devuelve el valor por defecto como cadena JSON.
|
||||
/// Devuelve el texto de ayuda bajo el campo, o [`Lc::none()`] si no tiene.
|
||||
help_text: Lc,
|
||||
/// Devuelve el valor por defecto, como texto, igual que guarda el formulario los valores.
|
||||
default_value: Option<String>,
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl SettingField {
|
||||
/// Crea un campo de texto con nombre y etiqueta.
|
||||
pub fn text(name: impl Into<String>, label: impl Into<String>) -> Self {
|
||||
pub fn text(name: impl Into<String>, label: Lc) -> Self {
|
||||
SettingField {
|
||||
name: name.into(),
|
||||
label: label.into(),
|
||||
label,
|
||||
field_type: SettingFieldType::Text { max_length: None },
|
||||
required: false,
|
||||
help_text: None,
|
||||
help_text: Lc::none(),
|
||||
default_value: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Crea un campo numérico con nombre y etiqueta.
|
||||
pub fn number(name: impl Into<String>, label: impl Into<String>) -> Self {
|
||||
pub fn number(name: impl Into<String>, label: Lc) -> Self {
|
||||
SettingField {
|
||||
name: name.into(),
|
||||
label: label.into(),
|
||||
label,
|
||||
field_type: SettingFieldType::Number {
|
||||
min: None,
|
||||
max: None,
|
||||
},
|
||||
required: false,
|
||||
help_text: None,
|
||||
help_text: Lc::none(),
|
||||
default_value: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Crea un campo booleano con nombre y etiqueta.
|
||||
pub fn boolean(name: impl Into<String>, label: impl Into<String>) -> Self {
|
||||
pub fn boolean(name: impl Into<String>, label: Lc) -> Self {
|
||||
SettingField {
|
||||
name: name.into(),
|
||||
label: label.into(),
|
||||
label,
|
||||
field_type: SettingFieldType::Boolean,
|
||||
required: false,
|
||||
help_text: None,
|
||||
help_text: Lc::none(),
|
||||
default_value: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Crea un campo de selección con nombre, etiqueta y opciones.
|
||||
pub fn select(
|
||||
name: impl Into<String>,
|
||||
label: impl Into<String>,
|
||||
options: Vec<(String, String)>,
|
||||
) -> Self {
|
||||
pub fn select(name: impl Into<String>, label: Lc, options: Vec<(String, Lc)>) -> Self {
|
||||
SettingField {
|
||||
name: name.into(),
|
||||
label: label.into(),
|
||||
label,
|
||||
field_type: SettingFieldType::Select { options },
|
||||
required: false,
|
||||
help_text: None,
|
||||
help_text: Lc::none(),
|
||||
default_value: None,
|
||||
}
|
||||
}
|
||||
|
|
@ -191,14 +180,20 @@ impl SettingField {
|
|||
}
|
||||
|
||||
/// Añade texto de ayuda bajo el campo.
|
||||
pub fn with_help(mut self, text: impl Into<String>) -> Self {
|
||||
self.help_text = Some(text.into());
|
||||
pub fn with_help(mut self, text: Lc) -> Self {
|
||||
self.help_text = text;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece el valor por defecto (como valor JSON serializado).
|
||||
/// Establece el valor por defecto, el que muestra el formulario mientras no se guarde otro.
|
||||
///
|
||||
/// Se guarda como texto, igual que los valores que envía el formulario: un número o un
|
||||
/// booleano, con su forma habitual (`42`, `true`), y una cadena, tal cual, sin comillas.
|
||||
pub fn with_default<T: Serialize>(mut self, value: &T) -> Self {
|
||||
self.default_value = serde_json::to_string(value).ok();
|
||||
self.default_value = serde_json::to_value(value).ok().map(|value| match value {
|
||||
serde_json::Value::String(text) => text,
|
||||
other => other.to_string(),
|
||||
});
|
||||
self
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue