refactor(diary): API mor produc nutritional and new Product model

This commit is contained in:
2024-07-17 12:39:09 +03:00
parent 20d253313a
commit b5becbe665
8 changed files with 935 additions and 188 deletions

View File

@@ -1,19 +0,0 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'diary.freezed.dart';
part 'diary.g.dart';
@freezed
class Diary with _$Diary {
const factory Diary({
required int id,
required DateTime date,
required int closed,
String? comment,
DateTime? wakeup,
DateTime? retire,
}) = _Diary;
factory Diary.fromJson(Map<String, Object?> json) =>
_$DiaryFromJson(json);
}

View File

@@ -0,0 +1,32 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'product.freezed.dart';
part 'product.g.dart';
@freezed
class Product with _$Product {
const factory Product({
required int id,
required String name,
required String image,
required int productGroupId,
required String description,
required String formulations,
required int energyOn100gr,
required double proteinsOn100gr,
required double fatsOn100gr,
required double carbohydratesOn100gr,
required int portionMassGr,
required int energyOnPortion,
required int proteinsOnPortion,
required int fatsOnPortion,
required int carbohydratesOnPortion,
required String createdAt,
required String updatedAt,
required String lastState,
String? reqjectReason,
}) = _Product;
factory Product.fromJson(Map<String, Object?> json) =>
_$ProductFromJson(json);
}

View File

@@ -0,0 +1,548 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'product.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
Product _$ProductFromJson(Map<String, dynamic> json) {
return _Product.fromJson(json);
}
/// @nodoc
mixin _$Product {
int get id => throw _privateConstructorUsedError;
String get name => throw _privateConstructorUsedError;
String get image => throw _privateConstructorUsedError;
int get productGroupId => throw _privateConstructorUsedError;
String get description => throw _privateConstructorUsedError;
String get formulations => throw _privateConstructorUsedError;
int get energyOn100gr => throw _privateConstructorUsedError;
double get proteinsOn100gr => throw _privateConstructorUsedError;
double get fatsOn100gr => throw _privateConstructorUsedError;
double get carbohydratesOn100gr => throw _privateConstructorUsedError;
int get portionMassGr => throw _privateConstructorUsedError;
int get energyOnPortion => throw _privateConstructorUsedError;
int get proteinsOnPortion => throw _privateConstructorUsedError;
int get fatsOnPortion => throw _privateConstructorUsedError;
int get carbohydratesOnPortion => throw _privateConstructorUsedError;
String get createdAt => throw _privateConstructorUsedError;
String get updatedAt => throw _privateConstructorUsedError;
String get lastState => throw _privateConstructorUsedError;
String? get reqjectReason => throw _privateConstructorUsedError;
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$ProductCopyWith<Product> get copyWith => throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $ProductCopyWith<$Res> {
factory $ProductCopyWith(Product value, $Res Function(Product) then) =
_$ProductCopyWithImpl<$Res, Product>;
@useResult
$Res call(
{int id,
String name,
String image,
int productGroupId,
String description,
String formulations,
int energyOn100gr,
double proteinsOn100gr,
double fatsOn100gr,
double carbohydratesOn100gr,
int portionMassGr,
int energyOnPortion,
int proteinsOnPortion,
int fatsOnPortion,
int carbohydratesOnPortion,
String createdAt,
String updatedAt,
String lastState,
String? reqjectReason});
}
/// @nodoc
class _$ProductCopyWithImpl<$Res, $Val extends Product>
implements $ProductCopyWith<$Res> {
_$ProductCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
@pragma('vm:prefer-inline')
@override
$Res call({
Object? id = null,
Object? name = null,
Object? image = null,
Object? productGroupId = null,
Object? description = null,
Object? formulations = null,
Object? energyOn100gr = null,
Object? proteinsOn100gr = null,
Object? fatsOn100gr = null,
Object? carbohydratesOn100gr = null,
Object? portionMassGr = null,
Object? energyOnPortion = null,
Object? proteinsOnPortion = null,
Object? fatsOnPortion = null,
Object? carbohydratesOnPortion = null,
Object? createdAt = null,
Object? updatedAt = null,
Object? lastState = null,
Object? reqjectReason = freezed,
}) {
return _then(_value.copyWith(
id: null == id
? _value.id
: id // ignore: cast_nullable_to_non_nullable
as int,
name: null == name
? _value.name
: name // ignore: cast_nullable_to_non_nullable
as String,
image: null == image
? _value.image
: image // ignore: cast_nullable_to_non_nullable
as String,
productGroupId: null == productGroupId
? _value.productGroupId
: productGroupId // ignore: cast_nullable_to_non_nullable
as int,
description: null == description
? _value.description
: description // ignore: cast_nullable_to_non_nullable
as String,
formulations: null == formulations
? _value.formulations
: formulations // ignore: cast_nullable_to_non_nullable
as String,
energyOn100gr: null == energyOn100gr
? _value.energyOn100gr
: energyOn100gr // ignore: cast_nullable_to_non_nullable
as int,
proteinsOn100gr: null == proteinsOn100gr
? _value.proteinsOn100gr
: proteinsOn100gr // ignore: cast_nullable_to_non_nullable
as double,
fatsOn100gr: null == fatsOn100gr
? _value.fatsOn100gr
: fatsOn100gr // ignore: cast_nullable_to_non_nullable
as double,
carbohydratesOn100gr: null == carbohydratesOn100gr
? _value.carbohydratesOn100gr
: carbohydratesOn100gr // ignore: cast_nullable_to_non_nullable
as double,
portionMassGr: null == portionMassGr
? _value.portionMassGr
: portionMassGr // ignore: cast_nullable_to_non_nullable
as int,
energyOnPortion: null == energyOnPortion
? _value.energyOnPortion
: energyOnPortion // ignore: cast_nullable_to_non_nullable
as int,
proteinsOnPortion: null == proteinsOnPortion
? _value.proteinsOnPortion
: proteinsOnPortion // ignore: cast_nullable_to_non_nullable
as int,
fatsOnPortion: null == fatsOnPortion
? _value.fatsOnPortion
: fatsOnPortion // ignore: cast_nullable_to_non_nullable
as int,
carbohydratesOnPortion: null == carbohydratesOnPortion
? _value.carbohydratesOnPortion
: carbohydratesOnPortion // ignore: cast_nullable_to_non_nullable
as int,
createdAt: null == createdAt
? _value.createdAt
: createdAt // ignore: cast_nullable_to_non_nullable
as String,
updatedAt: null == updatedAt
? _value.updatedAt
: updatedAt // ignore: cast_nullable_to_non_nullable
as String,
lastState: null == lastState
? _value.lastState
: lastState // ignore: cast_nullable_to_non_nullable
as String,
reqjectReason: freezed == reqjectReason
? _value.reqjectReason
: reqjectReason // ignore: cast_nullable_to_non_nullable
as String?,
) as $Val);
}
}
/// @nodoc
abstract class _$$ProductImplCopyWith<$Res> implements $ProductCopyWith<$Res> {
factory _$$ProductImplCopyWith(
_$ProductImpl value, $Res Function(_$ProductImpl) then) =
__$$ProductImplCopyWithImpl<$Res>;
@override
@useResult
$Res call(
{int id,
String name,
String image,
int productGroupId,
String description,
String formulations,
int energyOn100gr,
double proteinsOn100gr,
double fatsOn100gr,
double carbohydratesOn100gr,
int portionMassGr,
int energyOnPortion,
int proteinsOnPortion,
int fatsOnPortion,
int carbohydratesOnPortion,
String createdAt,
String updatedAt,
String lastState,
String? reqjectReason});
}
/// @nodoc
class __$$ProductImplCopyWithImpl<$Res>
extends _$ProductCopyWithImpl<$Res, _$ProductImpl>
implements _$$ProductImplCopyWith<$Res> {
__$$ProductImplCopyWithImpl(
_$ProductImpl _value, $Res Function(_$ProductImpl) _then)
: super(_value, _then);
@pragma('vm:prefer-inline')
@override
$Res call({
Object? id = null,
Object? name = null,
Object? image = null,
Object? productGroupId = null,
Object? description = null,
Object? formulations = null,
Object? energyOn100gr = null,
Object? proteinsOn100gr = null,
Object? fatsOn100gr = null,
Object? carbohydratesOn100gr = null,
Object? portionMassGr = null,
Object? energyOnPortion = null,
Object? proteinsOnPortion = null,
Object? fatsOnPortion = null,
Object? carbohydratesOnPortion = null,
Object? createdAt = null,
Object? updatedAt = null,
Object? lastState = null,
Object? reqjectReason = freezed,
}) {
return _then(_$ProductImpl(
id: null == id
? _value.id
: id // ignore: cast_nullable_to_non_nullable
as int,
name: null == name
? _value.name
: name // ignore: cast_nullable_to_non_nullable
as String,
image: null == image
? _value.image
: image // ignore: cast_nullable_to_non_nullable
as String,
productGroupId: null == productGroupId
? _value.productGroupId
: productGroupId // ignore: cast_nullable_to_non_nullable
as int,
description: null == description
? _value.description
: description // ignore: cast_nullable_to_non_nullable
as String,
formulations: null == formulations
? _value.formulations
: formulations // ignore: cast_nullable_to_non_nullable
as String,
energyOn100gr: null == energyOn100gr
? _value.energyOn100gr
: energyOn100gr // ignore: cast_nullable_to_non_nullable
as int,
proteinsOn100gr: null == proteinsOn100gr
? _value.proteinsOn100gr
: proteinsOn100gr // ignore: cast_nullable_to_non_nullable
as double,
fatsOn100gr: null == fatsOn100gr
? _value.fatsOn100gr
: fatsOn100gr // ignore: cast_nullable_to_non_nullable
as double,
carbohydratesOn100gr: null == carbohydratesOn100gr
? _value.carbohydratesOn100gr
: carbohydratesOn100gr // ignore: cast_nullable_to_non_nullable
as double,
portionMassGr: null == portionMassGr
? _value.portionMassGr
: portionMassGr // ignore: cast_nullable_to_non_nullable
as int,
energyOnPortion: null == energyOnPortion
? _value.energyOnPortion
: energyOnPortion // ignore: cast_nullable_to_non_nullable
as int,
proteinsOnPortion: null == proteinsOnPortion
? _value.proteinsOnPortion
: proteinsOnPortion // ignore: cast_nullable_to_non_nullable
as int,
fatsOnPortion: null == fatsOnPortion
? _value.fatsOnPortion
: fatsOnPortion // ignore: cast_nullable_to_non_nullable
as int,
carbohydratesOnPortion: null == carbohydratesOnPortion
? _value.carbohydratesOnPortion
: carbohydratesOnPortion // ignore: cast_nullable_to_non_nullable
as int,
createdAt: null == createdAt
? _value.createdAt
: createdAt // ignore: cast_nullable_to_non_nullable
as String,
updatedAt: null == updatedAt
? _value.updatedAt
: updatedAt // ignore: cast_nullable_to_non_nullable
as String,
lastState: null == lastState
? _value.lastState
: lastState // ignore: cast_nullable_to_non_nullable
as String,
reqjectReason: freezed == reqjectReason
? _value.reqjectReason
: reqjectReason // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// @nodoc
@JsonSerializable()
class _$ProductImpl implements _Product {
const _$ProductImpl(
{required this.id,
required this.name,
required this.image,
required this.productGroupId,
required this.description,
required this.formulations,
required this.energyOn100gr,
required this.proteinsOn100gr,
required this.fatsOn100gr,
required this.carbohydratesOn100gr,
required this.portionMassGr,
required this.energyOnPortion,
required this.proteinsOnPortion,
required this.fatsOnPortion,
required this.carbohydratesOnPortion,
required this.createdAt,
required this.updatedAt,
required this.lastState,
this.reqjectReason});
factory _$ProductImpl.fromJson(Map<String, dynamic> json) =>
_$$ProductImplFromJson(json);
@override
final int id;
@override
final String name;
@override
final String image;
@override
final int productGroupId;
@override
final String description;
@override
final String formulations;
@override
final int energyOn100gr;
@override
final double proteinsOn100gr;
@override
final double fatsOn100gr;
@override
final double carbohydratesOn100gr;
@override
final int portionMassGr;
@override
final int energyOnPortion;
@override
final int proteinsOnPortion;
@override
final int fatsOnPortion;
@override
final int carbohydratesOnPortion;
@override
final String createdAt;
@override
final String updatedAt;
@override
final String lastState;
@override
final String? reqjectReason;
@override
String toString() {
return 'Product(id: $id, name: $name, image: $image, productGroupId: $productGroupId, description: $description, formulations: $formulations, energyOn100gr: $energyOn100gr, proteinsOn100gr: $proteinsOn100gr, fatsOn100gr: $fatsOn100gr, carbohydratesOn100gr: $carbohydratesOn100gr, portionMassGr: $portionMassGr, energyOnPortion: $energyOnPortion, proteinsOnPortion: $proteinsOnPortion, fatsOnPortion: $fatsOnPortion, carbohydratesOnPortion: $carbohydratesOnPortion, createdAt: $createdAt, updatedAt: $updatedAt, lastState: $lastState, reqjectReason: $reqjectReason)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$ProductImpl &&
(identical(other.id, id) || other.id == id) &&
(identical(other.name, name) || other.name == name) &&
(identical(other.image, image) || other.image == image) &&
(identical(other.productGroupId, productGroupId) ||
other.productGroupId == productGroupId) &&
(identical(other.description, description) ||
other.description == description) &&
(identical(other.formulations, formulations) ||
other.formulations == formulations) &&
(identical(other.energyOn100gr, energyOn100gr) ||
other.energyOn100gr == energyOn100gr) &&
(identical(other.proteinsOn100gr, proteinsOn100gr) ||
other.proteinsOn100gr == proteinsOn100gr) &&
(identical(other.fatsOn100gr, fatsOn100gr) ||
other.fatsOn100gr == fatsOn100gr) &&
(identical(other.carbohydratesOn100gr, carbohydratesOn100gr) ||
other.carbohydratesOn100gr == carbohydratesOn100gr) &&
(identical(other.portionMassGr, portionMassGr) ||
other.portionMassGr == portionMassGr) &&
(identical(other.energyOnPortion, energyOnPortion) ||
other.energyOnPortion == energyOnPortion) &&
(identical(other.proteinsOnPortion, proteinsOnPortion) ||
other.proteinsOnPortion == proteinsOnPortion) &&
(identical(other.fatsOnPortion, fatsOnPortion) ||
other.fatsOnPortion == fatsOnPortion) &&
(identical(other.carbohydratesOnPortion, carbohydratesOnPortion) ||
other.carbohydratesOnPortion == carbohydratesOnPortion) &&
(identical(other.createdAt, createdAt) ||
other.createdAt == createdAt) &&
(identical(other.updatedAt, updatedAt) ||
other.updatedAt == updatedAt) &&
(identical(other.lastState, lastState) ||
other.lastState == lastState) &&
(identical(other.reqjectReason, reqjectReason) ||
other.reqjectReason == reqjectReason));
}
@JsonKey(ignore: true)
@override
int get hashCode => Object.hashAll([
runtimeType,
id,
name,
image,
productGroupId,
description,
formulations,
energyOn100gr,
proteinsOn100gr,
fatsOn100gr,
carbohydratesOn100gr,
portionMassGr,
energyOnPortion,
proteinsOnPortion,
fatsOnPortion,
carbohydratesOnPortion,
createdAt,
updatedAt,
lastState,
reqjectReason
]);
@JsonKey(ignore: true)
@override
@pragma('vm:prefer-inline')
_$$ProductImplCopyWith<_$ProductImpl> get copyWith =>
__$$ProductImplCopyWithImpl<_$ProductImpl>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$ProductImplToJson(
this,
);
}
}
abstract class _Product implements Product {
const factory _Product(
{required final int id,
required final String name,
required final String image,
required final int productGroupId,
required final String description,
required final String formulations,
required final int energyOn100gr,
required final double proteinsOn100gr,
required final double fatsOn100gr,
required final double carbohydratesOn100gr,
required final int portionMassGr,
required final int energyOnPortion,
required final int proteinsOnPortion,
required final int fatsOnPortion,
required final int carbohydratesOnPortion,
required final String createdAt,
required final String updatedAt,
required final String lastState,
final String? reqjectReason}) = _$ProductImpl;
factory _Product.fromJson(Map<String, dynamic> json) = _$ProductImpl.fromJson;
@override
int get id;
@override
String get name;
@override
String get image;
@override
int get productGroupId;
@override
String get description;
@override
String get formulations;
@override
int get energyOn100gr;
@override
double get proteinsOn100gr;
@override
double get fatsOn100gr;
@override
double get carbohydratesOn100gr;
@override
int get portionMassGr;
@override
int get energyOnPortion;
@override
int get proteinsOnPortion;
@override
int get fatsOnPortion;
@override
int get carbohydratesOnPortion;
@override
String get createdAt;
@override
String get updatedAt;
@override
String get lastState;
@override
String? get reqjectReason;
@override
@JsonKey(ignore: true)
_$$ProductImplCopyWith<_$ProductImpl> get copyWith =>
throw _privateConstructorUsedError;
}

View File

@@ -0,0 +1,53 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'product.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$ProductImpl _$$ProductImplFromJson(Map<String, dynamic> json) =>
_$ProductImpl(
id: (json['id'] as num).toInt(),
name: json['name'] as String,
image: json['image'] as String,
productGroupId: (json['productGroupId'] as num).toInt(),
description: json['description'] as String,
formulations: json['formulations'] as String,
energyOn100gr: (json['energyOn100gr'] as num).toInt(),
proteinsOn100gr: (json['proteinsOn100gr'] as num).toDouble(),
fatsOn100gr: (json['fatsOn100gr'] as num).toDouble(),
carbohydratesOn100gr: (json['carbohydratesOn100gr'] as num).toDouble(),
portionMassGr: (json['portionMassGr'] as num).toInt(),
energyOnPortion: (json['energyOnPortion'] as num).toInt(),
proteinsOnPortion: (json['proteinsOnPortion'] as num).toInt(),
fatsOnPortion: (json['fatsOnPortion'] as num).toInt(),
carbohydratesOnPortion: (json['carbohydratesOnPortion'] as num).toInt(),
createdAt: json['createdAt'] as String,
updatedAt: json['updatedAt'] as String,
lastState: json['lastState'] as String,
reqjectReason: json['reqjectReason'] as String?,
);
Map<String, dynamic> _$$ProductImplToJson(_$ProductImpl instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'image': instance.image,
'productGroupId': instance.productGroupId,
'description': instance.description,
'formulations': instance.formulations,
'energyOn100gr': instance.energyOn100gr,
'proteinsOn100gr': instance.proteinsOn100gr,
'fatsOn100gr': instance.fatsOn100gr,
'carbohydratesOn100gr': instance.carbohydratesOn100gr,
'portionMassGr': instance.portionMassGr,
'energyOnPortion': instance.energyOnPortion,
'proteinsOnPortion': instance.proteinsOnPortion,
'fatsOnPortion': instance.fatsOnPortion,
'carbohydratesOnPortion': instance.carbohydratesOnPortion,
'createdAt': instance.createdAt,
'updatedAt': instance.updatedAt,
'lastState': instance.lastState,
'reqjectReason': instance.reqjectReason,
};

View File

@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:eatvio_app/features/diary/models/diary_model.dart';
import 'package:eatvio_app/features/diary/models/meal.dart';
import 'package:eatvio_app/features/diary/models/product.dart';
import 'package:eatvio_app/features/diary/repositories/diary_repository.dart';
import 'package:intl/intl.dart';
import 'package:equatable/equatable.dart';
@@ -18,7 +19,8 @@ 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); // пользователь нажимает на шкалу настроения
@@ -57,7 +59,10 @@ 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> portionList = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")];
List<SelectionPopupModel> portionList = [
SelectionPopupModel(title: "gr"),
SelectionPopupModel(title: "pcs")
];
List<SelectionPopupModel> mealList = [
SelectionPopupModel(title: "Прием пищи 1", id: 1),
SelectionPopupModel(title: "Прием пищи 2", id: 2),
@@ -114,14 +119,22 @@ 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
}
@@ -148,8 +161,10 @@ 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);
}
}
@@ -160,9 +175,11 @@ 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
}
@@ -174,9 +191,11 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
) async {
if (state is DiaryStateLoaded) {
var currentState = state as DiaryStateLoaded;
var updatedState = currentState.copyWith(wakeupController: event.selectedTime);
var updatedState =
currentState.copyWith(wakeupController: event.selectedTime);
final DateFormat formatter = DateFormat('HH:mm');
final String wakeupString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute));
final String wakeupString = formatter.format(DateTime(
2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute));
await diaryRepository.changeWakeup(
currentState.diary.id,
wakeupString,
@@ -191,9 +210,11 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
) async {
if (state is DiaryStateLoaded) {
var currentState = state as DiaryStateLoaded;
var updatedState = currentState.copyWith(retireController: event.selectedTime);
var updatedState =
currentState.copyWith(retireController: event.selectedTime);
final DateFormat formatter = DateFormat('HH:mm');
final String retireString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute));
final String retireString = formatter.format(DateTime(
2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute));
await diaryRepository.changeRetire(
currentState.diary.id,
retireString,
@@ -219,7 +240,8 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
) async {
if (state is DiaryStateLoaded) {
final currentState = state as DiaryStateLoaded;
final Meal meal = currentState.diary.meals.firstWhere((meal) => meal.type == event.value.id);
final Meal meal = currentState.diary.meals
.firstWhere((meal) => meal.type == event.value.id);
DiaryStateLoaded updatedState = currentState.copyWith(
currentMeal: meal,
portions: meal.portions,
@@ -239,8 +261,9 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
if (state is DiaryStateLoaded) {
var currentState = state as DiaryStateLoaded;
final productNutritionalValues = await diaryRepository.inputProduct(event.input);
final Map<String, List<Product>> productNutritionalValues =
await diaryRepository.inputProduct(event.input);
print(productNutritionalValues);
// Create a new controller with the input text and update the autocomplete list
/*var updatedState = currentState.copyWith(
productNameController: TextEditingController(text: event.input),
@@ -309,52 +332,18 @@ class DiaryBloc extends Bloc<DiaryEvent, DiaryState> {
if (state is DiaryStateLoaded) {
var currentState = state as DiaryStateLoaded;
var response = await sendPortionData(
currentState.productNameController.text,
currentState.portionController.id == 0 ? 'pcs' : 'gr',
int.parse(currentState.productQuantityController.text),
currentState.currentMeal.id,
await diaryRepository.addPortion(
currentState.diary.id,
currentState.currentMeal.id,
currentState.productNameController.text,
currentState.portionController.value,
int.parse(currentState.productQuantityController.text),
);
if (response.statusCode == 200) {
emit(currentState.copyWith(isAdded: true));
await reloadScreen(event, emit);
} else {
print(
'Failed to add portion. Status Code: ${response.statusCode} ${response.body}',
);
}
emit(currentState.copyWith(isAdded: true));
}
}
FutureOr<http.Response> sendPortionData(
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<String, dynamic> credentials = {
'product_name': name,
'portion': portion,
'quantity': quantity,
};
var response = await http.post(
Uri.parse(url),
headers: {
'Content-Type': 'application/json',
},
body: json.encode(credentials),
encoding: utf8,
);
return response;
}
Future<void> _removePortion(
RemovePortionEvent event,
Emitter<DiaryState> emit,
@@ -362,7 +351,8 @@ 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,
@@ -385,7 +375,8 @@ 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),
@@ -428,7 +419,8 @@ 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,
@@ -469,8 +461,10 @@ 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,
@@ -514,7 +508,8 @@ 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));

View File

@@ -1,4 +1,5 @@
import 'package:eatvio_app/features/diary/models/diary_model.dart';
import 'package:eatvio_app/features/diary/models/product.dart';
import 'package:eatvio_app/features/diary/services/diary_service.dart';
class DiaryRepository {
@@ -22,9 +23,9 @@ class DiaryRepository {
}
}
Future<DiaryModel> inputProduct(String name) async {
Future<Map<String, List<Product>>> inputProduct(String name) async {
try {
return await diaryService.sendInputProduct(name);
return await diaryService.getInputProduct(name);
} catch (e) {
rethrow;
}
@@ -81,4 +82,40 @@ class DiaryRepository {
rethrow;
}
}
Future<void> addPortion(
int diaryID,
int mealID,
String name,
String product,
int quantity,
) async {
try {
await diaryService.sendPortionData(
diaryID,
mealID,
name,
product,
quantity,
);
} catch (e) {
rethrow;
}
}
Future<void> removePortion(
int diaryID,
int mealID,
int portionID,
) async {
try {
await diaryService.sendRemovePortionData(
diaryID,
mealID,
portionID,
);
} catch (e) {
rethrow;
}
}
}

View File

@@ -1,5 +1,6 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/features/diary/models/diary_model.dart';
import 'package:eatvio_app/features/diary/models/product.dart';
import 'package:retrofit/retrofit.dart';
part 'diary_service.g.dart';
@@ -17,8 +18,9 @@ abstract class DiaryService {
@GET('/diary/{id}/dailyNutritionData/')
Future<DiaryModel> getChart(@Path() String id);
@GET('/diary/product_nutritional_values/filter?{name}')
Future<DiaryModel> sendInputProduct(@Path() String name);
@GET('/diary/product_nutritional_values/filter')
Future<Map<String, List<Product>>> getInputProduct(
@Query('name') String name);
@POST('/diary/{diary_id}/meal/{meal_id}/satiety/fill')
Future<Map<String, int>> sendSatietyData(
@@ -41,8 +43,24 @@ abstract class DiaryService {
);
@POST('/diary/{diary_id}/retire/fill')
Future<DiaryModel> sendRetire(
Future<DiaryModel> sendRetireData(
@Path() int diary_id,
@Query('retire') String retire,
);
@POST('/diary/{diary_id}/meal/{meal_id}/portions/create')
Future<Map<String, int>> sendPortionData(
@Path() int diary_id,
@Path() int meal_id,
@Query('product_name') String product_name,
@Query('portion') String portion,
@Query('quantity') int quantity,
);
@POST('/diary/{diary_id}/meal/{meal_id}/portions/{portion_id}/delete')
Future<Map<String, int>> sendRemovePortionData(
@Path() int diary_id,
@Path() int meal_id,
@Path() int portion_id,
);
}

View File

@@ -24,22 +24,23 @@ class _DiaryService implements DiaryService {
final queryParameters = <String, dynamic>{};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio.fetch<Map<String, dynamic>>(_setStreamType<Map<String, int>>(Options(
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<Map<String, int>>(Options(
method: 'GET',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/index',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
.compose(
_dio.options,
'/diary/index',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = _result.data!.cast<String, int>();
return _value;
}
@@ -50,23 +51,25 @@ class _DiaryService implements DiaryService {
final queryParameters = <String, dynamic>{};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio.fetch<Map<String, dynamic>>(_setStreamType<Map<String, DiaryModel>>(Options(
final _result = await _dio.fetch<Map<String, dynamic>>(
_setStreamType<Map<String, DiaryModel>>(Options(
method: 'GET',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/${id}/show/',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
var _value = _result.data!.map((k, dynamic v) => MapEntry(k, DiaryModel.fromJson(v as Map<String, dynamic>)));
.compose(
_dio.options,
'/diary/${id}/show/',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
var _value = _result.data!.map((k, dynamic v) =>
MapEntry(k, DiaryModel.fromJson(v as Map<String, dynamic>)));
return _value;
}
@@ -76,49 +79,55 @@ class _DiaryService implements DiaryService {
final queryParameters = <String, dynamic>{};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio.fetch<Map<String, dynamic>>(_setStreamType<DiaryModel>(Options(
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<DiaryModel>(Options(
method: 'GET',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/${id}/dailyNutritionData/',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
.compose(
_dio.options,
'/diary/${id}/dailyNutritionData/',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = DiaryModel.fromJson(_result.data!);
return _value;
}
@override
Future<DiaryModel> sendInputProduct(String name) async {
Future<Map<String, List<Product>>> getInputProduct(String name) async {
final _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{};
final queryParameters = <String, dynamic>{r'name': name};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio.fetch<Map<String, dynamic>>(_setStreamType<DiaryModel>(Options(
final _result = await _dio.fetch<Map<String, dynamic>>(
_setStreamType<Map<String, List<Product>>>(Options(
method: 'GET',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/product_nutritional_values/filter?${name}',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = DiaryModel.fromJson(_result.data!);
.compose(
_dio.options,
'/diary/product_nutritional_values/filter',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
var _value = _result.data!.map((k, dynamic v) => MapEntry(
k,
(v as List)
.map((i) => Product.fromJson(i as Map<String, dynamic>))
.toList()));
return _value;
}
@@ -132,22 +141,23 @@ class _DiaryService implements DiaryService {
final queryParameters = <String, dynamic>{r'satiety': satiety};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio.fetch<Map<String, dynamic>>(_setStreamType<Map<String, int>>(Options(
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<Map<String, int>>(Options(
method: 'POST',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/${diary_id}/meal/${meal_id}/satiety/fill',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
.compose(
_dio.options,
'/diary/${diary_id}/meal/${meal_id}/satiety/fill',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = _result.data!.cast<String, int>();
return _value;
}
@@ -162,22 +172,23 @@ class _DiaryService implements DiaryService {
final queryParameters = <String, dynamic>{r'mood': mood};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio.fetch<Map<String, dynamic>>(_setStreamType<Map<String, int>>(Options(
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<Map<String, int>>(Options(
method: 'POST',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/${diary_id}/meal/${meal_id}/mood/fill',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
.compose(
_dio.options,
'/diary/${diary_id}/meal/${meal_id}/mood/fill',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = _result.data!.cast<String, int>();
return _value;
}
@@ -191,28 +202,29 @@ class _DiaryService implements DiaryService {
final queryParameters = <String, dynamic>{r'wakeup': wakeup};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio.fetch<Map<String, dynamic>>(_setStreamType<DiaryModel>(Options(
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<DiaryModel>(Options(
method: 'POST',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/${diary_id}/wakeup/fill',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
.compose(
_dio.options,
'/diary/${diary_id}/wakeup/fill',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = DiaryModel.fromJson(_result.data!);
return _value;
}
@override
Future<DiaryModel> sendRetire(
Future<DiaryModel> sendRetireData(
int diary_id,
String retire,
) async {
@@ -220,28 +232,99 @@ class _DiaryService implements DiaryService {
final queryParameters = <String, dynamic>{r'retire': retire};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio.fetch<Map<String, dynamic>>(_setStreamType<DiaryModel>(Options(
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<DiaryModel>(Options(
method: 'POST',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/${diary_id}/retire/fill',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
.compose(
_dio.options,
'/diary/${diary_id}/retire/fill',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = DiaryModel.fromJson(_result.data!);
return _value;
}
@override
Future<Map<String, int>> sendPortionData(
int diary_id,
int meal_id,
String product_name,
String portion,
int quantity,
) async {
final _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{
r'product_name': product_name,
r'portion': portion,
r'quantity': quantity,
};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<Map<String, int>>(Options(
method: 'POST',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/${diary_id}/meal/${meal_id}/portions/create',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = _result.data!.cast<String, int>();
return _value;
}
@override
Future<Map<String, int>> sendRemovePortionData(
int diary_id,
int meal_id,
int portion_id,
) async {
final _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<Map<String, int>>(Options(
method: 'POST',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/diary/${diary_id}/meal/${meal_id}/portions/${portion_id}/delete',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = _result.data!.cast<String, int>();
return _value;
}
RequestOptions _setStreamType<T>(RequestOptions requestOptions) {
if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) {
if (T != dynamic &&
!(requestOptions.responseType == ResponseType.bytes ||
requestOptions.responseType == ResponseType.stream)) {
if (T == String) {
requestOptions.responseType = ResponseType.plain;
} else {