Files
prosappco/lib/screens/professional/professional_form_screen.dart
T
Lizandro GuarnizoandClaude Opus 5 8631e6f729 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>
2026-08-24 16:45:42 -05:00

501 lines
20 KiB
Dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:injector/injector.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';
import 'package:prosappco/blocs/auth_bloc/auth_bloc.dart';
import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart';
import 'package:prosappco/blocs/professional_bloc/professional_bloc.dart';
import 'package:prosappco/blocs/profile_bloc/profile_bloc.dart';
import 'package:prosappco/screens/lists/profession_list_screen.dart';
import 'package:user_repository/user_repository.dart';
import 'package:file_picker/file_picker.dart';
class ProfessionalFormScreen extends StatefulWidget {
const ProfessionalFormScreen({super.key});
@override
State<ProfessionalFormScreen> createState() => _ProfessionalFormScreenState();
}
class _ProfessionalFormScreenState extends State<ProfessionalFormScreen> {
final TextEditingController _cedulaController = TextEditingController();
final TextEditingController _professionController = TextEditingController();
final TextEditingController _specialityController = TextEditingController();
final List<String> _items = [];
XFile? _imageFile;
PlatformFile? _cedulaPdfFile;
PlatformFile? _certificadoPdfFile;
List<PlatformFile>? _especializacionesPdfFiles = [];
bool _isSubmitting = false;
late final AuthBloc authBloc;
@override
void initState() {
super.initState();
authBloc = Injector.appInstance.get<AuthBloc>();
}
@override
void dispose() {
_cedulaController.dispose();
_professionController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocProvider<AuthBloc>(
create: (context) => authBloc,
child: BlocListener<ProfessionalBloc, ProfessionalState>(
listener: (context, professionalState) {
if (professionalState is SendProfessionalToReviewLoading) {
setState(() => _isSubmitting = true);
} else if (professionalState is SendProfessionalToReviewSuccess) {
setState(() => _isSubmitting = false);
// The picture upload only runs once the application actually landed.
final user = context.read<MyUserBloc>().state.user;
if (user != null) {
context.read<ProfileBloc>().add(UpdateUserInfo(
myUser: user.copyWith(proState: ProState.pending),
filePicture: _imageFile?.path));
}
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Información enviada a revisión')),
);
Navigator.pop(context);
} else if (professionalState is SendProfessionalToReviewFailure) {
setState(() => _isSubmitting = false);
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'No se pudo enviar tu solicitud. Revisa tu conexión e inténtalo de nuevo.')),
);
}
},
child: Scaffold(
appBar: AppBar(
title: const Text('Perfil profesional'),
),
body: BlocBuilder<MyUserBloc, MyUserState>(
builder: (context, state) {
return Column(
children: [
Expanded(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 40, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
pictureWidget(state, context),
const SizedBox(height: 30),
TextFormField(
controller: _cedulaController,
decoration: const InputDecoration(
labelText: 'Cedula',
prefixIcon: Icon(Icons.assignment_ind),
hintText: 'Ingresa tu cedula',
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red, width: 2.0),
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor, ingrese su nombre';
}
return null;
},
),
const SizedBox(height: 10.0),
ElevatedButton(
onPressed: _pickCedulaPDF,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Cargar pdf de la cedula'),
_cedulaPdfFile != null
? const Icon(Icons.check)
: const Icon(Icons.file_upload_outlined),
],
),
),
const SizedBox(height: 20.0),
TextFormField(
controller: _professionController,
readOnly: true,
onTap: () async {
final professionName = await Navigator.push(
context,
CupertinoPageRoute(
builder: (BuildContext context) {
return const ProfessionListScreen();
},
),
);
if (professionName != null) {
_professionController.text = professionName;
}
},
decoration: const InputDecoration(
labelText: 'Profesión',
prefixIcon: Icon(Icons.work_rounded),
hintText: 'Selecciona tu profesión',
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red, width: 2.0),
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor, ingrese su nombre';
}
return null;
},
),
const SizedBox(height: 10.0),
ElevatedButton(
onPressed: _pickCertificadoPDF,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Cargar pdf del certificado'),
_certificadoPdfFile != null
? const Icon(Icons.check)
: const Icon(Icons.file_upload_outlined),
],
),
),
const SizedBox(height: 20.0),
TextField(
controller: _specialityController,
onSubmitted: (value) {
_addItemToList();
},
decoration: InputDecoration(
labelText: 'Especializaciones',
prefixIcon: const Icon(Icons.assignment_rounded),
suffixIcon: IconButton(
onPressed: () {
_addItemToList();
},
icon: const Icon(Icons.add)),
hintText: 'Ingresa tus especializaciones',
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
)),
errorBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: const OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red, width: 2.0),
),
),
),
const SizedBox(height: 10.0),
ElevatedButton(
onPressed: _pickEspecializacionesPDF,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Expanded(
child: Text(
'Cargar pdfs de tus especializaciones',
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
),
_especializacionesPdfFiles?.isNotEmpty == true
? const Icon(Icons.check)
: const Icon(Icons.file_upload_outlined),
],
),
),
const SizedBox(height: 10.0),
Wrap(
spacing: 8.0,
runSpacing: 4.0,
children: _items
.map((item) => Chip(
label: Text(item),
backgroundColor: Theme.of(context)
.colorScheme
.tertiary,
labelStyle:
const TextStyle(color: Colors.blue),
deleteIconColor: Colors.blue,
onDeleted: () {
_removeItemFromList(item);
},
shape: RoundedRectangleBorder(
side: const BorderSide(
color: Colors.blue, width: 0.3),
borderRadius: BorderRadius.circular(8),
),
))
.toList(),
),
const SizedBox(height: 20),
],
),
),
),
),
const Divider(
height: 1,
thickness: 0.5,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10,
horizontal: 15,
),
child: FilledButton(
onPressed: _isSubmitting
? null
: () {
final userId =
context.read<MyUserBloc>().state.user?.id;
if (userId == null) {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'No se pudo identificar tu usuario, vuelve a iniciar sesión')));
return;
}
final String? cedulaPdfPath = _cedulaPdfFile?.path;
final String? certificadoPdfPath =
_certificadoPdfFile?.path;
final List<String> especializacionesPdfPaths =
_especializacionesPdfFiles
?.map((file) => file.path)
.where((file) => file != null)
.map((e) => e!)
.toList() ??
[];
if (_cedulaController.text.isEmpty ||
_professionController.text.isEmpty) {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Llena los campos de cedula y profesión')));
return;
}
if (cedulaPdfPath == null) {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Carga el pdf de tu cedula')));
return;
}
if (certificadoPdfPath == null) {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text(
'Carga el pdf de tu certificado profesional')));
return;
}
context
.read<ProfessionalBloc>()
.add(SendProfessionalToReviewEvent(
id: userId,
identification: _cedulaController.text,
identificationPicture: cedulaPdfPath,
profession: _professionController.text,
certificatePicture: certificadoPdfPath,
specializations: _items,
specializationsPictures:
especializacionesPdfPaths,
));
},
style: FilledButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
padding: const EdgeInsets.symmetric(vertical: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
child: Container(
alignment: Alignment.center,
width: double.infinity,
child: _isSubmitting
? const SizedBox(
height: 22,
width: 22,
child: CircularProgressIndicator(
strokeWidth: 2, color: Colors.white),
)
: const Text(
'Enviar a revisión',
style: TextStyle(
color: Colors.white,
fontSize: 18,
),
),
),
)),
],
);
},
),
),
),
);
}
void _addItemToList() {
setState(() {
String newItem = _specialityController.text.trim();
if (newItem.isNotEmpty) {
_items.add(newItem);
_specialityController.clear();
}
});
}
void _removeItemFromList(String item) {
setState(() {
_items.remove(item);
});
}
Future<void> _pickCedulaPDF() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if (result != null) {
setState(() {
_cedulaPdfFile = result.files.first;
});
}
}
Future<void> _pickCertificadoPDF() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if (result != null) {
setState(() {
_certificadoPdfFile = result.files.first;
});
}
}
Future<void> _pickEspecializacionesPDF() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
allowMultiple: true,
);
if (result != null) {
setState(() {
_especializacionesPdfFiles = result.files;
});
}
}
Widget pictureWidget(MyUserState state, BuildContext context) {
final pictureUrl = state.user?.picture;
final pathImageFile = _imageFile?.path;
ImageProvider<Object>? imageProvider;
if (pathImageFile != null && pathImageFile.isNotEmpty) {
imageProvider = FileImage(File(pathImageFile));
} else if (pictureUrl != null && pictureUrl.isNotEmpty) {
imageProvider = NetworkImage(pictureUrl);
}
return GestureDetector(
onTap: () async {
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(
source: ImageSource.gallery,
maxHeight: 500,
maxWidth: 500,
imageQuality: 40,
);
if (image != null) {
setState(() {
_imageFile = image;
});
}
},
child: Hero(
tag: 'picture-profile',
child: pictureContainerWidget(imageProvider),
),
);
}
Widget pictureContainerWidget(ImageProvider<Object>? imageProvider) {
final image = imageProvider == null
? null
: DecorationImage(
image: imageProvider,
fit: BoxFit.contain,
);
final widget = image == null
? Icon(
CupertinoIcons.person,
color: Colors.grey.shade400,
size: 40,
)
: null;
return Container(
width: 120,
height: 120,
decoration: BoxDecoration(
color: Colors.grey.shade300,
shape: BoxShape.circle,
image: image,
),
child: widget,
);
}
}