diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart index cd9dc303..32a1c637 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart @@ -388,64 +388,62 @@ class DiaryEditBloc extends Bloc { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; - int? id = currentState.currentMeal?.id; - - // Отправляем данные по HTTP маршруту и ждем ответ var response = await sendPortionData( - currentState.token, - currentState.productNameController?.text, - 'pcs', - int.parse(currentState.productQuantityController!.text), - currentState.currentMeal!.id, - currentState.diaryId); + currentState.token, + currentState.productNameController?.text, + 'pcs', + int.parse(currentState.productQuantityController!.text), + currentState.currentMeal!.id, + currentState.diaryId, + ); + if (response.statusCode == 200) { dynamic newPortion = jsonDecode(response.body)['portion']; - print(newPortion); - var updatedState = currentState.copyWith( - portions: currentState.meals?[id ?? 0]['portions'], // + newPortion, - ); - emit(updatedState); // Передаем обновленное состояние в emit + + final updatedPortions = List.from(currentState.portions ?? []) + ..add(newPortion); + + final updatedState = currentState.copyWith(portions: updatedPortions); + + emit(updatedState); // Emit the updated state } } } - Future sendPortionData( - String? token, - String? name, - String portion, - int? quantity, - int? mealID, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + - '/diary/$diaryID/meal/$mealID/portions/create'; + FutureOr sendPortionData(String? token, String? name, + String portion, int? quantity, int? mealID, int diaryID) async { + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; + final Map credentials = { 'product_name': name, 'portion': portion, 'quantity': quantity, }; - var response = await http.post(Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8); + + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }, + body: json.encode(credentials), + encoding: utf8, + ); return response; } - FutureOr _inputProduct( + Future _inputProduct( ProductInput event, Emitter emit) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; String? token = currentState.token; - final Map credentials = { - 'name': event.input, - }; - final uri = Uri.parse(dotenv.env['SERVER_ROOT']! + - '/diary/product_nutritional_values/filter?' + - Uri(queryParameters: credentials).query); + + final Map credentials = {'name': event.input}; + final uri = Uri.parse( + '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}'); + final response = await http.get( uri, headers: { @@ -453,64 +451,78 @@ class DiaryEditBloc extends Bloc { 'Authorization': 'Bearer $token', }, ); + final productNutritionalValues = jsonDecode(response.body)['product_nutritional_value']; - if (productNutritionalValues is List) { - var updatedState = currentState.copyWith( - productNameController: TextEditingController(text: event.input), - autocompleteList: productNutritionalValues - .map((product) => product['name']) - .toList()); - emit(updatedState); + if (productNutritionalValues is List) { + // Create a new controller with the input text and update the autocomplete list + var updatedState = currentState.copyWith( + productNameController: TextEditingController(text: event.input), + autocompleteList: productNutritionalValues + .map((product) => product['name']) + .toList(), + ); + + emit(updatedState); // Emit the updated state } else { print("Ошибка в декодировании ответа из API"); } } } - FutureOr _removePortion( + Future _removePortion( RemovePortionEvent event, Emitter emit) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; - int? id = currentState.currentMeal?.id; + int? mealId = + currentState.currentMeal?.id; // Rename id to mealId for clarity - // Отправляем данные по HTTP маршруту и ждем ответ var response = await sendRemovePortion( - currentState.token, event.portionId, id, currentState.diaryId); + currentState.token, + event.portionId, + mealId, + currentState.diaryId, + ); + if (response.statusCode == 200) { + final updatedPortions = currentState.portions + ?.where((portion) => portion['id'] != event.portionId) + .toList(); + + final updatedState = currentState.copyWith(portions: updatedPortions); + + emit(updatedState); // Emit the updated state print("removed"); } } } Future sendRemovePortion( - String? token, - int? portionID, - int? mealID, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + - '/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; + String? token, int? portionID, int? mealID, int diaryID) async { + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; + + var response = await http.delete( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }, + encoding: utf8, + ); - var response = await http.delete(Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - encoding: utf8); print(response.body); return response; } - Future> _finishDay( - FinishDay event, Emitter emit) async { + Future _finishDay(FinishDay event, Emitter emit) async { print("imageUrl"); + if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; - // Отправляем данные по HTTP маршруту и ждем ответ var response = await sendFinishDay( currentState.token, currentState.diaryId, @@ -518,45 +530,78 @@ class DiaryEditBloc extends Bloc { currentState.retireController, currentState.commentController?.text, ); + if (response.statusCode == 200) { print("finished"); } } } - Future sendFinishDay( - String? token, - int diaryID, - TimeOfDay? wakeup, - TimeOfDay? retire, - String? comment, - ) async { + Future sendFinishDay(String? token, int diaryID, + TimeOfDay? wakeup, TimeOfDay? retire, String? comment) async { final formatter = DateFormat('HH:mm'); final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); final retireString = formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); + final Map credentials = { 'wakeup': wakeupString, 'retire': retireString, 'comment': comment ?? " ", }; - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/finishDay'; - var response = await http.post(Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8); + + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/finishDay'; + + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }, + body: json.encode(credentials), + encoding: utf8, + ); + print(response.body); return response; } - Future> _uploadImages( + Future _uploadImages( UploadImages event, Emitter emit) async { - String imageUrl = await uploadImageToServer(event.image.path); - print(imageUrl); + if (state is DiaryEditLoadedState) { + var currentState = state as DiaryEditLoadedState; + + String imageUrl = await uploadImageToServer( + event.image.path, + currentState.diaryId, + currentState.currentMeal!.id!, + currentState.token); + + print(imageUrl); + } + } + + Future uploadImageToServer( + String imagePath, int diaryID, int mealId, String? token) async { + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; + + var request = http.MultipartRequest('POST', Uri.parse(url)); + request.headers.addAll({ + 'Authorization': 'Bearer $token', + }); + + request.files.add(await http.MultipartFile.fromPath('image', imagePath)); + + var response = await request.send(); + if (response.statusCode == 200) { + var imageUrl = await response.stream.bytesToString(); + return imageUrl; + } else { + throw Exception( + 'Failed to upload image. Status code: ${response.statusCode}'); + } } FutureOr _addComment( @@ -595,24 +640,6 @@ class DiaryEditBloc extends Bloc { return response; } - Future uploadImageToServer(String imagePath) async { - var request = http.MultipartRequest( - 'POST', - Uri.parse( - 'http://your-api-url.com/upload'), // Замените на ваш маршрут API - ); - - request.files.add(await http.MultipartFile.fromPath('image', imagePath)); - - var response = await request.send(); - if (response.statusCode == 200) { - var responseData = await response.stream.bytesToString(); - return responseData; - } else { - throw Exception('Ошибка при загрузке изображения'); - } - } - TimeOfDay toTime(String timeStr) { List timeParts = timeStr.split(":"); int hour = int.parse(timeParts[0]);