fix: repair the booking flow end to end
Verified the real contracts against the backend before changing anything.
Chat (three defects, one root cause):
- every chat endpoint is keyed by the chat id, not the service id. The app
called POST /chat/start, threw away the id it returned and kept using the
service id, so every later request 404'd.
- messages arrive as {data, meta}; reading the body as a bare list threw and
surfaced as an empty conversation.
- the bloc created the chat and then never emitted ChatLoaded (the else hung
off `if (chat == null)`), leaving a permanent spinner. Sending a message
emitted nothing at all, so it vanished until reopening.
Messages now render optimistically and roll back if the send fails, and the
screen distinguishes "loading" from "could not open" with a retry.
Appointments:
- a null range1_hour2 parsed as 00:00, so new appointments were born
"Caducado" and every action was hidden. It now falls back to the start time.
- service requests validate the HTTP status and tolerate an empty body: a 4xx
was treated as success and a 204 as failure.
- creating a service with no id in the response no longer reports success and
navigates to a service that does not exist.
- dispatching LoadService from build() looped forever on failure; the three
detail screens now load once and offer a retry.
Ratings:
- both sides read userScored, so only one of the two could ever rate. The
client side now reads professionalScored.
- the screen closed before the request finished, killing the provider mid
flight while addComment swallowed every error. It now waits for confirmation.
- score/reputation parsing tolerates integers and numeric strings instead of
emptying the review list.
Also: guarded map lookups in ScoreBloc, a nullable name in the search list,
and error states with retry where a failure used to shimmer forever.
Verified against the backend: `accepted` is the status the API expects, so the
suspected spelling bug was a false alarm and was left alone.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
8c6e2ae024
commit
389f876cfa
@@ -29,8 +29,10 @@ class ApiChatRepository {
|
||||
|
||||
ChatEntity _chatFromApi(Map<String, dynamic> json) {
|
||||
final rawMessages = json['messages'] as List? ?? [];
|
||||
// _msgFromApi, not MessageEntity.fromDocument: the backend sends
|
||||
// `sender_id` while fromDocument hard-casts `owner_id`.
|
||||
final messages = rawMessages
|
||||
.map((m) => MessageEntity.fromDocument(m as Map<String, dynamic>))
|
||||
.map((m) => _msgFromApi(m as Map<String, dynamic>))
|
||||
.toList();
|
||||
return ChatEntity(
|
||||
id: json['id']?.toString(),
|
||||
@@ -52,59 +54,68 @@ class ApiChatRepository {
|
||||
);
|
||||
}
|
||||
|
||||
/// Get or create a chat session. Maps to POST /chat/start/:professionalUserId.
|
||||
/// [chatId] here is used as the professional's userId for the REST call.
|
||||
Future<ChatEntity> createNewChat(
|
||||
String chatId, String userId, String professionalId) async {
|
||||
final res = await http.post(
|
||||
Uri.parse('$_base/chat/start/$professionalId'),
|
||||
headers: await _headers(),
|
||||
).timeout(_kHttpTimeout);
|
||||
final data = jsonDecode(res.body) as Map<String, dynamic>;
|
||||
return _chatFromApi(data);
|
||||
}
|
||||
|
||||
/// Streams a single chat by its ID. Fetches once and emits.
|
||||
Stream<ChatEntity?> getChatById(String chatId) {
|
||||
final controller = StreamController<ChatEntity?>();
|
||||
_fetchChat(chatId).then((chat) {
|
||||
controller.add(chat);
|
||||
controller.close();
|
||||
}).catchError((e) {
|
||||
controller.add(null);
|
||||
controller.close();
|
||||
});
|
||||
return controller.stream;
|
||||
}
|
||||
|
||||
Future<ChatEntity?> _fetchChat(String chatId) async {
|
||||
try {
|
||||
// Try to get messages for this chat — if the chat exists it'll succeed
|
||||
final res = await http.get(
|
||||
Uri.parse('$_base/chat/$chatId/messages'),
|
||||
headers: await _headers(),
|
||||
).timeout(_kHttpTimeout);
|
||||
if (res.statusCode == 404) return null;
|
||||
final messages = jsonDecode(res.body) as List? ?? [];
|
||||
return ChatEntity(
|
||||
id: chatId,
|
||||
userId: '',
|
||||
professionalId: '',
|
||||
messages: messages
|
||||
.map((m) => _msgFromApi(m as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
/// Opens the conversation with a professional, creating it if needed.
|
||||
///
|
||||
/// `POST /chat/start/:professionalUserId` is idempotent: calling it again
|
||||
/// returns the same chat. The returned `id` is the **chat** id, which is what
|
||||
/// every other chat endpoint is keyed by — not the service id.
|
||||
Future<ChatEntity> startChat(String professionalUserId) async {
|
||||
final res = await http
|
||||
.post(
|
||||
Uri.parse('$_base/chat/start/$professionalUserId'),
|
||||
headers: await _headers(),
|
||||
)
|
||||
.timeout(_kHttpTimeout);
|
||||
if (res.statusCode >= 400) {
|
||||
throw Exception('No se pudo abrir el chat (${res.statusCode})');
|
||||
}
|
||||
return _chatFromApi(jsonDecode(res.body) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<void> sendMessage(String chatId, MessageEntity message) async {
|
||||
await http.post(
|
||||
Uri.parse('$_base/chat/$chatId/message'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode({'content': message.content}),
|
||||
).timeout(_kHttpTimeout);
|
||||
/// Loads the conversation plus its messages, ready to render.
|
||||
Future<ChatEntity> loadConversation(String professionalUserId) async {
|
||||
final chat = await startChat(professionalUserId);
|
||||
final messages = await fetchMessages(chat.id ?? '');
|
||||
return ChatEntity(
|
||||
id: chat.id,
|
||||
userId: chat.userId,
|
||||
professionalId: chat.professionalId,
|
||||
messages: messages,
|
||||
);
|
||||
}
|
||||
|
||||
/// Messages come back wrapped as `{ "data": [...], "meta": {...} }`.
|
||||
/// Reading the body as a bare list threw and surfaced as an empty chat.
|
||||
Future<List<MessageEntity>> fetchMessages(String chatId) async {
|
||||
final res = await http
|
||||
.get(
|
||||
Uri.parse('$_base/chat/$chatId/messages'),
|
||||
headers: await _headers(),
|
||||
)
|
||||
.timeout(_kHttpTimeout);
|
||||
if (res.statusCode >= 400) {
|
||||
throw Exception('No se pudieron cargar los mensajes (${res.statusCode})');
|
||||
}
|
||||
final body = jsonDecode(res.body);
|
||||
final raw = body is Map ? (body['data'] as List? ?? []) : (body as List? ?? []);
|
||||
return raw
|
||||
.map((m) => _msgFromApi(m as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Posts a message and returns it as stored by the backend.
|
||||
Future<MessageEntity> sendMessage(String chatId, MessageEntity message) async {
|
||||
final res = await http
|
||||
.post(
|
||||
Uri.parse('$_base/chat/$chatId/message'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode({'content': message.content}),
|
||||
)
|
||||
.timeout(_kHttpTimeout);
|
||||
if (res.statusCode >= 400) {
|
||||
throw Exception('No se pudo enviar el mensaje (${res.statusCode})');
|
||||
}
|
||||
return _msgFromApi(jsonDecode(res.body) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
/// Get all chats for the current user.
|
||||
|
||||
@@ -21,12 +21,16 @@ class CommentEntity extends Equatable {
|
||||
|
||||
static CommentEntity fromDocument(Map<String, dynamic> doc) {
|
||||
return CommentEntity(
|
||||
authorId: doc['author_id'] as String,
|
||||
destinationId: doc['destination_id'] as String,
|
||||
serviceId: doc['service_id'] as String,
|
||||
content: doc['content'] as String,
|
||||
score: doc['score'] as double,
|
||||
isFromUser: doc['is_from_user'] as bool,
|
||||
// Tolerant on purpose: a whole-number score arrives as `5`, and
|
||||
// Postgres numerics can arrive as strings. Hard casts here emptied the
|
||||
// whole review list, which then read as "no reviews yet".
|
||||
authorId: doc['author_id']?.toString() ?? '',
|
||||
destinationId: doc['destination_id']?.toString() ?? '',
|
||||
serviceId: doc['service_id']?.toString() ?? '',
|
||||
content: doc['content']?.toString() ?? '',
|
||||
score: double.tryParse(doc['score']?.toString() ?? '') ?? 0.0,
|
||||
isFromUser: doc['is_from_user'] == true ||
|
||||
doc['is_from_user']?.toString() == 'true',
|
||||
createdAt: doc['created_at']?.toString() ?? DateTime.now().toIso8601String(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,10 +23,12 @@ class ReputationEntity extends Equatable {
|
||||
final averagePro = doc['average_pro'] ?? 0.0;
|
||||
|
||||
return ReputationEntity(
|
||||
total: int.parse(total.toString()),
|
||||
average: double.parse(average.toString()),
|
||||
totalPro: int.parse(totalPro.toString()),
|
||||
averagePro: double.parse(averagePro.toString()),
|
||||
// COUNT can come back as "5.0000"; parse as double then truncate so a
|
||||
// reputation of 0.0 never gets shown as if it were real.
|
||||
total: (double.tryParse(total.toString()) ?? 0).toInt(),
|
||||
average: double.tryParse(average.toString()) ?? 0.0,
|
||||
totalPro: (double.tryParse(totalPro.toString()) ?? 0).toInt(),
|
||||
averagePro: double.tryParse(averagePro.toString()) ?? 0.0,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -81,19 +81,29 @@ class ApiScoreRepository {
|
||||
return raw.map((e) => CommentEntity.fromDocument(e as Map<String, dynamic>)).toList();
|
||||
}
|
||||
|
||||
/// Throws when the rating could not be stored.
|
||||
///
|
||||
/// This used to swallow every error in an empty catch, so a lost rating was
|
||||
/// indistinguishable from a saved one — for the user *and* for us.
|
||||
Future<void> addComment(CommentEntity comment) async {
|
||||
final res = await http
|
||||
.post(
|
||||
Uri.parse('$_base/comments'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode({
|
||||
'destination_id': comment.destinationId,
|
||||
'service_id': comment.serviceId,
|
||||
'content': comment.content,
|
||||
'score': comment.score,
|
||||
'is_from_user': comment.isFromUser,
|
||||
}),
|
||||
)
|
||||
.timeout(_kHttpTimeout);
|
||||
if (res.statusCode >= 400) {
|
||||
throw Exception('No se pudo guardar la calificación (${res.statusCode})');
|
||||
}
|
||||
// Refreshing reputation is a nicety; never fail the rating over it.
|
||||
try {
|
||||
await http.post(
|
||||
Uri.parse('$_base/comments'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode({
|
||||
'destination_id': comment.destinationId,
|
||||
'service_id': comment.serviceId,
|
||||
'content': comment.content,
|
||||
'score': comment.score,
|
||||
'is_from_user': comment.isFromUser,
|
||||
}),
|
||||
).timeout(_kHttpTimeout);
|
||||
await getReputationByUserId(comment.destinationId);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
@@ -51,27 +51,55 @@ class ApiServiceRepository {
|
||||
};
|
||||
}
|
||||
|
||||
Future<dynamic> _get(String path) async {
|
||||
final res = await http.get(Uri.parse('$_base$path'), headers: await _headers()).timeout(_kHttpTimeout);
|
||||
/// Rejects error responses and tolerates an empty body.
|
||||
///
|
||||
/// Neither used to happen: a 4xx was parsed as if it had succeeded, and a
|
||||
/// 204 with no body made `jsonDecode` throw, so a change that *did* apply
|
||||
/// was reported to the user as a failure.
|
||||
dynamic _decode(http.Response res, String action) {
|
||||
if (res.statusCode >= 400) {
|
||||
String detail = '';
|
||||
try {
|
||||
final body = jsonDecode(res.body);
|
||||
if (body is Map && body['message'] != null) {
|
||||
final m = body['message'];
|
||||
detail = m is List ? m.join(', ') : m.toString();
|
||||
}
|
||||
} catch (_) {}
|
||||
throw Exception(
|
||||
'$action falló (${res.statusCode})${detail.isEmpty ? '' : ': $detail'}');
|
||||
}
|
||||
if (res.body.isEmpty) return null;
|
||||
return jsonDecode(res.body);
|
||||
}
|
||||
|
||||
Future<dynamic> _get(String path) async {
|
||||
final res = await http
|
||||
.get(Uri.parse('$_base$path'), headers: await _headers())
|
||||
.timeout(_kHttpTimeout);
|
||||
return _decode(res, 'La consulta');
|
||||
}
|
||||
|
||||
Future<dynamic> _post(String path, Map<String, dynamic> body) async {
|
||||
final res = await http.post(
|
||||
Uri.parse('$_base$path'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode(body),
|
||||
).timeout(_kHttpTimeout);
|
||||
return jsonDecode(res.body);
|
||||
final res = await http
|
||||
.post(
|
||||
Uri.parse('$_base$path'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode(body),
|
||||
)
|
||||
.timeout(_kHttpTimeout);
|
||||
return _decode(res, 'La operación');
|
||||
}
|
||||
|
||||
Future<dynamic> _patch(String path, Map<String, dynamic> body) async {
|
||||
final res = await http.patch(
|
||||
Uri.parse('$_base$path'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode(body),
|
||||
).timeout(_kHttpTimeout);
|
||||
return jsonDecode(res.body);
|
||||
final res = await http
|
||||
.patch(
|
||||
Uri.parse('$_base$path'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode(body),
|
||||
)
|
||||
.timeout(_kHttpTimeout);
|
||||
return _decode(res, 'La actualización');
|
||||
}
|
||||
|
||||
ServiceEntity _fromApi(Map<String, dynamic> json) {
|
||||
@@ -114,7 +142,13 @@ class ApiServiceRepository {
|
||||
createdAt: json['created_at']?.toString() ?? DateTime.now().toIso8601String(),
|
||||
description: json['description']?.toString() ?? '',
|
||||
range1Hour1: parseTime(json['range1_hour1']?.toString()),
|
||||
range1Hour2: parseTime(json['range1_hour2']?.toString()),
|
||||
// The backend often leaves range1_hour2 null. Defaulting it to 00:00
|
||||
// made every service look like it had ended at midnight, so the UI
|
||||
// marked brand new appointments as "Caducado" and hid every action.
|
||||
// Falling back to the start time keeps the comparison meaningful.
|
||||
range1Hour2: json['range1_hour2'] != null
|
||||
? parseTime(json['range1_hour2'].toString())
|
||||
: parseTime(json['range1_hour1']?.toString()),
|
||||
rate: json['rate']?.toString() ?? '0',
|
||||
status: intToEnumService(statusIndex),
|
||||
location: intToEnum(locationIndex),
|
||||
@@ -142,7 +176,13 @@ class ApiServiceRepository {
|
||||
'longitude': entity.longitude,
|
||||
'location_preference': _locationToString[entity.location.index],
|
||||
});
|
||||
return data['id']?.toString() ?? '';
|
||||
final id = data is Map ? data['id']?.toString() : null;
|
||||
if (id == null || id.isEmpty) {
|
||||
// Returning '' here used to be reported as success, and the app then
|
||||
// navigated to a service that did not exist.
|
||||
throw Exception('El servidor no devolvió la cita creada');
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
Future<void> updateServiceStatus(String serviceId, ServiceStatus newStatus) async {
|
||||
|
||||
Reference in New Issue
Block a user