This commit is contained in:
Felipe
2023-11-14 17:20:12 -05:00
parent 26780112d8
commit a4f631497d
3 changed files with 725 additions and 1332 deletions
+59 -27
View File
@@ -47,7 +47,6 @@ class _ServiceScreenState extends State<ServiceScreen> {
Completer<GoogleMapController>();
static const LatLng _pGooglePlex = LatLng(7.080486, -73.087447);
static const LatLng _pApplePark = LatLng(7.074710, -73.090807);
LatLng? _currentP;
Map<PolylineId, Polyline> polylines = {};
@@ -90,15 +89,7 @@ class _ServiceScreenState extends State<ServiceScreen> {
_getAppVersion();
getLocationUpdates().then(
(_) => {
getPolylinePoints().then(
(coordinates) => {
generatePolyLineFromPoints(coordinates),
},
),
},
);
getLocationUpdates();
if (settings == null) {
SettingModel.getSettings().then(
@@ -210,16 +201,6 @@ class _ServiceScreenState extends State<ServiceScreen> {
icon: BitmapDescriptor.defaultMarker,
position: _currentP!,
),
// const Marker(
// markerId: MarkerId("_sourceLocation"),
// icon: BitmapDescriptor.defaultMarker,
// position: _pGooglePlex,
// ),
// const Marker(
// markerId: MarkerId("_destionationLocation"),
// icon: BitmapDescriptor.defaultMarker,
// position: _pApplePark,
// ),
},
polylines: Set<Polyline>.of(polylines.values),
onCameraIdle: () {
@@ -269,6 +250,17 @@ class _ServiceScreenState extends State<ServiceScreen> {
},
),
),
const Positioned(
bottom: 25,
right: 0,
left: 0,
top: 0,
child: Icon(
Icons.location_on,
size: 40,
color: Color(0xFFFF0000),
),
),
Positioned(
top: 10,
right: 20,
@@ -347,6 +339,31 @@ class _ServiceScreenState extends State<ServiceScreen> {
controller: _profesionalController,
readOnly: true,
onTap: () async {
if (_currentP == null) {
try {
Position position = await _determinePosition();
if (mounted) {
setState(() {
_currentP = LatLng(
position.latitude,
position.longitude,
);
});
_animateCameraToPosition(_currentP!);
}
} catch (e) {
WarningSnackbar.show(
title: 'Ubicación desactivada',
message:
'Por favor activa la ubicacion de tu telefono para solicitar un servicio.',
);
}
return;
}
final dynamic datos = await Navigator.push(
context,
CupertinoPageRoute(
@@ -386,15 +403,29 @@ class _ServiceScreenState extends State<ServiceScreen> {
_locacionController.text =
profesional.realAddress;
LatLng professionalCoordinates = LatLng(
professionalLatitude!,
professionalLongitude!);
if (professionalLatitude != null &&
professionalLatitude != 0 &&
professionalLongitude != null &&
professionalLongitude != 0) {
_animateCameraToPosition(LatLng(
professionalLatitude!,
professionalLongitude!,
));
_animateCameraToPosition(
LatLng(professionalLatitude!,
professionalLongitude!),
);
getPolylinePoints(
_currentP!, professionalCoordinates)
.then(
(coordinates) => {
generatePolyLineFromPoints(coordinates),
},
);
}
} else {
polylines.clear();
}
});
}
@@ -655,13 +686,14 @@ class _ServiceScreenState extends State<ServiceScreen> {
});
}
Future<List<LatLng>> getPolylinePoints() async {
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(_pGooglePlex.latitude, _pGooglePlex.longitude),
PointLatLng(_pApplePark.latitude, _pApplePark.longitude),
PointLatLng(originP.latitude, originP.longitude),
PointLatLng(destinationP.latitude, destinationP.longitude),
travelMode: TravelMode.driving,
);
if (result.points.isNotEmpty) {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,666 @@
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:prosappco/src/authentication/authentication_repository.dart';
import 'package:prosappco/src/presentation/widgets/shared/drawer_menu.dart';
import 'package:prosappco/src/models/event_model.dart';
import 'package:prosappco/src/models/setting_model.dart';
import 'package:prosappco/src/models/user_model.dart';
import 'package:prosappco/src/presentation/screens/professional.dart';
import 'package:intl/intl.dart';
import 'package:prosappco/src/presentation/screens/profile/profile.dart';
import 'package:prosappco/src/presentation/screens/profile/profile_web.dart';
import 'package:prosappco/src/presentation/screens/service_after.dart';
import 'package:prosappco/src/presentation/screens/service_type.dart';
import 'package:prosappco/src/presentation/screens/ubicacion.dart';
import 'package:http/http.dart' as http;
import 'package:prosappco/src/components/network_utility.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:prosappco/src/presentation/widgets/shared/primary_button.dart';
import 'package:prosappco/src/presentation/widgets/shared/warning_snackbar.dart';
import 'package:url_launcher/url_launcher.dart';
class ServiceWebScreen extends StatefulWidget {
const ServiceWebScreen({super.key});
@override
State<ServiceWebScreen> createState() => _ServiceOldScreenState();
}
class _ServiceOldScreenState extends State<ServiceWebScreen> {
void _saveToken() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
final token = await messaging.getToken();
try {
await FirebaseFirestore.instance
.collection('users')
.doc(uid)
.update({'token': token});
} catch (e) {
print(e);
}
}
Future<void> sendPushNotification(String pro) async {
try {
http.Response response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization':
'key=AAAAORdR-xU:APA91bF_wblg86jHAC-uexrXPHavYRlk5wge1Gf46m56V4J2D2L37Cp_hf46JZUzpvsWPSpqc5ewHelKI9LTifUG_s2mciMI6e5VLKo7E1R8btbNo7iaM9do2ctoyHKUm1atlZBdKaN2',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'alguien a solicitado tus servicios',
'title': 'Nueva solicitud',
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done',
'screen': 'solicitud'
},
'to': pro
},
),
);
response;
} catch (e) {
print('error al enviar notificacion $e');
}
}
EventoService eventoService = EventoService();
String ubicacion = '';
final TextEditingController _locationController = TextEditingController();
final TextEditingController _ubicationController = TextEditingController();
final TextEditingController _profesionalController = TextEditingController();
final TextEditingController _serviceTypeController = TextEditingController();
final TextEditingController _observacionController = TextEditingController();
String professionalId = '';
String professionalToken = '';
int? professionalTarifa;
String professionalAddress = '';
String professionalUbicacion = '';
double? professionalLatitude;
double? professionalLongitude;
String _serviceType = 'Servicio';
final DateFormat formatter = DateFormat('dd/MM/yyyy');
final DateTime now = DateTime.now();
List<dynamic> _placesList = [];
String selectedPlace = '';
String _coordsOfCity = '0.0,0.0';
DateTime? _selectedDate;
TimeOfDay? _selectedTime;
GoogleMapController? googleMapController;
Set<Marker> markers = {};
Future<Position> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permission denied');
}
}
if (permission == LocationPermission.deniedForever) {
return Future.error('Location permissions are permanently denied');
}
Position position = await Geolocator.getCurrentPosition();
return position;
}
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: now,
firstDate: now,
lastDate: DateTime(now.year + 1),
// builder: (context, child) {
// return Theme(data: ThemeData.dark(), child: child!);
// },
);
if (picked != null && picked != _selectedDate) {
if (mounted) {
setState(() {
_selectedDate = picked;
});
}
}
}
Future<void> _selectTime(BuildContext context) async {
final TimeOfDay? pickedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (pickedTime != null) {
if (mounted) {
setState(() {
_selectedTime = pickedTime;
});
}
}
}
Future<List<DocumentSnapshot<Map<String, dynamic>>>> getUsersWithActiveStatus(
String _serviceType) async {
var querySnapshot;
if (_serviceType != "Servicio") {
querySnapshot = await FirebaseFirestore.instance
.collection('users')
.where('estado', isEqualTo: 'activo')
.where('profesion', isEqualTo: _serviceType)
.get();
} else {
querySnapshot = await FirebaseFirestore.instance
.collection('users')
.where('estado', isEqualTo: 'activo')
.get();
}
return querySnapshot.docs;
}
final FirebaseStorage storage = FirebaseStorage.instance;
final uid = AuthenticationRepository.instance.getCurrentUserUid();
UserModel? user;
final fcmToken = FirebaseMessaging.instance.getToken();
BitmapDescriptor? _markerIcon;
String _ciudad = '...';
void _setInitialCameraPosition(String coordsOfCity) async {
List<String> coords = coordsOfCity.split(',');
double lat = double.parse(coords[0]);
double lng = double.parse(coords[1]);
googleMapController?.moveCamera(
CameraUpdate.newLatLngZoom(
LatLng(lat, lng),
14.4746,
),
);
try {
Position position = await _determinePosition();
googleMapController?.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(
position.latitude,
position.longitude,
),
zoom: 17,
),
),
);
if (mounted) {
setState(() {});
}
} catch (e) {
print('Error: $e');
}
}
@override
void dispose() {
_locationController.dispose();
_ubicationController.dispose();
_profesionalController.dispose();
_serviceTypeController.dispose();
_observacionController.dispose();
super.dispose();
}
void updateMarkersForServiceType(String serviceType) {
getUsersWithActiveStatus(serviceType).then((value) {
markers.clear();
for (var doc in value) {
final element = doc.data()!;
if (element['latitude'] != null && element['longitude'] != null) {
markers.add(
Marker(
icon: _markerIcon!,
markerId: MarkerId(doc.id),
position: LatLng(
element['latitude'],
element['longitude'],
),
),
);
}
}
}).catchError((e) {
print('Error al actualizar los marcadores: $e');
});
}
String? settings;
@override
void initState() {
super.initState();
if (_ciudad == '...') {
AuthenticationRepository.instance
.getCity(uid.toString())
.then((String s) {
if (s.isEmpty) {
FirebaseFirestore.instance.collection('users').doc(uid).set({
'city': 'Cúcuta',
}).then((_) {
if (mounted) {
setState(() {
_ciudad = 'Cúcuta';
});
}
});
} else {
if (mounted) {
setState(() {
_ciudad = s;
});
}
}
});
}
if (_coordsOfCity == '0.0,0.0') {
AuthenticationRepository.instance
.getCoordsOfCity(uid.toString())
.then((String s) {
if (mounted) {
setState(() {
_coordsOfCity = s;
_setInitialCameraPosition(_coordsOfCity);
});
}
});
}
_saveToken();
if (user == null) {
UserModel.getUser(uid.toString()).then((UserModel s) => (value) {
if (mounted) {
setState(() => user = s);
}
});
}
BitmapDescriptor.fromAssetImage(
const ImageConfiguration(size: Size(6, 6)), 'images/pro_marke.png')
.then((icon) {
if (mounted) {
setState(() {
_markerIcon = icon;
});
}
});
updateMarkersForServiceType(_serviceType);
}
static CameraPosition initialCameraPosition = const CameraPosition(
target: LatLng(7.8939100, -72.5078200),
zoom: 14.4746,
);
void setInitialCameraPosition(String coordsOfCity) {
if (coordsOfCity != '0.0,0.0') {
List<String> coords = coordsOfCity.split(',');
double lat = double.parse(coords[0]);
double lng = double.parse(coords[1]);
initialCameraPosition = CameraPosition(
target: LatLng(lat, lng),
zoom: 14.4746,
);
}
}
late String lat;
late String long;
double latUser = 0.0;
double lngUser = 0.0;
var coordinates;
Future<String> getLocationName(double latitude, double longitude) async {
String address;
List<Placemark> placemarks =
await placemarkFromCoordinates(latitude, longitude);
Placemark place = placemarks[0];
if (place.thoroughfare != '' || place.subThoroughfare != '') {
address =
"${place.thoroughfare} ${place.subThoroughfare} ${place.subLocality}, ${place.locality}, ${place.administrativeArea}";
} else {
address = '';
}
return address;
}
void placeAutoComplete(String query) async {
Uri uri = Uri.https("admin.prosapp.co", "/autocomplete", {
"input": query,
"location": _coordsOfCity,
});
String? response = await NetworkUtility.fetchUrl(uri);
if (response != null) {
if (mounted) {
setState(() {
_placesList = jsonDecode(response.toString())['results'];
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFD6F4FF),
drawer: DrawerMenu(),
appBar: AppBar(
elevation: 0,
title: const Text(
'Prosapp',
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
)),
body: Center(
child: SizedBox(
width: 300,
height: 470,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.white,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: _profesionalController,
readOnly: true,
onTap: () async {
final dynamic datos = await Navigator.push(
context,
CupertinoPageRoute(
builder: (BuildContext context) {
return ProfessionalScreen(
profession: _serviceTypeController.text,
);
},
),
);
if (datos != null) {
Professional? profesional = datos[0];
ubicacion = datos[1];
if (profesional != null) {
if (mounted) {
setState(() {
_profesionalController.text =
profesional.name.toString();
professionalId = profesional.id;
professionalTarifa = profesional.tarifa ?? 0;
professionalUbicacion = profesional.ubicacion;
professionalAddress = _ubicationController.text;
if (profesional.token != '') {
professionalToken = profesional.token!;
print(professionalToken);
}
if (ubicacion == 'sitio') {
professionalAddress = profesional.realAddress;
_ubicationController.text =
profesional.realAddress;
latUser = profesional.latitude;
lngUser = profesional.longitude;
}
});
}
}
}
},
decoration: const InputDecoration(
prefixIcon: Icon(Icons.assignment_ind_rounded),
suffixIcon: Icon(Icons.arrow_drop_down),
hintText: 'Seleccionar profesional'),
),
const SizedBox(height: 20.0),
TextFormField(
controller: _ubicationController,
readOnly: true,
onTap: () async {
final List<dynamic> datos = await Navigator.push(
context,
CupertinoPageRoute(
builder: (BuildContext context) {
return const UbicacionScreen();
},
),
);
if (datos.length == 3) {
final formattedAddress = datos[0];
final lat = datos[1];
final lng = datos[2];
if (mounted) {
setState(() {
_ubicationController.text = formattedAddress;
latUser = lat;
lngUser = lng;
});
}
}
},
decoration: const InputDecoration(
hintText: 'Escribe tu ubicación',
prefixIcon: Icon(Icons.location_on),
),
),
const SizedBox(height: 20.0),
TextFormField(
onTap: () {
if (_profesionalController.text.isNotEmpty) {
_selectDate(context);
} else {
Get.snackbar(
'Selecciona un profesional',
'Selecciona un profesional antes de elegir la fecha y la hora de la cita.',
snackPosition: SnackPosition.BOTTOM,
);
}
},
readOnly: true,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.calendar_month),
suffixIcon: _selectedDate == null
? const Icon(Icons.arrow_drop_down)
: null,
hintText: 'Fecha',
),
controller: TextEditingController(
text: _selectedDate == null
? ''
: formatter.format(_selectedDate!)),
),
const SizedBox(height: 20.0),
TextFormField(
onTap: () {
if (_profesionalController.text.isNotEmpty) {
_selectTime(context);
} else {
Get.snackbar(
'Selecciona un profesional',
'Selecciona un profesional antes de elegir la fecha y la hora de la cita.',
snackPosition: SnackPosition.BOTTOM,
);
}
},
readOnly: true,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.access_time),
suffixIcon: Icon(Icons.arrow_drop_down),
hintText: 'Hora',
),
controller: TextEditingController(
text: _selectedTime == null
? ''
: ' ${_selectedTime!.format(context)}'),
),
const SizedBox(height: 20.0),
TextFormField(
controller: _observacionController,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.message_outlined),
hintText: 'Observaciones'),
),
const SizedBox(height: 40.0),
ElevatedButton(
onPressed: () {
if (user?.name == null ||
user?.name == '' ||
user?.phoneNumber == null ||
user?.phoneNumber == '') {
Navigator.push(
context,
CupertinoPageRoute(
builder: (BuildContext context) {
return const ProfileWebScreen();
},
),
);
} else {
try {
final DateTime combinedDate = DateTime(
_selectedDate!.year,
_selectedDate!.month,
_selectedDate!.day,
_selectedTime!.hour,
_selectedTime!.minute,
);
DateTime time2 =
combinedDate.add(const Duration(hours: 2));
UserModel.getUser(uid.toString()).then((value) {
eventoService
.createEvent(
value.name,
_observacionController.text,
'$_selectedDate',
'$combinedDate',
'$time2',
professionalId,
ubicacion,
professionalAddress,
latUser,
lngUser,
'pendiente',
professionalTarifa == 0 ? 0 : professionalTarifa,
false,
false,
)
.then((value) {
if (professionalToken != '') {
sendPushNotification(professionalToken);
}
Navigator.pushReplacement(
context,
CupertinoPageRoute(
builder: (BuildContext context) {
return ServiceAfterScreen(
eventoId: value,
);
},
),
);
});
});
} catch (e) {
Get.snackbar(
'Llena todos los campos',
'Asegurate de llenar todos los campos.',
snackPosition: SnackPosition.BOTTOM,
);
}
}
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF2BA4EC),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
elevation: 0,
minimumSize: const Size(230, 50),
),
child: const Text(
'Solicitar servicio',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
),
],
),
),
),
),
),
);
}
}