fix(diary): Satiety and mood change API method call fix

This commit is contained in:
2024-07-15 15:06:14 +03:00
parent b4993c827c
commit b8227a492d
5 changed files with 127 additions and 173 deletions

View File

@@ -18,8 +18,7 @@ part 'diary_event.dart';
class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
final DiaryRepository diaryRepository;
DiaryBloc({required this.diaryRepository})
: super(const DiaryState.loading()) {
DiaryBloc({required this.diaryRepository}) : super(const DiaryState.loading()) {
on<LoadDiary>(loadDiary);
on<ChangeSatiety>(_changeSatiety); // пользователь нажимает на шкалу сытости
on<ChangeMood>(_changeMood); // пользователь нажимает на шкалу настроения
@@ -58,10 +57,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
final int? diaryID = data['id'];
final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45);
final Meal currentMeal = diary.meals[0];
List<SelectionPopupModel> portions = [
SelectionPopupModel(title: "gr"),
SelectionPopupModel(title: "pcs")
];
List<SelectionPopupModel> portions = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")];
emit(DiaryState.loaded(
diary: diary,
currentMeal: currentMeal,
@@ -69,8 +65,8 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
photos: currentMeal.photos,
portionList: portions,
portionController: portions[0],
selectedMood: 3,
selectedSatiety: 3,
selectedMood: currentMeal.mood,
selectedSatiety: currentMeal.satiety,
commentController: TextEditingController(),
productNameController: TextEditingController(),
productQuantityController: TextEditingController(),
@@ -88,7 +84,6 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
consumedChartValues: [1, 1, 1, 1]));
} catch (e) {
emit(DiaryState.error(errorMessage: e.toString()));
print(e);
}
}
@@ -110,22 +105,14 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
if (responseChart.statusCode == 200) {
final responseBody = jsonDecode(responseChart.body);
final recommendedChartValues =
responseBody['dailyNutritionRecommendation']
.values
.map<int>((value) => convertToInt(value))
.toList();
final recommendedChartValues = responseBody['dailyNutritionRecommendation'].values.map<int>((value) => convertToInt(value)).toList();
final consumedChartValues = responseBody['dailyNutritionIntake']
.values
.map<int>((value) => convertToInt(value))
.toList();
final consumedChartValues = responseBody['dailyNutritionIntake'].values.map<int>((value) => convertToInt(value)).toList();
print([recommendedChartValues, consumedChartValues]);
return [recommendedChartValues, consumedChartValues];
} else {
emit(DiaryStateError(
errorMessage: 'Ошибка при декодировании данных КБЖУ'));
emit(DiaryStateError(errorMessage: 'Ошибка при декодировании данных КБЖУ'));
print('fail');
return [[], []]; // Return empty lists instead of -1
}
@@ -152,69 +139,23 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
) async {
if (state is DiaryStateLoaded) {
var currentState = state as DiaryStateLoaded;
var updatedState =
currentState.copyWith(selectedMood: event.selectedElement);
// Отправляем данные по HTTP маршруту и ждем ответ
var response = await sendSatietyData(
event.selectedElement,
currentState.currentMeal.id,
currentState.diary.id,
);
if (response.statusCode == 200) {
print(
'Satiety change success! meal_id: ${currentState.currentMeal.id}, mood: ${event.selectedElement}',
);
emit(updatedState); // Передаем обновленное состояние в emit
} else
print("dad");
var updatedState = currentState.copyWith(selectedSatiety: event.selectedElement);
diaryRepository.changeSatiety(event.selectedElement, currentState.currentMeal.id, currentState.diary.id);
emit(updatedState);
}
}
Future<http.Response> sendSatietyData(
int selectedSatiety,
int? mealID,
int diaryID,
) async {
String url = dotenv.env['SERVER_ROOT']! +
'/diary/$diaryID/meal/$mealID/satiety/fill';
final Map<String, dynamic> credentials = {
'satiety': selectedSatiety,
};
var response = await http.post(
Uri.parse(url),
headers: {
'Content-Type': 'application/json',
},
body: json.encode(credentials),
encoding: utf8,
);
return response;
}
Future<void> _changeMood(
ChangeMood event,
Emitter<DiaryState> emit,
) async {
if (state is DiaryStateLoaded) {
var currentState = state as DiaryStateLoaded;
var updatedState =
currentState.copyWith(selectedMood: event.selectedElement);
var updatedState = currentState.copyWith(selectedMood: event.selectedElement);
// Отправляем данные по HTTP маршруту и ждем ответ
var response = await sendMoodData(
event.selectedElement,
currentState.currentMeal.id,
currentState.diary.id,
);
diaryRepository.changeMood(event.selectedElement, currentState.currentMeal.id, currentState.diary.id);
if (response.statusCode == 200) {
print(
'Mood change success! meal_id: ${currentState.currentMeal.id}, mood: ${event.selectedElement}',
);
emit(updatedState); // Передаем обновленное состояние в emit
}
emit(updatedState); // Передаем обновленное состояние в emit
}
}
@@ -223,8 +164,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
int? mealID,
int diaryID,
) async {
String url =
dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill';
String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill';
final Map<String, dynamic> credentials = {
'mood': selectedMood,
};
@@ -253,8 +193,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
);
if (response.statusCode == 200) {
await reloadScreen(event, emit);
var updatedState =
currentState.copyWith(wakeupController: event.selectedTime);
var updatedState = currentState.copyWith(wakeupController: event.selectedTime);
print("Wakeup time changed to ${event.selectedTime}");
emit(updatedState); // Передаем обновленное состояние в emit
} else
@@ -274,8 +213,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
);
if (response.statusCode == 200) {
await reloadScreen(event, emit);
var updatedState =
currentState.copyWith(retireController: event.selectedTime);
var updatedState = currentState.copyWith(retireController: event.selectedTime);
print("Retire time changed to ${event.selectedTime}");
emit(updatedState); // Передаем обновленное состояние в emit
} else
@@ -289,8 +227,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
) async {
String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/wakeUp/fill';
final formatter = DateFormat('HH:mm');
final wakeupString =
formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute));
final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute));
final Map<String, dynamic> credentials = {
'wakeUp': wakeupString,
};
@@ -313,8 +250,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
) async {
String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill';
final formatter = DateFormat('HH:mm');
final retireString =
formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute));
final retireString = formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute));
final Map<String, dynamic> credentials = {
'retire': retireString,
};
@@ -375,8 +311,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
) async {
if (state is DiaryStateLoaded) {
var currentState = state as DiaryStateLoaded;
Meal? meal =
currentState.diary.meals.firstWhere((meal) => meal.id == event.value);
Meal? meal = currentState.diary.meals.firstWhere((meal) => meal.id == event.value);
DiaryStateLoaded updatedState = currentState.copyWith(
currentMeal: event.value,
@@ -469,8 +404,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
int? mealID,
int diaryID,
) async {
String url =
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create';
String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create';
final Map<String, dynamic> credentials = {
'product_name': name,
@@ -509,16 +443,13 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
},
);
final productNutritionalValues =
jsonDecode(response.body)['product_nutritional_value'];
final productNutritionalValues = jsonDecode(response.body)['product_nutritional_value'];
if (productNutritionalValues is List<dynamic>) {
// 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(),
autocompleteList: productNutritionalValues.map((product) => product['name']).toList(),
);
if (event.input.length > 3) {
updatedState = updatedState.copyWith(moderationExpanded: true);
@@ -538,8 +469,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
if (state is DiaryStateLoaded) {
var currentState = state as DiaryStateLoaded;
int? mealId =
currentState.currentMeal.id; // Rename id to mealId for clarity
int? mealId = currentState.currentMeal.id; // Rename id to mealId for clarity
var response = await sendRemovePortion(
event.portionId,
@@ -562,8 +492,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
int? mealID,
int diaryID,
) async {
String url =
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete';
String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete';
var response = await http.delete(
Uri.parse(url),
@@ -606,8 +535,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
int? mealID,
int diaryID,
) async {
String url =
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete';
String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete';
final Map<String, dynamic> credentials = {
'id': photoID,
'path': path,
@@ -648,10 +576,8 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
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 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<String, dynamic> credentials = {
'wakeup': wakeupString,
@@ -695,8 +621,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
int diaryID,
int mealId,
) async {
String url =
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload';
String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload';
var request = http.MultipartRequest('POST', Uri.parse(url));