forked from eatvio/eatvio_app
refactor(diary): API methods all refactored and new nutrition charty finished
This commit is contained in:
@@ -38,7 +38,6 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
_removeImage,
|
||||
); // пользователь нажимает на крестик около продукта
|
||||
on<UploadImages>(_uploadImages); //пользователь нажимает "Добавить фото"
|
||||
on<AddComment>(_addComment); //пользователь нажимает "Добавить комментарий"
|
||||
on<ProductInput>(
|
||||
_inputProduct,
|
||||
);
|
||||
@@ -57,13 +56,50 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
emit(const DiaryState.loading());
|
||||
try {
|
||||
Map<String, int> data = await diaryRepository.getDiaryID();
|
||||
|
||||
final int? diaryID = data['id'];
|
||||
final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45);
|
||||
final Meal currentMeal = diary.meals[0];
|
||||
|
||||
List<SelectionPopupModel> portionList = [
|
||||
SelectionPopupModel(title: "gr"),
|
||||
SelectionPopupModel(title: "pcs")
|
||||
];
|
||||
|
||||
final Map<String, dynamic> chartData =
|
||||
await diaryRepository.getChartData(diaryID ?? 45);
|
||||
final Map<String, dynamic> dailyNutritionIntake =
|
||||
chartData['dailyNutritionIntake']!;
|
||||
final Map<String, dynamic> dailyNutritionRecommendations =
|
||||
chartData['dailyNutritionRecommendation']!;
|
||||
final double ccal = dailyNutritionIntake['energy']! /
|
||||
dailyNutritionRecommendations['energy']! *
|
||||
100;
|
||||
final double proteins = dailyNutritionIntake['proteins']! /
|
||||
dailyNutritionRecommendations['proteins']! *
|
||||
100;
|
||||
final double fats = dailyNutritionIntake['fats']! /
|
||||
dailyNutritionRecommendations['fats']! *
|
||||
100;
|
||||
final double carbs = dailyNutritionIntake['carbohydrates']! /
|
||||
dailyNutritionRecommendations['carbohydrates']! *
|
||||
100;
|
||||
|
||||
Color getColor(double value) {
|
||||
if (value >= 99.1) {
|
||||
return Colors.red;
|
||||
} else {
|
||||
return Colors.blue;
|
||||
}
|
||||
}
|
||||
|
||||
final List<NutritionData> chartDataCounted = [
|
||||
NutritionData('Калории', ccal, getColor(ccal)),
|
||||
NutritionData('Белки', proteins, getColor(proteins)),
|
||||
NutritionData('Жиры', fats, getColor(fats)),
|
||||
NutritionData('Углеводы', carbs, getColor(carbs)),
|
||||
];
|
||||
|
||||
List<SelectionPopupModel> mealList = [
|
||||
SelectionPopupModel(title: "Прием пищи 1", id: 1),
|
||||
SelectionPopupModel(title: "Прием пищи 2", id: 2),
|
||||
@@ -72,14 +108,17 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
SelectionPopupModel(title: "Прием пищи 5", id: 5),
|
||||
SelectionPopupModel(title: "Прием пищи 6", id: 6),
|
||||
];
|
||||
|
||||
print(dailyNutritionRecommendations);
|
||||
print(dailyNutritionIntake);
|
||||
emit(DiaryState.loaded(
|
||||
diary: diary,
|
||||
currentMeal: currentMeal,
|
||||
portions: currentMeal.portions,
|
||||
photos: currentMeal.photos,
|
||||
portionList: portionList,
|
||||
portionController: portionList[0],
|
||||
mealList: mealList,
|
||||
chartData: chartDataCounted,
|
||||
selectedMood: currentMeal.mood,
|
||||
selectedSatiety: currentMeal.satiety,
|
||||
commentController: TextEditingController(),
|
||||
@@ -119,7 +158,7 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
|
||||
if (responseChart.statusCode == 200) {
|
||||
final responseBody = jsonDecode(responseChart.body);
|
||||
|
||||
print(responseBody);
|
||||
final recommendedChartValues =
|
||||
responseBody['dailyNutritionRecommendation']
|
||||
.values
|
||||
@@ -131,13 +170,22 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
.map<int>((value) => convertToInt(value))
|
||||
.toList();
|
||||
|
||||
print([recommendedChartValues, consumedChartValues]);
|
||||
return [recommendedChartValues, consumedChartValues];
|
||||
print([
|
||||
recommendedChartValues,
|
||||
consumedChartValues,
|
||||
]);
|
||||
return [
|
||||
recommendedChartValues,
|
||||
consumedChartValues,
|
||||
];
|
||||
} else {
|
||||
emit(DiaryStateError(
|
||||
errorMessage: 'Ошибка при декодировании данных КБЖУ'));
|
||||
print('fail');
|
||||
return [[], []]; // Return empty lists instead of -1
|
||||
return [
|
||||
[],
|
||||
[],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,10 +210,14 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
var updatedState =
|
||||
currentState.copyWith(selectedSatiety: event.selectedElement);
|
||||
diaryRepository.changeSatiety(event.selectedElement,
|
||||
currentState.currentMeal.id, currentState.diary.id);
|
||||
var updatedState = currentState.copyWith(
|
||||
selectedSatiety: event.selectedElement,
|
||||
);
|
||||
diaryRepository.changeSatiety(
|
||||
event.selectedElement,
|
||||
currentState.currentMeal.id,
|
||||
currentState.diary.id,
|
||||
);
|
||||
emit(updatedState);
|
||||
}
|
||||
}
|
||||
@@ -176,11 +228,15 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
var updatedState =
|
||||
currentState.copyWith(selectedMood: event.selectedElement);
|
||||
var updatedState = currentState.copyWith(
|
||||
selectedMood: event.selectedElement,
|
||||
);
|
||||
|
||||
diaryRepository.changeMood(event.selectedElement,
|
||||
currentState.currentMeal.id, currentState.diary.id);
|
||||
diaryRepository.changeMood(
|
||||
event.selectedElement,
|
||||
currentState.currentMeal.id,
|
||||
currentState.diary.id,
|
||||
);
|
||||
|
||||
emit(updatedState); // Передаем обновленное состояние в emit
|
||||
}
|
||||
@@ -246,7 +302,6 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
DiaryStateLoaded updatedState = currentState.copyWith(
|
||||
currentMeal: meal,
|
||||
portions: meal.portions,
|
||||
photos: meal.photos,
|
||||
mealTimeController: toTime(meal.time),
|
||||
selectedMood: meal.mood,
|
||||
selectedSatiety: meal.satiety,
|
||||
@@ -279,6 +334,76 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _addPortion(
|
||||
AddPortionEvent event,
|
||||
Emitter<DiaryState> emit,
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
|
||||
Map<String, Portion> data = await diaryRepository.addPortion(
|
||||
currentState.diary.id,
|
||||
currentState.currentMeal.id,
|
||||
currentState.product_nameController.text,
|
||||
currentState.portionController.title,
|
||||
int.parse(currentState.productQuantityController.text),
|
||||
);
|
||||
List<Portion> newPortions = currentState.portions;
|
||||
|
||||
final Portion newPortion = data['portion'] ??
|
||||
new Portion(id: 1, portion: 'gr', product_name: '1', quantity: 1);
|
||||
newPortions.add(newPortion);
|
||||
emit(currentState.copyWith(isAdded: true, portions: newPortions));
|
||||
//TODO update screen after addPortion() call
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _removePortion(
|
||||
RemovePortionEvent event,
|
||||
Emitter<DiaryState> emit,
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
await diaryRepository.removePortion(
|
||||
currentState.diary.id,
|
||||
currentState.currentMeal.id,
|
||||
event.portionId,
|
||||
);
|
||||
}
|
||||
//TODO update screen after _removePortion() call
|
||||
}
|
||||
|
||||
Future<void> _uploadImages(
|
||||
UploadImages event,
|
||||
Emitter<DiaryState> emit,
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
|
||||
emit(currentState.copyWith(isLoading: true));
|
||||
await diaryRepository.uploadImage(
|
||||
event.image.path,
|
||||
currentState.diary.id,
|
||||
currentState.currentMeal.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _sendModeration(
|
||||
SendModeration event,
|
||||
Emitter<DiaryState> emit,
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
await diaryRepository.sendModeration(
|
||||
event.name,
|
||||
event.energyOn100gr,
|
||||
event.proteinsOn100gr,
|
||||
event.fatsOn100gr,
|
||||
event.carbohydratesOn100gr,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _clearInput(
|
||||
ClearInput event,
|
||||
Emitter<DiaryState> emit,
|
||||
@@ -325,48 +450,6 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _addPortion(
|
||||
AddPortionEvent event,
|
||||
Emitter<DiaryState> emit,
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
print(currentState.diary.id);
|
||||
print(currentState.currentMeal.id);
|
||||
print(currentState.product_nameController.text);
|
||||
print(currentState.portionController.title);
|
||||
print(currentState.productQuantityController.text);
|
||||
|
||||
Map<String, Portion> data = await diaryRepository.addPortion(
|
||||
currentState.diary.id,
|
||||
currentState.currentMeal.id,
|
||||
currentState.product_nameController.text,
|
||||
currentState.portionController.title,
|
||||
int.parse(currentState.productQuantityController.text),
|
||||
);
|
||||
List<Portion> newPortions = currentState.portions;
|
||||
|
||||
final Portion newPortion = data['portion'] ??
|
||||
new Portion(id: 1, portion: 'gr', product_name: '1', quantity: 1);
|
||||
newPortions.add(newPortion);
|
||||
emit(currentState.copyWith(isAdded: true, portions: newPortions));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _removePortion(
|
||||
RemovePortionEvent event,
|
||||
Emitter<DiaryState> emit,
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
await diaryRepository.removePortion(
|
||||
currentState.diary.id,
|
||||
currentState.currentMeal.id,
|
||||
event.portionId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _removeImage(
|
||||
RemoveImageEvent event,
|
||||
Emitter<DiaryState> emit,
|
||||
@@ -374,244 +457,28 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
|
||||
var response = await sendRemovePhoto(
|
||||
event.path,
|
||||
event.photoID,
|
||||
currentState.currentMeal.id,
|
||||
await diaryRepository.removeImage(
|
||||
currentState.diary.id,
|
||||
currentState.currentMeal.id,
|
||||
int.parse(event.photoID),
|
||||
event.path,
|
||||
);
|
||||
print(response.statusCode);
|
||||
if (response.statusCode == 204) {
|
||||
await reloadScreen(event, emit);
|
||||
} else {
|
||||
print(
|
||||
'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<http.Response> sendRemovePhoto(
|
||||
String? path,
|
||||
String? photoID,
|
||||
int? mealID,
|
||||
int diaryID,
|
||||
) async {
|
||||
String url =
|
||||
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete';
|
||||
final Map<String, dynamic> credentials = {
|
||||
'id': photoID,
|
||||
'path': path,
|
||||
};
|
||||
var response = await http.delete(
|
||||
Uri.parse(url),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: json.encode(credentials),
|
||||
encoding: utf8,
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
Future<void> _finishDay(FinishDay event, Emitter<DiaryState> emit) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
|
||||
var response = await sendFinishDay(
|
||||
await diaryRepository.finishDay(
|
||||
currentState.diary.id,
|
||||
currentState.wakeupController,
|
||||
currentState.retireController,
|
||||
currentState.commentController.text,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
await reloadScreen(event, emit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<http.Response> sendFinishDay(
|
||||
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<String, dynamic> 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',
|
||||
},
|
||||
body: json.encode(credentials),
|
||||
encoding: utf8,
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
Future<void> _uploadImages(
|
||||
UploadImages event,
|
||||
Emitter<DiaryState> emit,
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
|
||||
emit(currentState.copyWith(isLoading: true));
|
||||
await uploadImageToServer(
|
||||
event.image.path,
|
||||
currentState.diary.id,
|
||||
currentState.currentMeal.id,
|
||||
);
|
||||
await reloadScreen(event, emit);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> uploadImageToServer(
|
||||
String imagePath,
|
||||
int diaryID,
|
||||
int mealId,
|
||||
) async {
|
||||
String url =
|
||||
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload';
|
||||
|
||||
var request = http.MultipartRequest('POST', Uri.parse(url));
|
||||
|
||||
request.files.add(await http.MultipartFile.fromPath('photo', imagePath));
|
||||
|
||||
var client = http.Client();
|
||||
var streamedResponse = await client.send(request);
|
||||
|
||||
if (streamedResponse.statusCode == 200) {
|
||||
var response = await http.Response.fromStream(streamedResponse);
|
||||
var imageUrl = response.body;
|
||||
print('Image successfully uploaded');
|
||||
return imageUrl;
|
||||
} else {
|
||||
throw Exception(
|
||||
'Failed to upload image. Status code: ${streamedResponse.statusCode}}',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _sendModeration(
|
||||
SendModeration event,
|
||||
Emitter<DiaryState> emit,
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
final response = await _sendModerationData(
|
||||
event.name,
|
||||
event.energyOn100gr,
|
||||
event.proteinsOn100gr,
|
||||
event.fatsOn100gr,
|
||||
event.carbohydratesOn100gr,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200)
|
||||
print("Moderation success");
|
||||
else
|
||||
print("Moderation error");
|
||||
}
|
||||
}
|
||||
|
||||
Future<http.Response> _sendModerationData(
|
||||
String name,
|
||||
String energy_on_100gr,
|
||||
String proteins_on_100gr,
|
||||
String fats_on_100gr,
|
||||
String carbohydrates_on_100gr,
|
||||
) async {
|
||||
final Uri url = Uri.parse(
|
||||
'${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/sendToModeration',
|
||||
);
|
||||
final Uri serverURL = Uri.parse('${dotenv.env['SERVER_ROOT']!}');
|
||||
String host = serverURL.host;
|
||||
final Map<String, String> credentials = {
|
||||
'name': name,
|
||||
'energy_on_100gr': energy_on_100gr,
|
||||
'proteins_on_100gr': proteins_on_100gr,
|
||||
'fats_on_100gr': fats_on_100gr,
|
||||
'carbohydrates_on_100gr': carbohydrates_on_100gr,
|
||||
};
|
||||
|
||||
var headers = {
|
||||
//'Content-Length': bodyBytes,
|
||||
'Host': host,
|
||||
};
|
||||
|
||||
var response = await http.post(
|
||||
url,
|
||||
headers: headers,
|
||||
body: credentials,
|
||||
encoding: utf8,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return response;
|
||||
} else {
|
||||
throw Exception(
|
||||
'Failed to send a product for moderation ${response.statusCode}',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _addComment(
|
||||
AddComment event,
|
||||
Emitter<DiaryState> emit,
|
||||
) async {
|
||||
if (state is DiaryStateLoaded) {
|
||||
var currentState = state as DiaryStateLoaded;
|
||||
var updatedState = currentState.copyWith(
|
||||
commentController: TextEditingController(text: event.comment),
|
||||
);
|
||||
|
||||
// Отправляем данные по HTTP маршруту и ждем ответ
|
||||
var response = await sendCommentData(
|
||||
event.comment,
|
||||
currentState.diary.id,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
emit(updatedState); // Передаем обновленное состояние в emit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<http.Response> sendCommentData(
|
||||
String comment,
|
||||
int diaryID,
|
||||
) async {
|
||||
String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill';
|
||||
final Map<String, dynamic> credentials = {
|
||||
'comment': comment,
|
||||
};
|
||||
|
||||
var response = await http.post(
|
||||
Uri.parse(url),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: json.encode(credentials),
|
||||
encoding: utf8,
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
TimeOfDay toTime(String timeStr) {
|
||||
List<String> timeParts = timeStr.split(":");
|
||||
int hour = int.parse(timeParts[0]);
|
||||
@@ -621,14 +488,6 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
|
||||
return timeOfDay;
|
||||
}
|
||||
|
||||
List<SelectionPopupModel> fillMealList(List<dynamic> meals) {
|
||||
meals.sort(compareTypes);
|
||||
return meals.map((meal) {
|
||||
String title = "Прием пищи ${meal['type']}";
|
||||
return SelectionPopupModel(id: meal['id'], title: title);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
int compareTypes(a, b) {
|
||||
return a['type'].compareTo(b['type']);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user