This commit is contained in:
Felipe
2024-04-05 11:56:45 -05:00
parent f46450e5db
commit e82c7c3afd
18 changed files with 1297 additions and 546 deletions
+33 -4
View File
@@ -17,10 +17,14 @@ class ServiceBloc extends Bloc<ServiceEvent, ServiceState> {
: _serviceRepository = serviceRepository, : _serviceRepository = serviceRepository,
super(CreateServiceInitial()) { super(CreateServiceInitial()) {
on<CreateService>(_onCreateService); on<CreateService>(_onCreateService);
on<LoadService>(_onLoadService);
on<UpdateServiceStatus>(_onUpdateServiceStatus);
} }
void _onCreateService(CreateService event, Emitter<ServiceState> emit) async { void _onCreateService(CreateService event, Emitter<ServiceState> emit) async {
try { try {
emit(CreateServiceLoading());
ServiceEntity service = ServiceEntity( ServiceEntity service = ServiceEntity(
professionalId: event.professionalId, professionalId: event.professionalId,
professionalScored: false, professionalScored: false,
@@ -40,12 +44,37 @@ class ServiceBloc extends Bloc<ServiceEvent, ServiceState> {
location: event.location, location: event.location,
); );
log('xd -- $service'); String serviceId = await _serviceRepository.createService(service);
await _serviceRepository.createService(service); emit(CreateServiceSuccess(serviceId));
emit(const CreateServiceSuccess());
} catch (e) { } catch (e) {
log(e.toString());
emit(CreateServiceFailure());
}
}
void _onLoadService(LoadService event, Emitter<ServiceState> emit) async {
try {
final serviceStream = _serviceRepository.getService(event.serviceId);
await for (var service in serviceStream) {
emit(ServiceLoaded(service));
}
} catch (e) {
log(e.toString());
emit(CreateServiceFailure());
}
}
void _onUpdateServiceStatus(
UpdateServiceStatus event, Emitter<ServiceState> emit) async {
try {
emit(CreateServiceLoading());
await _serviceRepository.updateServiceStatus(
event.serviceId, event.newStatus);
emit(ServiceStatusUpdated(event.newStatus));
} catch (e) {
log(e.toString());
emit(CreateServiceFailure()); emit(CreateServiceFailure());
} }
} }
+19
View File
@@ -7,6 +7,25 @@ abstract class ServiceEvent extends Equatable {
List<Object?> get props => []; List<Object?> get props => [];
} }
class LoadService extends ServiceEvent {
final String serviceId;
const LoadService(this.serviceId);
@override
List<Object?> get props => [serviceId];
}
class UpdateServiceStatus extends ServiceEvent {
final String serviceId;
final ServiceStatus newStatus;
const UpdateServiceStatus(this.serviceId, this.newStatus);
@override
List<Object> get props => [serviceId, newStatus];
}
class CreateService extends ServiceEvent { class CreateService extends ServiceEvent {
final String professionalId; final String professionalId;
final bool? professionalScored; final bool? professionalScored;
+22 -2
View File
@@ -7,6 +7,15 @@ abstract class ServiceState extends Equatable {
List<Object> get props => []; List<Object> get props => [];
} }
class ServiceLoaded extends ServiceState {
final ServiceEntity service;
const ServiceLoaded(this.service);
@override
List<Object> get props => [service];
}
class CreateServiceInitial extends ServiceState {} class CreateServiceInitial extends ServiceState {}
class CreateServiceFailure extends ServiceState {} class CreateServiceFailure extends ServiceState {}
@@ -14,8 +23,19 @@ class CreateServiceFailure extends ServiceState {}
class CreateServiceLoading extends ServiceState {} class CreateServiceLoading extends ServiceState {}
class CreateServiceSuccess extends ServiceState { class CreateServiceSuccess extends ServiceState {
const CreateServiceSuccess(); final String serviceId;
const CreateServiceSuccess(this.serviceId);
@override @override
List<Object> get props => []; List<Object> get props => [serviceId];
}
class ServiceStatusUpdated extends ServiceState {
final ServiceStatus newStatus;
const ServiceStatusUpdated(this.newStatus);
@override
List<Object> get props => [newStatus];
} }
+32 -5
View File
@@ -9,11 +9,13 @@ import 'package:prosappco/components/general_drawer_item.dart';
import 'package:prosappco/screens/configuration/configuration_screen.dart'; import 'package:prosappco/screens/configuration/configuration_screen.dart';
import 'package:prosappco/screens/configuration/configuration_support_screen.dart'; import 'package:prosappco/screens/configuration/configuration_support_screen.dart';
import 'package:prosappco/screens/lists/professional_list_screen.dart'; import 'package:prosappco/screens/lists/professional_list_screen.dart';
import 'package:prosappco/screens/lists/user_service_list_screen.dart';
import 'package:prosappco/screens/professional/professional_calendar_screen.dart'; import 'package:prosappco/screens/professional/professional_calendar_screen.dart';
import 'package:prosappco/screens/professional/professional_denied_screen.dart'; import 'package:prosappco/screens/professional/professional_denied_screen.dart';
import 'package:prosappco/screens/professional/professional_form_screen.dart'; import 'package:prosappco/screens/professional/professional_form_screen.dart';
import 'package:prosappco/screens/professional/professional_pending_screen.dart'; import 'package:prosappco/screens/professional/professional_pending_screen.dart';
import 'package:prosappco/screens/professional/professional_profile_screen.dart'; import 'package:prosappco/screens/professional/professional_profile_screen.dart';
import 'package:prosappco/screens/profile/profile_screen.dart';
import 'package:prosappco/screens/user/user_history_services_screen.dart'; import 'package:prosappco/screens/user/user_history_services_screen.dart';
import 'package:prosappco/screens/web/web_view_screen.dart'; import 'package:prosappco/screens/web/web_view_screen.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
@@ -81,7 +83,7 @@ class GeneralDrawer extends StatelessWidget {
context, context,
CupertinoPageRoute( CupertinoPageRoute(
builder: (context) => builder: (context) =>
const ProfessionalListScreen(), const UserServiceListScreen(),
// const UserServicesScreen(), // const UserServicesScreen(),
), ),
); );
@@ -230,11 +232,17 @@ class GeneralDrawer extends StatelessWidget {
if (myUserState.status == MyUserStatus.success) { if (myUserState.status == MyUserStatus.success) {
final user = myUserState.user!; final user = myUserState.user!;
if (user.name != null &&
user.email != null &&
user.city != null &&
user.phone != null) {
switch (user.proState) { switch (user.proState) {
case ProState.active: case ProState.active:
Navigator.pop(context); Navigator.pop(context);
context.read<ProfessionalBloc>().add(const SwitchProModeEvent()); context
.read<ProfessionalBloc>()
.add(const SwitchProModeEvent());
break; break;
case ProState.inactive: case ProState.inactive:
@@ -262,6 +270,19 @@ class GeneralDrawer extends StatelessWidget {
); );
break; break;
} }
} else {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Por favor, completa tu perfil'),
));
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => const ProfileScreen(),
),
);
}
} else {} } else {}
}, },
style: FilledButton.styleFrom( style: FilledButton.styleFrom(
@@ -269,15 +290,21 @@ class GeneralDrawer extends StatelessWidget {
padding: const EdgeInsets.symmetric(vertical: 15), padding: const EdgeInsets.symmetric(vertical: 15),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
)), ),
),
child: (state is LoadedModeProState) child: (state is LoadedModeProState)
? Text( ? Text(
state.isProModeActive ? 'Modo cliente' : 'Modo profesional', state.isProModeActive ? 'Modo cliente' : 'Modo profesional',
style: const TextStyle(color: Colors.white, fontSize: 18), style: const TextStyle(color: Colors.white, fontSize: 18),
) )
: const CircularProgressIndicator( : const Text(
color: Colors.white, 'Modo profesional',
style: TextStyle(color: Colors.white, fontSize: 18),
), ),
// const CircularProgressIndicator(
// color: Colors.white,
// ),
); );
} }
+3 -1
View File
@@ -4,12 +4,14 @@ class GeneralPrimaryButton extends StatelessWidget {
final VoidCallback onPressed; final VoidCallback onPressed;
final String label; final String label;
final bool isEnabled; final bool isEnabled;
final Color? color;
const GeneralPrimaryButton({ const GeneralPrimaryButton({
super.key, super.key,
required this.onPressed, required this.onPressed,
required this.label, required this.label,
this.isEnabled = true, this.isEnabled = true,
this.color,
}); });
@override @override
@@ -17,7 +19,7 @@ class GeneralPrimaryButton extends StatelessWidget {
return ElevatedButton( return ElevatedButton(
onPressed: isEnabled ? onPressed : null, onPressed: isEnabled ? onPressed : null,
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: color ?? Theme.of(context).colorScheme.primary,
elevation: 5, elevation: 5,
minimumSize: Size( minimumSize: Size(
MediaQuery.of(context).size.width * 0.5, MediaQuery.of(context).size.width * 0.5,
@@ -0,0 +1,27 @@
import 'package:flutter/material.dart';
class UserServiceListScreen extends StatefulWidget {
const UserServiceListScreen({super.key});
@override
State<UserServiceListScreen> createState() => _UserServiceListScreenState();
}
class _UserServiceListScreenState extends State<UserServiceListScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Mis Servicios'),
),
body: ListView.builder(
itemCount: 10,
itemBuilder: (_, __) {
return ListTile(
onTap: () {},
title: Text('Servicio ${__ + 1}'),
);
}),
);
}
}
@@ -72,7 +72,7 @@ class ScheduleItem extends StatelessWidget {
children: [ children: [
timePickerField( timePickerField(
context: context, context: context,
text: schedule.getFormatTime(schedule.range1Hour1), text: ScheduleEntity.getFormatTime(schedule.range1Hour1),
onPick: (pickedTime) { onPick: (pickedTime) {
onChanged.call(schedule.copyWith(range1Hour1: pickedTime)); onChanged.call(schedule.copyWith(range1Hour1: pickedTime));
}, },
@@ -88,7 +88,7 @@ class ScheduleItem extends StatelessWidget {
visible: !schedule.continuousDay, visible: !schedule.continuousDay,
child: timePickerField( child: timePickerField(
context: context, context: context,
text: schedule.getFormatTime(schedule.range1Hour2), text: ScheduleEntity.getFormatTime(schedule.range1Hour2),
onPick: (pickedTime) { onPick: (pickedTime) {
onChanged.call(schedule.copyWith(range1Hour2: pickedTime)); onChanged.call(schedule.copyWith(range1Hour2: pickedTime));
}, },
@@ -104,7 +104,7 @@ class ScheduleItem extends StatelessWidget {
visible: !schedule.continuousDay, visible: !schedule.continuousDay,
child: timePickerField( child: timePickerField(
context: context, context: context,
text: schedule.getFormatTime(schedule.range2Hour1), text: ScheduleEntity.getFormatTime(schedule.range2Hour1),
onPick: (pickedTime) { onPick: (pickedTime) {
onChanged.call(schedule.copyWith(range2Hour1: pickedTime)); onChanged.call(schedule.copyWith(range2Hour1: pickedTime));
}, },
@@ -122,7 +122,7 @@ class ScheduleItem extends StatelessWidget {
), ),
timePickerField( timePickerField(
context: context, context: context,
text: schedule.getFormatTime(schedule.range2Hour2), text: ScheduleEntity.getFormatTime(schedule.range2Hour2),
onPick: (pickedTime) { onPick: (pickedTime) {
onChanged.call(schedule.copyWith(range2Hour2: pickedTime)); onChanged.call(schedule.copyWith(range2Hour2: pickedTime));
}, },
@@ -510,6 +510,8 @@ class _ProfessionalProfileScreenState extends State<ProfessionalProfileScreen> {
context.read<ProfessionalProfileBloc>().add( context.read<ProfessionalProfileBloc>().add(
UpdateProfessionalBannerInfo(fileBanner: _imageFile?.path), UpdateProfessionalBannerInfo(fileBanner: _imageFile?.path),
); );
log('xd -- si pasa');
}, },
label: 'Guardar', label: 'Guardar',
), ),
@@ -588,13 +590,13 @@ class _ProfessionalProfileScreenState extends State<ProfessionalProfileScreen> {
return 'N/A'; return 'N/A';
} }
if (schedule.continuousDay) { if (schedule.continuousDay) {
return '${schedule.range1Hour1?.format(context).toString()} - ${schedule.range2Hour2?.format(context).toString()}'; return '${ScheduleEntity.getFormatTime(schedule.range1Hour1)} - ${ScheduleEntity.getFormatTime(schedule.range2Hour2)}';
} else { } else {
if (schedule.range1Hour2 == null || schedule.range2Hour1 == null) { if (schedule.range1Hour2 == null || schedule.range2Hour1 == null) {
return 'N/A'; return 'N/A';
} }
return '${schedule.range1Hour1?.format(context).toString()} - ${schedule.range1Hour2?.format(context).toString()}; ${schedule.range2Hour1?.format(context).toString()} - ${schedule.range2Hour2?.format(context).toString()}'; return '${ScheduleEntity.getFormatTime(schedule.range1Hour1)} - ${ScheduleEntity.getFormatTime(schedule.range1Hour2)}; ${ScheduleEntity.getFormatTime(schedule.range2Hour1)} - ${ScheduleEntity.getFormatTime(schedule.range2Hour2)}';
} }
} }
} }
@@ -31,6 +31,8 @@ class _ProfessionalScheduleScreenState
title: const Text('Horario'), title: const Text('Horario'),
), ),
body: SingleChildScrollView( body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: Column( child: Column(
children: [ children: [
ScheduleItem( ScheduleItem(
@@ -93,6 +95,7 @@ class _ProfessionalScheduleScreenState
], ],
), ),
), ),
),
); );
} }
} }
@@ -6,6 +6,8 @@ import 'package:prosappco/blocs/auth_bloc/auth_bloc.dart';
import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart'; import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart';
import 'package:prosappco/components/general_primary_button.dart'; import 'package:prosappco/components/general_primary_button.dart';
final _formKey = GlobalKey<FormState>();
class ProfileRegisterEmailScreen extends StatefulWidget { class ProfileRegisterEmailScreen extends StatefulWidget {
const ProfileRegisterEmailScreen({super.key}); const ProfileRegisterEmailScreen({super.key});
@@ -14,13 +16,38 @@ class ProfileRegisterEmailScreen extends StatefulWidget {
_ProfileRegisterEmailScreenState(); _ProfileRegisterEmailScreenState();
} }
class _ProfileRegisterEmailScreenState extends State<ProfileRegisterEmailScreen> { class _ProfileRegisterEmailScreenState
extends State<ProfileRegisterEmailScreen> {
final TextEditingController _emailController = TextEditingController(); final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController(); final TextEditingController _passwordController = TextEditingController();
final TextEditingController _confirmPasswordController =
TextEditingController();
late final AuthBloc authBloc; late final AuthBloc authBloc;
late String verificationCode; late String verificationCode;
String? validateEmail(String? email) {
RegExp emailRegex = RegExp(r'^[\w\.-]+@[\w-]+\.\w{2,3}(\.\w{2,3})?$');
final isEmailValid = emailRegex.hasMatch(email ?? '');
if (isEmailValid) {
return null;
} else {
return 'Ingresa un correo electronico valido';
}
}
String? validatePassword(String? password) {
RegExp passwordRegex = RegExp(r'^(?=.*?[0-9])');
final isPasswordValid = passwordRegex.hasMatch(password ?? '');
if (isPasswordValid) {
return null;
} else {
return 'La contraseña debe tener al menos un número';
}
}
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -31,6 +58,7 @@ class _ProfileRegisterEmailScreenState extends State<ProfileRegisterEmailScreen>
void dispose() { void dispose() {
_emailController.dispose(); _emailController.dispose();
_passwordController.dispose(); _passwordController.dispose();
_confirmPasswordController.dispose();
super.dispose(); super.dispose();
} }
@@ -46,7 +74,6 @@ class _ProfileRegisterEmailScreenState extends State<ProfileRegisterEmailScreen>
child: BlocConsumer<AuthBloc, AuthState>( child: BlocConsumer<AuthBloc, AuthState>(
listener: (context, state) { listener: (context, state) {
if (state is AuthStateSuccess) { if (state is AuthStateSuccess) {
// here update email and password autentication
authBloc.add( authBloc.add(
AuthEventAddEmailAndPassword( AuthEventAddEmailAndPassword(
email: _emailController.text, email: _emailController.text,
@@ -82,7 +109,6 @@ class _ProfileRegisterEmailScreenState extends State<ProfileRegisterEmailScreen>
numberOfFields: 6, numberOfFields: 6,
fieldWidth: 35, fieldWidth: 35,
borderColor: const Color(0xFF512DA8), borderColor: const Color(0xFF512DA8),
// showFieldAsBox: true,
onCodeChanged: (String code) { onCodeChanged: (String code) {
verificationCode = code; verificationCode = code;
}, },
@@ -110,7 +136,6 @@ class _ProfileRegisterEmailScreenState extends State<ProfileRegisterEmailScreen>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// _showLoginModal(context);
return BlocProvider<AuthBloc>( return BlocProvider<AuthBloc>(
create: (context) => authBloc, create: (context) => authBloc,
child: BlocListener<AuthBloc, AuthState>( child: BlocListener<AuthBloc, AuthState>(
@@ -126,9 +151,7 @@ class _ProfileRegisterEmailScreenState extends State<ProfileRegisterEmailScreen>
Navigator.of(context).pop(); Navigator.of(context).pop();
} }
if (state is AuthStateRequiresRecentLogin) { if (state is AuthStateRequiresRecentLogin) {}
// _showLoginModal(context, state);
}
}, },
child: BlocBuilder<MyUserBloc, MyUserState>( child: BlocBuilder<MyUserBloc, MyUserState>(
builder: (context, state) { builder: (context, state) {
@@ -139,113 +162,114 @@ class _ProfileRegisterEmailScreenState extends State<ProfileRegisterEmailScreen>
appBar: AppBar( appBar: AppBar(
title: const Text('Agregar correo'), title: const Text('Agregar correo'),
), ),
body: Center( body: Column(
// Centro del contenido children: [
Expanded(
child: SingleChildScrollView( child: SingleChildScrollView(
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 40, vertical: 10), horizontal: 40, vertical: 10),
child: Form(
key: _formKey,
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
TextFormField( TextFormField(
controller: _emailController, controller: _emailController,
decoration: const InputDecoration( decoration: InputDecoration(
labelText: 'Email', labelText: 'Email',
prefixIcon: Icon(Icons.email_rounded), prefixIcon: const Icon(Icons.email_rounded),
hintText: 'Email', hintText: 'Email',
border: OutlineInputBorder( border: inputBorder(),
borderRadius: BorderRadius.all( errorBorder: inputBorderError(),
Radius.circular(10.0), focusedErrorBorder: inputBorderFocus(),
)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
), ),
focusedErrorBorder: OutlineInputBorder( validator: validateEmail,
borderSide: autovalidateMode:
BorderSide(color: Colors.red, width: 2.0), AutovalidateMode.onUserInteraction,
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor, ingrese su contraseña';
}
return null;
},
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
TextFormField( TextFormField(
controller: _passwordController, controller: _passwordController,
obscureText: true, obscureText: true,
decoration: const InputDecoration( decoration: InputDecoration(
labelText: 'Contrasea', labelText: 'Contraseña',
prefixIcon: Icon(Icons.lock_rounded), prefixIcon: const Icon(Icons.lock_rounded),
hintText: 'Contrasea', hintText: 'Contraseña',
border: OutlineInputBorder( border: inputBorder(),
borderRadius: BorderRadius.all( errorBorder: inputBorderError(),
Radius.circular(10.0), focusedErrorBorder: inputBorderFocus(),
)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
), ),
focusedErrorBorder: OutlineInputBorder( validator: validatePassword,
borderSide: autovalidateMode:
BorderSide(color: Colors.red, width: 2.0), AutovalidateMode.onUserInteraction,
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor, ingrese su contraseña';
}
return null;
},
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
TextFormField( TextFormField(
controller: _passwordController, controller: _confirmPasswordController,
obscureText: true, obscureText: true,
decoration: const InputDecoration( decoration: InputDecoration(
labelText: 'Confirmar contraseña', labelText: 'Confirmar contraseña',
prefixIcon: Icon(Icons.lock_rounded), prefixIcon: const Icon(Icons.lock_rounded),
hintText: 'Contraseña', hintText: 'Contraseña',
border: OutlineInputBorder( border: inputBorder(),
borderRadius: BorderRadius.all( errorBorder: inputBorderError(),
Radius.circular(10.0), focusedErrorBorder: inputBorderFocus(),
)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red, width: 2.0),
),
), ),
validator: (value) { validator: (value) {
if (value == null || value.isEmpty) { if (value != _passwordController.text) {
return 'Por favor, ingrese su contraseña'; return 'Las contraseñas no coinciden';
}
if (value!.isEmpty) {
return 'La contraseña es obligatoria';
} }
return null; return null;
}, },
autovalidateMode:
AutovalidateMode.onUserInteraction,
), ),
const SizedBox(height: 30), const SizedBox(height: 30),
GeneralPrimaryButton(
onPressed: () {
if (_emailController.text.isEmpty) {
return;
}
if (_passwordController.text.isEmpty) {
return;
}
_showLoginModal(context, state);
},
label: 'Guardar',
),
], ],
), ),
), ),
), ),
), ),
),
const Divider(
height: 1,
thickness: 0.5,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10,
horizontal: 15,
),
child: FilledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_showLoginModal(context, state);
}
},
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: const Text(
'Guardar',
style: TextStyle(color: Colors.white, fontSize: 18),
),
),
),
),
],
),
); );
} else { } else {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
@@ -255,4 +279,27 @@ class _ProfileRegisterEmailScreenState extends State<ProfileRegisterEmailScreen>
), ),
); );
} }
OutlineInputBorder inputBorderFocus() {
return OutlineInputBorder(
borderSide: BorderSide(
color: Colors.red,
width: 2.0,
),
);
}
OutlineInputBorder inputBorderError() {
return OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
);
}
OutlineInputBorder inputBorder() {
return OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
),
);
}
} }
+43 -24
View File
@@ -98,7 +98,10 @@ class _ProfileScreenState extends State<ProfileScreen> {
_birthdayController.text = state.user!.birthday ?? ''; _birthdayController.text = state.user!.birthday ?? '';
_genderController.text = state.user!.gender ?? ''; _genderController.text = state.user!.gender ?? '';
return SingleChildScrollView( return Column(
children: [
Expanded(
child: SingleChildScrollView(
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 40, vertical: 10), horizontal: 40, vertical: 10),
@@ -121,8 +124,8 @@ class _ProfileScreenState extends State<ProfileScreen> {
borderSide: BorderSide(color: Colors.red), borderSide: BorderSide(color: Colors.red),
), ),
focusedErrorBorder: OutlineInputBorder( focusedErrorBorder: OutlineInputBorder(
borderSide: borderSide: BorderSide(
BorderSide(color: Colors.red, width: 2.0), color: Colors.red, width: 2.0),
), ),
), ),
validator: (value) { validator: (value) {
@@ -162,8 +165,8 @@ class _ProfileScreenState extends State<ProfileScreen> {
borderSide: BorderSide(color: Colors.red), borderSide: BorderSide(color: Colors.red),
), ),
focusedErrorBorder: OutlineInputBorder( focusedErrorBorder: OutlineInputBorder(
borderSide: borderSide: BorderSide(
BorderSide(color: Colors.red, width: 2.0), color: Colors.red, width: 2.0),
), ),
), ),
validator: (value) { validator: (value) {
@@ -201,7 +204,8 @@ class _ProfileScreenState extends State<ProfileScreen> {
onTap: () { onTap: () {
if (state.user!.name == null || if (state.user!.name == null ||
state.user!.name == '') { state.user!.name == '') {
ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context)
.clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( const SnackBar(
content: Text( content: Text(
@@ -211,19 +215,20 @@ class _ProfileScreenState extends State<ProfileScreen> {
if (state.user!.city == null || if (state.user!.city == null ||
state.user!.city == '') { state.user!.city == '') {
ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context)
.clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( const SnackBar(
content: Text( content: Text(
'Por favor, ingrese su nombre'))); 'Por favor, ingrese su ciudad')));
return; return;
} }
Navigator.push( Navigator.push(
context, context,
CupertinoPageRoute( CupertinoPageRoute(
builder: (context) => builder: (context) => _emailController
_emailController.text.isEmpty .text.isEmpty
? ProfileRegisterEmailScreen() ? ProfileRegisterEmailScreen()
: ProfileUpdatePasswordScreen( : ProfileUpdatePasswordScreen(
email: _emailController.text)), email: _emailController.text)),
@@ -232,13 +237,15 @@ class _ProfileScreenState extends State<ProfileScreen> {
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
ProfileItem( ProfileItem(
title: 'Configurar inicio de sesión con celular', title:
'Configurar inicio de sesión con celular',
subtitle: _phoneController.text, subtitle: _phoneController.text,
leading: Icons.phone_iphone_rounded, leading: Icons.phone_iphone_rounded,
onTap: () { onTap: () {
if (state.user!.name == null || if (state.user!.name == null ||
state.user!.name == '') { state.user!.name == '') {
ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context)
.clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( const SnackBar(
content: Text( content: Text(
@@ -248,7 +255,8 @@ class _ProfileScreenState extends State<ProfileScreen> {
if (state.user!.city == null || if (state.user!.city == null ||
state.user!.city == '') { state.user!.city == '') {
ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context)
.clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( const SnackBar(
content: Text( content: Text(
@@ -267,11 +275,24 @@ class _ProfileScreenState extends State<ProfileScreen> {
} }
}, },
), ),
const SizedBox(height: 60.0), const SizedBox(height: 10),
saveButton(state, context),
], ],
), ),
), ),
),
),
const Divider(
height: 1,
thickness: 0.5,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10,
horizontal: 15,
),
child: saveButton(state, context),
),
],
); );
} else { } else {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
@@ -302,6 +323,8 @@ class _ProfileScreenState extends State<ProfileScreen> {
ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Por favor, ingrese su ciudad'))); const SnackBar(content: Text('Por favor, ingrese su ciudad')));
return;
} }
final myUser = state.user!.copyWith( final myUser = state.user!.copyWith(
@@ -325,17 +348,14 @@ class _ProfileScreenState extends State<ProfileScreen> {
Navigator.pop(context); Navigator.pop(context);
}, },
style: ElevatedButton.styleFrom( style: FilledButton.styleFrom(
backgroundColor: Colors.blue, backgroundColor: Theme.of(context).colorScheme.primary,
padding: const EdgeInsets.symmetric(vertical: 5), padding: const EdgeInsets.symmetric(vertical: 15),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50), borderRadius: BorderRadius.circular(10),
), ),
shadowColor: Colors.grey,
// elevation: 0,
), ),
child: Container( child: Container(
constraints: const BoxConstraints(maxWidth: 300.0, minHeight: 50.0),
alignment: Alignment.center, alignment: Alignment.center,
child: isLoading child: isLoading
? const CircularProgressIndicator( ? const CircularProgressIndicator(
@@ -345,8 +365,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
'Actualizar', 'Actualizar',
style: TextStyle( style: TextStyle(
color: Colors.white, color: Colors.white,
fontSize: 16, fontSize: 18,
fontWeight: FontWeight.bold,
), ),
), ),
), ),
+1 -1
View File
@@ -350,7 +350,7 @@ class UserCalendarScreenState extends State<UserCalendarScreen> {
), ),
), ),
title: Text( title: Text(
time.format(context), ScheduleEntity.getFormatTime(time) ?? '',
style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
), ),
subtitle: const Text( subtitle: const Text(
+164 -17
View File
@@ -1,17 +1,25 @@
import 'dart:async'; import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:geocoding/geocoding.dart'; import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart'; import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:injector/injector.dart'; import 'package:injector/injector.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:professional_repository/professional_repository.dart';
import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart'; import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart';
import 'package:prosappco/blocs/professional_list_bloc/professional_list_bloc.dart'; import 'package:prosappco/blocs/professional_list_bloc/professional_list_bloc.dart';
import 'package:prosappco/blocs/service_bloc/service_bloc.dart'; import 'package:prosappco/blocs/service_bloc/service_bloc.dart';
import 'package:prosappco/constansts.dart';
import 'package:prosappco/screens/lists/city_list_screen.dart';
import 'package:prosappco/screens/lists/professional_list_screen.dart'; import 'package:prosappco/screens/lists/professional_list_screen.dart';
import 'package:prosappco/screens/user/user_service_screen.dart';
import 'package:prosappco/screens/web/web_view_screen.dart';
import 'package:prosappco/utils/time_of_day_extension.dart'; import 'package:prosappco/utils/time_of_day_extension.dart';
import 'package:service_repository/service_repository.dart'; import 'package:service_repository/service_repository.dart';
import 'package:setting_repository/setting_repository.dart'; import 'package:setting_repository/setting_repository.dart';
@@ -42,13 +50,42 @@ class _UserMapScreenState extends State<UserMapScreen> {
ServiceLocationPreferences? serviceLocationPreference; ServiceLocationPreferences? serviceLocationPreference;
UserProfessional? profesionalSeleccionado; UserProfessional? profesionalSeleccionado;
Map<PolylineId, Polyline> polylines = {};
bool isClearButtonVisible = false; bool isClearButtonVisible = false;
bool isLoading = false;
Set<Marker> markers = {};
BitmapDescriptor? _markerIcon;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_loadSettings(); _loadSettings();
getLocation();
if (Platform.isAndroid) {
BitmapDescriptor.fromAssetImage(
const ImageConfiguration(size: Size(2, 2)),
'images/pro_marke_android.png',
).then((icon) {
setState(() {
_markerIcon = icon;
});
});
} else {
BitmapDescriptor.fromAssetImage(
const ImageConfiguration(size: Size(1, 1)),
'images/pro_marke.png',
).then((icon) {
setState(() {
_markerIcon = icon;
});
});
}
} }
void _loadSettings() { void _loadSettings() {
@@ -63,8 +100,31 @@ class _UserMapScreenState extends State<UserMapScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocProvider<ServiceBloc>( return BlocProvider<ServiceBloc>(
create: (context) => Injector.appInstance.get<ServiceBloc>(), create: (context) => Injector.appInstance.get<ServiceBloc>(),
child: BlocBuilder<MyUserBloc, MyUserState>( child: BlocConsumer<ServiceBloc, ServiceState>(
listener: (context, serviceState) {
if (serviceState is CreateServiceLoading) {
isLoading = true;
}
if (serviceState is CreateServiceFailure) {
isLoading = false;
}
if (serviceState is CreateServiceSuccess) {
isLoading = false;
Navigator.push(
context,
CupertinoPageRoute(
builder: (BuildContext context) {
return UserServiceScreen(serviceId: serviceState.serviceId);
},
),
);
}
},
builder: (context, state) { builder: (context, state) {
return BlocBuilder<MyUserBloc, MyUserState>(
builder: (context, myUserState) {
return Column( return Column(
children: [ children: [
Expanded( Expanded(
@@ -72,10 +132,17 @@ class _UserMapScreenState extends State<UserMapScreen> {
children: [ children: [
GoogleMap( GoogleMap(
myLocationEnabled: true, myLocationEnabled: true,
// polylines: Set<Polyline>.of(polylines.values), polylines: Set<Polyline>.of(polylines.values),
onMapCreated: (GoogleMapController controller) { onMapCreated: (GoogleMapController controller) {
_mapController.complete(controller); _mapController.complete(controller);
}, },
markers: {
...markers,
Marker(
markerId: const MarkerId('currentLocation'),
position: _currentP ?? const LatLng(0, 0),
),
},
onCameraIdle: () { onCameraIdle: () {
getLocationName( getLocationName(
coordenadas.latitude, coordenadas.longitude) coordenadas.latitude, coordenadas.longitude)
@@ -138,7 +205,6 @@ class _UserMapScreenState extends State<UserMapScreen> {
try { try {
Position position = await _determinePosition(); Position position = await _determinePosition();
if (mounted) {
setState(() { setState(() {
_currentP = LatLng( _currentP = LatLng(
position.latitude, position.latitude,
@@ -147,12 +213,12 @@ class _UserMapScreenState extends State<UserMapScreen> {
}); });
_animateCameraToPosition(_currentP!); _animateCameraToPosition(_currentP!);
}
} catch (e) { } catch (e) {
ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( const SnackBar(
content: Text('Por favor activa la ubicacion'), content:
Text('Por favor activa la ubicacion'),
), ),
); );
} }
@@ -167,13 +233,12 @@ class _UserMapScreenState extends State<UserMapScreen> {
], ],
), ),
), ),
BlocListener<ServiceBloc, ServiceState>( buildBottom(context, myUserState),
listener: (context, state) {},
child: buildBottom(context, state),
),
], ],
); );
}, },
);
},
), ),
); );
} }
@@ -199,6 +264,8 @@ class _UserMapScreenState extends State<UserMapScreen> {
})); }));
if (datos != null) { if (datos != null) {
polylines.clear();
fechaSeleccionada = datos[0]; fechaSeleccionada = datos[0];
horaSeleccionada = datos[1]; horaSeleccionada = datos[1];
serviceLocationPreference = datos[2]; serviceLocationPreference = datos[2];
@@ -220,6 +287,31 @@ class _UserMapScreenState extends State<UserMapScreen> {
profesionalSeleccionado!.professionalInfo.latitude, profesionalSeleccionado!.professionalInfo.latitude,
profesionalSeleccionado!.professionalInfo.longitude, profesionalSeleccionado!.professionalInfo.longitude,
); );
if (_currentP != null) {
getPolylinePoints(
_currentP!,
LatLng(
profesionalSeleccionado!.professionalInfo.latitude,
profesionalSeleccionado!.professionalInfo.longitude,
)).then(
(coordinates) => {
generatePolyLineFromPoints(coordinates),
},
);
}
markers.add(
Marker(
icon: _markerIcon!,
markerId: MarkerId(
profesionalSeleccionado!.professionalInfo.id),
position: LatLng(
profesionalSeleccionado!.professionalInfo.latitude,
profesionalSeleccionado!.professionalInfo.longitude,
),
),
);
} else {} } else {}
isClearButtonVisible = true; isClearButtonVisible = true;
@@ -267,7 +359,7 @@ class _UserMapScreenState extends State<UserMapScreen> {
controller: TextEditingController( controller: TextEditingController(
text: horaSeleccionada == null text: horaSeleccionada == null
? '' ? ''
: horaSeleccionada!.format(context), : ScheduleEntity.getFormatTime(horaSeleccionada),
), ),
decoration: const InputDecoration( decoration: const InputDecoration(
prefixIcon: Icon(Icons.watch_later_outlined), prefixIcon: Icon(Icons.watch_later_outlined),
@@ -278,9 +370,9 @@ class _UserMapScreenState extends State<UserMapScreen> {
], ],
), ),
const SizedBox(height: 15), const SizedBox(height: 15),
const TextField( TextField(
// controller: _observacionController, controller: _observationController,
decoration: InputDecoration( decoration: const InputDecoration(
prefixIcon: Icon(Icons.message_outlined), prefixIcon: Icon(Icons.message_outlined),
hintText: 'Observaciones', hintText: 'Observaciones',
), ),
@@ -293,18 +385,20 @@ class _UserMapScreenState extends State<UserMapScreen> {
children: [ children: [
Expanded( Expanded(
child: FilledButton( child: FilledButton(
onPressed: () { onPressed: isLoading
? null
: () {
if (serviceLocationPreference == if (serviceLocationPreference ==
ServiceLocationPreferences.office) { ServiceLocationPreferences.office) {
context.read<ServiceBloc>().add( context.read<ServiceBloc>().add(
CreateService( CreateService(
professionalId: professionalId: profesionalSeleccionado!
profesionalSeleccionado!.professionalInfo.id, .professionalInfo.id,
userId: state.user!.id, userId: state.user!.id,
address: profesionalSeleccionado! address: profesionalSeleccionado!
.professionalInfo.address, .professionalInfo.address,
aditionalAddress: profesionalSeleccionado! aditionalAddress: profesionalSeleccionado!
.professionalInfo.address, .professionalInfo.aditionalAddress,
latitude: profesionalSeleccionado! latitude: profesionalSeleccionado!
.professionalInfo.latitude, .professionalInfo.latitude,
longitude: profesionalSeleccionado! longitude: profesionalSeleccionado!
@@ -351,6 +445,9 @@ class _UserMapScreenState extends State<UserMapScreen> {
isClearButtonVisible = false; isClearButtonVisible = false;
_observationController.text = ''; _observationController.text = '';
serviceLocationPreference = null; serviceLocationPreference = null;
polylines.clear();
markers.clear();
setState(() {}); setState(() {});
}, },
style: FilledButton.styleFrom( style: FilledButton.styleFrom(
@@ -387,6 +484,56 @@ class _UserMapScreenState extends State<UserMapScreen> {
); );
} }
Future<List<LatLng>> getPolylinePoints(
LatLng originP, LatLng destinationP) async {
List<LatLng> polylineCoordinates = [];
PolylinePoints polylinePoints = PolylinePoints();
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
GOOGLE_MAPS_API_KEY,
PointLatLng(originP.latitude, originP.longitude),
PointLatLng(destinationP.latitude, destinationP.longitude),
travelMode: TravelMode.driving,
);
if (result.points.isNotEmpty) {
for (var point in result.points) {
polylineCoordinates.add(LatLng(point.latitude, point.longitude));
}
} else {
print(result.errorMessage);
}
return polylineCoordinates;
}
void getLocation() async {
try {
Position position = await _determinePosition();
setState(() {
_currentP = LatLng(
position.latitude,
position.longitude,
);
});
_animateCameraToPosition(_currentP!);
} catch (e) {
log(e.toString());
}
}
void generatePolyLineFromPoints(List<LatLng> polylineCoordinates) async {
PolylineId id = const PolylineId("poly");
Polyline polyline = Polyline(
polylineId: id,
color: Colors.blue,
points: polylineCoordinates,
width: 6,
);
setState(() {
polylines[id] = polyline;
});
}
Future<String> getLocationName(double latitude, double longitude) async { Future<String> getLocationName(double latitude, double longitude) async {
String address; String address;
List<Placemark> placemarks = List<Placemark> placemarks =
+380
View File
@@ -0,0 +1,380 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injector/injector.dart';
import 'package:intl/intl.dart';
import 'package:professional_repository/professional_repository.dart';
import 'package:prosappco/blocs/service_bloc/service_bloc.dart';
import 'package:prosappco/components/general_primary_button.dart';
import 'package:service_repository/service_repository.dart';
import 'package:setting_repository/setting_repository.dart';
import 'package:user_repository/user_repository.dart';
class UserServiceScreen extends StatefulWidget {
final String serviceId;
const UserServiceScreen({Key? key, required this.serviceId})
: super(key: key);
@override
State<UserServiceScreen> createState() => _UserServiceScreenState();
}
class _UserServiceScreenState extends State<UserServiceScreen> {
final settingRepository = Injector.appInstance.get<SettingRepository>();
SettingEntity? settings;
@override
void initState() {
super.initState();
_loadSettings();
}
void _loadSettings() {
settingRepository.getSettings().then(
(value) => setState(() {
settings = value;
}),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Servicio'),
),
body: BlocBuilder<ServiceBloc, ServiceState>(
builder: (context, state) {
if (state is ServiceLoaded) {
final service = state.service;
return FutureBuilder(
future: _getUserAndProfessionalInfo(service),
builder: (BuildContext context,
AsyncSnapshot<List<dynamic>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else {
if (snapshot.hasError) {
return Center(
child: Text('Error inesperado: ${snapshot.error}'),
);
} else {
final userInfo = snapshot.data![0] as MyUser;
final professionalInfo =
snapshot.data![1] as ProfessionalEntity;
return Column(
children: [
ListTile(
leading: Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Colors.grey.shade300,
shape: BoxShape.circle,
image: userInfo.picture == null
? null
: DecorationImage(
image: NetworkImage(userInfo.picture!),
fit: BoxFit.contain,
),
),
child: userInfo.picture == null
? Icon(
CupertinoIcons.person,
color: Colors.grey.shade400,
size: 40,
)
: null,
),
title: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${userInfo.name}',
style: const TextStyle(
fontWeight: FontWeight.bold),
),
const SizedBox(width: 5),
Text(
'${DateFormat('dd MMMM', 'es').format(DateTime.parse(service.day))} - ${ScheduleEntity.getFormatTime(service.range1Hour1)}',
style: TextStyle(
color: Colors.grey[600],
),
),
],
),
subtitle: const Text('Rating: 5.0'),
),
Container(
margin: const EdgeInsets.only(
left: 40, right: 40, top: 20, bottom: 20),
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 15),
decoration: BoxDecoration(
color: const Color(0xFFD6F4FF),
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 5,
offset: const Offset(1, 3),
),
],
),
child: Row(
children: [
const Icon(
Icons.error_outline,
size: 27,
color: Colors.black54,
),
const SizedBox(width: 15),
service.location ==
ServiceLocationPreferences.delivery
? const Text(
'Servicio a su domicilio.',
style: TextStyle(
color: Colors.black, fontSize: 14),
)
: const Text(
'Servicio en sitio / consultorio',
style: TextStyle(
color: Colors.black, fontSize: 14),
),
],
),
),
Visibility(
visible: settings?.tarifas ?? false,
child: Column(
children: [
Text(
formatCurrency(int.tryParse(service.rate) ?? 0),
style: const TextStyle(
fontWeight: FontWeight.w600, fontSize: 25),
),
const Text('Tarifa de consulta'),
const SizedBox(height: 15),
const Text(
'Metodos de pago',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
professionalInfo.paymentMethods.datafono ||
professionalInfo.paymentMethods.nequi ||
professionalInfo
.paymentMethods.transferencia
? Wrap(
spacing: 8,
runSpacing: 8,
alignment: WrapAlignment.center,
children: [
Visibility(
visible: professionalInfo
.paymentMethods.datafono,
child: const Chip(
label: Text('Datafono')),
),
Visibility(
visible: professionalInfo
.paymentMethods.nequi,
child:
const Chip(label: Text('Nequi')),
),
Visibility(
visible: professionalInfo
.paymentMethods.transferencia,
child: const Chip(
label: Text(
'Transferencia Bancaria')),
),
],
)
: const Text(
'No hay metodos de pago registrados',
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 15,
color: Colors.black45,
),
),
],
),
),
ListTile(
leading: const Icon(Icons.near_me),
title: Text(
service.address,
style: TextStyle(
fontSize: 15, color: Colors.grey[600]),
),
subtitle: service.aditionalAddress.isEmpty
? null
: Text(
service.aditionalAddress,
style: TextStyle(
fontSize: 15, color: Colors.grey[600]),
),
),
service.description.isEmpty
? const SizedBox()
: SizedBox(
width: MediaQuery.of(context).size.width * 0.8,
child: Text(
'"${service.description.trim()}"',
style: TextStyle(
color: Colors.grey[600],
fontStyle: FontStyle.italic,
),
),
),
Expanded(
child: customMessageStatus(service),
),
customButton(service, context),
const SizedBox(height: 20),
],
);
}
}
},
);
} else {
BlocProvider.of<ServiceBloc>(context)
.add(LoadService(widget.serviceId));
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
Center customMessageStatus(ServiceEntity service) {
if (service.status == ServiceStatus.cancelled) {
return const Center(
child: Column(
children: [
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: Icon(
CupertinoIcons.xmark_circle,
color: Color(0xFF35A8ED),
size: 70,
),
),
Text(
'Servicio cancelado exitosamente',
style: TextStyle(
color: Color(0xFF35A8ED),
fontSize: 17,
fontWeight: FontWeight.w600,
),
),
],
),
);
}
if (service.status == ServiceStatus.completed) {
return const Center(
child: Column(
children: [
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: Icon(
Icons.favorite_outline_sharp,
color: Color(0xFF35A8ED),
size: 70,
),
),
Text(
'Servicio terminado exitosamente',
style: TextStyle(
color: Color(0xFF35A8ED),
fontSize: 17,
fontWeight: FontWeight.w600,
),
),
],
),
);
}
return const Center(
child: Column(
children: [
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: Icon(
Icons.check_circle_outline_rounded,
color: Color(0xFF35A8ED),
size: 70,
),
),
Text(
'Servicio solicitado exitosamente',
style: TextStyle(
color: Color(0xFF35A8ED),
fontSize: 17,
fontWeight: FontWeight.w600,
),
),
],
),
);
}
GeneralPrimaryButton customButton(
ServiceEntity service, BuildContext context) {
if (service.status == ServiceStatus.pending) {
return GeneralPrimaryButton(
onPressed: () {
final currentState = context.read<ServiceBloc>().state;
if (currentState is ServiceLoaded) {
context.read<ServiceBloc>().add(
UpdateServiceStatus(
widget.serviceId,
ServiceStatus.cancelled,
),
);
}
},
color: Colors.red,
label: 'Cancelar Servicio',
);
}
return GeneralPrimaryButton(
onPressed: () {
Navigator.pop(context);
},
label: 'Volver',
);
}
String formatCurrency(int number) {
final formatter =
NumberFormat.currency(locale: 'es_CO', decimalDigits: 0, symbol: '');
return '\$${formatter.format(number)}';
}
Future<List<dynamic>> _getUserAndProfessionalInfo(
ServiceEntity service) async {
final userRepo = FirebaseUserRepository(FirebaseAuth.instance);
final userInfo = await userRepo.getMyUser(service.professionalId);
final professionalRepo = FirebaseProfessionalRepository();
final professionalInfo =
await professionalRepo.getProInfo(service.professionalId);
return [userInfo, professionalInfo];
}
}
@@ -91,7 +91,7 @@ class ScheduleEntity extends Equatable {
return null; return null;
} }
String? getFormatTime(TimeOfDay? time) { static String? getFormatTime(TimeOfDay? time) {
if (time == null) { if (time == null) {
return null; return null;
} }
@@ -53,14 +53,19 @@ class ServiceEntity extends Equatable {
day: doc['day'] as String, day: doc['day'] as String,
createdAt: doc['created_at'] as Timestamp, createdAt: doc['created_at'] as Timestamp,
description: doc['description'] as String, description: doc['description'] as String,
range1Hour1: doc['range1_hour1'] as TimeOfDay, range1Hour1: parseTimeOfDay(doc['range1_hour1'] as String),
range1Hour2: doc['range1_hour2'] as TimeOfDay, range1Hour2: parseTimeOfDay(doc['range1_hour2'] as String),
status: intToEnumService(doc['status'] as int), status: intToEnumService(doc['status'] as int),
rate: doc['rate'] as String, rate: doc['rate'] as String,
location: intToEnum(doc['location'] as int), location: intToEnum(doc['location'] as int),
); );
} }
static TimeOfDay parseTimeOfDay(String timeString) {
final parts = timeString.split(':');
return TimeOfDay(hour: int.parse(parts[0]), minute: int.parse(parts[1]));
}
Map<String, dynamic> toDocument() { Map<String, dynamic> toDocument() {
return { return {
'professional_id': professionalId, 'professional_id': professionalId,
@@ -74,14 +79,21 @@ class ServiceEntity extends Equatable {
'day': day, 'day': day,
'created_at': createdAt, 'created_at': createdAt,
'description': description, 'description': description,
'range1_hour1': range1Hour1, 'range1_hour1': formatTimeOfDay(range1Hour1),
'range1_hour2': range1Hour2, 'range1_hour2': formatTimeOfDay(range1Hour2),
'rate': rate, 'rate': rate,
'status': enumToIntService(status), 'status': enumToIntService(status),
'location': enumToInt(location), 'location': enumToInt(location),
}; };
} }
String? formatTimeOfDay(TimeOfDay? time) {
if (time != null) {
return "${time.hour.toString()}:${time.minute.toString()}";
}
return null;
}
@override @override
List<Object> get props => [ List<Object> get props => [
professionalId, professionalId,
@@ -1,6 +1,6 @@
export 'service_status.dart'; export 'service_status.dart';
enum ServiceStatus { pending, active, cancelled, completed } enum ServiceStatus { pending, acepted, active, cancelled, completed }
int enumToIntService(ServiceStatus state) { int enumToIntService(ServiceStatus state) {
return state.index; return state.index;
@@ -1,13 +1,30 @@
import 'dart:developer';
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:service_repository/service_repository.dart'; import 'package:service_repository/service_repository.dart';
class FirebaseServiceRepository { class FirebaseServiceRepository {
final serviceCollection = FirebaseFirestore.instance.collection('services'); final serviceCollection =
FirebaseFirestore.instance.collection('services v2');
Future<void> createService(ServiceEntity entity) async { Future<String> createService(ServiceEntity entity) async {
log('xd -- ${entity.toString()}'); DocumentReference<Map<String, dynamic>> docRef =
await serviceCollection.add(entity.toDocument()); await serviceCollection.add(entity.toDocument());
return docRef.id;
}
Stream<ServiceEntity> getService(String serviceId) {
return serviceCollection.doc(serviceId).snapshots().map((snapshot) {
if (snapshot.exists) {
return ServiceEntity.fromDocument(snapshot.data()!);
} else {
throw Exception('El servicio con ID $serviceId no existe');
}
});
}
Future<void> updateServiceStatus(
String serviceId, ServiceStatus newStatus) async {
await serviceCollection
.doc(serviceId)
.update({'status': enumToIntService(newStatus)});
} }
} }