Add nutritional values calculations to diary

This commit is contained in:
Roland Geider
2020-12-27 11:22:46 +01:00
parent 33a3c71af0
commit 5f4a25e9ec
9 changed files with 138 additions and 18 deletions

View File

@@ -17,10 +17,13 @@
*/
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/models/nutrition/ingredient.dart';
import 'package:wger/models/nutrition/ingredient_weight_unit.dart';
import 'package:wger/models/nutrition/meal_item.dart';
import 'nutritrional_values.dart';
part 'log.g.dart';
@JsonSerializable()
@@ -41,13 +44,13 @@ class Log {
Ingredient ingredientObj;
@JsonKey(required: true)
@JsonKey(required: true, name: 'weight_unit')
int weightUnit;
IngredientWeightUnit weightUnitObj;
@JsonKey(required: true)
double amount;
@JsonKey(required: true, fromJson: toNum)
num amount;
Log({
this.id,
@@ -70,4 +73,32 @@ class Log {
// Boilerplate
factory Log.fromJson(Map<String, dynamic> json) => _$LogFromJson(json);
Map<String, dynamic> toJson() => _$LogToJson(this);
/// Calculations
NutritionalValues get nutritionalValues {
// This is already done on the server. It might be better to read it from there.
var out = NutritionalValues();
final weight =
this.weightUnitObj == null ? amount : amount * weightUnitObj.amount * weightUnitObj.grams;
out.energy = ingredientObj.energy * weight / 100;
out.protein = ingredientObj.protein * weight / 100;
out.carbohydrates = ingredientObj.carbohydrates * weight / 100;
out.fat = ingredientObj.fat * weight / 100;
if (ingredientObj.fatSaturated != null) {
out.fatSaturated = ingredientObj.fatSaturated * weight / 100;
}
if (ingredientObj.fibres != null) {
out.fibres = ingredientObj.fibres * weight / 100;
}
if (ingredientObj.sodium != null) {
out.sodium + ingredientObj.sodium * weight / 100;
}
return out;
}
}

View File

@@ -12,7 +12,7 @@ Log _$LogFromJson(Map<String, dynamic> json) {
'plan',
'datetime',
'ingredient',
'weightUnit',
'weight_unit',
'amount'
]);
return Log(
@@ -21,12 +21,12 @@ Log _$LogFromJson(Map<String, dynamic> json) {
ingredientObj: json['ingredientObj'] == null
? null
: Ingredient.fromJson(json['ingredientObj'] as Map<String, dynamic>),
weightUnit: json['weightUnit'] as int,
weightUnit: json['weight_unit'] as int,
weightUnitObj: json['weightUnitObj'] == null
? null
: IngredientWeightUnit.fromJson(
json['weightUnitObj'] as Map<String, dynamic>),
amount: (json['amount'] as num)?.toDouble(),
amount: toNum(json['amount'] as String),
planId: json['plan'] as int,
datetime: json['datetime'] == null
? null
@@ -42,7 +42,7 @@ Map<String, dynamic> _$LogToJson(Log instance) => <String, dynamic>{
'comment': instance.comment,
'ingredient': instance.ingredientId,
'ingredientObj': instance.ingredientObj,
'weightUnit': instance.weightUnit,
'weight_unit': instance.weightUnit,
'weightUnitObj': instance.weightUnitObj,
'amount': instance.amount,
};

View File

@@ -18,6 +18,7 @@
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/models/nutrition/log.dart';
import 'package:wger/models/nutrition/meal.dart';
import 'nutritrional_values.dart';
@@ -36,13 +37,17 @@ class NutritionalPlan {
DateTime creationDate;
@JsonKey(required: false)
List<Meal> meals;
List<Meal> meals = [];
@JsonKey(ignore: true)
List<Log> logs = [];
NutritionalPlan({
this.id,
this.description,
this.creationDate,
this.meals,
//this.logs,
});
// Boilerplate
@@ -60,4 +65,18 @@ class NutritionalPlan {
return out;
}
Map<DateTime, NutritionalValues> get logEntriesValues {
var out = <DateTime, NutritionalValues>{};
for (var log in logs) {
final date = DateTime(log.datetime.year, log.datetime.month, log.datetime.day);
if (!out.containsKey(date)) {
out[date] = NutritionalValues();
}
out[date].add(log.nutritionalValues);
}
return out;
}
}

View File

@@ -60,10 +60,9 @@ class WgerBaseProvider {
}
// Send the request
requestUrl = urlPath == null ? makeUrl(urlPath) : urlPath;
final response = await client.get(
requestUrl + '?ordering=-date',
headers: <String, String>{
urlPath,
headers: {
'Authorization': 'Token ${auth.token}',
'User-Agent': 'wger Workout Manager App',
},
@@ -71,6 +70,7 @@ class WgerBaseProvider {
// Something wrong with our request
if (response.statusCode >= 400) {
print(response);
throw WgerHttpException(response.body);
}

View File

@@ -41,6 +41,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier {
String _url;
Auth _auth;
List<NutritionalPlan> _plans = [];
List<Ingredient> _ingredients = [];
Nutrition(Auth auth, List<NutritionalPlan> entries)
: this._plans = entries,
@@ -208,14 +209,23 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier {
}
/// Fetch and return an ingredient
///
/// If the ingredient is not known locally, it is fetched from the server
Future<Ingredient> fetchIngredient(int ingredientId, {http.Client client}) async {
if (client == null) {
client = http.Client();
}
var ingredient = _ingredients.firstWhere((e) => e.id == ingredientId, orElse: () => null);
if (ingredient != null) {
return ingredient;
}
// fetch and return
final data = await fetch(client, makeUrl(ingredientUrl, id: ingredientId.toString()));
return Ingredient.fromJson(data);
ingredient = Ingredient.fromJson(data);
_ingredients.add(ingredient);
return ingredient;
}
/// Searches for an ingredient
@@ -259,4 +269,22 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier {
}
notifyListeners();
}
/// Log meal to nutrition diary
Future<void> fetchAndSetLogs(NutritionalPlan plan, {http.Client client}) async {
if (client == null) {
client = http.Client();
}
final data =
await fetch(client, makeUrl(nutritionDiaryUrl, query: {'plan': plan.id.toString()}));
for (var logData in data['results']) {
var log = Log.fromJson(logData);
final ingredient = await fetchIngredient(log.ingredientId);
log.ingredientObj = ingredient;
plan.logs.add(log);
}
notifyListeners();
}
}

View File

@@ -33,6 +33,8 @@ class NutritrionalPlanScreen extends StatefulWidget {
class _NutritrionalPlanScreenState extends State<NutritrionalPlanScreen> {
Future<NutritionalPlan> _loadNutritionalPlanDetail(BuildContext context, int planId) async {
var plan = await Provider.of<Nutrition>(context, listen: false).findById(planId);
await Provider.of<Nutrition>(context, listen: false).fetchAndSetLogs(plan);
return plan;
}

View File

@@ -185,7 +185,7 @@ class DismissibleMealHeader extends StatelessWidget {
// Log meal
} else {
Provider.of<Nutrition>(context, listen: false).addMealToDiary(_meal);
Provider.of<Nutrition>(context, listen: false).logMealToDiary(_meal);
}
return false;
},

View File

@@ -20,6 +20,7 @@ import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
import 'package:wger/locale/locales.dart';
import 'package:wger/models/nutrition/nutritional_plan.dart';
import 'package:wger/models/nutrition/nutritrional_values.dart';
import 'package:wger/widgets/core/bottom_sheet.dart';
import 'package:wger/widgets/nutrition/forms.dart';
import 'package:wger/widgets/nutrition/meal.dart';
@@ -129,10 +130,53 @@ class NutritionalPlanDetailWidget extends StatelessWidget {
]),
],
),
)
),
Padding(padding: const EdgeInsets.all(8.0)),
Text(
'Nutritional diary',
style: Theme.of(context).textTheme.headline6,
),
Container(
height: 200,
child: SingleChildScrollView(
child: Column(
children: [
..._nutritionalPlan.logEntriesValues.entries
.map((entry) => NutritionDiaryEntry(entry.key, entry.value))
.toList(),
],
),
),
),
],
),
),
);
}
}
class NutritionDiaryEntry extends StatelessWidget {
DateTime date;
NutritionalValues values;
NutritionDiaryEntry(
this.date,
this.values,
);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Column(
children: [
Text(DefaultMaterialLocalizations().formatMediumDate(date).toString()),
Text(values.energy.toStringAsFixed(0)),
Text(values.protein.toStringAsFixed(0)),
Text(values.carbohydrates.toStringAsFixed(0)),
Text(values.fat.toStringAsFixed(0)),
],
),
);
}
}

View File

@@ -63,10 +63,6 @@ class NutritionalPlansList extends StatelessWidget {
direction: DismissDirection.endToStart,
child: Card(
child: ListTile(
//onTap: () => Navigator.of(context).pushNamed(
// WorkoutPlanScreen.routeName,
// arguments: currentPlan,
//),
onTap: () {
Navigator.of(context).pushNamed(
NutritrionalPlanScreen.routeName,