fix: port 7 web features and repair the endless-loading screens
Root cause behind most "stuck loading" reports: the backend changed shape (schedules became an array, location_preferences a string) while the mobile parser still hard-cast to Map/int. The TypeError was swallowed by a silent catch that returned null, and screens only handled the success state, so a parse failure rendered as a permanent spinner. Same class of bug appeared across service lists via non-null map lookups and a total absence of request timeouts. Ported from prosappweb: - in-app suggestions (POST /suggestions) - policies/terms from GET /settings/policies - configurable appointment length (slot_duration_minutes) - block/unblock calendar slots (POST /services/block) - GPS city detection on the profile (Nominatim) - server-side professional search with haversine distance - retry cooldown after a rejected professional application Reliability: - parse schedules array (day_of_week 0=Mon) and string location_preferences - read times as wall clock, so 08:00 stays 08:00 across timezones - carry minutes into hours in TimeOfDay.add; a minute-based step used to loop forever and freeze the calendar (covered by test/time_slots_test.dart) - semver update check instead of string equality, which blocked every build that did not exactly match the configured version - request timeouts across all repositories - surface HTTP >= 400 instead of reporting failed writes as success - error states with retry instead of an indefinite shimmer Includes pre-existing uncommitted work from the UI redesign. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
06a89df690
commit
8631e6f729
@@ -19,9 +19,9 @@ class PaymentMethodEntity extends Equatable {
|
||||
|
||||
static PaymentMethodEntity fromDocument(Map<String, dynamic> doc) {
|
||||
return PaymentMethodEntity(
|
||||
nequi: doc['nequi'] as bool,
|
||||
datafono: doc['datafono'] as bool,
|
||||
transferencia: doc['transferencia'] as bool,
|
||||
nequi: doc['nequi'] as bool? ?? false,
|
||||
datafono: doc['datafono'] as bool? ?? false,
|
||||
transferencia: doc['transferencia'] as bool? ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ class ProfessionalEntity extends Equatable {
|
||||
final List<String> specializationsPictures;
|
||||
final Schedules schedules;
|
||||
final PaymentMethodEntity paymentMethods;
|
||||
final int slotDurationMinutes;
|
||||
|
||||
const ProfessionalEntity({
|
||||
required this.id,
|
||||
@@ -38,6 +39,7 @@ class ProfessionalEntity extends Equatable {
|
||||
required this.specializationsPictures,
|
||||
required this.schedules,
|
||||
required this.paymentMethods,
|
||||
this.slotDurationMinutes = 120,
|
||||
});
|
||||
|
||||
static ProfessionalEntity fromDocument(Map<String, dynamic> doc) {
|
||||
@@ -60,6 +62,8 @@ class ProfessionalEntity extends Equatable {
|
||||
List<String>.from(doc['specializations_pictures']),
|
||||
schedules: Schedules.fromDocument(doc['schedules']),
|
||||
paymentMethods: PaymentMethodEntity.fromDocument(doc['payment_methods']),
|
||||
slotDurationMinutes:
|
||||
(doc['slot_duration_minutes'] as num?)?.toInt() ?? 120,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -81,6 +85,7 @@ class ProfessionalEntity extends Equatable {
|
||||
List<String>? specializationsPictures,
|
||||
Schedules? schedules,
|
||||
PaymentMethodEntity? paymentMethods,
|
||||
int? slotDurationMinutes,
|
||||
}) {
|
||||
return ProfessionalEntity(
|
||||
id: id ?? this.id,
|
||||
@@ -102,6 +107,7 @@ class ProfessionalEntity extends Equatable {
|
||||
specializationsPictures ?? this.specializationsPictures,
|
||||
schedules: schedules ?? this.schedules,
|
||||
paymentMethods: paymentMethods ?? this.paymentMethods,
|
||||
slotDurationMinutes: slotDurationMinutes ?? this.slotDurationMinutes,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -124,6 +130,7 @@ class ProfessionalEntity extends Equatable {
|
||||
'specializations_pictures': specializationsPictures,
|
||||
'schedules': schedules.toJson(),
|
||||
'payment_methods': paymentMethods.toDocument(),
|
||||
'slot_duration_minutes': slotDurationMinutes,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -145,7 +152,8 @@ class ProfessionalEntity extends Equatable {
|
||||
specializations,
|
||||
specializationsPictures,
|
||||
schedules,
|
||||
paymentMethods
|
||||
paymentMethods,
|
||||
slotDurationMinutes,
|
||||
];
|
||||
|
||||
@override
|
||||
|
||||
@@ -58,11 +58,17 @@ class ScheduleEntity extends Equatable {
|
||||
);
|
||||
}
|
||||
|
||||
static TimeOfDay? _parseTime(String? time) {
|
||||
static TimeOfDay? _parseTime(String? time) => parseTime(time);
|
||||
|
||||
/// Accepts both "HH:MM" and the ISO8601 the backend returns
|
||||
/// (e.g. "1970-01-01T08:30:00.000Z"). The time is read as wall clock —
|
||||
/// no timezone conversion — so 08:00 stays 08:00.
|
||||
static TimeOfDay? parseTime(String? time) {
|
||||
try {
|
||||
if (time == null) return null;
|
||||
final components = time.split(':');
|
||||
if (components.length != 2) {
|
||||
final t = time.contains('T') ? time.split('T')[1] : time;
|
||||
final components = t.split(':');
|
||||
if (components.length < 2) {
|
||||
return null;
|
||||
}
|
||||
final hour = int.parse(components[0]);
|
||||
|
||||
+155
-56
@@ -1,5 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:developer';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:professional_repository/professional_repository.dart';
|
||||
@@ -19,6 +20,8 @@ class ApiProfessionalRepository {
|
||||
|
||||
String? _token;
|
||||
|
||||
static const _timeout = Duration(seconds: 20);
|
||||
|
||||
ApiProfessionalRepository() {
|
||||
_isProModeActiveBroadcast.add(isProModeActive);
|
||||
}
|
||||
@@ -38,19 +41,58 @@ class ApiProfessionalRepository {
|
||||
}
|
||||
|
||||
Future<dynamic> _get(String path) async {
|
||||
final res = await http.get(Uri.parse('$_base$path'), headers: await _headers());
|
||||
final res = await http
|
||||
.get(Uri.parse('$_base$path'), headers: await _headers())
|
||||
.timeout(_timeout);
|
||||
return jsonDecode(res.body);
|
||||
}
|
||||
|
||||
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),
|
||||
);
|
||||
final res = await http
|
||||
.patch(
|
||||
Uri.parse('$_base$path'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode(body),
|
||||
)
|
||||
.timeout(_timeout);
|
||||
if (res.statusCode >= 400) {
|
||||
throw Exception('No se pudo guardar la información (${res.statusCode})');
|
||||
}
|
||||
return jsonDecode(res.body);
|
||||
}
|
||||
|
||||
/// Uploads [file] to storage and returns its public URL.
|
||||
/// Throws when the upload fails, so callers never treat a failure as success.
|
||||
Future<String> _uploadFile(String file) async {
|
||||
final token = await _getToken();
|
||||
final req =
|
||||
http.MultipartRequest('POST', Uri.parse('$_base/storage/upload'));
|
||||
if (token != null) req.headers['Authorization'] = 'Bearer $token';
|
||||
req.files.add(await http.MultipartFile.fromPath('file', file));
|
||||
final streamed = await req.send().timeout(const Duration(seconds: 60));
|
||||
final res = await http.Response.fromStream(streamed);
|
||||
if (res.statusCode >= 400) {
|
||||
throw Exception('No se pudo subir el archivo (${res.statusCode})');
|
||||
}
|
||||
final body = jsonDecode(res.body) as Map<String, dynamic>;
|
||||
final url = body['url']?.toString();
|
||||
if (url == null || url.isEmpty) {
|
||||
throw Exception('El servidor no devolvió la URL del archivo');
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
Future<void> _delete(String path) async {
|
||||
final res = await http
|
||||
.delete(Uri.parse('$_base$path'), headers: await _headers())
|
||||
.timeout(_timeout);
|
||||
if (res.statusCode >= 400) {
|
||||
throw Exception('Error al reiniciar la solicitud (${res.statusCode})');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteProfessionalInfo() => _delete('/professionals/me');
|
||||
|
||||
ProfessionalEntity? lastProInfo() => _proInfo;
|
||||
|
||||
Stream<ProfessionalEntity?> streamProInfo() => _proInfoBroadcast.stream;
|
||||
@@ -62,34 +104,97 @@ class ApiProfessionalRepository {
|
||||
_isProModeActiveBroadcast.add(isProModeActive);
|
||||
}
|
||||
|
||||
/// The backend sends `location_preferences` as a string ('office' |
|
||||
/// 'delivery' | 'both'); older payloads used the enum index.
|
||||
LocationPreferences _locationPrefsFromValue(dynamic v) {
|
||||
if (v is num) return intToEnum(v.toInt());
|
||||
if (v is String) {
|
||||
switch (v) {
|
||||
case 'delivery':
|
||||
return LocationPreferences.delivery;
|
||||
case 'both':
|
||||
return LocationPreferences.both;
|
||||
default:
|
||||
return LocationPreferences.office;
|
||||
}
|
||||
}
|
||||
return LocationPreferences.office;
|
||||
}
|
||||
|
||||
/// The backend sends `schedules` as an array of rows keyed by
|
||||
/// `day_of_week` (0 = Monday … 6 = Sunday), not as a map of day names.
|
||||
Schedules _schedulesFromApi(dynamic raw) {
|
||||
if (raw is Map) {
|
||||
return Schedules.fromDocument(raw as Map<String, dynamic>);
|
||||
}
|
||||
if (raw is! List || raw.isEmpty) return Schedules.empty;
|
||||
|
||||
final byDay = <int, Map<String, dynamic>>{};
|
||||
for (final s in raw) {
|
||||
if (s is! Map) continue;
|
||||
final day = (s['day_of_week'] as num?)?.toInt();
|
||||
if (day != null) byDay[day] = s.cast<String, dynamic>();
|
||||
}
|
||||
|
||||
ScheduleEntity entityFor(int day) {
|
||||
final s = byDay[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()),
|
||||
);
|
||||
}
|
||||
|
||||
return Schedules(
|
||||
monday: entityFor(0),
|
||||
tuesday: entityFor(1),
|
||||
wednesday: entityFor(2),
|
||||
thursday: entityFor(3),
|
||||
friday: entityFor(4),
|
||||
saturday: entityFor(5),
|
||||
sunday: entityFor(6),
|
||||
);
|
||||
}
|
||||
|
||||
ProfessionalEntity _fromApi(Map<String, dynamic> json) {
|
||||
return ProfessionalEntity(
|
||||
id: json['user_id']?.toString() ?? json['id']?.toString() ?? '',
|
||||
identification: json['identification']?.toString() ?? '',
|
||||
address: json['address']?.toString() ?? '',
|
||||
aditionalAddress: json['aditional_address']?.toString() ?? '',
|
||||
aditionalAddress: (json['additional_address'] ?? json['aditional_address'])
|
||||
?.toString() ??
|
||||
'',
|
||||
profession: json['profession']?.toString() ?? '',
|
||||
ratePreferences: json['rate_preferences'] as bool? ?? false,
|
||||
rate: json['rate']?.toString() ?? '',
|
||||
locationPreferences: intToEnum((json['location_preferences'] as num?)?.toInt() ?? 0),
|
||||
locationPreferences:
|
||||
_locationPrefsFromValue(json['location_preferences']),
|
||||
bannerPicture: json['banner_picture']?.toString() ?? '',
|
||||
identificationPicture: json['identification_picture']?.toString() ?? '',
|
||||
certificatePicture: json['certificate_picture']?.toString() ?? '',
|
||||
latitude: double.tryParse(json['latitude']?.toString() ?? '0') ?? 0.0,
|
||||
longitude: double.tryParse(json['longitude']?.toString() ?? '0') ?? 0.0,
|
||||
specializations: json['specializations'] != null
|
||||
? List<String>.from(json['specializations'])
|
||||
: [],
|
||||
specializationsPictures: json['specializations_pictures'] != null
|
||||
? List<String>.from(json['specializations_pictures'])
|
||||
: [],
|
||||
schedules: json['schedules'] != null
|
||||
? Schedules.fromDocument(json['schedules'] as Map<String, dynamic>)
|
||||
: Schedules.empty,
|
||||
specializations: json['specializations'] is List
|
||||
? (json['specializations'] as List)
|
||||
.map((e) => e.toString())
|
||||
.toList()
|
||||
: <String>[],
|
||||
specializationsPictures: json['specializations_pictures'] is List
|
||||
? (json['specializations_pictures'] as List)
|
||||
.map((e) => e.toString())
|
||||
.toList()
|
||||
: <String>[],
|
||||
schedules: _schedulesFromApi(json['schedules']),
|
||||
paymentMethods: json['payment_methods'] != null
|
||||
? PaymentMethodEntity.fromDocument(
|
||||
json['payment_methods'] as Map<String, dynamic>)
|
||||
: PaymentMethodEntity.empty,
|
||||
slotDurationMinutes:
|
||||
(json['slot_duration_minutes'] as num?)?.toInt() ?? 120,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -109,7 +214,9 @@ class ApiProfessionalRepository {
|
||||
final data = await _get('/professionals/$myUserId');
|
||||
if (data == null) return null;
|
||||
return _fromApi(data as Map<String, dynamic>);
|
||||
} catch (_) {
|
||||
} catch (e) {
|
||||
// Logged because a silent null here surfaces as an endless spinner.
|
||||
log('getProInfo($myUserId) failed: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -123,8 +230,9 @@ class ApiProfessionalRepository {
|
||||
double latitude,
|
||||
double longitude,
|
||||
Schedules schedules,
|
||||
PaymentMethodEntity paymentMethods,
|
||||
) async {
|
||||
PaymentMethodEntity paymentMethods, {
|
||||
int slotDurationMinutes = 120,
|
||||
}) async {
|
||||
await _patch('/professionals/me', {
|
||||
'address': address,
|
||||
'aditional_address': aditionalAddress,
|
||||
@@ -135,6 +243,7 @@ class ApiProfessionalRepository {
|
||||
'longitude': longitude,
|
||||
'schedules': schedules.toJson(),
|
||||
'payment_methods': paymentMethods.toDocument(),
|
||||
'slot_duration_minutes': slotDurationMinutes,
|
||||
});
|
||||
|
||||
if (_proInfo != null) {
|
||||
@@ -147,51 +256,21 @@ class ApiProfessionalRepository {
|
||||
}
|
||||
|
||||
Future<void> uploadBannerPicture(String file) async {
|
||||
final token = await _getToken();
|
||||
final req = http.MultipartRequest('POST', Uri.parse('$_base/storage/upload'));
|
||||
if (token != null) req.headers['Authorization'] = 'Bearer $token';
|
||||
req.files.add(await http.MultipartFile.fromPath('file', file));
|
||||
final streamed = await req.send();
|
||||
final res = await http.Response.fromStream(streamed);
|
||||
final body = jsonDecode(res.body) as Map<String, dynamic>;
|
||||
final url = body['url'] as String;
|
||||
final url = await _uploadFile(file);
|
||||
await _patch('/professionals/me', {'banner_picture': url});
|
||||
}
|
||||
|
||||
Future<String> uploadPdfCedula(String file, String userId) async {
|
||||
final token = await _getToken();
|
||||
final req = http.MultipartRequest('POST', Uri.parse('$_base/storage/upload'));
|
||||
if (token != null) req.headers['Authorization'] = 'Bearer $token';
|
||||
req.files.add(await http.MultipartFile.fromPath('file', file));
|
||||
final streamed = await req.send();
|
||||
final res = await http.Response.fromStream(streamed);
|
||||
final body = jsonDecode(res.body) as Map<String, dynamic>;
|
||||
return body['url'] as String;
|
||||
}
|
||||
Future<String> uploadPdfCedula(String file, String userId) =>
|
||||
_uploadFile(file);
|
||||
|
||||
Future<String> uploadPdfCertificado(String file, String userId) async {
|
||||
final token = await _getToken();
|
||||
final req = http.MultipartRequest('POST', Uri.parse('$_base/storage/upload'));
|
||||
if (token != null) req.headers['Authorization'] = 'Bearer $token';
|
||||
req.files.add(await http.MultipartFile.fromPath('file', file));
|
||||
final streamed = await req.send();
|
||||
final res = await http.Response.fromStream(streamed);
|
||||
final body = jsonDecode(res.body) as Map<String, dynamic>;
|
||||
return body['url'] as String;
|
||||
}
|
||||
Future<String> uploadPdfCertificado(String file, String userId) =>
|
||||
_uploadFile(file);
|
||||
|
||||
Future<List<String>> uploadPdfsEspecializaciones(
|
||||
List<String> files, String userId) async {
|
||||
final List<String> urls = [];
|
||||
for (final file in files) {
|
||||
final token = await _getToken();
|
||||
final req = http.MultipartRequest('POST', Uri.parse('$_base/storage/upload'));
|
||||
if (token != null) req.headers['Authorization'] = 'Bearer $token';
|
||||
req.files.add(await http.MultipartFile.fromPath('file', file));
|
||||
final streamed = await req.send();
|
||||
final res = await http.Response.fromStream(streamed);
|
||||
final body = jsonDecode(res.body) as Map<String, dynamic>;
|
||||
urls.add(body['url'] as String);
|
||||
urls.add(await _uploadFile(file));
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
@@ -206,6 +285,26 @@ class ApiProfessionalRepository {
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<ProfessionalEntity>> searchProfessionals({
|
||||
String? search,
|
||||
String? city,
|
||||
double? lat,
|
||||
double? lng,
|
||||
}) async {
|
||||
final params = <String, String>{};
|
||||
if (search != null && search.isNotEmpty) params['search'] = search;
|
||||
if (city != null && city.isNotEmpty) params['city'] = city;
|
||||
if (lat != null) params['lat'] = lat.toString();
|
||||
if (lng != null) params['lng'] = lng.toString();
|
||||
|
||||
final uri = Uri.parse('$_base/professionals')
|
||||
.replace(queryParameters: params.isEmpty ? null : params);
|
||||
final res = await http.get(uri, headers: await _headers());
|
||||
final body = jsonDecode(res.body);
|
||||
final List raw = body is Map ? (body['data'] as List? ?? []) : (body as List? ?? []);
|
||||
return raw.map((e) => _fromApi(e as Map<String, dynamic>)).toList();
|
||||
}
|
||||
|
||||
Future<List<ProfessionalEntity>> getProfessionalsFromIds(
|
||||
Iterable<String> ids) async {
|
||||
final result = <ProfessionalEntity>[];
|
||||
|
||||
Reference in New Issue
Block a user