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:
Lizandro Guarnizo
2026-06-18 15:53:39 -05:00
co-authored by Claude Sonnet 4.6
parent 15175c1b91
commit 60216fd0e3
29 changed files with 440 additions and 1304 deletions
+1 -7
View File
@@ -1,7 +1 @@
API_KEY=AIzaSyCNpUV_4cMEL9QZx7NESXK7QAlRjRGwx_Y API_BASE_URL=https://backend.prosapp.co/api/v1
AUTH_DOMAIN=prosapp-5747a.firebaseapp.com
PROJECT_ID=prosapp-5747a
STORAGE_BUCKET=prosapp-5747a.appspot.com
MESSAGING_SENDER_ID=245204384533
APP_ID=1:245204384533:web:1b8f0b4c1d9ae21d9f871c
MEASUREMENT_ID=G-EVBEQRZEDY
-13
View File
@@ -1,4 +1,3 @@
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:intl/date_symbol_data_local.dart'; import 'package:intl/date_symbol_data_local.dart';
@@ -30,18 +29,6 @@ void main() async {
await dotenv.load(fileName: ".env"); await dotenv.load(fileName: ".env");
await Firebase.initializeApp(
options: FirebaseOptions(
apiKey: dotenv.env['API_KEY']!,
authDomain: dotenv.env['AUTH_DOMAIN'],
projectId: dotenv.env['PROJECT_ID']!,
storageBucket: dotenv.env['STORAGE_BUCKET'],
messagingSenderId: dotenv.env['MESSAGING_SENDER_ID']!,
appId: dotenv.env['APP_ID']!,
measurementId: dotenv.env['MEASUREMENT_ID'],
),
);
await LocalStorage.configurePrefs(); await LocalStorage.configurePrefs();
await initializeDateFormatting('es_ES', null); await initializeDateFormatting('es_ES', null);
+9 -19
View File
@@ -1,5 +1,3 @@
import 'package:cloud_firestore/cloud_firestore.dart';
class CommentEntity { class CommentEntity {
final String authorId; final String authorId;
final String destinationId; final String destinationId;
@@ -7,7 +5,7 @@ class CommentEntity {
final String content; final String content;
final double score; final double score;
final bool isFromUser; final bool isFromUser;
final Timestamp createdAt; final String createdAt;
const CommentEntity({ const CommentEntity({
required this.authorId, required this.authorId,
@@ -21,13 +19,13 @@ class CommentEntity {
static CommentEntity fromDocument(Map<String, dynamic> doc) { static CommentEntity fromDocument(Map<String, dynamic> doc) {
return CommentEntity( return CommentEntity(
authorId: doc['author_id'] as String, authorId: doc['author_id'] as String? ?? '',
destinationId: doc['destination_id'] as String, destinationId: doc['destination_id'] as String? ?? '',
serviceId: doc['service_id'] as String, serviceId: doc['service_id'] as String? ?? '',
content: doc['content'] as String, content: doc['content'] as String? ?? '',
score: doc['score'] as double, score: (doc['score'] as num?)?.toDouble() ?? 0.0,
isFromUser: doc['is_from_user'] as bool, isFromUser: doc['is_from_user'] as bool? ?? false,
createdAt: doc['created_at'] as Timestamp, createdAt: doc['created_at']?.toString() ?? '',
); );
} }
@@ -45,14 +43,6 @@ class CommentEntity {
@override @override
String toString() { String toString() {
return '''CommentEntity{ return 'CommentEntity{authorId: $authorId, destinationId: $destinationId, score: $score}';
authorId: $authorId,
destinationId: $destinationId,
serviceId: $serviceId,
content: $content,
score: $score,
isFromUser: $isFromUser,
createdAt: $createdAt
}''';
} }
} }
+17 -31
View File
@@ -1,4 +1,3 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/service_location_preferences.dart'; import 'package:prosapp_web_app/models/service_location_preferences.dart';
import 'package:prosapp_web_app/models/service_status.dart'; import 'package:prosapp_web_app/models/service_status.dart';
@@ -14,7 +13,7 @@ class Service {
final double latitude; final double latitude;
final double longitude; final double longitude;
final String day; final String day;
final Timestamp createdAt; final String createdAt;
final String description; final String description;
final TimeOfDay range1Hour1; final TimeOfDay range1Hour1;
final TimeOfDay range1Hour2; final TimeOfDay range1Hour2;
@@ -46,28 +45,24 @@ class Service {
return Service( return Service(
id: id, id: id,
professionalId: doc['professional_id'] as String, professionalId: doc['professional_id'] as String,
professionalScored: doc['professional_scored'] as bool, professionalScored: doc['professional_scored'] as bool? ?? false,
userId: doc['user_id'] as String, userId: doc['user_id'] as String,
userScored: doc['user_scored'] as bool, userScored: doc['user_scored'] as bool? ?? false,
address: doc['address'] as String, address: doc['address'] as String? ?? '',
aditionalAddress: doc['aditional_address'] as String, aditionalAddress: doc['aditional_address'] as String? ?? '',
latitude: doc['latitude'] as double, latitude: (doc['latitude'] as num?)?.toDouble() ?? 0.0,
longitude: doc['longitude'] as double, longitude: (doc['longitude'] as num?)?.toDouble() ?? 0.0,
day: doc['day'] as String, day: doc['day'] as String? ?? '',
createdAt: doc['created_at'] as Timestamp, createdAt: doc['created_at']?.toString() ?? '',
description: doc['description'] as String, description: doc['description'] as String? ?? '',
range1Hour1: parseTimeOfDay(doc['range1_hour1'] as String), range1Hour1: parseTimeOfDay(doc['range1_hour1'] as String? ?? '0:0'),
range1Hour2: parseTimeOfDay(doc['range1_hour2'] as String), range1Hour2: parseTimeOfDay(doc['range1_hour2'] as String? ?? '0:0'),
status: intToEnumService(doc['status'] as int), status: intToEnumService((doc['status'] as num?)?.toInt() ?? 0),
rate: doc['rate'] as String, rate: doc['rate'] as String? ?? '',
location: intToEnum(doc['location'] as int), location: intToEnum((doc['location'] as num?)?.toInt() ?? 0),
); );
} }
static Service fromDocument(DocumentSnapshot<Map<String, dynamic>> doc) {
return fromJson(doc.data()!, doc.id);
}
Map<String, dynamic> toDocument() { Map<String, dynamic> toDocument() {
return { return {
'id': id, 'id': id,
@@ -96,21 +91,12 @@ class Service {
} }
String? formatTimeOfDay(TimeOfDay? time) { String? formatTimeOfDay(TimeOfDay? time) {
if (time != null) { if (time != null) return '${time.hour}:${time.minute}';
return "${time.hour.toString()}:${time.minute.toString()}";
}
return null; return null;
} }
@override @override
String toString() { String toString() {
return '''Service { return 'Service{professionalId: $professionalId, userId: $userId, day: $day, status: $status}';
professionalId: $professionalId,
userId: $userId,
day: $day,
createdAt: $createdAt,
status: $status,
location: $location
}''';
} }
} }
+9 -2
View File
@@ -21,12 +21,19 @@ class UsuarioProfesional {
}; };
} }
// Método para deserializar desde JSON
factory UsuarioProfesional.fromJson(Map<String, dynamic> json) { factory UsuarioProfesional.fromJson(Map<String, dynamic> json) {
return UsuarioProfesional( return UsuarioProfesional(
user: Usuario.fromDocument(json['user']), user: Usuario.fromDocument(json['user']),
professionalInfo: Profesional.fromDocument(json['professionalInfo']), professionalInfo: Profesional.fromDocument(json['professionalInfo']),
averageScore: json['averageScore'].toDouble(), averageScore: (json['averageScore'] as num?)?.toDouble() ?? 0.0,
);
}
static UsuarioProfesional fromDocument(Map<String, dynamic> doc) {
return UsuarioProfesional(
user: Usuario.fromDocument(doc['user'] as Map<String, dynamic>),
professionalInfo: Profesional.fromDocument(doc['professional_info'] as Map<String, dynamic>),
averageScore: (doc['average_score'] as num?)?.toDouble() ?? 0.0,
); );
} }
+93 -253
View File
@@ -1,13 +1,9 @@
import 'package:flutter/material.dart'; 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/models/usuario.dart';
import 'package:prosapp_web_app/providers/professional_provider.dart'; import 'package:prosapp_web_app/providers/professional_provider.dart';
import 'package:prosapp_web_app/providers/services_provider.dart'; import 'package:prosapp_web_app/providers/services_provider.dart';
import 'package:prosapp_web_app/router/router.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/navigation_service.dart';
import 'package:prosapp_web_app/services/notifications_service.dart'; import 'package:prosapp_web_app/services/notifications_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@@ -16,14 +12,10 @@ enum AuthStatus { checking, authenticated, notAuthenticated }
class AuthProvider extends ChangeNotifier { class AuthProvider extends ChangeNotifier {
Usuario? user; Usuario? user;
Profesional? professional;
double userAverageScore = 0.0; double userAverageScore = 0.0;
AuthStatus authStatus = AuthStatus.checking; AuthStatus authStatus = AuthStatus.checking;
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
String? _verificationId; final _api = ApiService.instance;
AuthProvider() { AuthProvider() {
isAuthenticated(); isAuthenticated();
@@ -31,81 +23,59 @@ class AuthProvider extends ChangeNotifier {
Future<void> login(String email, String password) async { Future<void> login(String email, String password) async {
try { try {
await _firebaseAuth.signInWithEmailAndPassword( final data = await _api.post('/auth/login', {'email': email, 'password': password});
email: email, password: password); await _api.saveToken(data['token'] as String);
user = Usuario.fromDocument(data['user'] as Map<String, dynamic>);
final userData = await _firestore userAverageScore = await _loadAverageScore(user!.id);
.collection('users')
.doc(_firebaseAuth.currentUser!.uid)
.get();
user = Usuario.fromDocument(userData.data()!);
authStatus = AuthStatus.authenticated; authStatus = AuthStatus.authenticated;
notifyListeners(); notifyListeners();
NavigationService.replaceTo(Flurorouter.dashboardRoute); NavigationService.replaceTo(Flurorouter.dashboardRoute);
} catch (e) { } catch (e) {
authStatus = AuthStatus.notAuthenticated; authStatus = AuthStatus.notAuthenticated;
notifyListeners(); 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 { try {
await _firebaseAuth.verifyPhoneNumber( final data = await _api.post('/auth/register', {
phoneNumber: phoneNumber, 'email': email,
timeout: const Duration(seconds: 60), 'password': password,
verificationCompleted: (PhoneAuthCredential credential) async { 'name': name.trim(),
if (_firebaseAuth.currentUser != null) { });
// Vincula el número de teléfono a la cuenta actual await _api.saveToken(data['token'] as String);
await _firebaseAuth.currentUser!.linkWithCredential(credential); user = Usuario.fromDocument(data['user'] as Map<String, dynamic>);
NotificationsService.showSnackbar('Número vinculado exitosamente'); authStatus = AuthStatus.authenticated;
authStatus = AuthStatus.authenticated; notifyListeners();
notifyListeners(); NavigationService.replaceTo(Flurorouter.dashboardRoute);
} } catch (e) {
}, authStatus = AuthStatus.notAuthenticated;
verificationFailed: (FirebaseAuthException e) { notifyListeners();
NotificationsService.showSnackBarError( NotificationsService.showSnackBarError('Email ya registrado');
'Error en la verificación del teléfono: ${e.message}'); }
}, }
codeSent: (String verificationId, int? resendToken) {
_verificationId = verificationId; Future<void> verifyPhoneNumber(String phoneNumber) async {
notifyListeners(); try {
}, await _api.post('/auth/phone/send', {'phone': phoneNumber});
codeAutoRetrievalTimeout: (String verificationId) { notifyListeners();
_verificationId = verificationId;
},
);
} catch (e) { } catch (e) {
NotificationsService.showSnackBarError('Error al enviar OTP'); NotificationsService.showSnackBarError('Error al enviar OTP');
} }
} }
Future<void> linkPhoneWithOTP(String smsCode) async { Future<void> signInWithOTP(String phoneNumber, String smsCode) async {
try { try {
final credential = PhoneAuthProvider.credential( final data = await _api.post('/auth/phone/verify', {
verificationId: _verificationId!, 'phone': phoneNumber,
smsCode: smsCode, 'code': smsCode,
); });
await _api.saveToken(data['token'] as String);
if (_firebaseAuth.currentUser != null) { user = Usuario.fromDocument(data['user'] as Map<String, dynamic>);
await _firebaseAuth.currentUser!.linkWithCredential(credential); authStatus = AuthStatus.authenticated;
notifyListeners();
await FirebaseFirestore.instance NavigationService.replaceTo(Flurorouter.dashboardRoute);
.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) { } catch (e) {
authStatus = AuthStatus.notAuthenticated; authStatus = AuthStatus.notAuthenticated;
notifyListeners(); 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 { try {
UserCredential userCredential = await _api.post('/auth/phone/link/send', {'phone': phoneNumber});
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(); 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 { Future<bool> isAuthenticated() async {
final User? firebaseUser = _firebaseAuth.currentUser; final token = await _api.getToken();
if (token == null) {
if (firebaseUser == null) {
authStatus = AuthStatus.notAuthenticated; authStatus = AuthStatus.notAuthenticated;
notifyListeners(); notifyListeners();
return false; return false;
} }
final userData = try {
await _firestore.collection('users').doc(firebaseUser.uid).get(); final data = await _api.get('/auth/me');
user = Usuario.fromDocument(data as Map<String, dynamic>);
if (userData.exists) { userAverageScore = await _loadAverageScore(user!.id);
user = Usuario.fromDocument(userData.data()!);
userAverageScore = await _getUserAverageScore(user!.id);
authStatus = AuthStatus.authenticated; authStatus = AuthStatus.authenticated;
notifyListeners(); notifyListeners();
return true; return true;
} else { } catch (e) {
await _api.deleteToken();
authStatus = AuthStatus.notAuthenticated; authStatus = AuthStatus.notAuthenticated;
notifyListeners(); notifyListeners();
return false; return false;
@@ -177,158 +143,32 @@ class AuthProvider extends ChangeNotifier {
} }
Future<void> logout() async { Future<void> logout() async {
await _firebaseAuth.signOut(); await _api.deleteToken();
authStatus = AuthStatus.notAuthenticated; authStatus = AuthStatus.notAuthenticated;
user = null;
notifyListeners(); notifyListeners();
Provider.of<ServicesProvider>( final ctx = NavigationService.navigatorKey.currentContext!;
NavigationService.navigatorKey.currentContext!, Provider.of<ServicesProvider>(ctx, listen: false).logout();
listen: false) Provider.of<ProfessionalProvider>(ctx, listen: false).logout();
.logout();
Provider.of<ProfessionalProvider>(
NavigationService.navigatorKey.currentContext!,
listen: false)
.logout();
NavigationService.replaceTo(Flurorouter.phoneLoginRoute); NavigationService.replaceTo(Flurorouter.phoneLoginRoute);
} }
void refreshUser() { void refreshUser() => isAuthenticated();
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 { try {
await _firebaseAuth.verifyPhoneNumber( final data = await _api.get('/comments/reputation/$userId');
phoneNumber: phoneNumber, final rep = data as Map<String, dynamic>;
timeout: const Duration(seconds: 60), return (rep['average'] as num?)?.toDouble() ?? 0.0;
verificationCompleted: (PhoneAuthCredential credential) async { } catch (_) {
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; 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;
} }
} }
+20 -40
View File
@@ -1,16 +1,14 @@
import 'package:flutter/material.dart'; 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/service.dart';
import 'package:prosapp_web_app/models/servicio_profesional.dart'; import 'package:prosapp_web_app/models/servicio_profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart'; import 'package:prosapp_web_app/models/usuario.dart';
import 'package:prosapp_web_app/services/api_service.dart';
class CalendarServicesProvider extends ChangeNotifier { class CalendarServicesProvider extends ChangeNotifier {
List<ServicioProfesional> services = []; List<ServicioProfesional> services = [];
ServicioProfesional? service; ServicioProfesional? service;
bool isLoading = true; bool isLoading = true;
final _api = ApiService.instance;
final _servicesCollection = FirebaseFirestore.instance.collection('services');
final _usersCollection = FirebaseFirestore.instance.collection('users');
void logout() { void logout() {
services = []; services = [];
@@ -22,47 +20,29 @@ class CalendarServicesProvider extends ChangeNotifier {
getServicesForProfessional(String userId) async { getServicesForProfessional(String userId) async {
try { try {
isLoading = true; 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 final ids = servicios.map((s) => s.userId).toSet().toList();
.where('professional_id', isEqualTo: userId) final users = await Future.wait(ids.map((id) async {
.where('status', whereIn: [1, 3]).get(); 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(); services = servicios
.map((s) => ServicioProfesional(user: usersMap[s.userId]!, service: s))
final userIds = servicios.map((service) => service.userId).toList(); .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) { ..sort((a, b) {
final dateA = DateTime.parse(a.service.day); final dateA = DateTime.parse(a.service.day);
final dateB = DateTime.parse(b.service.day); final dateB = DateTime.parse(b.service.day);
final range1A = if (dateA != dateB) return dateA.compareTo(dateB);
a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute; final tA = a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
final range1B = final tB = b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute; return tA.compareTo(tB);
if (dateA.compareTo(dateB) != 0) {
return dateA.compareTo(dateB);
} else {
return range1A.compareTo(range1B);
}
}); });
} catch (e) { } catch (e) {
print('Error obteniendo servicios: $e'); print('Error obteniendo servicios: $e');
+13 -27
View File
@@ -1,49 +1,35 @@
import 'package:flutter/material.dart'; 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/city.dart';
import 'package:prosapp_web_app/models/country_entity.dart'; import 'package:prosapp_web_app/services/api_service.dart';
class CitiesProvider extends ChangeNotifier { class CitiesProvider extends ChangeNotifier {
List<City> cities = []; List<City> cities = [];
bool isLoading = true; bool isLoading = true;
final _api = ApiService.instance;
final _citiesCollection =
FirebaseFirestore.instance.collection('countries v2');
CitiesProvider() { CitiesProvider() {
getCities(); getCities();
} }
getCoordsOfCity(String cityName) { getCoordsOfCity(String cityName) {
if (cities.isEmpty) return null;
for (var city in cities) { for (var city in cities) {
if (city.cityName == cityName) { if (city.cityName == cityName) return city.coordsOfCity;
return city.coordsOfCity;
}
} }
return null; return null;
} }
getCities() async { getCities() async {
try { try {
final querySnapshot = await _citiesCollection.doc('Colombia').get(); final data = await _api.get('/cities') as List;
cities = data.map((e) {
final data = querySnapshot.data(); final m = e as Map<String, dynamic>;
return City(
final country = CountryEntity.fromDocument(data as Map<String, dynamic>); cityName: m['name'] as String,
coordsOfCity: m['coords'] as String? ?? '',
for (var region in country.regions) { stateOfCity: m['state'] as String? ?? '',
for (var city in region.cities) { countryOfCity: m['country'] as String? ?? 'Colombia',
cities.add(City( );
cityName: city.name, }).toList();
coordsOfCity: city.coords,
stateOfCity: region.name,
countryOfCity: country.name,
));
}
}
cities.sort((a, b) => a.cityName.compareTo(b.cityName)); cities.sort((a, b) => a.cityName.compareTo(b.cityName));
} catch (e) { } catch (e) {
print('Error obteniendo ciudades: $e'); print('Error obteniendo ciudades: $e');
@@ -1,43 +1,27 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.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/profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart'; import 'package:prosapp_web_app/models/usuario.dart';
import 'package:prosapp_web_app/models/usuario_profesional.dart'; import 'package:prosapp_web_app/models/usuario_profesional.dart';
import 'package:prosapp_web_app/services/api_service.dart';
class ProfessionalDetailProvider extends ChangeNotifier { class ProfessionalDetailProvider extends ChangeNotifier {
UsuarioProfesional? professional; UsuarioProfesional? professional;
bool isLoading = true; bool isLoading = true;
final _api = ApiService.instance;
Future<void> getProfessionalById(String uid) async { Future<void> getProfessionalById(String uid) async {
try { try {
isLoading = true; isLoading = true;
notifyListeners(); notifyListeners();
final userDoc = final userData = await _api.get('/users/$uid');
await FirebaseFirestore.instance.collection('users').doc(uid).get(); final user = Usuario.fromDocument(userData as Map<String, dynamic>);
if (!userDoc.exists) { final proData = await _api.get('/professional-info/$uid');
print('Profesional no encontrado.'); final professionalInfo = Profesional.fromDocument(proData as Map<String, dynamic>);
return;
}
final user = Usuario.fromDocument(userDoc.data()!); final repData = await _api.get('/comments/reputation/$uid');
final averageScore = (repData['average'] as num?)?.toDouble() ?? 0.0;
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( professional = UsuarioProfesional(
user: user, user: user,
@@ -51,22 +35,4 @@ class ProfessionalDetailProvider extends ChangeNotifier {
notifyListeners(); 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;
}
} }
+30 -121
View File
@@ -1,18 +1,17 @@
import 'dart:typed_data'; 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:flutter/material.dart';
import 'package:prosapp_web_app/models/location_preferences.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/payment_method_entity.dart';
import 'package:prosapp_web_app/models/profesional.dart'; import 'package:prosapp_web_app/models/profesional.dart';
import 'package:prosapp_web_app/models/schedules.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'; import 'package:prosapp_web_app/services/notifications_service.dart';
class ProfessionalFormProvider with ChangeNotifier { class ProfessionalFormProvider with ChangeNotifier {
Profesional? profesional; Profesional? profesional;
GlobalKey<FormState> formKey = GlobalKey<FormState>(); GlobalKey<FormState> formKey = GlobalKey<FormState>();
GlobalKey<FormState> profileFormKey = GlobalKey<FormState>(); GlobalKey<FormState> profileFormKey = GlobalKey<FormState>();
final _api = ApiService.instance;
copyProfesionalWith({ copyProfesionalWith({
String? id, String? id,
@@ -41,160 +40,70 @@ class ProfessionalFormProvider with ChangeNotifier {
profession: profession ?? profesional!.profession, profession: profession ?? profesional!.profession,
ratePreferences: ratePreferences, ratePreferences: ratePreferences,
rate: rate ?? profesional!.rate, rate: rate ?? profesional!.rate,
locationPreferences: locationPreferences: locationPreferences ?? profesional!.locationPreferences,
locationPreferences ?? profesional!.locationPreferences,
bannerPicture: bannerPicture ?? profesional!.bannerPicture, bannerPicture: bannerPicture ?? profesional!.bannerPicture,
identificationPicture: identificationPicture: identificationPicture ?? profesional!.identificationPicture,
identificationPicture ?? profesional!.identificationPicture,
certificatePicture: certificatePicture ?? profesional!.certificatePicture, certificatePicture: certificatePicture ?? profesional!.certificatePicture,
latitude: latitude ?? profesional!.latitude, latitude: latitude ?? profesional!.latitude,
longitude: longitude ?? profesional!.longitude, longitude: longitude ?? profesional!.longitude,
specializations: specializations ?? profesional!.specializations, specializations: specializations ?? profesional!.specializations,
specializationsPictures: specializationsPictures: specializationsPictures ?? profesional!.specializationsPictures,
specializationsPictures ?? profesional!.specializationsPictures,
schedules: schedules ?? profesional!.schedules, schedules: schedules ?? profesional!.schedules,
paymentMethods: paymentMethods ?? profesional!.paymentMethods, paymentMethods: paymentMethods ?? profesional!.paymentMethods,
); );
notifyListeners(); notifyListeners();
} }
bool _validForm() { bool _validForm() => formKey.currentState!.validate();
return formKey.currentState!.validate(); bool _validProfileForm() => profileFormKey.currentState!.validate();
}
bool _validProfileForm() { setProfesional(Profesional p) {
return profileFormKey.currentState!.validate(); profesional = p;
}
setProfesional(Profesional profesional) {
this.profesional = profesional;
notifyListeners(); notifyListeners();
} }
Future<bool> updateProfesionalInfo(String userId) async { Future<bool> updateProfesionalInfo(String userId) async {
if (!_validForm()) return false; if (!_validForm()) return false;
await _api.patch('/professional-info/$userId', profesional!.toDocument());
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'); NotificationsService.showSnackbar('Información actualizada');
return true; return true;
} }
Future<bool> updateProfesionalProfileInfo(String userId) async { Future<bool> updateProfesionalProfileInfo(String userId) async {
if (!_validProfileForm()) return false; if (!_validProfileForm()) return false;
await _api.patch('/professional-info/$userId', profesional!.toDocument());
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'); NotificationsService.showSnackbar('Información actualizada');
return true; return true;
} }
Future<bool> updateProfesionalProfileScheduleInfo(String userId) async { Future<bool> updateProfesionalProfileScheduleInfo(String userId) async {
final docProfessional = FirebaseFirestore.instance await _api.patch('/professional-info/$userId', profesional!.toDocument());
.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'); NotificationsService.showSnackbar('Información actualizada');
return true; return true;
} }
Future<Profesional> uploadPdfIdentification( Future<Profesional> uploadPdfIdentification(Uint8List fileBytes, String userId) async {
Uint8List fileBytes, String userId) async { final url = await _api.upload(fileBytes, '${userId}_cedula.pdf');
try { if (url != null) copyProfesionalWith(identificationPicture: url);
final storageRef = FirebaseStorage.instance notifyListeners();
.ref() return profesional!;
.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( Future<Profesional> uploadPdfCertificate(Uint8List fileBytes, String userId) async {
Uint8List fileBytes, String userId) async { final url = await _api.upload(fileBytes, '${userId}_certificado.pdf');
try { if (url != null) copyProfesionalWith(certificatePicture: url);
final storageRef = FirebaseStorage.instance notifyListeners();
.ref() return profesional!;
.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( Future<Profesional> uploadPdfSpecializations(List<Uint8List> filesBytes, String userId) async {
List<Uint8List> filesBytes, String userId) async { List<String> urls = [];
try { for (int i = 0; i < filesBytes.length; i++) {
List<String> urls = []; final url = await _api.upload(filesBytes[i], '${userId}_especializacion_$i.pdf');
if (url != null) urls.add(url);
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;
} }
copyProfesionalWith(specializationsPictures: urls);
notifyListeners();
return profesional!;
} }
} }
+7 -16
View File
@@ -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:flutter/widgets.dart';
import 'package:prosapp_web_app/models/location_preferences.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/payment_method_entity.dart';
import 'package:prosapp_web_app/models/profesional.dart'; import 'package:prosapp_web_app/models/profesional.dart';
import 'package:prosapp_web_app/models/schedules.dart'; import 'package:prosapp_web_app/models/schedules.dart';
import 'package:prosapp_web_app/services/api_service.dart';
class ProfessionalProvider extends ChangeNotifier { class ProfessionalProvider extends ChangeNotifier {
Profesional? profesional; Profesional? profesional;
bool _isProModeActive = false; bool _isProModeActive = false;
final _api = ApiService.instance;
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; bool get isProModeActive => _isProModeActive;
bool get isProModeActive {
return _isProModeActive;
}
Future<Profesional> getProfessional(String uid) async { Future<Profesional> getProfessional(String uid) async {
try { try {
final professional = await FirebaseFirestore.instance final data = await _api.get('/professional-info/$uid');
.collection('professional_info') profesional = Profesional.fromDocument(data as Map<String, dynamic>);
.doc(uid)
.get();
profesional = Profesional.fromDocument(professional.data()!);
} catch (e) { } catch (e) {
profesional = Profesional( profesional = Profesional(
id: _firebaseAuth.currentUser!.uid, id: uid,
identification: '', identification: '',
address: '', address: '',
aditionalAddress: '', aditionalAddress: '',
@@ -45,12 +37,11 @@ class ProfessionalProvider extends ChangeNotifier {
paymentMethods: PaymentMethodEntity.empty, paymentMethods: PaymentMethodEntity.empty,
); );
} }
notifyListeners(); notifyListeners();
return profesional!; return profesional!;
} }
logout() { void logout() {
_isProModeActive = false; _isProModeActive = false;
notifyListeners(); notifyListeners();
} }
+5 -58
View File
@@ -1,14 +1,11 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.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/models/usuario_profesional.dart';
import 'package:prosapp_web_app/services/api_service.dart';
class ProfessionalsProvider extends ChangeNotifier { class ProfessionalsProvider extends ChangeNotifier {
List<UsuarioProfesional> professionals = []; List<UsuarioProfesional> professionals = [];
bool isLoading = true; bool isLoading = true;
final _api = ApiService.instance;
ProfessionalsProvider() { ProfessionalsProvider() {
getProfessionals(); getProfessionals();
@@ -16,42 +13,10 @@ class ProfessionalsProvider extends ChangeNotifier {
getProfessionals() async { getProfessionals() async {
try { try {
final querySnapshot = await FirebaseFirestore.instance final data = await _api.get('/users/professionals');
.collection('users') professionals = (data as List)
.where('professional_state', isEqualTo: ProState.active.index) .map((e) => UsuarioProfesional.fromDocument(e as Map<String, dynamic>))
.get();
final users = querySnapshot.docs
.map((e) => Usuario.fromDocument(e.data()))
.toList(); .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) { } catch (e) {
print('Error obteniendo profesionales: $e'); print('Error obteniendo profesionales: $e');
} finally { } finally {
@@ -59,22 +24,4 @@ class ProfessionalsProvider extends ChangeNotifier {
notifyListeners(); 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;
}
} }
+10 -12
View File
@@ -1,13 +1,11 @@
import 'package:flutter/material.dart'; 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/models/profession.dart';
import 'package:prosapp_web_app/services/api_service.dart';
class ProfessionsProvider extends ChangeNotifier { class ProfessionsProvider extends ChangeNotifier {
List<Profession> professions = []; List<Profession> professions = [];
bool isLoading = true; bool isLoading = true;
final _api = ApiService.instance;
final _professionsCollection =
FirebaseFirestore.instance.collection('professions');
ProfessionsProvider() { ProfessionsProvider() {
getProfessions(); getProfessions();
@@ -15,14 +13,14 @@ class ProfessionsProvider extends ChangeNotifier {
getProfessions() async { getProfessions() async {
try { try {
final documentSnapshot = final data = await _api.get('/professions');
await _professionsCollection.doc('professions').get(); if (data is List) {
professions = data.map((e) => Profession(name: e['name'] as String)).toList();
final data = documentSnapshot.data() as Map<String, dynamic>; } else if (data is Map && data['professions'] is List) {
professions = (data['professions'] as List)
professions = (data['professions'] as List<dynamic>) .map((e) => Profession(name: e as String))
.map((item) => Profession(name: item as String)) .toList();
.toList(); }
} catch (e) { } catch (e) {
print('Error obteniendo profesiones: $e'); print('Error obteniendo profesiones: $e');
} finally { } finally {
+20 -96
View File
@@ -1,18 +1,14 @@
import 'dart:typed_data'; 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:flutter/material.dart';
import 'package:prosapp_web_app/models/pro_state.dart'; import 'package:prosapp_web_app/models/pro_state.dart';
import 'package:prosapp_web_app/models/usuario.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'; import 'package:prosapp_web_app/services/notifications_service.dart';
class ProfileFormProvider extends ChangeNotifier { class ProfileFormProvider extends ChangeNotifier {
Usuario? user; Usuario? user;
GlobalKey<FormState> formKey = GlobalKey<FormState>(); GlobalKey<FormState> formKey = GlobalKey<FormState>();
final _api = ApiService.instance;
String? _verificationId;
void copyUserWith({ void copyUserWith({
String? id, String? id,
@@ -43,117 +39,45 @@ class ProfileFormProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
bool _validForm() { bool _validForm() => formKey.currentState!.validate();
return formKey.currentState!.validate();
}
Future<void> updateUserInfo() async { Future<void> updateUserInfo() async {
if (!_validForm()) return; if (!_validForm()) return;
await _api.patch('/users/me', user!.toDocument());
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'); NotificationsService.showSnackbar('Información actualizada');
} }
Future<void> updateUserInfoNoValid() async { Future<void> updateUserInfoNoValid() async {
final docUser = FirebaseFirestore.instance await _api.patch('/users/me', user!.toDocument());
.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'); NotificationsService.showSnackbar('Información actualizada');
} }
Future<Usuario> uploadPicture(Uint8List bytes) async { Future<Usuario> uploadPicture(Uint8List bytes) async {
try { final url = await _api.upload(bytes, 'profile_${user!.id}.jpg');
final storageRef = FirebaseStorage.instance if (url != null) copyUserWith(picture: url);
.ref() notifyListeners();
.child('${user!.id}/PP/${user!.id}_lead'); return user!;
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 { Future<void> signUpWithPhoneNumber(String phoneNumber) async {
try { try {
await FirebaseAuth.instance.verifyPhoneNumber( await _api.post('/auth/phone/link/send', {'phone': phoneNumber});
phoneNumber: phoneNumber, NotificationsService.showSnackbar('Código enviado al número $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) { } catch (e) {
NotificationsService.showSnackbar('Error al registrar con teléfono: $e'); NotificationsService.showSnackbar('Error al enviar código: $e');
} }
} }
Future<bool> linkPhoneNumberToExistingAccount( Future<bool> linkPhoneNumberToExistingAccount(String phoneNumber, String code) async {
String phoneNumber, String code) async {
try { try {
var phoneAuthCredential = PhoneAuthProvider.credential( await _api.post('/auth/phone/link/verify', {'phone': phoneNumber, 'code': code});
verificationId: _verificationId!, copyUserWith(phone: phoneNumber);
smsCode: code, notifyListeners();
); NotificationsService.showSnackbar('Número vinculado exitosamente');
return true;
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) { } catch (e) {
if (e is FirebaseAuthException && e.code == 'invalid-verification-code') { NotificationsService.showSnackbar('Código de verificación inválido');
NotificationsService.showSnackbar('Código de verificación inválido'); return false;
return false;
} else {
NotificationsService.showSnackbar('Error al vincular número: $e');
rethrow;
}
} }
} }
} }
+50 -308
View File
@@ -1,18 +1,15 @@
import 'package:flutter/material.dart'; 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.dart';
import 'package:prosapp_web_app/models/service_status.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/servicio_profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart'; import 'package:prosapp_web_app/models/usuario.dart';
import 'package:prosapp_web_app/services/api_service.dart';
class ServicesProvider extends ChangeNotifier { class ServicesProvider extends ChangeNotifier {
List<ServicioProfesional> services = []; List<ServicioProfesional> services = [];
ServicioProfesional? service; ServicioProfesional? service;
bool isLoading = true; bool isLoading = true;
final _api = ApiService.instance;
final _servicesCollection = FirebaseFirestore.instance.collection('services');
final _usersCollection = FirebaseFirestore.instance.collection('users');
void logout() { void logout() {
services = []; services = [];
@@ -21,43 +18,30 @@ class ServicesProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
Future<void> changeServiceStatus( Future<void> changeServiceStatus(String serviceId, ServiceStatus newStatus) async {
String serviceId, ServiceStatus newStatus) async {
try { try {
final statusValue = enumToIntService(newStatus); await _api.patch('/services/$serviceId', {'status': enumToIntService(newStatus)});
await FirebaseFirestore.instance
.collection('services')
.doc(serviceId)
.update({'status': statusValue});
notifyListeners(); notifyListeners();
} catch (e) { } catch (e) {
print('Error al actualizar el estado: $e'); print('Error al actualizar el estado: $e');
} }
} }
// cambiar el user_scored a true
Future<void> changeUserScored(String serviceId) async { Future<void> changeUserScored(String serviceId) async {
try { try {
await FirebaseFirestore.instance await _api.patch('/services/$serviceId', {'user_scored': true});
.collection('services')
.doc(serviceId)
.update({'user_scored': true});
notifyListeners(); notifyListeners();
} catch (e) { } 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 { Future<void> changeProfessionalScored(String serviceId) async {
try { try {
await FirebaseFirestore.instance await _api.patch('/services/$serviceId', {'professional_scored': true});
.collection('services')
.doc(serviceId)
.update({'professional_scored': true});
notifyListeners(); notifyListeners();
} catch (e) { } 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 { getServiceForUser(String serviceId) async {
try { try {
isLoading = true; isLoading = true;
final data = await _api.get('/services/$serviceId');
final queryService = await _servicesCollection.doc(serviceId).get(); final map = data as Map<String, dynamic>;
final servicio = Service.fromJson(map, map['id'] as String);
final servicio = Service.fromDocument(queryService); final userData = await _api.get('/users/${servicio.professionalId}');
final user = Usuario.fromDocument(userData as Map<String, dynamic>);
final queryUsers = service = ServicioProfesional(user: user, service: servicio);
await _usersCollection.doc(servicio.professionalId).get();
final user = Usuario.fromDocument(queryUsers.data()!);
service = ServicioProfesional(
user: user,
service: servicio,
);
} catch (e) { } catch (e) {
service = null; service = null;
} finally { } finally {
@@ -94,19 +70,12 @@ class ServicesProvider extends ChangeNotifier {
getServiceForProfessional(String serviceId) async { getServiceForProfessional(String serviceId) async {
try { try {
isLoading = true; isLoading = true;
final data = await _api.get('/services/$serviceId');
final queryService = await _servicesCollection.doc(serviceId).get(); final map = data as Map<String, dynamic>;
final servicio = Service.fromJson(map, map['id'] as String);
final servicio = Service.fromDocument(queryService); final userData = await _api.get('/users/${servicio.userId}');
final user = Usuario.fromDocument(userData as Map<String, dynamic>);
final queryUsers = await _usersCollection.doc(servicio.userId).get(); service = ServicioProfesional(user: user, service: servicio);
final user = Usuario.fromDocument(queryUsers.data()!);
service = ServicioProfesional(
user: user,
service: servicio,
);
} catch (e) { } catch (e) {
service = null; service = null;
} finally { } 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 { try {
isLoading = true; 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 final ids = servicios.map((s) => forUser ? s.professionalId : s.userId).toSet().toList();
.where('user_id', isEqualTo: userId) final users = await Future.wait(ids.map((id) async {
.where('status', whereIn: [0, 1, 3]).get(); 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(); services = servicios.map((s) {
final userId = forUser ? s.professionalId : s.userId;
final professionalIds = return ServicioProfesional(user: usersMap[userId]!, service: s);
servicios.map((service) => service.professionalId).toList(); }).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) { ..sort((a, b) {
final dateA = DateTime.parse(a.service.day); final dateA = DateTime.parse(a.service.day);
final dateB = DateTime.parse(b.service.day); final dateB = DateTime.parse(b.service.day);
final range1A = if (dateA != dateB) return dateA.compareTo(dateB);
a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute; final tA = a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
final range1B = final tB = b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute; return tA.compareTo(tB);
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) { } catch (e) {
print('Error obteniendo servicios: $e'); print('Error obteniendo servicios: $e');
+4 -5
View File
@@ -1,12 +1,11 @@
import 'package:flutter/material.dart'; 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/models/setting.dart';
import 'package:prosapp_web_app/services/api_service.dart';
class SettingsProvider extends ChangeNotifier { class SettingsProvider extends ChangeNotifier {
Setting? settings; Setting? settings;
bool isLoading = true; bool isLoading = true;
final _api = ApiService.instance;
final _settingsCollection = FirebaseFirestore.instance.collection('settings');
SettingsProvider() { SettingsProvider() {
getSettings(); getSettings();
@@ -14,8 +13,8 @@ class SettingsProvider extends ChangeNotifier {
getSettings() async { getSettings() async {
try { try {
final querySnapshot = await _settingsCollection.doc('global').get(); final data = await _api.get('/settings');
settings = Setting.fromDocument(querySnapshot.data()!); settings = Setting.fromDocument(data as Map<String, dynamic>);
} catch (e) { } catch (e) {
print('Error obteniendo los settings: $e'); print('Error obteniendo los settings: $e');
} finally { } finally {
+21 -30
View File
@@ -1,43 +1,34 @@
import 'dart:developer'; import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:prosapp_web_app/models/chat_entity.dart'; import 'package:prosapp_web_app/models/chat_entity.dart';
import 'package:prosapp_web_app/models/message_entity.dart'; import 'package:prosapp_web_app/models/message_entity.dart';
import 'package:prosapp_web_app/services/api_service.dart';
// ponytail: renamed to ApiChatRepository but kept filename to avoid breaking imports
class FirebaseChatRepository { class FirebaseChatRepository {
final chatCollection = FirebaseFirestore.instance.collection('chats'); final _api = ApiService.instance;
Stream<ChatEntity?> getChatById(String chatId) { Stream<ChatEntity?> getChatById(String chatId) async* {
return chatCollection.doc(chatId).snapshots().map((snapshot) { while (true) {
try { try {
if (snapshot.exists) { final data = await _api.get('/chats/$chatId');
return ChatEntity.fromDocument(snapshot.data()!); yield ChatEntity.fromDocument(data as Map<String, dynamic>);
} else { } catch (_) {
return null; yield null;
}
} catch (e) {
log(e.toString());
return null;
} }
}); await Future.delayed(const Duration(seconds: 3));
}
} }
Future<ChatEntity> createNewChat( Future<ChatEntity> createNewChat(String chatId, String userId, String professionalId) async {
String chatId, String userId, String professionalId) async { final data = await _api.post('/chats', {
ChatEntity chat = ChatEntity( 'id': chatId,
id: chatId, 'user_id': userId,
userId: userId, 'professional_id': professionalId,
professionalId: professionalId, });
messages: const [], return ChatEntity.fromDocument(data as Map<String, dynamic>);
);
await chatCollection.doc(chatId).set(chat.toDocument());
return chat;
} }
sendMessage(String chatId, MessageEntity message) { Future<void> sendMessage(String chatId, MessageEntity message) async {
chatCollection.doc(chatId).update({ await _api.post('/chats/$chatId/messages', message.toDocument());
'messages': FieldValue.arrayUnion([message.toDocument()])
});
} }
} }
+33 -72
View File
@@ -1,91 +1,52 @@
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/comment_entity.dart';
import 'package:prosapp_web_app/models/score_entity.dart'; import 'package:prosapp_web_app/models/score_entity.dart';
import 'package:prosapp_web_app/services/api_service.dart';
// ponytail: renamed to ApiScoreRepository but kept filename to avoid breaking imports
class FirebaseScoreRepository { class FirebaseScoreRepository {
final reputationsCollection = final _api = ApiService.instance;
FirebaseFirestore.instance.collection('reputations');
final commentsCollection = FirebaseFirestore.instance.collection('comments');
Future<ReputationEntity> getReputationByUserId(String userId) async { Future<ReputationEntity> getReputationByUserId(String userId) async {
try { try {
final snap = await reputationsCollection.doc(userId).get(); final data = await _api.get('/comments/reputation/$userId');
return ReputationEntity.fromDocument(snap.data()!); return ReputationEntity.fromDocument(data as Map<String, dynamic>);
} catch (e) { } catch (e) {
return const ReputationEntity( return const ReputationEntity(total: 0, average: 0, totalPro: 0, averagePro: 0);
total: 0,
average: 0,
totalPro: 0,
averagePro: 0,
);
} }
} }
Stream<ReputationEntity> streamReputation() { Stream<ReputationEntity> streamReputation(String userId) async* {
return FirebaseAuth.instance.userChanges().asyncMap((user) async { while (true) {
if (user != null) { yield await getReputationByUserId(userId);
return await getReputationByUserId(user.uid); await Future.delayed(const Duration(seconds: 10));
} else { }
return const ReputationEntity( }
total: 0,
average: 0, Stream<List<CommentEntity>> getScoresForUser(String userId) async* {
totalPro: 0, while (true) {
averagePro: 0, try {
); final data = await _api.get('/comments?destination_id=$userId&is_from_user=false') as List;
yield data.map((e) => CommentEntity.fromDocument(e as Map<String, dynamic>)).toList();
} catch (_) {
yield [];
} }
}); await Future.delayed(const Duration(seconds: 10));
}
} }
Stream<List<CommentEntity>> getScoresForUser(String userId) { Stream<List<CommentEntity>> getScoresForProfessional(String userId) async* {
return commentsCollection while (true) {
.where('destination_id', isEqualTo: userId) try {
.where('is_from_user', isEqualTo: false) final data = await _api.get('/comments?destination_id=$userId&is_from_user=true') as List;
.snapshots() yield data.map((e) => CommentEntity.fromDocument(e as Map<String, dynamic>)).toList();
.map((querySnapshot) => querySnapshot.docs } catch (_) {
.map((doc) => CommentEntity.fromDocument(doc.data())) yield [];
.toList()); }
} await Future.delayed(const Duration(seconds: 10));
}
Stream<List<CommentEntity>> getScoresForProfessional(String userId) {
return commentsCollection
.where('destination_id', isEqualTo: userId)
.where('is_from_user', isEqualTo: true)
.snapshots()
.map((querySnapshot) => querySnapshot.docs
.map((doc) => CommentEntity.fromDocument(doc.data()))
.toList());
} }
Future<void> addComment(CommentEntity comment) async { Future<void> addComment(CommentEntity comment) async {
await commentsCollection.add(comment.toDocument()); await _api.post('/comments', comment.toDocument());
final query = await commentsCollection
.where('destination_id', isEqualTo: comment.destinationId)
.where('is_from_user', isEqualTo: comment.isFromUser)
.get();
var total = 0.0;
var count = 0;
for (var doc in query.docs) {
final comment = CommentEntity.fromDocument(doc.data());
total += comment.score;
count++;
}
if (count > 0) {
final average = total / count;
if (comment.isFromUser) {
await reputationsCollection.doc(comment.destinationId).set(
{'total_pro': count, 'average_pro': average},
SetOptions(merge: true));
} else {
await reputationsCollection.doc(comment.destinationId).set({
'total': count,
'average': average,
}, SetOptions(merge: true));
}
}
} }
} }
+73
View File
@@ -0,0 +1,73 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:http/http.dart' as http;
import 'package:prosapp_web_app/services/local_storage.dart';
class ApiService {
ApiService._();
static final instance = ApiService._();
static String get baseUrl => dotenv.env['API_BASE_URL'] ?? 'https://backend.prosapp.co/api/v1';
Future<String?> getToken() => Future.value(LocalStorage.prefs.getString('jwt_token'));
Future<void> saveToken(String token) => LocalStorage.prefs.setString('jwt_token', token);
Future<void> deleteToken() => LocalStorage.prefs.remove('jwt_token');
Future<Map<String, String>> _headers() async {
final token = await getToken();
return {
'Content-Type': 'application/json',
if (token != null) 'Authorization': 'Bearer $token',
};
}
dynamic _parse(http.Response res) {
final body = jsonDecode(res.body);
if (res.statusCode >= 200 && res.statusCode < 300) return body;
throw Exception(body['message'] ?? 'Error ${res.statusCode}');
}
Future<dynamic> get(String path) async {
final res = await http.get(Uri.parse('$baseUrl$path'), headers: await _headers());
return _parse(res);
}
Future<dynamic> post(String path, Map<String, dynamic> body) async {
final res = await http.post(
Uri.parse('$baseUrl$path'),
headers: await _headers(),
body: jsonEncode(body),
);
return _parse(res);
}
Future<dynamic> patch(String path, Map<String, dynamic> body) async {
final res = await http.patch(
Uri.parse('$baseUrl$path'),
headers: await _headers(),
body: jsonEncode(body),
);
return _parse(res);
}
Future<dynamic> delete(String path) async {
final res = await http.delete(Uri.parse('$baseUrl$path'), headers: await _headers());
return _parse(res);
}
Future<String?> upload(Uint8List bytes, String filename) async {
final token = await getToken();
final req = http.MultipartRequest('POST', Uri.parse('$baseUrl/storage/upload'));
if (token != null) req.headers['Authorization'] = 'Bearer $token';
req.files.add(http.MultipartFile.fromBytes('file', bytes, filename: filename));
final streamed = await req.send();
final res = await http.Response.fromStream(streamed);
if (res.statusCode >= 200 && res.statusCode < 300) {
return (jsonDecode(res.body) as Map<String, dynamic>)['url'] as String?;
}
return null;
}
}
+5 -5
View File
@@ -1,5 +1,5 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:prosapp_web_app/providers/auth_provider.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:prosapp_web_app/models/message_entity.dart'; import 'package:prosapp_web_app/models/message_entity.dart';
@@ -131,13 +131,13 @@ class ChatView extends StatelessWidget {
padding: const EdgeInsets.only(top: 10), padding: const EdgeInsets.only(top: 10),
reverse: true, reverse: true,
child: Column( child: Column(
children: _messagesList(chat.messages), children: _messagesList(chat.messages, Provider.of<AuthProvider>(context, listen: false).user!.id),
), ),
), ),
), ),
_MessageInput( _MessageInput(
serviceId: serviceId, serviceId: serviceId,
userId: FirebaseAuth.instance.currentUser!.uid), userId: Provider.of<AuthProvider>(context, listen: false).user!.id),
], ],
), ),
), ),
@@ -163,10 +163,10 @@ class ChatView extends StatelessWidget {
return resultado; return resultado;
} }
List<Widget> _messagesList(List<MessageEntity> messages) { List<Widget> _messagesList(List<MessageEntity> messages, String currentUserId) {
return messages return messages
.map( .map(
(e) => e.ownerId != FirebaseAuth.instance.currentUser!.uid (e) => e.ownerId != currentUserId
? ListTile( ? ListTile(
title: Column( title: Column(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
+3 -6
View File
@@ -1,8 +1,7 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:prosapp_web_app/services/api_service.dart';
import 'package:prosapp_web_app/models/schedules_entity.dart'; import 'package:prosapp_web_app/models/schedules_entity.dart';
import 'package:prosapp_web_app/models/service.dart'; import 'package:prosapp_web_app/models/service.dart';
import 'package:prosapp_web_app/models/service_location_preferences.dart'; import 'package:prosapp_web_app/models/service_location_preferences.dart';
@@ -142,7 +141,7 @@ class _DashboardViewState extends State<DashboardView> {
latitude: latitude, latitude: latitude,
longitude: longitude, longitude: longitude,
day: selectedDay.toString(), day: selectedDay.toString(),
createdAt: Timestamp.now(), createdAt: DateTime.now().toIso8601String(),
description: '', description: '',
range1Hour1: selectedHour!, range1Hour1: selectedHour!,
range1Hour2: selectedHour!.add(hour: 2), range1Hour2: selectedHour!.add(hour: 2),
@@ -153,9 +152,7 @@ class _DashboardViewState extends State<DashboardView> {
print('debug 1'); print('debug 1');
await FirebaseFirestore.instance await ApiService.instance.post('/services', service.toDocument());
.collection('services')
.add(service.toDocument());
print('debug 2'); print('debug 2');
+3 -3
View File
@@ -64,7 +64,7 @@ class PhoneLoginView extends StatelessWidget {
showDialog( showDialog(
context: context, context: context,
builder: (context) => builder: (context) =>
_buildOtpModal(context, authProvider), _buildOtpModal(context, authProvider, phoneFormProvider.phone),
); );
} }
}, },
@@ -89,7 +89,7 @@ class PhoneLoginView extends StatelessWidget {
); );
} }
Widget _buildOtpModal(BuildContext context, AuthProvider authProvider) { Widget _buildOtpModal(BuildContext context, AuthProvider authProvider, String phone) {
final _otpController = TextEditingController(); final _otpController = TextEditingController();
return AlertDialog( return AlertDialog(
@@ -111,7 +111,7 @@ class PhoneLoginView extends StatelessWidget {
final otp = _otpController.text.trim(); final otp = _otpController.text.trim();
if (otp.isNotEmpty) { if (otp.isNotEmpty) {
await authProvider.signInWithOTP(otp); await authProvider.signInWithOTP(phone, otp);
Navigator.of(context).pop(); Navigator.of(context).pop();
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
+3 -3
View File
@@ -77,7 +77,7 @@ class PhoneView extends StatelessWidget {
showDialog( showDialog(
context: context, context: context,
builder: (context) => _buildOtpModal( builder: (context) => _buildOtpModal(
context, authProvider), context, authProvider, phoneFormProvider.phone),
); );
} }
}, },
@@ -102,7 +102,7 @@ class PhoneView extends StatelessWidget {
); );
} }
Widget _buildOtpModal(BuildContext context, AuthProvider authProvider) { Widget _buildOtpModal(BuildContext context, AuthProvider authProvider, String phone) {
final _otpController = TextEditingController(); final _otpController = TextEditingController();
return AlertDialog( return AlertDialog(
@@ -124,7 +124,7 @@ class PhoneView extends StatelessWidget {
final otp = _otpController.text.trim(); final otp = _otpController.text.trim();
if (otp.isNotEmpty) { if (otp.isNotEmpty) {
await authProvider.linkPhoneWithOTP(otp); await authProvider.linkPhoneWithOTP(phone, otp);
Navigator.of(context).pop(); Navigator.of(context).pop();
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
+3 -3
View File
@@ -1,4 +1,4 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/comment_entity.dart'; import 'package:prosapp_web_app/models/comment_entity.dart';
import 'package:prosapp_web_app/providers/score_provider.dart'; import 'package:prosapp_web_app/providers/score_provider.dart';
@@ -181,7 +181,7 @@ class _RatingViewState extends State<RatingView> {
score: _rating, score: _rating,
isFromUser: true, isFromUser: true,
serviceId: widget.serviceId, serviceId: widget.serviceId,
createdAt: Timestamp.now(), createdAt: DateTime.now().toIso8601String(),
authorId: service.userId, authorId: service.userId,
destinationId: service.professionalId, destinationId: service.professionalId,
); );
@@ -200,7 +200,7 @@ class _RatingViewState extends State<RatingView> {
score: _rating, score: _rating,
isFromUser: false, isFromUser: false,
serviceId: widget.serviceId, serviceId: widget.serviceId,
createdAt: Timestamp.now(), createdAt: DateTime.now().toIso8601String(),
authorId: service.professionalId, authorId: service.professionalId,
destinationId: service.userId, destinationId: service.userId,
); );
@@ -5,21 +5,13 @@
import FlutterMacOS import FlutterMacOS
import Foundation import Foundation
import cloud_firestore
import file_selector_macos import file_selector_macos
import firebase_auth
import firebase_core
import firebase_storage
import path_provider_foundation import path_provider_foundation
import shared_preferences_foundation import shared_preferences_foundation
import url_launcher_macos import url_launcher_macos
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FLTFirebaseFirestorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseFirestorePlugin"))
FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))
FLTFirebaseAuthPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseAuthPlugin"))
FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin"))
FLTFirebaseStoragePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseStoragePlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
-104
View File
@@ -1,14 +1,6 @@
# Generated by pub # Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile # See https://dart.dev/tools/pub/glossary#lockfile
packages: packages:
_flutterfire_internals:
dependency: transitive
description:
name: _flutterfire_internals
sha256: a315d1c444402c3fa468de626d33a1c666041c87e9e195e8fb355b7084aefcc1
url: "https://pub.dev"
source: hosted
version: "1.3.38"
async: async:
dependency: transitive dependency: transitive
description: description:
@@ -41,30 +33,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.2" version: "1.1.2"
cloud_firestore:
dependency: "direct main"
description:
name: cloud_firestore
sha256: "1232370ad04c21c699d0e73b2dc2e1c3b49258f89a16f0119036fd3c6e8aa2f5"
url: "https://pub.dev"
source: hosted
version: "5.0.2"
cloud_firestore_platform_interface:
dependency: transitive
description:
name: cloud_firestore_platform_interface
sha256: cfc64ae4a48bbb0ff6730b04f2d4653043c7a9b9008a991b1f2012a534b79e26
url: "https://pub.dev"
source: hosted
version: "6.2.8"
cloud_firestore_web:
dependency: transitive
description:
name: cloud_firestore_web
sha256: "3db4e4c10feae18d80da86982781578c8e76cb6a43cf83110d8d6a62af9a952a"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
collection: collection:
dependency: transitive dependency: transitive
description: description:
@@ -169,78 +137,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.9.3+1" version: "0.9.3+1"
firebase_auth:
dependency: "direct main"
description:
name: firebase_auth
sha256: "087fdcb54b0af6f4c5c756e1db4f90e9b65871b9b3a75fabaa0e0ee578301669"
url: "https://pub.dev"
source: hosted
version: "5.1.1"
firebase_auth_platform_interface:
dependency: transitive
description:
name: firebase_auth_platform_interface
sha256: "8fac689f71ac3489a785579e99a4bad24a93ad3d78c313fb786ee517012d25f1"
url: "https://pub.dev"
source: hosted
version: "7.4.1"
firebase_auth_web:
dependency: transitive
description:
name: firebase_auth_web
sha256: "486b2527fcfcab01278378d8d4791f4f7bee8a9f15bf35e801ba08fbdd84c234"
url: "https://pub.dev"
source: hosted
version: "5.12.3"
firebase_core:
dependency: "direct main"
description:
name: firebase_core
sha256: "1e06b0538ab3108a61d895ee16951670b491c4a94fce8f2d30e5de7a5eca4b28"
url: "https://pub.dev"
source: hosted
version: "3.1.1"
firebase_core_platform_interface:
dependency: transitive
description:
name: firebase_core_platform_interface
sha256: "1003a5a03a61fc9a22ef49f37cbcb9e46c86313a7b2e7029b9390cf8c6fc32cb"
url: "https://pub.dev"
source: hosted
version: "5.1.0"
firebase_core_web:
dependency: transitive
description:
name: firebase_core_web
sha256: "6643fe3dbd021e6ccfb751f7882b39df355708afbdeb4130fc50f9305a9d1a3d"
url: "https://pub.dev"
source: hosted
version: "2.17.2"
firebase_storage:
dependency: "direct main"
description:
name: firebase_storage
sha256: "01fdcef335d2c86a265e9eb3c5b3b489ddc5589e7fc18a74df84b31be9f0c15b"
url: "https://pub.dev"
source: hosted
version: "12.1.0"
firebase_storage_platform_interface:
dependency: transitive
description:
name: firebase_storage_platform_interface
sha256: "8fdbfc63af3441434f33a420a304a670b464ff71b8f12fccc80accba1378ca3b"
url: "https://pub.dev"
source: hosted
version: "5.1.25"
firebase_storage_web:
dependency: transitive
description:
name: firebase_storage_web
sha256: bb9a387ae26bf7358e118f191ee22167b30217cad551184592cc73e7f73bd470
url: "https://pub.dev"
source: hosted
version: "3.9.10"
fluro: fluro:
dependency: "direct main" dependency: "direct main"
description: description:
-4
View File
@@ -28,13 +28,9 @@ environment:
# the latest version available on pub.dev. To see which dependencies have newer # the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`. # versions available, run `flutter pub outdated`.
dependencies: dependencies:
cloud_firestore: ^5.0.2
cupertino_icons: ^1.0.6 cupertino_icons: ^1.0.6
email_validator: ^3.0.0 email_validator: ^3.0.0
file_picker: ^8.0.6 file_picker: ^8.0.6
firebase_auth: ^5.1.1
firebase_core: ^3.1.1
firebase_storage: ^12.1.0
fluro: ^2.0.5 fluro: ^2.0.5
flutter: flutter:
sdk: flutter sdk: flutter
@@ -6,24 +6,12 @@
#include "generated_plugin_registrant.h" #include "generated_plugin_registrant.h"
#include <cloud_firestore/cloud_firestore_plugin_c_api.h>
#include <file_selector_windows/file_selector_windows.h> #include <file_selector_windows/file_selector_windows.h>
#include <firebase_auth/firebase_auth_plugin_c_api.h>
#include <firebase_core/firebase_core_plugin_c_api.h>
#include <firebase_storage/firebase_storage_plugin_c_api.h>
#include <url_launcher_windows/url_launcher_windows.h> #include <url_launcher_windows/url_launcher_windows.h>
void RegisterPlugins(flutter::PluginRegistry* registry) { void RegisterPlugins(flutter::PluginRegistry* registry) {
CloudFirestorePluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("CloudFirestorePluginCApi"));
FileSelectorWindowsRegisterWithRegistrar( FileSelectorWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FileSelectorWindows")); registry->GetRegistrarForPlugin("FileSelectorWindows"));
FirebaseAuthPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FirebaseAuthPluginCApi"));
FirebaseCorePluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FirebaseCorePluginCApi"));
FirebaseStoragePluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FirebaseStoragePluginCApi"));
UrlLauncherWindowsRegisterWithRegistrar( UrlLauncherWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("UrlLauncherWindows")); registry->GetRegistrarForPlugin("UrlLauncherWindows"));
} }
-4
View File
@@ -3,11 +3,7 @@
# #
list(APPEND FLUTTER_PLUGIN_LIST list(APPEND FLUTTER_PLUGIN_LIST
cloud_firestore
file_selector_windows file_selector_windows
firebase_auth
firebase_core
firebase_storage
url_launcher_windows url_launcher_windows
) )