Files
prosappweb/lib/providers/auth_provider.dart
T
Lizandro GuarnizoandClaude Sonnet 4.6 0ecca498ad fix: align Flutter endpoints and model parsing with actual NestJS backend
- Auth: phone login → POST /auth/phone (direct, no OTP); link phone → POST /auth/verify-phone; add email → POST /auth/link-email
- Services: replace query-param paths with dedicated role endpoints (/services/me, /services/professional/requests, /services/professional, etc.)
- Services: PATCH /services/:id → PATCH /services/:id/status
- Calendar: → GET /services/professional/calendar
- Professionals: /users/professionals → /professionals (handles {data:[...]} response)
- Professional info: /professional-info/:id → /professionals/:id; PATCH → /professionals/me
- Comments: /comments?... → /comments/user/:id and /comments/professional/:id
- Chat: /chats → /chat; start chat → POST /chat/start/:professionalId; poll GET /chat/:chatId/messages; send → POST /chat/:chatId/message
- Cities: /cities → GET /locations/countries (parse nested countries→regions→cities)
- Profesional.fromDocument: null-safe fields; convert schedules array→Schedules, specializations array→name/picture lists, payment_methods object/array
- Usuario.fromDocument: null-safe professional_state and id
- UsuarioProfesional.fromDocument: handle backend format (users nested, professional at top level)
- ScheduleEntity.parseTime: handle ISO8601 time strings from backend
- MessageEntity.fromDocument: accept sender_id (backend) or owner_id (legacy)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 16:07:44 -05:00

159 lines
5.4 KiB
Dart

import 'package:flutter/material.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';
enum AuthStatus { checking, authenticated, notAuthenticated }
class AuthProvider extends ChangeNotifier {
Usuario? user;
double userAverageScore = 0.0;
AuthStatus authStatus = AuthStatus.checking;
final _api = ApiService.instance;
AuthProvider() {
isAuthenticated();
}
Future<void> login(String email, String password) async {
try {
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');
}
}
Future<void> register(String email, String password, String name) async {
try {
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 {
// ponytail: backend does direct login by phone, no OTP step
}
Future<void> signInWithOTP(String phoneNumber, String smsCode) async {
try {
final data = await _api.post('/auth/phone', {'phone': phoneNumber});
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('Error al iniciar sesión con teléfono');
}
}
Future<void> verifyPhoneNumberForLink(String phoneNumber) async {
// ponytail: no OTP step, linkPhoneWithOTP does the actual call
}
Future<void> linkPhoneWithOTP(String phoneNumber, String smsCode) async {
try {
await _api.post('/auth/verify-phone', {'phone': phoneNumber});
user = await _fetchMe();
NotificationsService.showSnackbar('Número vinculado exitosamente');
authStatus = AuthStatus.authenticated;
notifyListeners();
NavigationService.replaceTo(Flurorouter.profileRoute);
} catch (e) {
NotificationsService.showSnackBarError('Error al vincular teléfono');
}
}
Future<void> addEmailAndPassword(String email, String password) async {
try {
await _api.post('/auth/link-email', {'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 token = await _api.getToken();
if (token == null) {
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
return false;
}
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;
} catch (e) {
await _api.deleteToken();
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
return false;
}
}
Future<void> logout() async {
await _api.deleteToken();
authStatus = AuthStatus.notAuthenticated;
user = null;
notifyListeners();
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();
Future<Usuario> _fetchMe() async {
final data = await _api.get('/auth/me');
return Usuario.fromDocument(data as Map<String, dynamic>);
}
Future<double> _loadAverageScore(String userId) async {
try {
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;
}
}
}