Merge pull request 'feature/suggestion-tag' (#30) from feature/suggestion-tag into main

Reviewed-on: #30
This commit is contained in:
v4l3n71n 2024-12-28 14:52:39 +01:00
commit d8b3bf7ca2
3 changed files with 283 additions and 205 deletions

View File

@ -180,24 +180,23 @@ class _EditEventState extends State<EditEvent>
if (accessToken.isNotEmpty) { if (accessToken.isNotEmpty) {
try { try {
await dotenv.load(); await dotenv.load();
final mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? ''; final ApiTokenGoogle = dotenv.env['PLACE_API_KEY'] ?? '';
print("place non encoded : ${place}"); // Searchbox API for geocoding the place (No session token)
final url = final searchboxUrl = Uri.parse(
'https://api.mapbox.com/geocoding/v5/mapbox.places/${place}.json?access_token=${mapboxAccessToken}&types=poi,address,place'; 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=${place}&key=${ApiTokenGoogle}');
var encoded = Uri.encodeFull(url);
print("encoded : ${encoded}");
final response = await http.get(Uri.parse(encoded));
if (response.statusCode == 200) { // Perform the request
final data = json.decode(response.body); final searchboxResponse = await http.get(searchboxUrl);
if (searchboxResponse.statusCode == 200) {
final data = json.decode(searchboxResponse.body);
print("data : ${data}"); print("data : ${data}");
if (data['features'].isNotEmpty) { if (data['results'].isNotEmpty) {
place = data['features'][0]['place_name']; place = data['results'][0]['formatted_address'];
final coordinates = final coordinates = data['results'][0]['geometry']['location'];
data['features'][0]['geometry']['coordinates']; final longitude = coordinates["lng"]; // Longitude
final longitude = coordinates[0]; // Longitude final latitude = coordinates["lat"]; // Latitude
final latitude = coordinates[1]; // Latitude
var urlGet = Uri.parse( var urlGet = Uri.parse(
"${globals.api}/events/search?item=${name}&date_event=${startDate}&min_lat=$latitude&max_lat=$latitude" "${globals.api}/events/search?item=${name}&date_event=${startDate}&min_lat=$latitude&max_lat=$latitude"
"&min_lon=$longitude&max_lon=$longitude"); "&min_lon=$longitude&max_lon=$longitude");

View File

@ -14,6 +14,7 @@ import '../variable/globals.dart' as globals;
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import "Camera.dart"; import "Camera.dart";
import 'package:camera/camera.dart'; import 'package:camera/camera.dart';
import 'package:textfield_tags/textfield_tags.dart';
void main() { void main() {
initializeDateFormatting("fr_FR", null).then((_) => runApp(const MyApp())); initializeDateFormatting("fr_FR", null).then((_) => runApp(const MyApp()));
@ -43,17 +44,22 @@ class _MyHomePageState extends State<ListItemMenu> {
List<Events> filteredPosts = []; List<Events> filteredPosts = [];
String geographicalZone = ''; String geographicalZone = '';
String itemName = ''; String itemName = '';
String itemTags = '';
String query = ''; String query = '';
List<Map<String, dynamic>> suggestions = []; List<Map<String, dynamic>> suggestions = [];
List<Map<String, dynamic>> suggestionsItem = []; List<Map<String, dynamic>> suggestionsItem = [];
List<Map<String, dynamic>> suggestionsTags = [];
TextEditingController inputGeo = TextEditingController(); TextEditingController inputGeo = TextEditingController();
TextEditingController startDatepicker = TextEditingController(); TextEditingController startDatepicker = TextEditingController();
TextEditingController endDatepicker = TextEditingController(); TextEditingController endDatepicker = TextEditingController();
TextEditingController inputItem = TextEditingController(); TextEditingController inputItem = TextEditingController();
TextEditingController inputTags = TextEditingController();
bool showDateFields = false; // State to toggle date fields bool showDateFields = false; // State to toggle date fields
bool showArrow = true; bool showArrow = true;
bool showInputSearch = true; bool showInputSearch = true;
bool showInputGeo = true;
bool showInputTag = true;
// Fetching events from API // Fetching events from API
static Future<List<Events>> getPosts() async { static Future<List<Events>> getPosts() async {
PermissionStatus status = await Permission.location.status; PermissionStatus status = await Permission.location.status;
@ -264,6 +270,7 @@ class _MyHomePageState extends State<ListItemMenu> {
if (suggestions.isNotEmpty) { if (suggestions.isNotEmpty) {
showArrow = false; showArrow = false;
showInputSearch = false; showInputSearch = false;
showInputTag = false;
} }
}); });
} else { } else {
@ -318,6 +325,10 @@ class _MyHomePageState extends State<ListItemMenu> {
stringParameter = stringParameter + "&item=${inputItem.text}"; stringParameter = stringParameter + "&item=${inputItem.text}";
endpoint = "events/search"; endpoint = "events/search";
} }
if (inputTags.text.isNotEmpty) {
stringParameter = stringParameter + "&tags=${inputTags.text}";
endpoint = "events/search";
}
if (stringParameter.isNotEmpty) { if (stringParameter.isNotEmpty) {
stringParameter = "$stringParameter&$dateParameter"; stringParameter = "$stringParameter&$dateParameter";
} else { } else {
@ -353,6 +364,36 @@ class _MyHomePageState extends State<ListItemMenu> {
} }
} }
Future<void> searchSuggestionsByTag(String input) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token") ?? "";
if (accessToken.isNotEmpty) {
var url = Uri.parse("${globals.api}/tags?name=${input}");
final response = await http.get(url, headers: {
"Content-Type": "application/json",
HttpHeaders.cookieHeader: "access_token=$accessToken"
});
print("status code tags : ${response.statusCode}");
if (response.statusCode == 200) {
final data = json.decode(utf8.decode(response.bodyBytes));
print("tags ${data}");
setState(() {
suggestionsTags = (data as List)
.map((feature) => {'name': feature['name']})
.toList();
print("suggesttion tag : ${suggestionsTags}");
if (suggestionsTags.isNotEmpty) {
showInputGeo = false;
showInputSearch = false;
showArrow = false;
}
});
}
}
}
Future<void> fetchPostsByLocation() async { Future<void> fetchPostsByLocation() async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token") ?? ""; var accessToken = prefs.getString("access_token") ?? "";
@ -363,6 +404,7 @@ class _MyHomePageState extends State<ListItemMenu> {
"Content-Type": "application/json", "Content-Type": "application/json",
HttpHeaders.cookieHeader: "access_token=$accessToken" HttpHeaders.cookieHeader: "access_token=$accessToken"
}); });
print("status code : ${response.statusCode}"); print("status code : ${response.statusCode}");
if (response.statusCode == 200) { if (response.statusCode == 200) {
final List<dynamic> body = json.decode(utf8.decode(response.bodyBytes)); final List<dynamic> body = json.decode(utf8.decode(response.bodyBytes));
@ -464,6 +506,7 @@ class _MyHomePageState extends State<ListItemMenu> {
showInputSearch = showInputSearch =
true; // Optionally clear suggestions true; // Optionally clear suggestions
/// Clear the filtered posts /// Clear the filtered posts
showInputTag = true;
}); });
fetchPostsByLocation(); fetchPostsByLocation();
}, },
@ -485,6 +528,7 @@ class _MyHomePageState extends State<ListItemMenu> {
suggestions.clear(); // Optionally clear suggestions suggestions.clear(); // Optionally clear suggestions
showArrow = true; showArrow = true;
showInputSearch = true; showInputSearch = true;
showInputTag = true;
/// Clear the filted posts /// Clear the filted posts
}); });
@ -517,6 +561,7 @@ class _MyHomePageState extends State<ListItemMenu> {
suggestions.clear(); suggestions.clear();
showArrow = true; showArrow = true;
showInputSearch = true; showInputSearch = true;
showInputTag = true;
}); });
SharedPreferences prefs = SharedPreferences prefs =
await SharedPreferences.getInstance(); await SharedPreferences.getInstance();
@ -533,6 +578,80 @@ class _MyHomePageState extends State<ListItemMenu> {
); );
} }
Padding _buildTagsField() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
TextField(
controller: inputTags,
decoration: InputDecoration(
labelText: 'Search by tags',
border: OutlineInputBorder(),
suffixIcon: inputTags.text.isEmpty
? null
: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
setState(() {
inputTags.clear();
});
fetchPostsByLocation();
},
),
),
onChanged: (value) {
if (value.isNotEmpty) {
setState(() {
itemTags = value;
searchSuggestionsByTag(value);
});
} else {
setState(() {
inputTags.clear();
showArrow = true;
showInputSearch = true;
showInputGeo = true; // Optionally clear suggestions
itemTags = ''; // Clear the text field
/// Clear the filted posts
});
fetchPostsByLocation();
}
}),
if (suggestionsTags.isNotEmpty)
Container(
height: 200,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue),
borderRadius: BorderRadius.circular(8),
),
child: ListView.builder(
shrinkWrap: true,
itemCount: suggestionsTags.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(suggestionsTags[index]['name']),
onTap: () async {
setState(() {
itemTags = suggestionsTags[index]['name'];
inputTags.text = itemTags;
suggestionsTags.clear();
showArrow = true;
showInputSearch = true;
showInputGeo = true;
});
await fetchPostsByLocation();
},
);
},
),
),
],
),
);
}
Padding _buildItemZoneSearchField() { Padding _buildItemZoneSearchField() {
return Padding( return Padding(
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
@ -567,11 +686,11 @@ class _MyHomePageState extends State<ListItemMenu> {
}); });
} else { } else {
setState(() { setState(() {
showDateFields = true;
showArrow = true; // Optionally clear suggestions
inputItem.clear(); // Clear the text field inputItem.clear(); // Clear the text field
itemName = ''; // Reset the geographical zone state itemName = ''; // Reset the geographical zone state
suggestionsItem.clear(); suggestionsItem.clear();
showDateFields = true;
showArrow = true; // Optionally clear suggestions
/// Clear the filted posts /// Clear the filted posts
}); });
@ -626,6 +745,7 @@ class _MyHomePageState extends State<ListItemMenu> {
body: Column( body: Column(
children: [ children: [
if (showInputSearch) _buildItemZoneSearchField(), if (showInputSearch) _buildItemZoneSearchField(),
if ((showDateFields) && (showInputTag)) _buildTagsField(),
if ((showDateFields) && (showArrow)) if ((showDateFields) && (showArrow))
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
@ -633,7 +753,8 @@ class _MyHomePageState extends State<ListItemMenu> {
Flexible(child: _buildDateField("start")), Flexible(child: _buildDateField("start")),
Flexible(child: _buildDateField("end")) Flexible(child: _buildDateField("end"))
]), ]),
if (showDateFields) _buildGeographicalZoneSearchField(), if ((showDateFields) && (showInputGeo))
_buildGeographicalZoneSearchField(),
if (showArrow) if (showArrow)
IconButton( IconButton(
onPressed: () { onPressed: () {

View File

@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:uuid/uuid.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:textfield_tags/textfield_tags.dart'; import 'package:textfield_tags/textfield_tags.dart';
@ -138,6 +139,7 @@ class _UpdateeventImageState extends State<UpdateeventImage>
} }
Future<void> _updateEvent(BuildContext context) async { Future<void> _updateEvent(BuildContext context) async {
// Gather inputs
var name = inputName.text; var name = inputName.text;
var place = inputGeo.text; var place = inputGeo.text;
var description = inputDesc.text; var description = inputDesc.text;
@ -152,101 +154,96 @@ class _UpdateeventImageState extends State<UpdateeventImage>
var startDate = var startDate =
"${startDateFormat}T${startTimepicker.text.replaceAll('-', ':')}"; "${startDateFormat}T${startTimepicker.text.replaceAll('-', ':')}";
var endDate = "${endDateFormat}T${endTimepicker.text.replaceAll('-', ':')}"; var endDate = "${endDateFormat}T${endTimepicker.text.replaceAll('-', ':')}";
if (startDateCompare.isAfter(dateNow)) {
if (!startDateCompare.isAfter(dateNow)) {
showErrorDialog(context, "Evenement non futur");
return;
}
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token") ?? ""; var accessToken = prefs.getString("access_token") ?? "";
if (accessToken.isNotEmpty) { if (accessToken.isEmpty) {
showErrorDialog(context, "Token d'accès manquant");
return;
}
try { try {
await dotenv.load(); await dotenv.load();
final mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? ''; final ApiTokenGoogle = dotenv.env['PLACE_API_KEY'] ?? '';
print("place non encoded : ${place}"); // Searchbox API for geocoding the place (No session token)
final url = final searchboxUrl = Uri.parse(
'https://api.mapbox.com/geocoding/v5/mapbox.places/${place}.json?access_token=${mapboxAccessToken}&types=poi,address,place'; 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=${place}&key=${ApiTokenGoogle}');
var encoded = Uri.encodeFull(url);
print("encoded : ${encoded}");
final response = await http.get(Uri.parse(encoded));
if (response.statusCode == 200) { // Perform the request
final data = json.decode(response.body); final searchboxResponse = await http.get(searchboxUrl);
print("data : ${data}");
if (data['features'].isNotEmpty) { if (searchboxResponse.statusCode != 200) {
place = data['features'][0]['place_name']; showErrorDialog(context, "Erreur lors de la géocodage avec Searchbox");
final coordinates =
data['features'][0]['geometry']['coordinates'];
final longitude = coordinates[0]; // Longitude
final latitude = coordinates[1]; // Latitude
var urlGet = Uri.parse(
"${globals.api}/events/search?item=${name}&date_event=${startDate}");
var responseGet = await http.get(urlGet, headers: {
HttpHeaders.cookieHeader: 'access_token=${accessToken}'
});
if (responseGet.statusCode == 200) {
var events = jsonDecode(utf8.decode(responseGet.bodyBytes));
print("reponse http : ${events.length}");
if (events.length == 0) {
urlGet = Uri.parse(
"${globals.api}/events/search?min_lat=$latitude&max_lat=$latitude"
"&min_lon=$longitude&max_lon=$longitude&date_event=${startDate}");
responseGet = await http.get(urlGet, headers: {
HttpHeaders.cookieHeader: 'access_token=${accessToken}'
});
if (responseGet.statusCode == 200) {
events = jsonDecode(utf8.decode(responseGet.bodyBytes));
print("reponse http : ${events.length}");
if (events.length != 0) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
ItemMenu(title: events[0]["id"])));
return; return;
} }
final searchboxData = json.decode(searchboxResponse.body);
if (searchboxData['results'].isEmpty) {
showErrorDialog(context, "Lieu introuvable");
return;
} }
} else {
// Extract place details from the searchbox response
final firstFeature = searchboxData['results'][0];
place = firstFeature["formatted_address"];
final coordinates = firstFeature['geometry']['location'];
final longitude = coordinates["lng"];
final latitude = coordinates["lat"];
// Check if a similar event exists
final eventsUrl = Uri.parse(
"${globals.api}/events/search?item=$name&date_event=$startDate");
final eventsResponse = await http.get(eventsUrl, headers: {
HttpHeaders.cookieHeader: 'access_token=$accessToken',
});
if (eventsResponse.statusCode == 200) {
final events = json.decode(utf8.decode(eventsResponse.bodyBytes));
if (events.isNotEmpty) {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (_) => ItemMenu(title: events[0]["id"]))); builder: (_) => ItemMenu(title: events[0]["id"]),
),
);
return; return;
} }
} }
final params = { // Upload image to imgbb
'expiration': '15552000', final imgbbUrl = Uri.parse(
'key': dotenv.env["IMGBB_API_KEY"], 'https://api.imgbb.com/1/upload?expiration=15552000&key=${dotenv.env["IMGBB_API_KEY"]}');
};
print("Post Img");
final urlPost = Uri.parse('https://api.imgbb.com/1/upload')
.replace(queryParameters: params);
File image = File(widget.imagePath); File image = File(widget.imagePath);
Uint8List _bytes = await image.readAsBytes(); Uint8List imageBytes = await image.readAsBytes();
String _base64String = base64.encode(_bytes); String base64Image = base64.encode(imageBytes);
final req = http.MultipartRequest('POST', urlPost) final imgbbRequest = http.MultipartRequest('POST', imgbbUrl)
..fields['image'] = _base64String; ..fields['image'] = base64Image;
final imgbbResponse =
await http.Response.fromStream(await imgbbRequest.send());
final stream = await req.send(); if (imgbbResponse.statusCode != 200) {
final res = await http.Response.fromStream(stream); showErrorDialog(context, "Erreur lors de l'upload d'image");
return;
}
final status = res.statusCode; final imgbbData = json.decode(imgbbResponse.body);
print("code status imgbb ${status}"); final imgUrl = imgbbData['data']['url'];
if (status == 200) {
var body = json.decode(utf8.decode(res.bodyBytes));
String imgUrl = body["data"]["url"];
//String credentials = "${pseudo}:${password}"; // Create or update the event
//Codec<String, String> stringToBase64 = utf8.fuse(base64); final eventUrl = Uri.parse("${globals.api}/events");
//String encoded = stringToBase64.encode(credentials); final eventResponse = await http.put(
var urlPut = Uri.parse("${globals.api}/events"); eventUrl,
var responsePut = await http.put(urlPut,
headers: { headers: {
HttpHeaders.cookieHeader: 'access_token=${accessToken}', HttpHeaders.cookieHeader: 'access_token=$accessToken',
HttpHeaders.acceptHeader: HttpHeaders.acceptHeader: 'application/json, text/plain, */*',
'application/json, text/plain, */*', HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.contentTypeHeader: 'application/json'
}, },
body: jsonEncode({ body: jsonEncode({
'name': name, 'name': name,
@ -257,72 +254,32 @@ class _UpdateeventImageState extends State<UpdateeventImage>
'latitude': latitude, 'latitude': latitude,
'longitude': longitude, 'longitude': longitude,
'description': description, 'description': description,
"imgUrl": imgUrl, 'imgUrl': imgUrl,
"tags": tags 'tags': tags,
})); }),
print(responsePut.statusCode); );
if ((responsePut.statusCode == 200) ||
(responsePut.statusCode == 201)) { if (eventResponse.statusCode == 200 || eventResponse.statusCode == 201) {
showEventDialog(context, "Evenement ${name} ajoute"); showEventDialog(context, "Événement $name ajouté");
} else { } else {
var text = ""; handleHttpError(eventResponse.statusCode, context);
switch (responsePut.statusCode) {
case 400:
{
text = "Requête mal construite";
}
break;
case 406:
{
text = "Mot de passe incorrect";
}
break;
case 404:
{
text = "Utilisateur inconnu";
}
break;
case 403:
{
text = "Utilisateur desactive";
}
break;
case 410:
{
text = "Token invalide";
}
break;
case 500:
{
text = "Probleme interne du serveur";
}
break;
default:
{
text = "Probleme d'authentification inconnu";
}
break;
}
showErrorDialog(context, text);
}
} else {
print("imgbb error : ${status}");
}
} else {
showErrorDialog(context, "Aucune donnée geographique");
}
} else {
showErrorDialog(context, "Mapbox non accessible");
} }
} catch (e) { } catch (e) {
showErrorDialog(context, "${e}"); showErrorDialog(context, "Erreur: ${e.toString()}");
} }
} else {
showErrorDialog(context, "Champ vide");
}
} else {
showErrorDialog(context, "Evenement non futur");
} }
// Utility function to handle HTTP errors
void handleHttpError(int statusCode, BuildContext context) {
final errorMessages = {
400: "Requête mal construite",
403: "Utilisateur désactivé",
404: "Utilisateur inconnu",
406: "Mot de passe incorrect",
410: "Token invalide",
500: "Problème interne du serveur",
};
showErrorDialog(context, errorMessages[statusCode] ?? "Erreur inconnue");
} }
void start() async { void start() async {
@ -360,23 +317,27 @@ class _UpdateeventImageState extends State<UpdateeventImage>
Future<void> searchSuggestions(String input) async { Future<void> searchSuggestions(String input) async {
await dotenv.load(fileName: ".env"); // Load .env file await dotenv.load(fileName: ".env"); // Load .env file
final mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? ''; final ApiTokenGoogle = dotenv.env['PLACE_API_KEY'] ?? '';
final url =
'https://api.mapbox.com/geocoding/v5/mapbox.places/${input}.json?access_token=${mapboxAccessToken}&types=poi,address,place'; // Define the Searchbox API URL
var encoded = Uri.encodeFull(url); final searchboxUrl = Uri.parse(
final response = await http.get(Uri.parse(encoded)); 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=${input}&key=${ApiTokenGoogle}');
print("response code suggesttion : ${response.statusCode}");
// Perform the request
final response = await http.get(searchboxUrl);
print("response code suggestion: ${response.statusCode}");
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
print("data suggestion : ${data}"); print("data suggestion: ${data}");
setState(() { setState(() {
suggestions = (data['features'] as List) // Map the results to extract name and full_address
suggestions = (data['results'] as List)
.map((feature) => { .map((feature) => {
'place_name': feature['place_name'], 'name': feature['name'],
'text': feature['text'], 'formatted_address': feature[
'geometry': feature[ 'formatted_address'] // Adjusted to match the data structure
'geometry'], // Include geometry for latitude/longitude
}) })
.toList(); .toList();
}); });
@ -426,17 +387,14 @@ class _UpdateeventImageState extends State<UpdateeventImage>
itemCount: suggestions.length, itemCount: suggestions.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
return ListTile( return ListTile(
title: Text(suggestions[index]['text']), title: Text(suggestions[index]['name']),
subtitle: Text(suggestions[index]['place_name']), subtitle: Text(suggestions[index]['formatted_address']),
onTap: () async { onTap: () async {
print("suggestion tapped : ${suggestions[index]}"); print("suggestion tapped : ${suggestions[index]}");
final latitude =
suggestions[index]['geometry']['coordinates'][1];
final longitude =
suggestions[index]['geometry']['coordinates'][0];
setState(() { setState(() {
geographicalZone = suggestions[index]['text']; geographicalZone =
suggestions[index]['formatted_address'];
inputGeo.text = geographicalZone; inputGeo.text = geographicalZone;
suggestions.clear(); suggestions.clear();
}); });