Tell diary suggestions apart by portion and keep the newest

This commit is contained in:
Roland Geider
2026-12-03 19:31:48 +01:00
parent 0a1d38a809
commit 86af7ab9b1
2 changed files with 53 additions and 5 deletions

View File

@@ -263,19 +263,23 @@ class NutritionalPlan with _$NutritionalPlan {
return out;
}
/// returns diary entries
/// deduped by the combination of amount and ingredient ID
/// The diary entries as suggestions, newest first, one per combination of
/// ingredient, amount and weight unit. A combination logged several times
/// is represented by its newest entry, so it sits where it was used last.
List<LogItem> get dedupDiaryEntries {
final newestFirst = diaryEntries.sorted((a, b) => b.datetime.compareTo(a.datetime));
final out = <LogItem>[];
for (final log in diaryEntries) {
for (final log in newestFirst) {
final found = out.firstWhereOrNull(
(e) => e.amount == log.amount && e.ingredientId == log.ingredientId,
(e) =>
e.amount == log.amount &&
e.ingredientId == log.ingredientId &&
e.weightUnitId == log.weightUnitId,
);
if (found == null) {
out.add(log);
}
}
out.sort((a, b) => b.datetime.compareTo(a.datetime));
return out;
}

View File

@@ -17,6 +17,8 @@
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/features/nutrition/models/ingredient_weight_unit.dart';
import 'package:wger/features/nutrition/models/log.dart';
import 'package:wger/features/nutrition/models/meal.dart';
import 'package:wger/features/nutrition/models/meal_item.dart';
import 'package:wger/features/nutrition/models/nutritional_goals.dart';
@@ -134,5 +136,47 @@ void main() {
expect(result[2], same(otherAmount));
expect(result[3], same(otherIngredient));
});
group('dedupDiaryEntries', () {
const cup = IngredientWeightUnit(
id: 1,
uuid: '00000000-0000-0000-0000-000000000001',
ingredientId: 1,
name: 'Cup',
grams: 80,
);
LogItem log(int ingredientId, num amount, DateTime datetime, {IngredientWeightUnit? unit}) =>
LogItem(
planId: 'plan',
ingredientId: ingredientId,
amount: amount,
datetime: datetime,
weightUnitId: unit?.id,
weightUnitObj: unit,
);
// The repository delivers the diary oldest first
NutritionalPlan planWith(List<LogItem> diary) => NutritionalPlan(
description: 'diary',
startDate: DateTime(2026, 3, 1),
diaryEntries: diary,
);
test('the same amount in another unit is a suggestion of its own', () {
final cups = log(1, 2, DateTime(2026, 3, 2), unit: cup);
final grams = log(1, 2, DateTime(2026, 3, 3));
expect(planWith([cups, grams]).dedupDiaryEntries, [grams, cups]);
});
test('a combination logged again sits where it was logged last', () {
final oatsFirst = log(1, 50, DateTime(2026, 3, 2, 8));
final apple = log(2, 150, DateTime(2026, 3, 5, 10));
final oatsLast = log(1, 50, DateTime(2026, 3, 9, 8));
expect(planWith([oatsFirst, apple, oatsLast]).dedupDiaryEntries, [oatsLast, apple]);
});
});
});
}