UserModal function
void
UserModal(})
Implementation
void UserModal(context, {
required User user,
required Function callback,
required Map permissions,
required Map<String, List> userRoles,
required List userStates,
required Profile? currentProfile,
required String myRole,
}) {
final language = Language();
ColorScheme colorScheme = Theme.of(context).colorScheme;
bool itsMe = user.getUid() == currentProfile?.uid;
bool isOwner = user.isOwner();
bool retirePermissions = itsMe || isOwner;
List roles = isOwner ? ['owner'] : userRoles[myRole] ?? [];
bool permissionCreate = permissions['create'] == true;
bool permissionUpdate = permissions['update'] == true;
bool permissionDelete = permissions['delete'] == true;
bool isNew = user.isEmpty();
bool isDeleting = false;
bool isEnableForm = isNew;
final TextEditingController emailController = TextEditingController(text: user.getEmail());
String selectedRole = user.getRole();
String selectedState = user.getState();
String photoURL = user.getPhotoURL();
String stateCopy = '';
final _formKey = GlobalKey<FormState>(); // đŸ‘ˆ Clave para el formulario
User getCurrentUser(){
return User(
uid: user.getUid(),
role: selectedRole,
state: selectedState,
email: isNew ? emailController.text : user.getEmail()
);
}
void confirm(action) {
try {
User userToSave = getCurrentUser();
//if (!_formKey.currentState!.validate()) throw('Error al vĂ¡lidar formulario');
if(retirePermissions) throw('No tiene permisos para modificar el usuario');
if (action == 'create' || action == 'update') {
if(emailController.text == '') throw('Ingrese un email vĂ¡lido');
if(selectedRole == '') throw('Debe seleccionar un Rol para el usuario');
if(selectedState == '') throw('Debe definir un estado para el usuario');
}
if (selectedRole == 'owner') throw('No tiene persmisos para modificar este Rol');
if (action == 'create' && !permissionDelete) throw('No tiene persmisos para crear usuarios');
if (action == 'delete' && !permissionDelete) throw('No tiene persmisos para eliminar usuarios');
if (action == 'update' && !permissionUpdate) throw('No tiene persmisos para actualizar usuarios');
Navigator.of(context).pop();
callback(action, userToSave);
} catch(error) {
if(action == 'delete') Navigator.of(context).pop();
showSnackBar(context, SnackType.error, error.toString());
}
}
void restore(setStateModal) {
setStateModal(() {
isEnableForm = isNew;
selectedRole = user.getRole();
selectedState = user.getState();
});
}
void copyUid(setStateModal) {
setStateModal(()=>stateCopy = '- Copiado');
Future.delayed(const Duration(seconds: 3), () {
setStateModal(()=>stateCopy = '');
});
}
Widget child = StatefulBuilder(
builder: (BuildContext context, StateSetter setStateModal ) {
final appIcons = AppIcons();
String title = '';
Map options = {};
if (!isNew && !isEnableForm && !retirePermissions){
title = '';
if(permissionDelete) options['delete'] = ()=>setStateModal(()=>isDeleting=true);
if(permissionUpdate) options['update'] = ()=>setStateModal(()=>isEnableForm=true);
} else if (!isNew && isEnableForm) {
title = language.translateDual('update', 'user');
if(permissionUpdate) options['confirm'] = ()=>confirm('update');
if(permissionUpdate) options['cancel'] = ()=>restore(setStateModal);
} else if (isNew && isEnableForm) {
title = language.translateDual('create', 'user');
if(permissionCreate) options['confirm'] = ()=>confirm('create');
}
return isDeleting
? ContentConfirmDelete(
title: 'Eliminar ${user.getDisplayName()}',
message: 'Confirme que desea retirar los permisos de este usuario en su cuenta.',
onCancel: ()=>setStateModal(() { isDeleting = false; }),
onConfirm: ()=>confirm('delete'),
)
: Scaffold(
backgroundColor: colorScheme.surfaceVariant,
appBar: CustomAppBarModal(
buttonType: ButtonType.icon,
options: options,
iconSwipe: !isEnableForm,
title: language.translateUpperCase(title),
centerTitle: true,
backgroundColor: colorScheme.surfaceVariant,
),
body: Form(
key: _formKey,
child: Column(
children: [
/// ONLY SHOW USER //////////////////////
if(!isNew) ...[
CustomTileButton(
flex: 1,
//height: 48,
padding: photoURL.isNotEmpty ? const EdgeInsets.fromLTRB(24, 8, 16, 16) : const EdgeInsets.fromLTRB(24, 0, 16, 8),
backgroundColor: colorScheme.surfaceVariant,
overlayColor: colorScheme.background,
rightIcon: photoURL.isNotEmpty
? GET_IMAGE_NETWORK(photoURL, 44, 44, appIcons.photoProfileFilled, 8)
: SizedBox(
width: 50,
child: Icon(appIcons.photoProfileFilled, size: 56, color: colorScheme.onBackground.withOpacity(.6)),
),
//GET_IMAGE_NETWORK(photoURL, 44, 44, appIcons.photoProfileFilled, 8),
textTitle: CAPITALIZE_WORDS(user.getDisplayName()),
textSubtitle: 'UID: ${user.getUid()} $stateCopy',
onPressed: (){
Clipboard.setData(ClipboardData(text: user.getUid()));
copyUid(setStateModal);
}
),
if(!isEnableForm) ...[
OptionsPhone(user.getPhoneNumber(), margin: const EdgeInsets.fromLTRB(16, 0, 16, 8) ),
OptionsEmail(user.getEmail(), margin: const EdgeInsets.fromLTRB(16, 0, 16, 16) ),
]
],
/// ONLY CREATE USER
if(isNew)
CustomTextField(
labelText: 'Email',
controller: emailController,
textCapitalization: TextCapitalization.none,
keyboardType: TextInputType.emailAddress,
inputFormat: InputFormat.email,
margin: const EdgeInsets.all(16),
validator: (value)=> (value == null || value.isEmpty) ? 'Ingrese un correo vĂ¡lido' : null
),
Row(
children: [
CustomDropdownButton(
height: 48,
margin: const EdgeInsets.fromLTRB(16, 0, 8, 0),
disabled: !isEnableForm,
leftIcon: Icon(appIcons.userRole),
selectedKey: selectedRole,
hint: language.translate('role'),
items: roles.map((e) => {'key': e.toString(), 'value': language.translate(e)}).toList(),
onChanged: (selectedItem){
if(selectedItem['key'] != selectedRole) {
setStateModal(()=> selectedRole = selectedItem['key'] );
}
}
),
CustomDropdownButton(
height: 48,
margin: const EdgeInsets.fromLTRB(8, 0, 16, 0),
disabled: !isEnableForm,
leftIcon: Icon(appIcons.userState),
selectedKey: selectedState,
hint: language.translate('state'),
items: userStates.map((e) => {'key': e.toString(), 'value': language.translate(e)}).toList(),
onChanged: (selectedItem){
if(selectedItem['key'] != selectedState) {
setStateModal(()=> selectedState = selectedItem['key'] );
}
}
)
]
),
]
)
)
);
}
);
customAutoDialog(context, child);
}