//! Formulario de alta/edición de usuario, también usado para que cada usuario edite su perfil. use pagetop::prelude::*; use crate::LOCALES_USER; use crate::config::{SETTINGS, user_language_applies, user_timezone_applies}; use crate::user_path; use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH}; use crate::component::{PasswordConfirm, error_banner, form_actions, profile_form_actions}; use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars}; use crate::provider::{AccountPolicy, UserField}; use crate::service::user_admin::{ABOUT_MAX_CHARS, DISPLAY_NAME_MAX_CHARS}; use super::{USER_ADMIN_FORM_ID, roles_fieldset}; #[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)] pub(crate) struct UserForm { mode: UserFormMode, error: Option, user_id: Option, 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, 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, /// Política del proveedor que gestiona la cuenta, si lo hay: los datos que gestiona se muestran /// de sólo lectura (y quien recibe el formulario los ignora). policy: Option, /// En modo `New`, el proveedor con el que entrará la cuenta (`(id, nombre)`): sin contraseña. provider: Option<(String, String)>, } #[async_trait] impl Component for UserForm { fn new() -> Self { Self::default() } async fn prepare(&self, cx: &mut Context) -> Result { let action = match self.mode() { UserFormMode::New => util::join!(ADMIN_USERS_PATH.as_str(), "/new"), UserFormMode::Edit => user_path(self.user_id().copied().unwrap_or_default(), "edit"), UserFormMode::Profile => PROFILE_EDIT_PATH.into(), }; let policy = self.policy(); let managed = |field: UserField| policy.is_some_and(|p| p.manages(field)); let managed_help = match policy { Some(p) => Lc::t("help-managed-by", &LOCALES_USER).with_arg( "provider", p.provider_label().lookup(cx).unwrap_or_default(), ), None => Lc::none(), }; let help = |readonly: bool| { if readonly { managed_help.clone() } else { Lc::none() } }; let username_managed = policy.is_some_and(|p| !p.username().is_editable()); let username_readonly = username_managed || (*self.mode() == UserFormMode::Profile && !*self.allow_username_field()); // El propio usuario cambia su email en otra pantalla, que pide su contraseña y confirma la // nueva dirección antes de aplicarla. let email_managed = policy.is_some_and(|p| !p.email().is_editable()); let email_readonly = email_managed || *self.mode() == UserFormMode::Profile; let action = cx.route(action); let mut form = Form::new() .with_id(USER_ADMIN_FORM_ID) .with_action(action) .with_method(form::Method::Post) .with_child(error_banner(self.error().cloned())) .with_child( form::input::Field::text() .with_name("username") .with_value(self.username()) .with_label(Lc::t("field-username-admin", &LOCALES_USER)) .with_help_text(if username_managed { managed_help.clone() } else if username_readonly { Lc::none() } else { username_help(SETTINGS.identity_policy) }) .with_required(true) .with_readonly(username_readonly) .with_minlength(USERNAME_MIN_CHARS) .with_maxlength(username_max_chars(SETTINGS.identity_policy)), ) .with_child( form::input::Field::email() .with_name("email") .with_value(self.email()) .with_label(Lc::t("field-email", &LOCALES_USER)) .with_help_text(if email_managed { managed_help.clone() } else if email_readonly { Lc::t("help-email-readonly", &LOCALES_USER) } else { Lc::none() }) .with_required(true) .with_readonly(email_readonly) .with_maxlength(EMAIL_MAX_CHARS), ) .with_child( form::input::Field::text() .with_name("display_name") .with_value(self.display_name()) .with_label(Lc::t("field-display-name", &LOCALES_USER)) .with_help_text(help(managed(UserField::DisplayName))) .with_readonly(managed(UserField::DisplayName)) .with_maxlength(DISPLAY_NAME_MAX_CHARS), ); // Sólo se ofrecen si se aplican (ver `config::user_language_applies()` y // `config::user_timezone_applies()`). if user_language_applies() { form = form.with_child( form::SelectLanguage::new() .with_name("language") .with_label(Lc::t("field-language", &LOCALES_USER)) .with_disabled(managed(UserField::Language)) .with_selected(self.language()), ); } if user_timezone_applies() { form = form.with_child( form::SelectTimezone::new() .with_name("timezone") .with_label(Lc::t("field-timezone", &LOCALES_USER)) .with_utc_offset(true) .with_disabled(managed(UserField::Timezone)) .with_selected(self.timezone()), ); } form = form.with_child( form::SelectTheme::new() .with_name("theme") .with_label(Lc::t("field-theme", &LOCALES_USER)) .with_disabled(managed(UserField::Theme)) .with_selected(self.theme()), ); match (self.mode(), self.provider()) { // Una cuenta que entrará con un proveedor no tiene contraseña local. (UserFormMode::New, Some((id, name))) => { form = form .with_child(form::Hidden::field("provider", id.as_str())) .with_child(Html::with({ let note = Lc::t("help-external-user", &LOCALES_USER) .with_arg("provider", name.clone()); move |cx| html! { p { (note.using(cx)) } } })); } (UserFormMode::New, None) => { form = form.with_child(PasswordConfirm::new()); } _ => { form = form.with_child( form::Textarea::new() .with_name("about") .with_value(self.about()) .with_label(Lc::t("field-about", &LOCALES_USER)) .with_help_text(help(managed(UserField::About))) .with_readonly(managed(UserField::About)) .with_rows(Some(5)) .with_maxlength(Some(ABOUT_MAX_CHARS)), ); } } if *self.mode() != UserFormMode::Profile && !self.roles().is_empty() { let (managed_roles, provider) = match policy { Some(p) => ( p.managed_roles(), p.provider_label().lookup(cx).unwrap_or_default(), ), None => (&[][..], String::new()), }; form = form.with_child(roles_fieldset(self.roles(), managed_roles, &provider)); } 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" y "Cancelar" se renderizan fuera del formulario, junto al resto // de acciones de la pantalla (ver `USER_ADMIN_FORM_ID`). let save = Lc::t("btn-save", &LOCALES_USER); match self.mode() { UserFormMode::Edit => {} UserFormMode::Profile => { form = form.with_child(profile_form_actions(save, cx)); } UserFormMode::New => { let cancel = cx.route(ADMIN_USERS_PATH.as_str()); form = form.with_child(form_actions(save, cancel)); } } Ok(form.render(cx).await) } } #[builder_impl] impl UserForm { // **< UserForm BUILDER >*********************************************************************** pub(crate) fn with_mode(mut self, mode: UserFormMode) -> Self { self.mode = mode; self } pub(crate) fn with_error(mut self, error: impl Into>) -> Self { self.error = error.into(); self } pub(crate) fn with_user_id(mut self, user_id: impl Into>) -> Self { self.user_id = user_id.into(); self } pub(crate) fn with_username(mut self, username: impl Into) -> Self { self.username = username.into(); self } pub(crate) fn with_email(mut self, email: impl Into) -> Self { self.email = email.into(); self } pub(crate) fn with_display_name(mut self, display_name: impl Into) -> Self { self.display_name = display_name.into(); self } pub(crate) fn with_about(mut self, about: impl Into) -> Self { self.about = about.into(); self } pub(crate) fn with_language(mut self, language: impl Into) -> Self { self.language = language.into(); self } pub(crate) fn with_timezone(mut self, timezone: impl Into) -> Self { self.timezone = timezone.into(); self } pub(crate) fn with_theme(mut self, theme: impl Into) -> Self { self.theme = theme.into(); self } pub(crate) fn with_roles(mut self, roles: Vec<(i32, String, bool)>) -> Self { self.roles = roles; self } pub(crate) fn with_allow_admin_field(mut self, allow_admin_field: bool) -> Self { self.allow_admin_field = allow_admin_field; 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 } pub(crate) fn with_policy(mut self, policy: Option) -> Self { self.policy = policy; self } pub(crate) fn with_provider(mut self, provider: Option<(String, String)>) -> Self { self.provider = provider; self } }