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>
This commit is contained in:
Lizandro Guarnizo
2026-06-18 16:07:44 -05:00
co-authored by Claude Sonnet 4.6
parent 60216fd0e3
commit 0ecca498ad
17 changed files with 183 additions and 101 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ class MessageEntity {
static MessageEntity fromDocument(Map<String, dynamic> doc) {
return MessageEntity(
ownerId: doc['owner_id'] as String,
ownerId: (doc['sender_id'] ?? doc['owner_id']) as String,
content: doc['content'] as String,
createdAt: DateTime.parse(doc['created_at'] as String),
);
+74 -17
View File
@@ -1,6 +1,7 @@
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/schedules.dart';
import 'package:prosapp_web_app/models/schedules_entity.dart';
class Profesional {
final String id;
@@ -42,25 +43,81 @@ class Profesional {
});
static Profesional fromDocument(Map<String, dynamic> doc) {
// Backend returns schedules as array [{day_of_week, enabled, ...}]; convert to Schedules
Schedules parsedSchedules = Schedules.empty;
final rawSchedules = doc['schedules'];
if (rawSchedules is List && rawSchedules.isNotEmpty) {
final days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
final map = <int, Map<String, dynamic>>{};
for (final s in rawSchedules) {
map[(s['day_of_week'] as int)] = s as Map<String, dynamic>;
}
ScheduleEntity _se(int day) {
final s = map[day];
if (s == null) return ScheduleEntity.empty;
return ScheduleEntity(
enabled: (s['enabled'] as bool?) ?? false,
continuousDay: (s['continuous_day'] as bool?) ?? false,
range1Hour1: ScheduleEntity.parseTime(s['range1_hour1']?.toString()),
range1Hour2: ScheduleEntity.parseTime(s['range1_hour2']?.toString()),
range2Hour1: ScheduleEntity.parseTime(s['range2_hour1']?.toString()),
range2Hour2: ScheduleEntity.parseTime(s['range2_hour2']?.toString()),
);
}
parsedSchedules = Schedules(
monday: _se(0), tuesday: _se(1), wednesday: _se(2), thursday: _se(3),
friday: _se(4), saturday: _se(5), sunday: _se(6),
);
} else if (rawSchedules is Map) {
parsedSchedules = Schedules.fromDocument(rawSchedules as Map<String, dynamic>);
}
// Specializations: array of objects [{name, picture}] or list of strings
List<String> specs = [];
List<String> specPics = [];
final rawSpecs = doc['specializations'];
if (rawSpecs is List) {
for (final s in rawSpecs) {
if (s is Map) {
specs.add((s['name'] as String?) ?? '');
specPics.add((s['picture'] as String?) ?? '');
} else {
specs.add(s.toString());
}
}
}
final rawSpecPics = doc['specializations_pictures'];
if (specPics.isEmpty && rawSpecPics is List) {
specPics = List<String>.from(rawSpecPics);
}
// payment_methods: object {nequi, datafono, transferencia} or array with one element or null
PaymentMethodEntity pm = PaymentMethodEntity.empty;
final rawPm = doc['payment_methods'];
if (rawPm is Map<String, dynamic>) {
pm = PaymentMethodEntity.fromDocument(rawPm);
} else if (rawPm is List && rawPm.isNotEmpty) {
pm = PaymentMethodEntity.fromDocument(rawPm.first as Map<String, dynamic>);
}
return Profesional(
id: doc['id'] as String,
identification: doc['identification'] as String,
address: doc['address'] as String,
aditionalAddress: doc['aditional_address'] as String,
profession: doc['profession'] as String,
ratePreferences: doc['rate_preferences'] as bool,
rate: doc['rate'] as String,
locationPreferences: intToEnum(doc['location_preferences'] as int),
bannerPicture: doc['banner_picture'] as String,
identificationPicture: doc['identification_picture'] as String,
certificatePicture: doc['certificate_picture'] as String,
latitude: double.parse(doc['latitude'].toString()),
longitude: double.parse(doc['longitude'].toString()),
specializations: List<String>.from(doc['specializations']),
specializationsPictures:
List<String>.from(doc['specializations_pictures']),
schedules: Schedules.fromDocument(doc['schedules']),
paymentMethods: PaymentMethodEntity.fromDocument(doc['payment_methods']),
identification: (doc['identification'] as String?) ?? '',
address: (doc['address'] as String?) ?? '',
aditionalAddress: (doc['aditional_address'] as String?) ?? '',
profession: (doc['profession'] as String?) ?? '',
ratePreferences: (doc['rate_preferences'] as bool?) ?? false,
rate: (doc['rate'] as String?) ?? '',
locationPreferences: intToEnum((doc['location_preferences'] as int?) ?? 0),
bannerPicture: (doc['banner_picture'] as String?) ?? '',
identificationPicture: (doc['identification_picture'] as String?) ?? '',
certificatePicture: (doc['certificate_picture'] as String?) ?? '',
latitude: (doc['latitude'] as num?)?.toDouble() ?? 0.0,
longitude: (doc['longitude'] as num?)?.toDouble() ?? 0.0,
specializations: specs,
specializationsPictures: specPics,
schedules: parsedSchedules,
paymentMethods: pm,
);
}
+10 -12
View File
@@ -49,23 +49,21 @@ class ScheduleEntity {
return ScheduleEntity(
enabled: doc['habilitado'] as bool,
continuousDay: doc['continuous_day'] as bool,
range1Hour1: _parseTime(doc['range1Hour1']),
range1Hour2: _parseTime(doc['range1Hour2']),
range2Hour1: _parseTime(doc['range2Hour1']),
range2Hour2: _parseTime(doc['range2Hour2']),
range1Hour1: parseTime(doc['range1Hour1']),
range1Hour2: parseTime(doc['range1Hour2']),
range2Hour1: parseTime(doc['range2Hour1']),
range2Hour2: parseTime(doc['range2Hour2']),
);
}
static TimeOfDay? _parseTime(String? time) {
static TimeOfDay? parseTime(String? time) {
try {
if (time == null) return null;
final components = time.split(':');
if (components.length != 2) {
return null;
}
final hour = int.parse(components[0]);
final minutes = int.parse(components[1]);
return TimeOfDay(hour: hour, minute: minutes);
// Handle ISO8601 from backend (e.g. "1970-01-01T08:30:00.000Z")
final t = time.contains('T') ? time.split('T')[1] : time;
final components = t.split(':');
if (components.length < 2) return null;
return TimeOfDay(hour: int.parse(components[0]), minute: int.parse(components[1]));
} catch (e) {
return null;
}
+2 -2
View File
@@ -45,7 +45,7 @@ class Usuario {
static Usuario fromDocument(Map<String, dynamic> doc) {
return Usuario(
id: doc['id'],
id: (doc['id'] as String?) ?? '',
email: doc['email'],
phone: doc['phone'],
name: doc['name'] ?? '',
@@ -54,7 +54,7 @@ class Usuario {
picture: doc['picture'],
birthday: doc['birthday'],
gender: doc['gender'],
proState: intToEnum(doc['professional_state'] as int),
proState: intToEnum((doc['professional_state'] as int?) ?? 0),
token: doc['token'],
);
}
+8 -2
View File
@@ -30,9 +30,15 @@ class UsuarioProfesional {
}
static UsuarioProfesional fromDocument(Map<String, dynamic> doc) {
// Backend from /professionals returns professional at top level with 'users' nested
// Legacy format uses 'user' and 'professional_info' keys
final userDoc = (doc['users'] ?? doc['user']) as Map<String, dynamic>?;
final proDoc = doc.containsKey('professional_info')
? doc['professional_info'] as 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>),
user: Usuario.fromDocument(userDoc ?? {}),
professionalInfo: Profesional.fromDocument(proDoc),
averageScore: (doc['average_score'] as num?)?.toDouble() ?? 0.0,
);
}
+7 -23
View File
@@ -57,20 +57,12 @@ class AuthProvider extends ChangeNotifier {
}
Future<void> verifyPhoneNumber(String phoneNumber) async {
try {
await _api.post('/auth/phone/send', {'phone': phoneNumber});
notifyListeners();
} catch (e) {
NotificationsService.showSnackBarError('Error al enviar OTP');
}
// 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/verify', {
'phone': phoneNumber,
'code': smsCode,
});
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;
@@ -79,38 +71,30 @@ class AuthProvider extends ChangeNotifier {
} catch (e) {
authStatus = AuthStatus.notAuthenticated;
notifyListeners();
NotificationsService.showSnackBarError('Error en la verificación OTP');
NotificationsService.showSnackBarError('Error al iniciar sesión con teléfono');
}
}
Future<void> verifyPhoneNumberForLink(String phoneNumber) async {
try {
await _api.post('/auth/phone/link/send', {'phone': phoneNumber});
notifyListeners();
} catch (e) {
NotificationsService.showSnackBarError('Error al enviar OTP');
}
// ponytail: no OTP step, linkPhoneWithOTP does the actual call
}
Future<void> linkPhoneWithOTP(String phoneNumber, String smsCode) async {
try {
await _api.post('/auth/phone/link/verify', {
'phone': phoneNumber,
'code': smsCode,
});
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 en la verificación OTP');
NotificationsService.showSnackBarError('Error al vincular teléfono');
}
}
Future<void> addEmailAndPassword(String email, String password) async {
try {
await _api.patch('/users/me', {'email': email, 'password': password});
await _api.post('/auth/link-email', {'email': email, 'password': password});
user = await _fetchMe();
notifyListeners();
NotificationsService.showSnackbar('Email y contraseña añadidos exitosamente');
@@ -20,7 +20,7 @@ class CalendarServicesProvider extends ChangeNotifier {
getServicesForProfessional(String userId) async {
try {
isLoading = true;
final data = await _api.get('/services?professional_id=$userId&status=1,3') as List;
final data = await _api.get('/services/professional/calendar') as List;
final servicios = data.map((e) {
final m = e as Map<String, dynamic>;
return Service.fromJson(m, m['id'] as String);
+2 -2
View File
@@ -10,8 +10,8 @@ class ChatProvider with ChangeNotifier {
ChatEntity? _currentChat;
ChatEntity? get currentChat => _currentChat;
Stream<ChatEntity?> getChat(String chatId) {
return _firebaseChatRepository.getChatById(chatId).map((chat) {
Stream<ChatEntity?> getChat(String chatId, String professionalId) {
return _firebaseChatRepository.getChatById(chatId, professionalId).map((chat) {
_currentChat = chat;
notifyListeners();
return chat;
+20 -11
View File
@@ -20,17 +20,26 @@ class CitiesProvider extends ChangeNotifier {
getCities() async {
try {
final data = await _api.get('/cities') as List;
cities = data.map((e) {
final m = e as Map<String, dynamic>;
return City(
cityName: m['name'] as String,
coordsOfCity: m['coords'] as String? ?? '',
stateOfCity: m['state'] as String? ?? '',
countryOfCity: m['country'] as String? ?? 'Colombia',
);
}).toList();
cities.sort((a, b) => a.cityName.compareTo(b.cityName));
// GET /locations/countries returns nested {regions: [{cities: [...]}]}
final countries = await _api.get('/locations/countries') as List;
final result = <City>[];
for (final country in countries) {
final countryName = country['name'] as String? ?? 'Colombia';
for (final region in (country['regions'] as List? ?? [])) {
final regionName = region['name'] as String? ?? '';
for (final c in (region['cities'] as List? ?? [])) {
final lat = (c['latitude'] as num?)?.toDouble() ?? 0.0;
final lng = (c['longitude'] as num?)?.toDouble() ?? 0.0;
result.add(City(
cityName: c['name'] as String,
coordsOfCity: lat != 0.0 ? '$lat,$lng' : '',
stateOfCity: regionName,
countryOfCity: countryName,
));
}
}
}
cities = result..sort((a, b) => a.cityName.compareTo(b.cityName));
} catch (e) {
print('Error obteniendo ciudades: $e');
} finally {
@@ -17,7 +17,7 @@ class ProfessionalDetailProvider extends ChangeNotifier {
final userData = await _api.get('/users/$uid');
final user = Usuario.fromDocument(userData as Map<String, dynamic>);
final proData = await _api.get('/professional-info/$uid');
final proData = await _api.get('/professionals/$uid');
final professionalInfo = Profesional.fromDocument(proData as Map<String, dynamic>);
final repData = await _api.get('/comments/reputation/$uid');
@@ -64,20 +64,20 @@ class ProfessionalFormProvider with ChangeNotifier {
Future<bool> updateProfesionalInfo(String userId) async {
if (!_validForm()) return false;
await _api.patch('/professional-info/$userId', profesional!.toDocument());
await _api.patch('/professionals/me', profesional!.toDocument());
NotificationsService.showSnackbar('Información actualizada');
return true;
}
Future<bool> updateProfesionalProfileInfo(String userId) async {
if (!_validProfileForm()) return false;
await _api.patch('/professional-info/$userId', profesional!.toDocument());
await _api.patch('/professionals/me', profesional!.toDocument());
NotificationsService.showSnackbar('Información actualizada');
return true;
}
Future<bool> updateProfesionalProfileScheduleInfo(String userId) async {
await _api.patch('/professional-info/$userId', profesional!.toDocument());
await _api.patch('/professionals/me', profesional!.toDocument());
NotificationsService.showSnackbar('Información actualizada');
return true;
}
+1 -1
View File
@@ -14,7 +14,7 @@ class ProfessionalProvider extends ChangeNotifier {
Future<Profesional> getProfessional(String uid) async {
try {
final data = await _api.get('/professional-info/$uid');
final data = await _api.get('/professionals/$uid');
profesional = Profesional.fromDocument(data as Map<String, dynamic>);
} catch (e) {
profesional = Profesional(
+3 -2
View File
@@ -13,8 +13,9 @@ class ProfessionalsProvider extends ChangeNotifier {
getProfessionals() async {
try {
final data = await _api.get('/users/professionals');
professionals = (data as List)
final res = await _api.get('/professionals');
final list = (res is Map ? res['data'] : res) as List;
professionals = list
.map((e) => UsuarioProfesional.fromDocument(e as Map<String, dynamic>))
.toList();
} catch (e) {
+8 -8
View File
@@ -20,7 +20,7 @@ class ServicesProvider extends ChangeNotifier {
Future<void> changeServiceStatus(String serviceId, ServiceStatus newStatus) async {
try {
await _api.patch('/services/$serviceId', {'status': enumToIntService(newStatus)});
await _api.patch('/services/$serviceId/status', {'status': enumToIntService(newStatus)});
notifyListeners();
} catch (e) {
print('Error al actualizar el estado: $e');
@@ -29,7 +29,7 @@ class ServicesProvider extends ChangeNotifier {
Future<void> changeUserScored(String serviceId) async {
try {
await _api.patch('/services/$serviceId', {'user_scored': true});
await _api.patch('/services/$serviceId/status', {'user_scored': true});
notifyListeners();
} catch (e) {
print('Error al actualizar user_scored: $e');
@@ -38,7 +38,7 @@ class ServicesProvider extends ChangeNotifier {
Future<void> changeProfessionalScored(String serviceId) async {
try {
await _api.patch('/services/$serviceId', {'professional_scored': true});
await _api.patch('/services/$serviceId/status', {'professional_scored': true});
notifyListeners();
} catch (e) {
print('Error al actualizar professional_scored: $e');
@@ -84,15 +84,15 @@ class ServicesProvider extends ChangeNotifier {
}
}
getServicesForUser(String userId) async => _loadServices('/services?user_id=$userId&status=0,1,3', forUser: true);
getServicesForUser(String userId) async => _loadServices('/services/me', forUser: true);
getServicesRequestsForProfessional(String userId) async => _loadServices('/services?professional_id=$userId&status=0', forUser: false);
getServicesRequestsForProfessional(String userId) async => _loadServices('/services/professional/requests', forUser: false);
getServicesForProfessional(String userId) async => _loadServices('/services?professional_id=$userId&status=1,3', forUser: false);
getServicesForProfessional(String userId) async => _loadServices('/services/professional', forUser: false);
getServicesHistoryForUser(String userId) async => _loadServices('/services?user_id=$userId&status=2,4,5', forUser: true);
getServicesHistoryForUser(String userId) async => _loadServices('/services/me/history', forUser: true);
getServicesHistoryForProfessional(String userId) async => _loadServices('/services?professional_id=$userId&status=2,4,5', forUser: false);
getServicesHistoryForProfessional(String userId) async => _loadServices('/services/professional/history', forUser: false);
Future<void> _loadServices(String path, {required bool forUser}) async {
try {
+39 -12
View File
@@ -3,15 +3,36 @@ import 'package:prosapp_web_app/models/chat_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
// ponytail: kept filename to avoid breaking imports
class FirebaseChatRepository {
final _api = ApiService.instance;
Stream<ChatEntity?> getChatById(String chatId) async* {
Stream<ChatEntity?> getChatById(String serviceId, String professionalId) async* {
String? chatId;
while (true) {
try {
final data = await _api.get('/chats/$chatId');
yield ChatEntity.fromDocument(data as Map<String, dynamic>);
if (chatId == null) {
// Create/get the chat first; backend identifies chats by professional user ID
final chatData = await _api.post('/chat/start/$professionalId', {});
chatId = chatData['id'] as String;
final messages = _parseMessages(chatData['messages']);
yield ChatEntity(
id: chatId,
userId: chatData['user_id'] as String,
professionalId: chatData['professional_id'] as String,
messages: messages,
);
} else {
final res = await _api.get('/chat/$chatId/messages');
final list = (res is Map ? res['data'] : res) as List;
final messages = list.map((e) => MessageEntity.fromDocument(e as Map<String, dynamic>)).toList();
yield ChatEntity(
id: chatId,
userId: '',
professionalId: professionalId,
messages: messages,
);
}
} catch (_) {
yield null;
}
@@ -19,16 +40,22 @@ class FirebaseChatRepository {
}
}
Future<ChatEntity> createNewChat(String chatId, String userId, String professionalId) async {
final data = await _api.post('/chats', {
'id': chatId,
'user_id': userId,
'professional_id': professionalId,
});
return ChatEntity.fromDocument(data as Map<String, dynamic>);
Future<ChatEntity> createNewChat(String serviceId, String userId, String professionalId) async {
final data = await _api.post('/chat/start/$professionalId', {});
return ChatEntity(
id: data['id'] as String,
userId: data['user_id'] as String,
professionalId: data['professional_id'] as String,
messages: _parseMessages(data['messages']),
);
}
Future<void> sendMessage(String chatId, MessageEntity message) async {
await _api.post('/chats/$chatId/messages', message.toDocument());
await _api.post('/chat/$chatId/message', {'content': message.content});
}
List<MessageEntity> _parseMessages(dynamic raw) {
if (raw is! List) return [];
return raw.map((e) => MessageEntity.fromDocument(e as Map<String, dynamic>)).toList();
}
}
@@ -25,7 +25,7 @@ class FirebaseScoreRepository {
Stream<List<CommentEntity>> getScoresForUser(String userId) async* {
while (true) {
try {
final data = await _api.get('/comments?destination_id=$userId&is_from_user=false') as List;
final data = await _api.get('/comments/user/$userId') as List;
yield data.map((e) => CommentEntity.fromDocument(e as Map<String, dynamic>)).toList();
} catch (_) {
yield [];
@@ -37,7 +37,7 @@ class FirebaseScoreRepository {
Stream<List<CommentEntity>> getScoresForProfessional(String userId) async* {
while (true) {
try {
final data = await _api.get('/comments?destination_id=$userId&is_from_user=true') as List;
final data = await _api.get('/comments/professional/$userId') as List;
yield data.map((e) => CommentEntity.fromDocument(e as Map<String, dynamic>)).toList();
} catch (_) {
yield [];
+1 -1
View File
@@ -32,7 +32,7 @@ class ChatView extends StatelessWidget {
scoreProvider.loadReputation(professionalId);
return StreamBuilder(
stream: chatProvider.getChat(serviceId),
stream: chatProvider.getChat(serviceId, professionalId),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());