replace: swap prosappweb content for prosapp_web_app (more complete version)

prosapp_web_app has chat, dashboard, calendar, support, 13 providers and
Fluro URL routing. Keep Dockerfile + nginx.conf from previous prosappweb.
Upgrade google_fonts 6.2.1 → 8.1.0 (Dart 3.12 compat fix).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-06-18 15:26:32 -05:00
co-authored by Claude Sonnet 4.6
parent 74a4f41902
commit 15175c1b91
334 changed files with 12914 additions and 25727 deletions
+334
View File
@@ -0,0 +1,334 @@
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:prosapp_web_app/models/comment_entity.dart';
import 'package:prosapp_web_app/models/profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart';
import 'package:prosapp_web_app/providers/professional_provider.dart';
import 'package:prosapp_web_app/providers/services_provider.dart';
import 'package:prosapp_web_app/router/router.dart';
import 'package:prosapp_web_app/services/navigation_service.dart';
import 'package:prosapp_web_app/services/notifications_service.dart';
import 'package:provider/provider.dart';
enum AuthStatus { checking, authenticated, notAuthenticated }
class AuthProvider extends ChangeNotifier {
Usuario? user;
Profesional? professional;
double userAverageScore = 0.0;
AuthStatus authStatus = AuthStatus.checking;
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
String? _verificationId;
AuthProvider() {
isAuthenticated();
}
Future<void> login(String email, String password) async {
try {
await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
final userData = await _firestore
.collection('users')
.doc(_firebaseAuth.currentUser!.uid)
.get();
user = Usuario.fromDocument(userData.data()!);
authStatus = AuthStatus.authenticated;
notifyListeners();
NavigationService.replaceTo(Flurorouter.dashboardRoute);
} catch (e) {
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
NotificationsService.showSnackBarError(
'Usuario o contraseña incorrectos');
}
}
Future<void> verifyPhoneNumberForLink(String phoneNumber) async {
try {
await _firebaseAuth.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: const Duration(seconds: 60),
verificationCompleted: (PhoneAuthCredential credential) async {
if (_firebaseAuth.currentUser != null) {
// Vincula el número de teléfono a la cuenta actual
await _firebaseAuth.currentUser!.linkWithCredential(credential);
NotificationsService.showSnackbar('Número vinculado exitosamente');
authStatus = AuthStatus.authenticated;
notifyListeners();
}
},
verificationFailed: (FirebaseAuthException e) {
NotificationsService.showSnackBarError(
'Error en la verificación del teléfono: ${e.message}');
},
codeSent: (String verificationId, int? resendToken) {
_verificationId = verificationId;
notifyListeners();
},
codeAutoRetrievalTimeout: (String verificationId) {
_verificationId = verificationId;
},
);
} catch (e) {
NotificationsService.showSnackBarError('Error al enviar OTP');
}
}
Future<void> linkPhoneWithOTP(String smsCode) async {
try {
final credential = PhoneAuthProvider.credential(
verificationId: _verificationId!,
smsCode: smsCode,
);
if (_firebaseAuth.currentUser != null) {
await _firebaseAuth.currentUser!.linkWithCredential(credential);
await FirebaseFirestore.instance
.collection('users')
.doc(_firebaseAuth.currentUser!.uid)
.update({'phone': _firebaseAuth.currentUser!.phoneNumber});
NotificationsService.showSnackbar('Número vinculado exitosamente');
authStatus = AuthStatus.authenticated;
notifyListeners();
NavigationService.replaceTo(Flurorouter.profileRoute);
}
} catch (e) {
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
NotificationsService.showSnackBarError('Error en la verificación OTP');
}
}
Future<void> register(String email, String password, String name) async {
try {
UserCredential userCredential =
await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password,
);
User? user = userCredential.user;
if (user != null) {
await _firestore.collection('users').doc(user.uid).set({
'birthday': "",
'city': "",
'email': user.email,
'gender': "",
'id': user.uid,
'name': name.trim(),
'nickname': name.trim().toLowerCase(),
'phone': "",
'picture': "",
'professional_state': 0,
'token': "",
});
authStatus = AuthStatus.authenticated;
notifyListeners();
NavigationService.replaceTo(Flurorouter.dashboardRoute);
}
} catch (e) {
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
NotificationsService.showSnackBarError('Email ya registrado');
}
}
Future<bool> isAuthenticated() async {
final User? firebaseUser = _firebaseAuth.currentUser;
if (firebaseUser == null) {
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
return false;
}
final userData =
await _firestore.collection('users').doc(firebaseUser.uid).get();
if (userData.exists) {
user = Usuario.fromDocument(userData.data()!);
userAverageScore = await _getUserAverageScore(user!.id);
authStatus = AuthStatus.authenticated;
notifyListeners();
return true;
} else {
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
return false;
}
}
Future<void> logout() async {
await _firebaseAuth.signOut();
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
Provider.of<ServicesProvider>(
NavigationService.navigatorKey.currentContext!,
listen: false)
.logout();
Provider.of<ProfessionalProvider>(
NavigationService.navigatorKey.currentContext!,
listen: false)
.logout();
NavigationService.replaceTo(Flurorouter.phoneLoginRoute);
}
void refreshUser() {
isAuthenticated();
}
Future<void> verifyPhoneNumber(String phoneNumber) async {
try {
await _firebaseAuth.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: const Duration(seconds: 60),
verificationCompleted: (PhoneAuthCredential credential) async {
await _firebaseAuth.signInWithCredential(credential);
authStatus = AuthStatus.authenticated;
notifyListeners();
NavigationService.replaceTo(Flurorouter.dashboardRoute);
},
verificationFailed: (FirebaseAuthException e) {
NotificationsService.showSnackBarError(
'La verificación del teléfono falló: ${e.message}');
},
codeSent: (String verificationId, int? resendToken) {
_verificationId = verificationId;
notifyListeners();
},
codeAutoRetrievalTimeout: (String verificationId) {
_verificationId = verificationId;
},
);
} catch (e) {
NotificationsService.showSnackBarError('Error al enviar OTP');
}
}
Future<void> signInWithOTP(String smsCode) async {
try {
final credential = PhoneAuthProvider.credential(
verificationId: _verificationId!,
smsCode: smsCode,
);
await _firebaseAuth.signInWithCredential(credential);
User? currentUser = _firebaseAuth.currentUser;
if (currentUser != null) {
final userData =
await _firestore.collection('users').doc(currentUser.uid).get();
if (userData.exists) {
user = Usuario.fromDocument(userData.data()!);
} else {
await _firestore.collection('users').doc(currentUser.uid).set({
'birthday': "",
'city': "",
'email': "",
'gender': "",
'id': currentUser.uid,
'name': "",
'nickname': "",
'phone': currentUser.phoneNumber,
'picture': "",
'professional_state': 0,
'token': "",
});
final newUserData =
await _firestore.collection('users').doc(currentUser.uid).get();
user = Usuario.fromDocument(newUserData.data()!);
}
authStatus = AuthStatus.authenticated;
notifyListeners();
NavigationService.replaceTo(Flurorouter.dashboardRoute);
}
} catch (e) {
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
NotificationsService.showSnackBarError('Error en la verificación OTP');
}
}
Future<void> addEmailAndPassword(String email, String password) async {
try {
final User? currentUser = _firebaseAuth.currentUser;
if (currentUser != null) {
await currentUser.updateEmail(email);
await currentUser.updatePassword(password);
await _firestore.collection('users').doc(currentUser.uid).update({
'email': email,
});
notifyListeners();
NotificationsService.showSnackbar(
'Email y contraseña añadidos exitosamente');
NavigationService.replaceTo(Flurorouter.profileRoute);
}
} catch (e) {
if (e is FirebaseAuthException && e.code == 'email-already-in-use') {
NotificationsService.showSnackBarError('El correo ya existe');
}
if (e is FirebaseAuthException && e.code == 'invalid-email') {
NotificationsService.showSnackBarError('El correo no es vßlido');
}
if (e is FirebaseAuthException && e.code == 'weak-password') {
NotificationsService.showSnackBarError(
'La contraseña debe tener al menos 6 caracteres');
}
if (e is FirebaseAuthException && e.code == 'requires-recent-login') {
NotificationsService.showSnackBarError(
'Debes iniciar sesión recientemente antes de agregar email y contraseña');
}
}
}
Future<double> _getUserAverageScore(String userId) async {
final querySnapshot = await FirebaseFirestore.instance
.collection('comments')
.where('destination_id', isEqualTo: userId)
.where('is_from_user', isEqualTo: false)
.get();
if (querySnapshot.docs.isEmpty) {
return 0.0;
}
final scores = querySnapshot.docs
.map((e) => CommentEntity.fromDocument(e.data()).score)
.toList();
final averageScore = scores.reduce((a, b) => a + b) / scores.length;
return averageScore;
}
}
@@ -0,0 +1,74 @@
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:prosapp_web_app/models/service.dart';
import 'package:prosapp_web_app/models/servicio_profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart';
class CalendarServicesProvider extends ChangeNotifier {
List<ServicioProfesional> services = [];
ServicioProfesional? service;
bool isLoading = true;
final _servicesCollection = FirebaseFirestore.instance.collection('services');
final _usersCollection = FirebaseFirestore.instance.collection('users');
void logout() {
services = [];
service = null;
isLoading = false;
notifyListeners();
}
getServicesForProfessional(String userId) async {
try {
isLoading = true;
final queryServices = await _servicesCollection
.where('professional_id', isEqualTo: userId)
.where('status', whereIn: [1, 3]).get();
final servicios = queryServices.docs.map(Service.fromDocument).toList();
final userIds = servicios.map((service) => service.userId).toList();
final queryUsers = await _usersCollection
.where(FieldPath.documentId, whereIn: userIds)
.get();
final users =
queryUsers.docs.map((e) => Usuario.fromDocument(e.data())).toList();
final usersMap = {for (var doc in users) doc.id: doc};
final servicesMap = (servicios.map((service) {
final user = usersMap[service.userId];
return ServicioProfesional(
user: user!,
service: service,
);
}).toList());
services = servicesMap
..sort((a, b) {
final dateA = DateTime.parse(a.service.day);
final dateB = DateTime.parse(b.service.day);
final range1A =
a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
final range1B =
b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
if (dateA.compareTo(dateB) != 0) {
return dateA.compareTo(dateB);
} else {
return range1A.compareTo(range1B);
}
});
} catch (e) {
print('Error obteniendo servicios: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
}
+34
View File
@@ -0,0 +1,34 @@
import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/chat_entity.dart';
import 'package:prosapp_web_app/models/message_entity.dart';
import 'package:prosapp_web_app/repositories/firebase_chat_repository.dart';
class ChatProvider with ChangeNotifier {
final FirebaseChatRepository _firebaseChatRepository =
FirebaseChatRepository();
ChatEntity? _currentChat;
ChatEntity? get currentChat => _currentChat;
Stream<ChatEntity?> getChat(String chatId) {
return _firebaseChatRepository.getChatById(chatId).map((chat) {
_currentChat = chat;
notifyListeners();
return chat;
});
}
Future<ChatEntity> createChat(
String chatId, String userId, String professionalId) async {
final chat = await _firebaseChatRepository.createNewChat(
chatId, userId, professionalId);
_currentChat = chat;
notifyListeners();
return chat;
}
Future<void> sendMessage(String chatId, MessageEntity message) async {
await _firebaseChatRepository.sendMessage(chatId, message);
notifyListeners();
}
}
+55
View File
@@ -0,0 +1,55 @@
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:prosapp_web_app/models/city.dart';
import 'package:prosapp_web_app/models/country_entity.dart';
class CitiesProvider extends ChangeNotifier {
List<City> cities = [];
bool isLoading = true;
final _citiesCollection =
FirebaseFirestore.instance.collection('countries v2');
CitiesProvider() {
getCities();
}
getCoordsOfCity(String cityName) {
if (cities.isEmpty) return null;
for (var city in cities) {
if (city.cityName == cityName) {
return city.coordsOfCity;
}
}
return null;
}
getCities() async {
try {
final querySnapshot = await _citiesCollection.doc('Colombia').get();
final data = querySnapshot.data();
final country = CountryEntity.fromDocument(data as Map<String, dynamic>);
for (var region in country.regions) {
for (var city in region.cities) {
cities.add(City(
cityName: city.name,
coordsOfCity: city.coords,
stateOfCity: region.name,
countryOfCity: country.name,
));
}
}
cities.sort((a, b) => a.cityName.compareTo(b.cityName));
} catch (e) {
print('Error obteniendo ciudades: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
}
+18
View File
@@ -0,0 +1,18 @@
import 'package:flutter/material.dart';
class EmailFormProvider extends ChangeNotifier {
GlobalKey<FormState> formKey = GlobalKey<FormState>();
String email = '';
String password = '';
bool validateForm() {
if (formKey.currentState!.validate()) {
return true;
} else {
print('Formulario no válido');
return false;
}
}
}
+20
View File
@@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
class LoginFormProvider extends ChangeNotifier {
GlobalKey<FormState> formKey = GlobalKey<FormState>();
String email = "";
String password = "";
bool validateForm() {
if (formKey.currentState!.validate()) {
// print('Formulario válido');
// print('Email: $email, password: $password');
return true;
} else {
print('Formulario no válido');
return false;
}
}
}
+18
View File
@@ -0,0 +1,18 @@
import 'package:flutter/material.dart';
class PhoneFormProvider extends ChangeNotifier {
GlobalKey<FormState> formKey = GlobalKey<FormState>();
String phone = "";
String code = "";
bool validateForm() {
if (formKey.currentState!.validate()) {
return true;
} else {
print('Formulario no válido');
return false;
}
}
}
@@ -0,0 +1,72 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/comment_entity.dart';
import 'package:prosapp_web_app/models/profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart';
import 'package:prosapp_web_app/models/usuario_profesional.dart';
class ProfessionalDetailProvider extends ChangeNotifier {
UsuarioProfesional? professional;
bool isLoading = true;
Future<void> getProfessionalById(String uid) async {
try {
isLoading = true;
notifyListeners();
final userDoc =
await FirebaseFirestore.instance.collection('users').doc(uid).get();
if (!userDoc.exists) {
print('Profesional no encontrado.');
return;
}
final user = Usuario.fromDocument(userDoc.data()!);
final professionalDoc = await FirebaseFirestore.instance
.collection('professional_info')
.doc(uid)
.get();
if (!professionalDoc.exists) {
print('Información profesional no encontrada.');
return;
}
final professionalInfo =
Profesional.fromDocument(professionalDoc.data()!);
final averageScore = await _getAverageScore(uid);
professional = UsuarioProfesional(
user: user,
professionalInfo: professionalInfo,
averageScore: averageScore,
);
} catch (e) {
print('Error obteniendo profesional: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
Future<double> _getAverageScore(String userId) async {
final querySnapshot = await FirebaseFirestore.instance
.collection('comments')
.where('destination_id', isEqualTo: userId)
.where('is_from_user', isEqualTo: true)
.get();
if (querySnapshot.docs.isEmpty) {
return 0.0;
}
final scores = querySnapshot.docs
.map((e) => CommentEntity.fromDocument(e.data()).score)
.toList();
final averageScore = scores.reduce((a, b) => a + b) / scores.length;
return averageScore;
}
}
@@ -0,0 +1,200 @@
import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/location_preferences.dart';
import 'package:prosapp_web_app/models/payment_method_entity.dart';
import 'package:prosapp_web_app/models/profesional.dart';
import 'package:prosapp_web_app/models/schedules.dart';
import 'package:prosapp_web_app/services/notifications_service.dart';
class ProfessionalFormProvider with ChangeNotifier {
Profesional? profesional;
GlobalKey<FormState> formKey = GlobalKey<FormState>();
GlobalKey<FormState> profileFormKey = GlobalKey<FormState>();
copyProfesionalWith({
String? id,
String? identification,
String? address,
String? aditionalAddress,
String? profession,
bool ratePreferences = false,
String? rate,
LocationPreferences? locationPreferences,
String? bannerPicture,
String? identificationPicture,
String? certificatePicture,
double? latitude,
double? longitude,
List<String>? specializations,
List<String>? specializationsPictures,
Schedules? schedules,
PaymentMethodEntity? paymentMethods,
}) {
profesional = Profesional(
id: id ?? profesional!.id,
identification: identification ?? profesional!.identification,
address: address ?? profesional!.address,
aditionalAddress: aditionalAddress ?? profesional!.aditionalAddress,
profession: profession ?? profesional!.profession,
ratePreferences: ratePreferences,
rate: rate ?? profesional!.rate,
locationPreferences:
locationPreferences ?? profesional!.locationPreferences,
bannerPicture: bannerPicture ?? profesional!.bannerPicture,
identificationPicture:
identificationPicture ?? profesional!.identificationPicture,
certificatePicture: certificatePicture ?? profesional!.certificatePicture,
latitude: latitude ?? profesional!.latitude,
longitude: longitude ?? profesional!.longitude,
specializations: specializations ?? profesional!.specializations,
specializationsPictures:
specializationsPictures ?? profesional!.specializationsPictures,
schedules: schedules ?? profesional!.schedules,
paymentMethods: paymentMethods ?? profesional!.paymentMethods,
);
notifyListeners();
}
bool _validForm() {
return formKey.currentState!.validate();
}
bool _validProfileForm() {
return profileFormKey.currentState!.validate();
}
setProfesional(Profesional profesional) {
this.profesional = profesional;
notifyListeners();
}
Future<bool> updateProfesionalInfo(String userId) async {
if (!_validForm()) return false;
final docProfessional = FirebaseFirestore.instance
.collection('professional_info')
.doc(userId)
.withConverter(
fromFirestore: (snapshot, _) =>
Profesional.fromDocument(snapshot.data()!),
toFirestore: (user, _) => user.toDocument(),
);
await docProfessional.set(profesional!);
NotificationsService.showSnackbar('Información actualizada');
return true;
}
Future<bool> updateProfesionalProfileInfo(String userId) async {
if (!_validProfileForm()) return false;
final docProfessional = FirebaseFirestore.instance
.collection('professional_info')
.doc(userId)
.withConverter(
fromFirestore: (snapshot, _) =>
Profesional.fromDocument(snapshot.data()!),
toFirestore: (user, _) => user.toDocument(),
);
await docProfessional.set(profesional!);
NotificationsService.showSnackbar('Información actualizada');
return true;
}
Future<bool> updateProfesionalProfileScheduleInfo(String userId) async {
final docProfessional = FirebaseFirestore.instance
.collection('professional_info')
.doc(userId)
.withConverter(
fromFirestore: (snapshot, _) =>
Profesional.fromDocument(snapshot.data()!),
toFirestore: (user, _) => user.toDocument(),
);
await docProfessional.set(profesional!);
NotificationsService.showSnackbar('Información actualizada');
return true;
}
Future<Profesional> uploadPdfIdentification(
Uint8List fileBytes, String userId) async {
try {
final storageRef = FirebaseStorage.instance
.ref()
.child('$userId/PDF/${userId}_cedula.pdf');
await storageRef.putData(fileBytes);
final url = await storageRef.getDownloadURL();
copyProfesionalWith(identificationPicture: url);
notifyListeners();
return profesional!;
} catch (e) {
print("Error al subir el PDF de identificación: $e");
NotificationsService.showSnackbar('Error al subir el PDF');
rethrow;
}
}
Future<Profesional> uploadPdfCertificate(
Uint8List fileBytes, String userId) async {
try {
final storageRef = FirebaseStorage.instance
.ref()
.child('$userId/PDF/${userId}_certificado.pdf');
await storageRef.putData(fileBytes);
final url = await storageRef.getDownloadURL();
copyProfesionalWith(certificatePicture: url);
notifyListeners();
return profesional!;
} catch (e) {
print("Error al subir el PDF de identificación: $e");
NotificationsService.showSnackbar('Error al subir el PDF');
rethrow;
}
}
Future<Profesional> uploadPdfSpecializations(
List<Uint8List> filesBytes, String userId) async {
try {
List<String> urls = [];
for (int i = 0; i < filesBytes.length; i++) {
final storageRef = FirebaseStorage.instance.ref().child(
'$userId/PDF/${userId}_${DateTime.now().millisecondsSinceEpoch}_especializacion_$i.pdf');
await storageRef.putData(filesBytes[i]);
final url = await storageRef.getDownloadURL();
urls.add(url);
}
copyProfesionalWith(specializationsPictures: urls);
notifyListeners();
return profesional!;
} catch (e) {
print("Error al subir los PDFs de especialización: $e");
NotificationsService.showSnackbar('Error al subir los PDFs');
rethrow;
}
}
}
+69
View File
@@ -0,0 +1,69 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/widgets.dart';
import 'package:prosapp_web_app/models/location_preferences.dart';
import 'package:prosapp_web_app/models/payment_method_entity.dart';
import 'package:prosapp_web_app/models/profesional.dart';
import 'package:prosapp_web_app/models/schedules.dart';
class ProfessionalProvider extends ChangeNotifier {
Profesional? profesional;
bool _isProModeActive = false;
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
bool get isProModeActive {
return _isProModeActive;
}
Future<Profesional> getProfessional(String uid) async {
try {
final professional = await FirebaseFirestore.instance
.collection('professional_info')
.doc(uid)
.get();
profesional = Profesional.fromDocument(professional.data()!);
} catch (e) {
profesional = Profesional(
id: _firebaseAuth.currentUser!.uid,
identification: '',
address: '',
aditionalAddress: '',
profession: '',
ratePreferences: false,
rate: '',
locationPreferences: LocationPreferences.office,
bannerPicture: '',
identificationPicture: '',
certificatePicture: '',
latitude: 0,
longitude: 0,
specializations: [],
specializationsPictures: [],
schedules: Schedules.empty,
paymentMethods: PaymentMethodEntity.empty,
);
}
notifyListeners();
return profesional!;
}
logout() {
_isProModeActive = false;
notifyListeners();
}
void toggleProMode() {
_isProModeActive = !_isProModeActive;
notifyListeners();
}
void setIsProModeActive(bool value) {
_isProModeActive = value;
notifyListeners();
}
sendProfessionalToReview() {}
}
+80
View File
@@ -0,0 +1,80 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/comment_entity.dart';
import 'package:prosapp_web_app/models/pro_state.dart';
import 'package:prosapp_web_app/models/profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart';
import 'package:prosapp_web_app/models/usuario_profesional.dart';
class ProfessionalsProvider extends ChangeNotifier {
List<UsuarioProfesional> professionals = [];
bool isLoading = true;
ProfessionalsProvider() {
getProfessionals();
}
getProfessionals() async {
try {
final querySnapshot = await FirebaseFirestore.instance
.collection('users')
.where('professional_state', isEqualTo: ProState.active.index)
.get();
final users = querySnapshot.docs
.map((e) => Usuario.fromDocument(e.data()))
.toList();
final ids = users.map((e) => e.id).toList();
final querySnapshot2 = await FirebaseFirestore.instance
.collection('professional_info')
.where(FieldPath.documentId, whereIn: ids)
.get();
final professionalsInfo = querySnapshot2.docs
.map((e) => Profesional.fromDocument(e.data()))
.toList();
final professionalInfoMap = {
for (var doc in professionalsInfo) doc.id: doc
};
final usersMap = await Future.wait(users.map((user) async {
final professionalInfo = professionalInfoMap[user.id];
final averageScore = await _getAverageScore(user.id);
return UsuarioProfesional(
user: user,
professionalInfo: professionalInfo!,
averageScore: averageScore,
);
}).toList());
professionals = usersMap;
} catch (e) {
print('Error obteniendo profesionales: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
Future<double> _getAverageScore(String userId) async {
final querySnapshot = await FirebaseFirestore.instance
.collection('comments')
.where('destination_id', isEqualTo: userId)
.where('is_from_user', isEqualTo: true)
.get();
if (querySnapshot.docs.isEmpty) {
return 0.0;
}
final scores = querySnapshot.docs
.map((e) => CommentEntity.fromDocument(e.data()).score)
.toList();
final averageScore = scores.reduce((a, b) => a + b) / scores.length;
return averageScore;
}
}
+33
View File
@@ -0,0 +1,33 @@
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:prosapp_web_app/models/profession.dart';
class ProfessionsProvider extends ChangeNotifier {
List<Profession> professions = [];
bool isLoading = true;
final _professionsCollection =
FirebaseFirestore.instance.collection('professions');
ProfessionsProvider() {
getProfessions();
}
getProfessions() async {
try {
final documentSnapshot =
await _professionsCollection.doc('professions').get();
final data = documentSnapshot.data() as Map<String, dynamic>;
professions = (data['professions'] as List<dynamic>)
.map((item) => Profession(name: item as String))
.toList();
} catch (e) {
print('Error obteniendo profesiones: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
}
+159
View File
@@ -0,0 +1,159 @@
import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/pro_state.dart';
import 'package:prosapp_web_app/models/usuario.dart';
import 'package:prosapp_web_app/services/notifications_service.dart';
class ProfileFormProvider extends ChangeNotifier {
Usuario? user;
GlobalKey<FormState> formKey = GlobalKey<FormState>();
String? _verificationId;
void copyUserWith({
String? id,
String? email,
String? phone,
String? name,
String? nickname,
String? city,
String? picture,
String? birthday,
String? gender,
ProState? proState,
String? token,
}) {
user = Usuario(
id: id ?? user!.id,
email: email ?? user!.email,
phone: phone ?? user!.phone,
name: name ?? user!.name,
nickname: nickname ?? user!.nickname,
city: city ?? user!.city,
picture: picture ?? user!.picture,
birthday: birthday ?? user!.birthday,
gender: gender ?? user!.gender,
proState: proState ?? user!.proState,
token: token ?? user!.token,
);
notifyListeners();
}
bool _validForm() {
return formKey.currentState!.validate();
}
Future<void> updateUserInfo() async {
if (!_validForm()) return;
final docUser = FirebaseFirestore.instance
.collection('users')
.doc(user!.id)
.withConverter(
fromFirestore: (snapshot, _) =>
Usuario.fromDocument(snapshot.data()!),
toFirestore: (user, _) => user.toDocument(),
);
await docUser.set(user!);
NotificationsService.showSnackbar('Información actualizada');
}
Future<void> updateUserInfoNoValid() async {
final docUser = FirebaseFirestore.instance
.collection('users')
.doc(user!.id)
.withConverter(
fromFirestore: (snapshot, _) =>
Usuario.fromDocument(snapshot.data()!),
toFirestore: (user, _) => user.toDocument(),
);
await docUser.set(user!);
NotificationsService.showSnackbar('Información actualizada');
}
Future<Usuario> uploadPicture(Uint8List bytes) async {
try {
final storageRef = FirebaseStorage.instance
.ref()
.child('${user!.id}/PP/${user!.id}_lead');
await storageRef.putData(bytes);
final url = await storageRef.getDownloadURL();
copyUserWith(picture: url);
notifyListeners();
return user!;
} catch (e) {
print("Error al subir la imagen: $e");
rethrow;
}
}
// Agregar numero
Future<void> signUpWithPhoneNumber(String phoneNumber) async {
try {
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
verificationCompleted: (PhoneAuthCredential credential) async {
await FirebaseAuth.instance.signInWithCredential(credential);
NotificationsService.showSnackbar('Autenticación exitosa');
},
verificationFailed: (FirebaseAuthException e) {
NotificationsService.showSnackbar(
'Error en la verificación: ${e.message}');
},
codeSent: (String verificationId, int? resendToken) {
_verificationId = verificationId;
NotificationsService.showSnackbar(
'Código enviado al número $phoneNumber');
},
codeAutoRetrievalTimeout: (String verificationId) {
_verificationId = verificationId;
},
);
NotificationsService.showSnackbar('Código enviado');
} catch (e) {
NotificationsService.showSnackbar('Error al registrar con teléfono: $e');
}
}
Future<bool> linkPhoneNumberToExistingAccount(
String phoneNumber, String code) async {
try {
var phoneAuthCredential = PhoneAuthProvider.credential(
verificationId: _verificationId!,
smsCode: code,
);
User? user = FirebaseAuth.instance.currentUser;
if (user != null) {
await user.linkWithCredential(phoneAuthCredential);
copyUserWith(phone: phoneNumber);
notifyListeners();
NotificationsService.showSnackbar('Número vinculado exitosamente');
return true;
}
return false;
} catch (e) {
if (e is FirebaseAuthException && e.code == 'invalid-verification-code') {
NotificationsService.showSnackbar('Código de verificación inválido');
return false;
} else {
NotificationsService.showSnackbar('Error al vincular número: $e');
rethrow;
}
}
}
}
+21
View File
@@ -0,0 +1,21 @@
import 'package:flutter/material.dart';
class RegisterFormProvider extends ChangeNotifier {
GlobalKey<FormState> formKey = GlobalKey<FormState>();
String name = "";
String email = "";
String password = "";
validateForm() {
if (formKey.currentState!.validate()) {
print('Formulario válido');
print('Name: $name, Email: $email, password: $password');
return true;
} else {
print('Formulario no válido');
return false;
}
}
}
+53
View File
@@ -0,0 +1,53 @@
import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/comment_entity.dart';
import 'package:prosapp_web_app/models/score_entity.dart';
import 'package:prosapp_web_app/repositories/firebase_score_repository.dart';
class ScoreProvider with ChangeNotifier {
final FirebaseScoreRepository _firebaseScoreRepository =
FirebaseScoreRepository();
ReputationEntity _reputation = const ReputationEntity(
total: 0,
average: 0,
totalPro: 0,
averagePro: 0,
);
ReputationEntity get reputation => _reputation;
List<CommentEntity> _comments = [];
List<CommentEntity> get comments => _comments;
// Método para cargar reputación dinámica según el ID
Future<void> loadReputation(String userId) async {
try {
final reputation =
await _firebaseScoreRepository.getReputationByUserId(userId);
_reputation = reputation;
notifyListeners();
} catch (e) {
debugPrint('Error loading reputation: $e');
}
}
// Método para cargar comentarios dinámicamente
void loadComments(String userId, {required bool isProfessional}) {
final commentStream = isProfessional
? _firebaseScoreRepository.getScoresForProfessional(userId)
: _firebaseScoreRepository.getScoresForUser(userId);
commentStream.listen((comments) {
_comments = comments;
notifyListeners();
});
}
Future<void> addComment(CommentEntity comment) async {
try {
await _firebaseScoreRepository.addComment(comment);
notifyListeners();
} catch (e) {
debugPrint('Error adding comment: $e');
}
}
}
+390
View File
@@ -0,0 +1,390 @@
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:prosapp_web_app/models/pro_state.dart';
import 'package:prosapp_web_app/models/service.dart';
import 'package:prosapp_web_app/models/service_status.dart';
import 'package:prosapp_web_app/models/servicio_profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart';
class ServicesProvider extends ChangeNotifier {
List<ServicioProfesional> services = [];
ServicioProfesional? service;
bool isLoading = true;
final _servicesCollection = FirebaseFirestore.instance.collection('services');
final _usersCollection = FirebaseFirestore.instance.collection('users');
void logout() {
services = [];
service = null;
isLoading = false;
notifyListeners();
}
Future<void> changeServiceStatus(
String serviceId, ServiceStatus newStatus) async {
try {
final statusValue = enumToIntService(newStatus);
await FirebaseFirestore.instance
.collection('services')
.doc(serviceId)
.update({'status': statusValue});
notifyListeners();
} catch (e) {
print('Error al actualizar el estado: $e');
}
}
// cambiar el user_scored a true
Future<void> changeUserScored(String serviceId) async {
try {
await FirebaseFirestore.instance
.collection('services')
.doc(serviceId)
.update({'user_scored': true});
notifyListeners();
} catch (e) {
print('Error al actualizar el estado: $e');
}
}
// cambiar el professional_scored a true
Future<void> changeProfessionalScored(String serviceId) async {
try {
await FirebaseFirestore.instance
.collection('services')
.doc(serviceId)
.update({'professional_scored': true});
notifyListeners();
} catch (e) {
print('Error al actualizar el estado: $e');
}
}
void clearServices() {
services.clear();
notifyListeners();
}
getServiceForUser(String serviceId) async {
try {
isLoading = true;
final queryService = await _servicesCollection.doc(serviceId).get();
final servicio = Service.fromDocument(queryService);
final queryUsers =
await _usersCollection.doc(servicio.professionalId).get();
final user = Usuario.fromDocument(queryUsers.data()!);
service = ServicioProfesional(
user: user,
service: servicio,
);
} catch (e) {
service = null;
} finally {
isLoading = false;
notifyListeners();
}
}
getServiceForProfessional(String serviceId) async {
try {
isLoading = true;
final queryService = await _servicesCollection.doc(serviceId).get();
final servicio = Service.fromDocument(queryService);
final queryUsers = await _usersCollection.doc(servicio.userId).get();
final user = Usuario.fromDocument(queryUsers.data()!);
service = ServicioProfesional(
user: user,
service: servicio,
);
} catch (e) {
service = null;
} finally {
isLoading = false;
notifyListeners();
}
}
getServicesForUser(String userId) async {
try {
isLoading = true;
final queryServices = await _servicesCollection
.where('user_id', isEqualTo: userId)
.where('status', whereIn: [0, 1, 3]).get();
final servicios = queryServices.docs.map(Service.fromDocument).toList();
final professionalIds =
servicios.map((service) => service.professionalId).toList();
final queryUsers = await _usersCollection
.where('professional_state', isEqualTo: ProState.active.index)
.where(FieldPath.documentId, whereIn: professionalIds)
.get();
final professionalUsers =
queryUsers.docs.map((e) => Usuario.fromDocument(e.data())).toList();
final professionalUsersMap = {
for (var user in professionalUsers) user.id: user
};
final servicesMap = (servicios.map((service) {
final user = professionalUsersMap[service.professionalId];
return ServicioProfesional(
user: user!,
service: service,
);
}).toList());
services = servicesMap
..sort((a, b) {
final dateA = DateTime.parse(a.service.day);
final dateB = DateTime.parse(b.service.day);
final range1A =
a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
final range1B =
b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
if (dateA.compareTo(dateB) != 0) {
return dateA.compareTo(dateB);
} else {
return range1A.compareTo(range1B);
}
});
} catch (e) {
print('Error obteniendo servicios: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
getServicesRequestsForProfessional(String userId) async {
try {
isLoading = true;
final queryServices = await _servicesCollection
.where('professional_id', isEqualTo: userId)
.where('status', whereIn: [0]).get();
final servicios = queryServices.docs.map(Service.fromDocument).toList();
final userIds = servicios.map((service) => service.userId).toList();
final queryUsers = await _usersCollection
.where(FieldPath.documentId, whereIn: userIds)
.get();
final users =
queryUsers.docs.map((e) => Usuario.fromDocument(e.data())).toList();
final usersMap = {for (var doc in users) doc.id: doc};
final servicesMap = (servicios.map((service) {
final user = usersMap[service.userId];
return ServicioProfesional(
user: user!,
service: service,
);
}).toList());
services = servicesMap
..sort((a, b) {
final dateA = DateTime.parse(a.service.day);
final dateB = DateTime.parse(b.service.day);
final range1A =
a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
final range1B =
b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
if (dateA.compareTo(dateB) != 0) {
return dateA.compareTo(dateB);
} else {
return range1A.compareTo(range1B);
}
});
} catch (e) {
print('Error obteniendo servicios: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
getServicesForProfessional(String userId) async {
try {
isLoading = true;
final queryServices = await _servicesCollection
.where('professional_id', isEqualTo: userId)
.where('status', whereIn: [1, 3]).get();
final servicios = queryServices.docs.map(Service.fromDocument).toList();
final userIds = servicios.map((service) => service.userId).toList();
final queryUsers = await _usersCollection
.where(FieldPath.documentId, whereIn: userIds)
.get();
final users =
queryUsers.docs.map((e) => Usuario.fromDocument(e.data())).toList();
final usersMap = {for (var doc in users) doc.id: doc};
final servicesMap = (servicios.map((service) {
final user = usersMap[service.userId];
return ServicioProfesional(
user: user!,
service: service,
);
}).toList());
services = servicesMap
..sort((a, b) {
final dateA = DateTime.parse(a.service.day);
final dateB = DateTime.parse(b.service.day);
final range1A =
a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
final range1B =
b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
if (dateA.compareTo(dateB) != 0) {
return dateA.compareTo(dateB);
} else {
return range1A.compareTo(range1B);
}
});
} catch (e) {
print('Error obteniendo servicios: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
getServicesHistoryForUser(String userId) async {
try {
isLoading = true;
final queryServices = await _servicesCollection
.where('user_id', isEqualTo: userId)
.where('status', whereIn: [2, 4, 5]).get();
final servicios = queryServices.docs.map(Service.fromDocument).toList();
final professionalIds =
servicios.map((service) => service.professionalId).toList();
final queryUsers = await _usersCollection
.where('professional_state', isEqualTo: ProState.active.index)
.where(FieldPath.documentId, whereIn: professionalIds)
.get();
final professionalUsers =
queryUsers.docs.map((e) => Usuario.fromDocument(e.data())).toList();
final professionalUsersMap = {
for (var user in professionalUsers) user.id: user
};
final servicesMap = (servicios.map((service) {
final user = professionalUsersMap[service.professionalId];
return ServicioProfesional(
user: user!,
service: service,
);
}).toList());
services = servicesMap
..sort((a, b) {
final dateA = DateTime.parse(a.service.day);
final dateB = DateTime.parse(b.service.day);
final range1A =
a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
final range1B =
b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
if (dateA.compareTo(dateB) != 0) {
return dateA.compareTo(dateB);
} else {
return range1A.compareTo(range1B);
}
});
} catch (e) {
print('Error obteniendo servicios: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
getServicesHistoryForProfessional(String userId) async {
try {
isLoading = true;
final queryServices = await _servicesCollection
.where('professional_id', isEqualTo: userId)
.where('status', whereIn: [2, 4, 5]).get();
final servicios = queryServices.docs.map(Service.fromDocument).toList();
final userIds = servicios.map((service) => service.userId).toList();
final queryUsers = await _usersCollection
.where(FieldPath.documentId, whereIn: userIds)
.get();
final users =
queryUsers.docs.map((e) => Usuario.fromDocument(e.data())).toList();
final usersMap = {for (var doc in users) doc.id: doc};
final servicesMap = (servicios.map((service) {
final user = usersMap[service.userId];
return ServicioProfesional(
user: user!,
service: service,
);
}).toList());
services = servicesMap
..sort((a, b) {
final dateA = DateTime.parse(a.service.day);
final dateB = DateTime.parse(b.service.day);
final range1A =
a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
final range1B =
b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
if (dateA.compareTo(dateB) != 0) {
return dateA.compareTo(dateB);
} else {
return range1A.compareTo(range1B);
}
});
} catch (e) {
print('Error obteniendo servicios: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
}
+26
View File
@@ -0,0 +1,26 @@
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:prosapp_web_app/models/setting.dart';
class SettingsProvider extends ChangeNotifier {
Setting? settings;
bool isLoading = true;
final _settingsCollection = FirebaseFirestore.instance.collection('settings');
SettingsProvider() {
getSettings();
}
getSettings() async {
try {
final querySnapshot = await _settingsCollection.doc('global').get();
settings = Setting.fromDocument(querySnapshot.data()!);
} catch (e) {
print('Error obteniendo los settings: $e');
} finally {
isLoading = false;
notifyListeners();
}
}
}
+44
View File
@@ -0,0 +1,44 @@
import 'package:flutter/material.dart';
class SideMenuProvider extends ChangeNotifier {
static late AnimationController menuController;
static bool isOpen = false;
String _currentPage = '';
String get currentPage {
return _currentPage;
}
void setCurrentPageUrl(String routeName) {
_currentPage = routeName;
Future.delayed(const Duration(milliseconds: 100), () {
notifyListeners();
});
}
static Animation<double> movement =
Tween<double>(begin: -200, end: 0).animate(
CurvedAnimation(parent: menuController, curve: Curves.easeInOut),
);
static Animation<double> opacity = Tween<double>(begin: 0, end: 1).animate(
CurvedAnimation(parent: menuController, curve: Curves.easeInOut),
);
static void openMenu() {
isOpen = true;
menuController.forward();
}
static void closeMenu() {
isOpen = false;
menuController.reverse();
}
static void toggleMenu() {
(isOpen) ? menuController.reverse() : menuController.forward();
isOpen = !isOpen;
}
}