✨ (user): Asigna roles desde la edición de usuario

This commit is contained in:
Manuel Cillero 2026-10-05 00:36:47 +02:00
parent 806ed9e0dc
commit f819181872
26 changed files with 1219 additions and 544 deletions

View file

@ -1,49 +1,23 @@
//! Formulario de alta/edición de usuario.
use std::collections::BTreeMap;
use std::sync::LazyLock;
//! Formulario de alta/edición de usuario, también usado para que cada usuario edite su perfil.
use pagetop::prelude::*;
use crate::ADMIN_USERS_PATH;
use crate::LOCALES_USER;
use crate::user_path;
use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH};
use crate::component::{PasswordConfirm, error_banner};
use crate::service::user_admin::ABOUT_MAX_CHARS;
use super::{USER_ADMIN_FORM_ID, roles_fieldset};
// Regiones de la base IANA que sólo contienen alias heredados (fichero `backward`), todos con una
// zona canónica equivalente en otra región (p. ej. `US/Eastern` es `America/New_York`).
const LEGACY_REGIONS: [&str; 5] = ["Brazil", "Canada", "Chile", "Mexico", "US"];
// Zonas horarias IANA canónicas agrupadas por región (lo anterior a la primera `/`), ordenadas por
// región y nombre. Se descartan los alias heredados: los nombres sin región (`GB`, `Japan`,
// `EST5EDT`...), los de `LEGACY_REGIONS` y los de `Etc` salvo `Etc/UTC`, cuyo grupo va al final.
static TZ_BY_REGION: LazyLock<Vec<(&'static str, Vec<&'static str>)>> = LazyLock::new(|| {
let mut regions: BTreeMap<&'static str, Vec<&'static str>> = BTreeMap::new();
for tz in TZ_VARIANTS.iter() {
let name = tz.name();
let Some((region, _)) = name.split_once('/') else {
continue;
};
if LEGACY_REGIONS.contains(&region) || (region == "Etc" && name != "Etc/UTC") {
continue;
}
regions.entry(region).or_default().push(name);
}
for names in regions.values_mut() {
names.sort_unstable();
}
let etc = regions.remove_entry("Etc");
regions.into_iter().chain(etc).collect()
});
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
pub(crate) enum UserFormMode {
#[default]
New,
Edit,
/// Edición del perfil propio: sin roles ni casilla de administrador.
Profile,
}
#[derive(AutoDefault, Clone, Debug, Getters)]
@ -56,12 +30,17 @@ pub(crate) struct UserForm {
username: String,
email: String,
display_name: String,
/// Texto "Sobre mí"; sólo se edita en los modos `Edit` y `Profile`, no en el alta.
about: String,
language: String,
timezone: String,
/// Roles asignables (excluye "anonymous" y "authenticated"); sólo se renderiza en modo `New`.
theme: String,
/// Roles asignables (excluye "anonymous" y "authenticated"); si no hay ninguno, no se muestra.
roles: Vec<(i32, String, bool)>,
/// Si se ofrece la casilla "administrador"; sólo cuando quien da de alta ya es administrador.
allow_admin_field: bool,
/// En modo `Profile`, si el nombre de usuario es editable; si no, se muestra de sólo lectura.
allow_username_field: bool,
is_admin: bool,
}
@ -75,7 +54,10 @@ impl Component for UserForm {
let action = match self.mode() {
UserFormMode::New => util::join!(ADMIN_USERS_PATH, "/new"),
UserFormMode::Edit => user_path(self.user_id().copied().unwrap_or_default(), "edit"),
UserFormMode::Profile => PROFILE_EDIT_PATH.into(),
};
let username_readonly =
*self.mode() == UserFormMode::Profile && !*self.allow_username_field();
let action = self.waypoint().append_to(cx.route(action));
let mut form = Form::new()
@ -89,6 +71,7 @@ impl Component for UserForm {
.with_value(self.username())
.with_label(Lc::t("field-username-admin", &LOCALES_USER))
.with_required(true)
.with_readonly(username_readonly)
.with_maxlength(Some(64)),
)
.with_child(
@ -105,33 +88,54 @@ impl Component for UserForm {
.with_label(Lc::t("field-display-name", &LOCALES_USER)),
)
.with_child(
form::input::Field::text()
form::SelectLanguage::new()
.with_name("language")
.with_value(self.language())
.with_label(Lc::t("field-language", &LOCALES_USER)),
.with_label(Lc::t("field-language", &LOCALES_USER))
.with_selected(self.language()),
)
.with_child(timezone_field(self.timezone()));
.with_child(
form::SelectTimezone::new()
.with_name("timezone")
.with_label(Lc::t("field-timezone", &LOCALES_USER))
.with_selected(self.timezone()),
)
.with_child(
form::SelectTheme::new()
.with_name("theme")
.with_label(Lc::t("field-theme", &LOCALES_USER))
.with_selected(self.theme()),
);
if *self.mode() == UserFormMode::New {
form = form.with_child(PasswordConfirm::new());
if !self.roles().is_empty() {
form = form.with_child(roles_fieldset(self.roles()));
}
} else {
form = form.with_child(
form::Textarea::new()
.with_name("about")
.with_value(self.about())
.with_label(Lc::t("field-about", &LOCALES_USER))
.with_rows(Some(5))
.with_maxlength(Some(ABOUT_MAX_CHARS)),
);
}
if *self.allow_admin_field() {
form = form.with_child(
form::Checkbox::check()
.with_name("is_admin")
.with_label(Lc::t("field-is-admin", &LOCALES_USER))
.with_checked(*self.is_admin()),
);
}
if *self.mode() != UserFormMode::Profile && !self.roles().is_empty() {
form = form.with_child(roles_fieldset(self.roles()));
}
if *self.mode() == UserFormMode::New && *self.allow_admin_field() {
form = form.with_child(
form::Checkbox::check()
.with_name("is_admin")
.with_label(Lc::t("field-is-admin", &LOCALES_USER))
.with_checked(*self.is_admin()),
);
}
// En modo `Edit`, "Guardar" se renderiza fuera del formulario, junto al resto de acciones
// de la pantalla (ver `USER_ADMIN_FORM_ID`); en modo `New` no hay ninguna botonera con la
// que agruparlo, así que se queda aquí, dentro del propio `<form>`.
if *self.mode() == UserFormMode::New {
// de la pantalla (ver `USER_ADMIN_FORM_ID`); en los demás modos no hay ninguna botonera con
// la que agruparlo, así que se queda aquí, dentro del propio `<form>`.
if *self.mode() != UserFormMode::Edit {
form = form.with_child(
Button::submit(Lc::t("btn-save", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
@ -181,6 +185,11 @@ impl UserForm {
self
}
pub(crate) fn with_about(mut self, about: impl Into<String>) -> Self {
self.about = about.into();
self
}
pub(crate) fn with_language(mut self, language: impl Into<String>) -> Self {
self.language = language.into();
self
@ -191,6 +200,11 @@ impl UserForm {
self
}
pub(crate) fn with_theme(mut self, theme: impl Into<String>) -> Self {
self.theme = theme.into();
self
}
pub(crate) fn with_roles(mut self, roles: Vec<(i32, String, bool)>) -> Self {
self.roles = roles;
self
@ -201,34 +215,13 @@ impl UserForm {
self
}
pub(crate) fn with_allow_username_field(mut self, allow_username_field: bool) -> Self {
self.allow_username_field = allow_username_field;
self
}
pub(crate) fn with_is_admin(mut self, is_admin: bool) -> Self {
self.is_admin = is_admin;
self
}
}
// `<select>` de zona horaria: primero la opción de usar la predeterminada de la aplicación y luego
// un `<optgroup>` por región. La etiqueta de cada opción es el nombre IANA completo.
fn timezone_field(selected: &str) -> form::select::Field {
let mut field = form::select::Field::new()
.with_name("timezone")
.with_label(Lc::t("field-timezone", &LOCALES_USER))
.with_item(
form::select::Item::new(
"",
Lc::t("field-timezone-site-default", &LOCALES_USER)
.with_arg("tz", Timezone::default_tz().name()),
)
.with_selected(selected.is_empty()),
);
for (region, names) in TZ_BY_REGION.iter() {
let mut group = form::select::Group::new(Lc::n(*region));
for name in names {
group = group.with_item(
form::select::Item::new(*name, Lc::n(*name)).with_selected(*name == selected),
);
}
field = field.with_group(group);
}
field
}