feat: migrate Firebase → NestJS REST API backend
Replace all Firebase SDK (Auth, Firestore, Storage) with HTTP calls to backend.prosapp.co/api/v1: - New ApiService singleton (JWT token, GET/POST/PATCH/DELETE/upload) - auth_provider: Firebase Auth → /auth/login, /auth/register, /auth/phone/* - services_provider + calendar_services_provider → /services endpoints - professional_provider + professionals_provider → /professional-info, /users/professionals - profile_form_provider + professional_form_provider → /users/me, /storage/upload - cities/professions/settings providers → /cities, /professions, /settings - firebase_chat_repository → polling via /chats endpoints (3s interval) - firebase_score_repository → polling via /comments endpoints (10s interval) - professional_detail_provider → /users/:id + /professional-info/:id - dashboard_view: Firestore.add → POST /services - chat_view + rating_view: FirebaseAuth.uid → AuthProvider.user.id - Models: Timestamp → String for createdAt fields - google_fonts upgraded to ^8.1.0 (Dart 3.12 compat) - Remove firebase_core, firebase_auth, cloud_firestore, firebase_storage from pubspec Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
15175c1b91
commit
60216fd0e3
@@ -1,13 +1,9 @@
|
||||
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/api_service.dart';
|
||||
import 'package:prosapp_web_app/services/navigation_service.dart';
|
||||
import 'package:prosapp_web_app/services/notifications_service.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
@@ -16,14 +12,10 @@ 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;
|
||||
final _api = ApiService.instance;
|
||||
|
||||
AuthProvider() {
|
||||
isAuthenticated();
|
||||
@@ -31,81 +23,59 @@ class AuthProvider extends ChangeNotifier {
|
||||
|
||||
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()!);
|
||||
|
||||
final data = await _api.post('/auth/login', {'email': email, 'password': password});
|
||||
await _api.saveToken(data['token'] as String);
|
||||
user = Usuario.fromDocument(data['user'] as Map<String, dynamic>);
|
||||
userAverageScore = await _loadAverageScore(user!.id);
|
||||
authStatus = AuthStatus.authenticated;
|
||||
|
||||
notifyListeners();
|
||||
|
||||
NavigationService.replaceTo(Flurorouter.dashboardRoute);
|
||||
} catch (e) {
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
|
||||
NotificationsService.showSnackBarError(
|
||||
'Usuario o contraseña incorrectos');
|
||||
NotificationsService.showSnackBarError('Usuario o contraseña incorrectos');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> verifyPhoneNumberForLink(String phoneNumber) async {
|
||||
Future<void> register(String email, String password, String name) 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;
|
||||
},
|
||||
);
|
||||
final data = await _api.post('/auth/register', {
|
||||
'email': email,
|
||||
'password': password,
|
||||
'name': name.trim(),
|
||||
});
|
||||
await _api.saveToken(data['token'] as String);
|
||||
user = Usuario.fromDocument(data['user'] as Map<String, dynamic>);
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
NavigationService.replaceTo(Flurorouter.dashboardRoute);
|
||||
} catch (e) {
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
NotificationsService.showSnackBarError('Email ya registrado');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> verifyPhoneNumber(String phoneNumber) async {
|
||||
try {
|
||||
await _api.post('/auth/phone/send', {'phone': phoneNumber});
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackBarError('Error al enviar OTP');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> linkPhoneWithOTP(String smsCode) async {
|
||||
Future<void> signInWithOTP(String phoneNumber, 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);
|
||||
}
|
||||
final data = await _api.post('/auth/phone/verify', {
|
||||
'phone': phoneNumber,
|
||||
'code': smsCode,
|
||||
});
|
||||
await _api.saveToken(data['token'] as String);
|
||||
user = Usuario.fromDocument(data['user'] as Map<String, dynamic>);
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
NavigationService.replaceTo(Flurorouter.dashboardRoute);
|
||||
} catch (e) {
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
@@ -113,63 +83,59 @@ class AuthProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> register(String email, String password, String name) async {
|
||||
Future<void> verifyPhoneNumberForLink(String phoneNumber) 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;
|
||||
await _api.post('/auth/phone/link/send', {'phone': phoneNumber});
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackBarError('Error al enviar OTP');
|
||||
}
|
||||
}
|
||||
|
||||
NotificationsService.showSnackBarError('Email ya registrado');
|
||||
Future<void> linkPhoneWithOTP(String phoneNumber, String smsCode) async {
|
||||
try {
|
||||
await _api.post('/auth/phone/link/verify', {
|
||||
'phone': phoneNumber,
|
||||
'code': smsCode,
|
||||
});
|
||||
user = await _fetchMe();
|
||||
NotificationsService.showSnackbar('Número vinculado exitosamente');
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
NavigationService.replaceTo(Flurorouter.profileRoute);
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackBarError('Error en la verificación OTP');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addEmailAndPassword(String email, String password) async {
|
||||
try {
|
||||
await _api.patch('/users/me', {'email': email, 'password': password});
|
||||
user = await _fetchMe();
|
||||
notifyListeners();
|
||||
NotificationsService.showSnackbar('Email y contraseña añadidos exitosamente');
|
||||
NavigationService.replaceTo(Flurorouter.profileRoute);
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackBarError('Error al añadir email');
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> isAuthenticated() async {
|
||||
final User? firebaseUser = _firebaseAuth.currentUser;
|
||||
|
||||
if (firebaseUser == null) {
|
||||
final token = await _api.getToken();
|
||||
if (token == 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);
|
||||
|
||||
try {
|
||||
final data = await _api.get('/auth/me');
|
||||
user = Usuario.fromDocument(data as Map<String, dynamic>);
|
||||
userAverageScore = await _loadAverageScore(user!.id);
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
return true;
|
||||
} else {
|
||||
} catch (e) {
|
||||
await _api.deleteToken();
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
return false;
|
||||
@@ -177,158 +143,32 @@ class AuthProvider extends ChangeNotifier {
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
await _firebaseAuth.signOut();
|
||||
await _api.deleteToken();
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
user = null;
|
||||
notifyListeners();
|
||||
|
||||
Provider.of<ServicesProvider>(
|
||||
NavigationService.navigatorKey.currentContext!,
|
||||
listen: false)
|
||||
.logout();
|
||||
Provider.of<ProfessionalProvider>(
|
||||
NavigationService.navigatorKey.currentContext!,
|
||||
listen: false)
|
||||
.logout();
|
||||
final ctx = NavigationService.navigatorKey.currentContext!;
|
||||
Provider.of<ServicesProvider>(ctx, listen: false).logout();
|
||||
Provider.of<ProfessionalProvider>(ctx, listen: false).logout();
|
||||
|
||||
NavigationService.replaceTo(Flurorouter.phoneLoginRoute);
|
||||
}
|
||||
|
||||
void refreshUser() {
|
||||
isAuthenticated();
|
||||
void refreshUser() => isAuthenticated();
|
||||
|
||||
Future<Usuario> _fetchMe() async {
|
||||
final data = await _api.get('/auth/me');
|
||||
return Usuario.fromDocument(data as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<void> verifyPhoneNumber(String phoneNumber) async {
|
||||
Future<double> _loadAverageScore(String userId) 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) {
|
||||
final data = await _api.get('/comments/reputation/$userId');
|
||||
final rep = data as Map<String, dynamic>;
|
||||
return (rep['average'] as num?)?.toDouble() ?? 0.0;
|
||||
} catch (_) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
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';
|
||||
import 'package:prosapp_web_app/services/api_service.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');
|
||||
final _api = ApiService.instance;
|
||||
|
||||
void logout() {
|
||||
services = [];
|
||||
@@ -22,47 +20,29 @@ class CalendarServicesProvider extends ChangeNotifier {
|
||||
getServicesForProfessional(String userId) async {
|
||||
try {
|
||||
isLoading = true;
|
||||
final data = await _api.get('/services?professional_id=$userId&status=1,3') as List;
|
||||
final servicios = data.map((e) {
|
||||
final m = e as Map<String, dynamic>;
|
||||
return Service.fromJson(m, m['id'] as String);
|
||||
}).toList();
|
||||
|
||||
final queryServices = await _servicesCollection
|
||||
.where('professional_id', isEqualTo: userId)
|
||||
.where('status', whereIn: [1, 3]).get();
|
||||
final ids = servicios.map((s) => s.userId).toSet().toList();
|
||||
final users = await Future.wait(ids.map((id) async {
|
||||
final u = await _api.get('/users/$id');
|
||||
return Usuario.fromDocument(u as Map<String, dynamic>);
|
||||
}));
|
||||
final usersMap = {for (var u in users) u.id: u};
|
||||
|
||||
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
|
||||
services = servicios
|
||||
.map((s) => ServicioProfesional(user: usersMap[s.userId]!, service: s))
|
||||
.toList()
|
||||
..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);
|
||||
}
|
||||
if (dateA != dateB) return dateA.compareTo(dateB);
|
||||
final tA = a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
|
||||
final tB = b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
|
||||
return tA.compareTo(tB);
|
||||
});
|
||||
} catch (e) {
|
||||
print('Error obteniendo servicios: $e');
|
||||
|
||||
@@ -1,49 +1,35 @@
|
||||
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';
|
||||
import 'package:prosapp_web_app/services/api_service.dart';
|
||||
|
||||
class CitiesProvider extends ChangeNotifier {
|
||||
List<City> cities = [];
|
||||
bool isLoading = true;
|
||||
|
||||
final _citiesCollection =
|
||||
FirebaseFirestore.instance.collection('countries v2');
|
||||
final _api = ApiService.instance;
|
||||
|
||||
CitiesProvider() {
|
||||
getCities();
|
||||
}
|
||||
|
||||
getCoordsOfCity(String cityName) {
|
||||
if (cities.isEmpty) return null;
|
||||
|
||||
for (var city in cities) {
|
||||
if (city.cityName == cityName) {
|
||||
return city.coordsOfCity;
|
||||
}
|
||||
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,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
final data = await _api.get('/cities') as List;
|
||||
cities = data.map((e) {
|
||||
final m = e as Map<String, dynamic>;
|
||||
return City(
|
||||
cityName: m['name'] as String,
|
||||
coordsOfCity: m['coords'] as String? ?? '',
|
||||
stateOfCity: m['state'] as String? ?? '',
|
||||
countryOfCity: m['country'] as String? ?? 'Colombia',
|
||||
);
|
||||
}).toList();
|
||||
cities.sort((a, b) => a.cityName.compareTo(b.cityName));
|
||||
} catch (e) {
|
||||
print('Error obteniendo ciudades: $e');
|
||||
|
||||
@@ -1,43 +1,27 @@
|
||||
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';
|
||||
import 'package:prosapp_web_app/services/api_service.dart';
|
||||
|
||||
class ProfessionalDetailProvider extends ChangeNotifier {
|
||||
UsuarioProfesional? professional;
|
||||
bool isLoading = true;
|
||||
final _api = ApiService.instance;
|
||||
|
||||
Future<void> getProfessionalById(String uid) async {
|
||||
try {
|
||||
isLoading = true;
|
||||
notifyListeners();
|
||||
|
||||
final userDoc =
|
||||
await FirebaseFirestore.instance.collection('users').doc(uid).get();
|
||||
final userData = await _api.get('/users/$uid');
|
||||
final user = Usuario.fromDocument(userData as Map<String, dynamic>);
|
||||
|
||||
if (!userDoc.exists) {
|
||||
print('Profesional no encontrado.');
|
||||
return;
|
||||
}
|
||||
final proData = await _api.get('/professional-info/$uid');
|
||||
final professionalInfo = Profesional.fromDocument(proData as Map<String, dynamic>);
|
||||
|
||||
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);
|
||||
final repData = await _api.get('/comments/reputation/$uid');
|
||||
final averageScore = (repData['average'] as num?)?.toDouble() ?? 0.0;
|
||||
|
||||
professional = UsuarioProfesional(
|
||||
user: user,
|
||||
@@ -51,22 +35,4 @@ class ProfessionalDetailProvider extends ChangeNotifier {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
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/api_service.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>();
|
||||
final _api = ApiService.instance;
|
||||
|
||||
copyProfesionalWith({
|
||||
String? id,
|
||||
@@ -41,160 +40,70 @@ class ProfessionalFormProvider with ChangeNotifier {
|
||||
profession: profession ?? profesional!.profession,
|
||||
ratePreferences: ratePreferences,
|
||||
rate: rate ?? profesional!.rate,
|
||||
locationPreferences:
|
||||
locationPreferences ?? profesional!.locationPreferences,
|
||||
locationPreferences: locationPreferences ?? profesional!.locationPreferences,
|
||||
bannerPicture: bannerPicture ?? profesional!.bannerPicture,
|
||||
identificationPicture:
|
||||
identificationPicture ?? profesional!.identificationPicture,
|
||||
identificationPicture: identificationPicture ?? profesional!.identificationPicture,
|
||||
certificatePicture: certificatePicture ?? profesional!.certificatePicture,
|
||||
latitude: latitude ?? profesional!.latitude,
|
||||
longitude: longitude ?? profesional!.longitude,
|
||||
specializations: specializations ?? profesional!.specializations,
|
||||
specializationsPictures:
|
||||
specializationsPictures ?? profesional!.specializationsPictures,
|
||||
specializationsPictures: specializationsPictures ?? profesional!.specializationsPictures,
|
||||
schedules: schedules ?? profesional!.schedules,
|
||||
paymentMethods: paymentMethods ?? profesional!.paymentMethods,
|
||||
);
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
bool _validForm() {
|
||||
return formKey.currentState!.validate();
|
||||
}
|
||||
bool _validForm() => formKey.currentState!.validate();
|
||||
bool _validProfileForm() => profileFormKey.currentState!.validate();
|
||||
|
||||
bool _validProfileForm() {
|
||||
return profileFormKey.currentState!.validate();
|
||||
}
|
||||
|
||||
setProfesional(Profesional profesional) {
|
||||
this.profesional = profesional;
|
||||
setProfesional(Profesional p) {
|
||||
profesional = p;
|
||||
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!);
|
||||
|
||||
await _api.patch('/professional-info/$userId', profesional!.toDocument());
|
||||
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!);
|
||||
|
||||
await _api.patch('/professional-info/$userId', profesional!.toDocument());
|
||||
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!);
|
||||
|
||||
await _api.patch('/professional-info/$userId', profesional!.toDocument());
|
||||
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> uploadPdfIdentification(Uint8List fileBytes, String userId) async {
|
||||
final url = await _api.upload(fileBytes, '${userId}_cedula.pdf');
|
||||
if (url != null) copyProfesionalWith(identificationPicture: url);
|
||||
notifyListeners();
|
||||
return profesional!;
|
||||
}
|
||||
|
||||
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> uploadPdfCertificate(Uint8List fileBytes, String userId) async {
|
||||
final url = await _api.upload(fileBytes, '${userId}_certificado.pdf');
|
||||
if (url != null) copyProfesionalWith(certificatePicture: url);
|
||||
notifyListeners();
|
||||
return profesional!;
|
||||
}
|
||||
|
||||
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;
|
||||
Future<Profesional> uploadPdfSpecializations(List<Uint8List> filesBytes, String userId) async {
|
||||
List<String> urls = [];
|
||||
for (int i = 0; i < filesBytes.length; i++) {
|
||||
final url = await _api.upload(filesBytes[i], '${userId}_especializacion_$i.pdf');
|
||||
if (url != null) urls.add(url);
|
||||
}
|
||||
copyProfesionalWith(specializationsPictures: urls);
|
||||
notifyListeners();
|
||||
return profesional!;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,24 @@
|
||||
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';
|
||||
import 'package:prosapp_web_app/services/api_service.dart';
|
||||
|
||||
class ProfessionalProvider extends ChangeNotifier {
|
||||
Profesional? profesional;
|
||||
bool _isProModeActive = false;
|
||||
final _api = ApiService.instance;
|
||||
|
||||
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
|
||||
|
||||
bool get isProModeActive {
|
||||
return _isProModeActive;
|
||||
}
|
||||
bool get isProModeActive => _isProModeActive;
|
||||
|
||||
Future<Profesional> getProfessional(String uid) async {
|
||||
try {
|
||||
final professional = await FirebaseFirestore.instance
|
||||
.collection('professional_info')
|
||||
.doc(uid)
|
||||
.get();
|
||||
|
||||
profesional = Profesional.fromDocument(professional.data()!);
|
||||
final data = await _api.get('/professional-info/$uid');
|
||||
profesional = Profesional.fromDocument(data as Map<String, dynamic>);
|
||||
} catch (e) {
|
||||
profesional = Profesional(
|
||||
id: _firebaseAuth.currentUser!.uid,
|
||||
id: uid,
|
||||
identification: '',
|
||||
address: '',
|
||||
aditionalAddress: '',
|
||||
@@ -45,12 +37,11 @@ class ProfessionalProvider extends ChangeNotifier {
|
||||
paymentMethods: PaymentMethodEntity.empty,
|
||||
);
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
return profesional!;
|
||||
}
|
||||
|
||||
logout() {
|
||||
void logout() {
|
||||
_isProModeActive = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
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';
|
||||
import 'package:prosapp_web_app/services/api_service.dart';
|
||||
|
||||
class ProfessionalsProvider extends ChangeNotifier {
|
||||
List<UsuarioProfesional> professionals = [];
|
||||
bool isLoading = true;
|
||||
final _api = ApiService.instance;
|
||||
|
||||
ProfessionalsProvider() {
|
||||
getProfessionals();
|
||||
@@ -16,42 +13,10 @@ class ProfessionalsProvider extends ChangeNotifier {
|
||||
|
||||
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()))
|
||||
final data = await _api.get('/users/professionals');
|
||||
professionals = (data as List)
|
||||
.map((e) => UsuarioProfesional.fromDocument(e as Map<String, dynamic>))
|
||||
.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 {
|
||||
@@ -59,22 +24,4 @@ class ProfessionalsProvider extends ChangeNotifier {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:prosapp_web_app/models/profession.dart';
|
||||
import 'package:prosapp_web_app/services/api_service.dart';
|
||||
|
||||
class ProfessionsProvider extends ChangeNotifier {
|
||||
List<Profession> professions = [];
|
||||
bool isLoading = true;
|
||||
|
||||
final _professionsCollection =
|
||||
FirebaseFirestore.instance.collection('professions');
|
||||
final _api = ApiService.instance;
|
||||
|
||||
ProfessionsProvider() {
|
||||
getProfessions();
|
||||
@@ -15,14 +13,14 @@ class ProfessionsProvider extends ChangeNotifier {
|
||||
|
||||
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();
|
||||
final data = await _api.get('/professions');
|
||||
if (data is List) {
|
||||
professions = data.map((e) => Profession(name: e['name'] as String)).toList();
|
||||
} else if (data is Map && data['professions'] is List) {
|
||||
professions = (data['professions'] as List)
|
||||
.map((e) => Profession(name: e as String))
|
||||
.toList();
|
||||
}
|
||||
} catch (e) {
|
||||
print('Error obteniendo profesiones: $e');
|
||||
} finally {
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
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/api_service.dart';
|
||||
import 'package:prosapp_web_app/services/notifications_service.dart';
|
||||
|
||||
class ProfileFormProvider extends ChangeNotifier {
|
||||
Usuario? user;
|
||||
GlobalKey<FormState> formKey = GlobalKey<FormState>();
|
||||
|
||||
String? _verificationId;
|
||||
final _api = ApiService.instance;
|
||||
|
||||
void copyUserWith({
|
||||
String? id,
|
||||
@@ -43,117 +39,45 @@ class ProfileFormProvider extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
bool _validForm() {
|
||||
return formKey.currentState!.validate();
|
||||
}
|
||||
bool _validForm() => 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!);
|
||||
await _api.patch('/users/me', user!.toDocument());
|
||||
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!);
|
||||
await _api.patch('/users/me', user!.toDocument());
|
||||
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;
|
||||
}
|
||||
final url = await _api.upload(bytes, 'profile_${user!.id}.jpg');
|
||||
if (url != null) copyUserWith(picture: url);
|
||||
notifyListeners();
|
||||
return user!;
|
||||
}
|
||||
|
||||
// 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');
|
||||
await _api.post('/auth/phone/link/send', {'phone': phoneNumber});
|
||||
NotificationsService.showSnackbar('Código enviado al número $phoneNumber');
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackbar('Error al registrar con teléfono: $e');
|
||||
NotificationsService.showSnackbar('Error al enviar código: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> linkPhoneNumberToExistingAccount(
|
||||
String phoneNumber, String code) async {
|
||||
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;
|
||||
await _api.post('/auth/phone/link/verify', {'phone': phoneNumber, 'code': code});
|
||||
copyUserWith(phone: phoneNumber);
|
||||
notifyListeners();
|
||||
NotificationsService.showSnackbar('Número vinculado exitosamente');
|
||||
return true;
|
||||
} 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;
|
||||
}
|
||||
NotificationsService.showSnackbar('Código de verificación inválido');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
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';
|
||||
import 'package:prosapp_web_app/services/api_service.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');
|
||||
final _api = ApiService.instance;
|
||||
|
||||
void logout() {
|
||||
services = [];
|
||||
@@ -21,43 +18,30 @@ class ServicesProvider extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> changeServiceStatus(
|
||||
String serviceId, ServiceStatus newStatus) async {
|
||||
Future<void> changeServiceStatus(String serviceId, ServiceStatus newStatus) async {
|
||||
try {
|
||||
final statusValue = enumToIntService(newStatus);
|
||||
await FirebaseFirestore.instance
|
||||
.collection('services')
|
||||
.doc(serviceId)
|
||||
.update({'status': statusValue});
|
||||
await _api.patch('/services/$serviceId', {'status': enumToIntService(newStatus)});
|
||||
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});
|
||||
await _api.patch('/services/$serviceId', {'user_scored': true});
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
print('Error al actualizar el estado: $e');
|
||||
print('Error al actualizar user_scored: $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});
|
||||
await _api.patch('/services/$serviceId', {'professional_scored': true});
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
print('Error al actualizar el estado: $e');
|
||||
print('Error al actualizar professional_scored: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,20 +53,12 @@ class ServicesProvider extends ChangeNotifier {
|
||||
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,
|
||||
);
|
||||
final data = await _api.get('/services/$serviceId');
|
||||
final map = data as Map<String, dynamic>;
|
||||
final servicio = Service.fromJson(map, map['id'] as String);
|
||||
final userData = await _api.get('/users/${servicio.professionalId}');
|
||||
final user = Usuario.fromDocument(userData as Map<String, dynamic>);
|
||||
service = ServicioProfesional(user: user, service: servicio);
|
||||
} catch (e) {
|
||||
service = null;
|
||||
} finally {
|
||||
@@ -94,19 +70,12 @@ class ServicesProvider extends ChangeNotifier {
|
||||
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,
|
||||
);
|
||||
final data = await _api.get('/services/$serviceId');
|
||||
final map = data as Map<String, dynamic>;
|
||||
final servicio = Service.fromJson(map, map['id'] as String);
|
||||
final userData = await _api.get('/users/${servicio.userId}');
|
||||
final user = Usuario.fromDocument(userData as Map<String, dynamic>);
|
||||
service = ServicioProfesional(user: user, service: servicio);
|
||||
} catch (e) {
|
||||
service = null;
|
||||
} finally {
|
||||
@@ -115,270 +84,43 @@ class ServicesProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
getServicesForUser(String userId) async {
|
||||
getServicesForUser(String userId) async => _loadServices('/services?user_id=$userId&status=0,1,3', forUser: true);
|
||||
|
||||
getServicesRequestsForProfessional(String userId) async => _loadServices('/services?professional_id=$userId&status=0', forUser: false);
|
||||
|
||||
getServicesForProfessional(String userId) async => _loadServices('/services?professional_id=$userId&status=1,3', forUser: false);
|
||||
|
||||
getServicesHistoryForUser(String userId) async => _loadServices('/services?user_id=$userId&status=2,4,5', forUser: true);
|
||||
|
||||
getServicesHistoryForProfessional(String userId) async => _loadServices('/services?professional_id=$userId&status=2,4,5', forUser: false);
|
||||
|
||||
Future<void> _loadServices(String path, {required bool forUser}) async {
|
||||
try {
|
||||
isLoading = true;
|
||||
final data = await _api.get(path) as List;
|
||||
final servicios = data.map((e) {
|
||||
final m = e as Map<String, dynamic>;
|
||||
return Service.fromJson(m, m['id'] as String);
|
||||
}).toList();
|
||||
|
||||
final queryServices = await _servicesCollection
|
||||
.where('user_id', isEqualTo: userId)
|
||||
.where('status', whereIn: [0, 1, 3]).get();
|
||||
final ids = servicios.map((s) => forUser ? s.professionalId : s.userId).toSet().toList();
|
||||
final users = await Future.wait(ids.map((id) async {
|
||||
final u = await _api.get('/users/$id');
|
||||
return Usuario.fromDocument(u as Map<String, dynamic>);
|
||||
}));
|
||||
final usersMap = {for (var u in users) u.id: u};
|
||||
|
||||
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
|
||||
services = servicios.map((s) {
|
||||
final userId = forUser ? s.professionalId : s.userId;
|
||||
return ServicioProfesional(user: usersMap[userId]!, service: s);
|
||||
}).toList()
|
||||
..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);
|
||||
}
|
||||
if (dateA != dateB) return dateA.compareTo(dateB);
|
||||
final tA = a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
|
||||
final tB = b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
|
||||
return tA.compareTo(tB);
|
||||
});
|
||||
} catch (e) {
|
||||
print('Error obteniendo servicios: $e');
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:prosapp_web_app/models/setting.dart';
|
||||
import 'package:prosapp_web_app/services/api_service.dart';
|
||||
|
||||
class SettingsProvider extends ChangeNotifier {
|
||||
Setting? settings;
|
||||
bool isLoading = true;
|
||||
|
||||
final _settingsCollection = FirebaseFirestore.instance.collection('settings');
|
||||
final _api = ApiService.instance;
|
||||
|
||||
SettingsProvider() {
|
||||
getSettings();
|
||||
@@ -14,8 +13,8 @@ class SettingsProvider extends ChangeNotifier {
|
||||
|
||||
getSettings() async {
|
||||
try {
|
||||
final querySnapshot = await _settingsCollection.doc('global').get();
|
||||
settings = Setting.fromDocument(querySnapshot.data()!);
|
||||
final data = await _api.get('/settings');
|
||||
settings = Setting.fromDocument(data as Map<String, dynamic>);
|
||||
} catch (e) {
|
||||
print('Error obteniendo los settings: $e');
|
||||
} finally {
|
||||
|
||||
Reference in New Issue
Block a user