save before flutter upgrade

This commit is contained in:
Abraham
2025-07-15 16:40:14 -07:00
commit 813c586a1c
197 changed files with 11144 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
export 'package:nethive_neo/providers/visual_state_provider.dart';
export 'package:nethive_neo/providers/users_provider.dart';
export 'package:nethive_neo/providers/user_provider.dart';

View File

@@ -0,0 +1,383 @@
import 'dart:developer';
import 'dart:typed_data';
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:image_picker/image_picker.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:uuid/uuid.dart';
import 'package:nethive_neo/helpers/globals.dart';
import 'package:nethive_neo/helpers/supabase/queries.dart';
import 'package:nethive_neo/router/router.dart';
class UserState extends ChangeNotifier {
//EMAIL
Future<void> setEmail() async {
await prefs.setString('email', emailController.text);
}
//Controlador para LoginScreen
TextEditingController emailController = TextEditingController();
//PASSWORD
Future<void> setPassword() async {
await prefs.setString('password', passwordController.text);
}
//Controlador para LoginScreen
TextEditingController passwordController = TextEditingController();
bool recuerdame = false;
//Variables para editar perfil
TextEditingController nombrePerfil = TextEditingController();
TextEditingController apellidosPerfil = TextEditingController();
TextEditingController telefonoPerfil = TextEditingController();
TextEditingController extensionPerfil = TextEditingController();
TextEditingController emailPerfil = TextEditingController();
TextEditingController contrasenaAnteriorPerfil = TextEditingController();
TextEditingController confirmarContrasenaPerfil = TextEditingController();
TextEditingController contrasenaPerfil = TextEditingController();
String? imageName;
Uint8List? webImage;
int loginAttempts = 0;
bool userChangedPasswordInLast90Days = true;
//Constructor de provider
UserState() {
recuerdame = prefs.getBool('recuerdame') ?? false;
if (recuerdame == true) {
emailController.text = prefs.getString('email') ?? '';
passwordController.text = prefs.getString('password') ?? '';
}
}
Future<bool> actualizarContrasena() async {
try {
final res = await supabase.rpc('change_user_password', params: {
'current_plain_password': contrasenaAnteriorPerfil.text,
'new_plain_password': contrasenaPerfil.text,
});
if (res == null) {
log('Error en actualizarContrasena()');
return false;
}
return true;
} catch (e) {
log('Error en actualizarContrasena() - $e');
return false;
}
}
// void initPerfilUsuario() {
// if (currentUser == null) return;
// nombrePerfil.text = currentUser!.nombre;
// // apellidosPerfil.text = currentUser!.apellidos;
// emailPerfil.text = currentUser!.email;
// webImage = null;
// contrasenaPerfil.clear();
// contrasenaAnteriorPerfil.clear();
// confirmarContrasenaPerfil.clear();
// }
Future<void> selectImage() async {
final ImagePicker picker = ImagePicker();
final XFile? pickedImage = await picker.pickImage(
source: ImageSource.gallery,
);
if (pickedImage == null) return;
final String fileExtension = p.extension(pickedImage.name);
const uuid = Uuid();
final String fileName = uuid.v1();
imageName = 'avatar-$fileName$fileExtension';
webImage = await pickedImage.readAsBytes();
notifyListeners();
}
void clearImage() {
webImage = null;
imageName = null;
notifyListeners();
}
Future<String?> uploadImage() async {
if (webImage != null && imageName != null) {
await supabase.storage.from('avatars').uploadBinary(
imageName!,
webImage!,
fileOptions: const FileOptions(
cacheControl: '3600',
upsert: false,
),
);
return imageName;
}
return null;
}
Future<bool> editarPerfilDeUsuario() async {
try {
await supabase.from('perfil_usuario').update(
{
'nombre': nombrePerfil.text,
'apellidos': apellidosPerfil.text,
'telefono': telefonoPerfil.text,
'imagen': imageName,
},
).eq('perfil_usuario_id', currentUser!.id);
return true;
} catch (e) {
log('Error en editarPerfilDeUsuario() - $e');
return false;
}
}
Future<void> updateRecuerdame() async {
recuerdame = !recuerdame;
await prefs.setBool('recuerdame', recuerdame);
notifyListeners();
}
String generateToken(String userId, String email) {
//Generar token
final jwt = JWT(
{
'user_id': userId,
'email': email,
'created': DateTime.now().toUtc().toIso8601String(),
},
issuer: 'https://github.com/jonasroussel/dart_jsonwebtoken',
);
// Sign it (default with HS256 algorithm)
return jwt.sign(SecretKey('secret'));
}
// Future<bool> sendEmailWithToken(String email, String password, String token, String type) async {
// //Mandar correo
// final response = await http.post(
// Uri.parse(bonitaConnectionUrl),
// body: json.encode(
// {
// "user": "Web",
// "action": "bonitaBpmCaseVariables",
// 'process': 'Alta_de_Usuario',
// 'data': {
// 'variables': [
// {
// 'name': 'correo',
// 'value': email,
// },
// {
// 'name': 'password',
// 'value': password,
// },
// {
// 'name': 'token',
// 'value': token,
// },
// {
// 'name': 'type',
// 'value': type,
// },
// ]
// },
// },
// ),
// );
// if (response.statusCode > 204) {
// return false;
// }
// return true;
// }
// Future<bool> sendEmailWithAccessCode(String email, String id) async {
// //Mandar correo
// final response = await http.post(
// Uri.parse(bonitaConnectionUrl),
// body: json.encode(
// {
// "user": "Web",
// "action": "bonitaBpmCaseVariables",
// 'process': 'DVLogin',
// 'data': {
// 'variables': [
// {
// 'name': 'correo',
// 'value': email,
// },
// {
// 'name': 'id',
// 'value': id,
// },
// ]
// },
// },
// ),
// );
// if (response.statusCode > 204) {
// return false;
// }
// return true;
// }
Future<Map<String, String>?> resetPassword(String email) async {
try {
final res = await supabase.from('users').select('id').eq('email', email);
if ((res as List).isEmpty) {
return {'Error': 'El correo no está registrado'};
}
final userId = res[0]['id'];
if (userId == null) return {'Error': 'El correo no está registrado'};
final token = generateToken(userId, email);
// Guardar token
await SupabaseQueries.saveToken(
userId,
'token_reset',
token,
);
// final res2 = await sendEmailWithToken(email, '', token, 'reset');
// if (!res2) return {'Error': 'Error al realizar petición'};
return null;
} catch (e) {
log('Error en resetPassword() - $e');
}
return {'Error': 'There was an error after sending request'};
}
Future<String?> getUserId(String email) async {
try {
final res = await supabase.from('users').select('id').eq('email', email);
if ((res as List).isNotEmpty) {
return res[0]['id'];
}
return null;
} catch (e) {
log('Error en getUserId - $e');
return null;
}
}
Future<bool> validateAccessCode(String userId, String accessCode) async {
try {
final res = await supabase.rpc('validate_access_code', params: {
'id': userId,
'access_code_attempt': accessCode,
});
return res;
} catch (e) {
log('Error en getAccessCode() - $e');
return false;
}
}
Future<bool> sendAccessCode(String userId) async {
try {
final codeSaved = await supabase.rpc(
'save_access_code',
params: {'id': userId},
);
if (!codeSaved) return false;
// final emailSent = await sendEmailWithAccessCode(
// emailController.text,
// userId,
// );
// if (!emailSent) return false;
return true;
} catch (e) {
log('Error en sendEmailWithAccessCode() -$e');
return false;
}
}
Future<void> incrementLoginAttempts(String email) async {
loginAttempts += 1;
if (loginAttempts >= 3) {
try {
await supabase.rpc('block_user', params: {'email': email});
} catch (e) {
log('Error en incrementLoginAttempts() - $e');
} finally {
loginAttempts = 0;
}
}
notifyListeners();
}
Future<void> registerLogin(String userId) async {
try {
await supabase.from('login_historico').insert({'usuario_fk': userId});
} catch (e) {
log('registerLogin() - $e');
}
}
Future<bool> checkIfUserBlocked(String email) async {
try {
final res = await supabase.rpc('check_if_user_blocked', params: {
'email': email,
});
return res;
} catch (e) {
log('Error en checkIfUserIsBlocked() - $e');
return true;
}
}
Future<void> checkIfUserChangedPasswordInLast90Days(String userId) async {
try {
final res = await supabase.rpc('usuario_cambio_contrasena', params: {
'user_id': userId,
});
userChangedPasswordInLast90Days = res;
} catch (e) {
log('Error en checkIfUserChangedPasswordInLast90Days() - $e');
}
}
Future<void> logout() async {
await supabase.auth.signOut();
currentUser = null;
await prefs.remove('currentRol');
/* Configuration? conf = await SupabaseQueries.getDefaultTheme();
AppTheme.initConfiguration(conf); */
router.pushReplacement('/');
}
@override
void dispose() {
emailController.dispose();
passwordController.dispose();
nombrePerfil.dispose();
emailPerfil.dispose();
contrasenaPerfil.dispose();
super.dispose();
}
}

View File

@@ -0,0 +1,370 @@
import 'dart:convert';
import 'dart:developer';
import 'dart:typed_data';
import 'package:path/path.dart' as p;
import 'package:random_password_generator/random_password_generator.dart';
import 'package:uuid/uuid.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pluto_grid/pluto_grid.dart';
import 'package:supabase_flutter/supabase_flutter.dart' hide User;
import 'package:http/http.dart' as http;
import 'package:nethive_neo/helpers/constants.dart';
import 'package:nethive_neo/helpers/globals.dart';
import 'package:nethive_neo/models/models.dart';
import 'package:nethive_neo/services/api_error_handler.dart';
class UsersProvider extends ChangeNotifier {
PlutoGridStateManager? stateManager;
List<PlutoRow> rows = [];
//CREATE USUARIO
TextEditingController nameController = TextEditingController();
TextEditingController lastNameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController phoneController = TextEditingController();
Role? selectedRole;
List<Role> roles = [];
List<User> users = [];
String? imageName;
Uint8List? webImage;
//PANTALLA USUARIOS
final busquedaController = TextEditingController();
String orden = "sequential_id";
Future<void> updateState() async {
busquedaController.clear();
await getRoles(notify: false);
await getUsers();
}
void clearControllers({bool clearEmail = true, bool notify = true}) {
nameController.clear();
if (clearEmail) emailController.clear();
lastNameController.clear();
phoneController.clear();
selectedRole = null;
imageName = null;
webImage = null;
if (notify) notifyListeners();
}
void setSelectedRole(String role) async {
selectedRole = roles.firstWhere((e) => e.name == role);
notifyListeners();
}
Future<void> getRoles({bool notify = true}) async {
if (roles.isNotEmpty) return;
final res = await supabase
.from('role')
.select()
.eq('organization_fk', organizationId)
.order('name', ascending: true);
roles = (res as List<dynamic>).map((role) => Role.fromMap(role)).toList();
if (notify) notifyListeners();
}
Future<void> getUsers() async {
try {
final query =
supabase.from('users').select().eq('organization_id', organizationId);
final res = await query
.like('first_name', '%${busquedaController.text}%')
.order(orden, ascending: true);
if (res == null) {
log('Error in getUsers()');
return;
}
users = (res as List<dynamic>).map((user) => User.fromMap(user)).toList();
fillPlutoGrid(users);
} catch (e) {
log('Error in getUsers() - $e');
}
}
void fillPlutoGrid(List<User> users) {
rows.clear();
for (User user in users) {
rows.add(
PlutoRow(
cells: {
'sequential_id': PlutoCell(value: user.sequentialId),
'full_name': PlutoCell(value: user.fullName),
'role': PlutoCell(value: user.role.name),
'email': PlutoCell(value: user.email),
'mobile_phone': PlutoCell(value: user.mobilePhone ?? '-'),
'status': PlutoCell(value: user),
'actions': PlutoCell(value: user),
},
),
);
}
if (stateManager != null) stateManager!.notifyListeners();
notifyListeners();
}
Future<void> selectImage() async {
final ImagePicker picker = ImagePicker();
final XFile? pickedImage = await picker.pickImage(
source: ImageSource.gallery,
);
if (pickedImage == null) return;
final String fileExtension = p.extension(pickedImage.name);
const uuid = Uuid();
final String fileName = uuid.v1();
imageName = 'avatar-$fileName$fileExtension';
webImage = await pickedImage.readAsBytes();
notifyListeners();
}
void clearImage() {
webImage = null;
imageName = null;
notifyListeners();
}
Future<String?> uploadImage() async {
if (webImage != null && imageName != null) {
await supabase.storage.from('avatars').uploadBinary(
imageName!,
webImage!,
fileOptions: const FileOptions(
cacheControl: '3600',
upsert: false,
),
);
return imageName;
}
return null;
}
Future<void> validateImage(String? imagen) async {
if (imagen == null) {
if (webImage != null) {
//usuario no tiene imagen y se agrego => se sube imagen
final res = await uploadImage();
if (res == null) {
ApiErrorHandler.callToast('Error uploading image');
}
}
//usuario no tiene imagen y no se agrego => no hace nada
} else {
//usuario tiene imagen y se borro => se borra en bd
if (webImage == null && imageName == null) {
await supabase.storage.from('avatars').remove([imagen]);
}
//usuario tiene imagen y no se modifico => no se hace nada
//usuario tiene imagen y se cambio => se borra en bd y se sube la nueva
if (webImage != null && imageName != imagen) {
await supabase.storage.from('avatars').remove([imagen]);
final res2 = await uploadImage();
if (res2 == null) {
ApiErrorHandler.callToast('Error uploading image');
}
}
}
}
Future<Map<String, String>?> registerUser() async {
try {
//Generar contrasena aleatoria
// final password = generatePassword();
//Registrar al usuario con una contraseña temporal
var response = await http.post(
Uri.parse('$supabaseUrl/auth/v1/signup'),
headers: {'Content-Type': 'application/json', 'apiKey': anonKey},
body: json.encode(
{
"email": emailController.text,
"password": 'default',
},
),
);
if (response.statusCode > 204)
return {'Error': 'The user already exists'};
final String? userId = jsonDecode(response.body)['user']['id'];
if (userId == null) return {'Error': 'Could not register user'};
// final token = generateToken(userId, correoController.text);
// final bool tokenSaved = await SupabaseQueries.saveToken(userId, 'token_ingreso', token);
// if (!tokenSaved) return {'Error': 'Error al guardar token'};
// final bool emailSent = await sendEmail(correoController.text, password, token, 'alta');
// if (!emailSent) return {'Error': 'Error al mandar email'};
//retornar el id del usuario
return {'userId': userId};
} catch (e) {
log('Error en registerUser() - $e');
return {'Error': 'Could not register user'};
}
}
Future<bool> createUserProfile(String userId) async {
if (selectedRole == null) {
return false;
}
try {
await supabase.from('user_profile').insert(
{
'user_profile_id': userId,
'first_name': nameController.text,
'last_name': lastNameController.text,
'mobile_phone': phoneController.text,
'role_fk': selectedRole!.roleId,
'image': imageName,
'organization_fk': organizationId,
},
);
return true;
} catch (e) {
log('Error in createUserProfile() - $e');
return false;
}
}
Future<bool> editUserProfile(String userId) async {
try {
await supabase.from('user_profile').update(
{
'first_name': nameController.text,
'last_name': lastNameController.text,
'mobile_phone': phoneController.text,
'role_fk': selectedRole!.roleId,
'image': imageName,
},
).eq('user_profile_id', userId);
return true;
} catch (e) {
log('Error in editUserProfile() - $e');
return false;
}
}
Future<void> initEditUser(User user) async {
nameController.text = user.firstName;
lastNameController.text = user.lastName;
emailController.text = user.email;
phoneController.text = user.mobilePhone ?? '';
selectedRole = user.role;
imageName = user.image;
webImage = null;
}
// Future<bool> updateActivado(User usuario, bool value, int rowIndex) async {
// try {
// //actualizar usuario
// await supabase.from('perfil_usuario').update({'activo': value}).eq('perfil_usuario_id', usuario.id);
// rows[rowIndex].cells['activo']?.value = usuario.estatus;
// if (stateManager != null) stateManager!.notifyListeners();
// return true;
// } catch (e) {
// log('Error en updateActivado() - $e');
// return false;
// }
// }
String generatePassword() {
//Generar contrasena aleatoria
final passwordGenerator = RandomPasswordGenerator();
return passwordGenerator.randomPassword(
letters: true,
uppercase: true,
numbers: true,
specialChar: true,
passwordLength: 8,
);
}
Future<bool> sendEmail(
String email, String? password, String token, String type) async {
//Mandar correo
// final response = await http.post(
// Uri.parse(bonitaConnectionUrl),
// body: json.encode(
// {
// "user": "Web",
// "action": "bonitaBpmCaseVariables",
// 'process': 'Alta_de_Usuario',
// 'data': {
// 'variables': [
// {
// 'name': 'correo',
// 'value': email,
// },
// {
// 'name': 'password',
// 'value': password,
// },
// {
// 'name': 'token',
// 'value': token,
// },
// {
// 'name': 'type',
// 'value': type,
// },
// ]
// },
// },
// ),
// );
// if (response.statusCode > 204) {
// return false;
// }
return true;
}
Future<bool> borrarUsuario(String userId) async {
try {
final res = await supabase.rpc('borrar_usuario_id', params: {
'user_id': userId,
});
users.removeWhere((user) => user.id == userId);
fillPlutoGrid(users);
return res;
} catch (e) {
log('Error en borrarUsuario() - $e');
return false;
}
}
@override
void dispose() {
busquedaController.dispose();
nameController.dispose();
emailController.dispose();
lastNameController.dispose();
phoneController.dispose();
super.dispose();
}
}

View File

@@ -0,0 +1,184 @@
import 'package:flutter/material.dart';
import 'package:flutter_side_menu/flutter_side_menu.dart';
import 'package:nethive_neo/theme/theme.dart';
class VisualStateProvider extends ChangeNotifier {
List<bool> isTaped = [
true, //Administrador contenido lu 0
false, //CRM 1
false, //Customers 2
false, //QR 3
false, //Usuarios 4
false, //Administrador contenido videos 5
false, //Administrador cupones 6
false //Inventario 7
];
//THEME
late Color primaryColorLight;
late Color secondaryColorLight;
late Color tertiaryColorLight;
late Color primaryTextColorLight;
late Color primaryBackgroundColorLight;
late Color primaryColorDark;
late Color secondaryColorDark;
late Color tertiaryColorDark;
late Color primaryTextColorDark;
late Color primaryBackgroundColorDark;
late TextEditingController primaryColorLightController;
late TextEditingController secondaryColorLightController;
late TextEditingController tertiaryColorLightController;
late TextEditingController primaryTextLightController;
late TextEditingController primaryBackgroundLightController;
late TextEditingController primaryColorDarkController;
late TextEditingController secondaryColorDarkController;
late TextEditingController tertiaryColorDarkController;
late TextEditingController primaryTextDarkController;
late TextEditingController primaryBackgroundDarkController;
//nombreTema
TextEditingController nombreTema = TextEditingController();
//SideMenu
SideMenuController sideMenuController = SideMenuController();
VisualStateProvider(BuildContext context) {
final lightTheme = AppTheme.lightTheme;
final darkTheme = AppTheme.darkTheme;
primaryColorLight = lightTheme.primaryColor;
secondaryColorLight = lightTheme.secondaryColor;
tertiaryColorLight = lightTheme.tertiaryColor;
primaryTextColorLight = lightTheme.primaryText;
primaryBackgroundColorLight = lightTheme.primaryBackground;
primaryColorDark = darkTheme.primaryColor;
secondaryColorDark = darkTheme.secondaryColor;
tertiaryColorDark = darkTheme.tertiaryColor;
primaryTextColorDark = darkTheme.primaryText;
primaryBackgroundColorDark = darkTheme.primaryBackground;
primaryColorLightController = TextEditingController(
text: primaryColorLight.value.toRadixString(16).toUpperCase());
secondaryColorLightController = TextEditingController(
text: secondaryColorLight.value.toRadixString(16).toUpperCase());
tertiaryColorLightController = TextEditingController(
text: tertiaryColorLight.value.toRadixString(16).toUpperCase());
primaryTextLightController = TextEditingController(
text: primaryTextColorLight.value.toRadixString(16).toUpperCase());
primaryBackgroundLightController = TextEditingController(
text:
primaryBackgroundColorLight.value.toRadixString(16).toUpperCase());
primaryColorDarkController = TextEditingController(
text: primaryColorDark.value.toRadixString(16).toUpperCase());
secondaryColorDarkController = TextEditingController(
text: secondaryColorDark.value.toRadixString(16).toUpperCase());
tertiaryColorDarkController = TextEditingController(
text: tertiaryColorDark.value.toRadixString(16).toUpperCase());
primaryTextDarkController = TextEditingController(
text: primaryTextColorDark.value.toRadixString(16).toUpperCase());
primaryBackgroundDarkController = TextEditingController(
text: primaryBackgroundColorDark.value.toRadixString(16).toUpperCase());
}
void setPrimaryColorLight(Color color) {
primaryColorLight = color;
primaryColorLightController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void setSecondaryColorLight(Color color) {
secondaryColorLight = color;
secondaryColorLightController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void setTerciaryColorLight(Color color) {
tertiaryColorLight = color;
tertiaryColorLightController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void setPrimaryTextColorLight(Color color) {
primaryTextColorLight = color;
primaryTextLightController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void setPrimaryBackgroundColorLight(Color color) {
primaryBackgroundColorLight = color;
primaryBackgroundLightController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void setPrimaryColorDark(Color color) {
primaryColorDark = color;
primaryColorDarkController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void setSecondaryColorDark(Color color) {
secondaryColorDark = color;
secondaryColorDarkController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void setTerciaryColorDark(Color color) {
tertiaryColorDark = color;
tertiaryColorDarkController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void setPrimaryTextColorDark(Color color) {
primaryTextColorDark = color;
primaryTextDarkController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void setPrimaryBackgroundColorDark(Color color) {
primaryBackgroundColorDark = color;
primaryBackgroundDarkController.text =
color.value.toRadixString(16).toUpperCase();
notifyListeners();
}
void toggleSideMenu() {
sideMenuController.toggle();
}
void setTapedOption(int index) {
for (var i = 0; i < isTaped.length; i++) {
isTaped[i] = false;
}
isTaped[index] = true;
}
@override
void dispose() {
primaryColorLightController.dispose();
secondaryColorLightController.dispose();
tertiaryColorLightController.dispose();
primaryTextLightController.dispose();
primaryBackgroundLightController.dispose();
primaryColorDarkController.dispose();
secondaryColorDarkController.dispose();
tertiaryColorDarkController.dispose();
primaryTextDarkController.dispose();
primaryBackgroundDarkController.dispose();
super.dispose();
}
}