From d6affe4036d681fff0d190d41c6e8d5f5c5ed1b8 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 2 May 2026 12:36:08 +0200 Subject: [PATCH] Sync the rest of the nutrition tables with powersync --- lib/database/powersync/database.g.dart | 253 +++++++++--------- lib/database/powersync/tables/nutrition.dart | 38 +-- lib/helpers/consts.dart | 7 +- lib/models/nutrition/log.dart | 7 +- lib/models/nutrition/meal.dart | 54 ++-- lib/models/nutrition/meal.g.dart | 23 -- lib/models/nutrition/meal_item.dart | 50 ++-- lib/models/nutrition/meal_item.g.dart | 26 -- lib/models/nutrition/nutritional_plan.dart | 46 +--- lib/models/nutrition/nutritional_plan.g.dart | 55 ---- lib/providers/nutrition_notifier.dart | 224 +++++----------- lib/providers/nutrition_notifier.g.dart | 2 +- lib/providers/nutrition_repository.dart | 180 +++++++++---- lib/screens/nutritional_plan_screen.dart | 53 ++-- lib/widgets/nutrition/forms.dart | 86 +++--- ...measurement_entries_screen_test.mocks.dart | 75 +++--- test/nutrition/nutrition_provider_test.dart | 164 +++++------- .../nutrition_provider_test.mocks.dart | 75 +++--- test/nutrition/nutrition_repository_test.dart | 250 ++++++++++------- .../nutrition/nutritional_meal_form_test.dart | 51 +--- .../nutritional_meal_item_form_test.dart | 18 +- .../nutrition/nutritional_plan_form_test.dart | 11 +- .../nutritional_plan_form_test.mocks.dart | 75 +++--- .../nutritional_plan_screen_test.dart | 56 +--- .../nutritional_plan_screen_test.mocks.dart | 75 +++--- .../nutritional_plans_screen_test.dart | 9 +- .../nutritional_plans_screen_test.mocks.dart | 75 +++--- test/weight/weight_screen_test.mocks.dart | 75 +++--- test_data/nutritional_plans.dart | 66 +++-- 29 files changed, 946 insertions(+), 1233 deletions(-) delete mode 100644 lib/models/nutrition/meal.g.dart delete mode 100644 lib/models/nutrition/meal_item.g.dart delete mode 100644 lib/models/nutrition/nutritional_plan.g.dart diff --git a/lib/database/powersync/database.g.dart b/lib/database/powersync/database.g.dart index b77e0a8ce..1cf0ce912 100644 --- a/lib/database/powersync/database.g.dart +++ b/lib/database/powersync/database.g.dart @@ -5319,12 +5319,13 @@ class $NutritionalPlanTableTable extends NutritionalPlanTable $NutritionalPlanTableTable(this.attachedDatabase, [this._alias]); static const VerificationMeta _idMeta = const VerificationMeta('id'); @override - late final GeneratedColumn id = GeneratedColumn( + late final GeneratedColumn id = GeneratedColumn( 'id', aliasedName, false, - type: DriftSqlType.int, - requiredDuringInsert: true, + type: DriftSqlType.string, + requiredDuringInsert: false, + clientDefault: () => ps.uuid.v4(), ); static const VerificationMeta _descriptionMeta = const VerificationMeta( 'description', @@ -5482,8 +5483,6 @@ class $NutritionalPlanTableTable extends NutritionalPlanTable final data = instance.toColumns(true); if (data.containsKey('id')) { context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); - } else if (isInserting) { - context.missing(_idMeta); } if (data.containsKey('description')) { context.handle( @@ -5589,7 +5588,7 @@ class $NutritionalPlanTableTable extends NutritionalPlanTable final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; return NutritionalPlan( id: attachedDatabase.typeMapping.read( - DriftSqlType.int, + DriftSqlType.string, data['${effectivePrefix}id'], )!, description: attachedDatabase.typeMapping.read( @@ -5646,7 +5645,7 @@ class $NutritionalPlanTableTable extends NutritionalPlanTable } class NutritionalPlanTableCompanion extends UpdateCompanion { - final Value id; + final Value id; final Value description; final Value creationDate; final Value startDate; @@ -5675,7 +5674,7 @@ class NutritionalPlanTableCompanion extends UpdateCompanion { this.rowid = const Value.absent(), }); NutritionalPlanTableCompanion.insert({ - required int id, + this.id = const Value.absent(), required String description, required DateTime creationDate, required DateTime startDate, @@ -5688,14 +5687,13 @@ class NutritionalPlanTableCompanion extends UpdateCompanion { this.goalFat = const Value.absent(), required bool hasGoalCalories, this.rowid = const Value.absent(), - }) : id = Value(id), - description = Value(description), + }) : description = Value(description), creationDate = Value(creationDate), startDate = Value(startDate), onlyLogging = Value(onlyLogging), hasGoalCalories = Value(hasGoalCalories); static Insertable custom({ - Expression? id, + Expression? id, Expression? description, Expression? creationDate, Expression? startDate, @@ -5727,7 +5725,7 @@ class NutritionalPlanTableCompanion extends UpdateCompanion { } NutritionalPlanTableCompanion copyWith({ - Value? id, + Value? id, Value? description, Value? creationDate, Value? startDate, @@ -5762,7 +5760,7 @@ class NutritionalPlanTableCompanion extends UpdateCompanion { Map toColumns(bool nullToAbsent) { final map = {}; if (id.present) { - map['id'] = Variable(id.value); + map['id'] = Variable(id.value); } if (description.present) { map['description'] = Variable(description.value); @@ -7355,20 +7353,21 @@ class $MealTableTable extends MealTable with TableInfo<$MealTableTable, Meal> { $MealTableTable(this.attachedDatabase, [this._alias]); static const VerificationMeta _idMeta = const VerificationMeta('id'); @override - late final GeneratedColumn id = GeneratedColumn( + late final GeneratedColumn id = GeneratedColumn( 'id', aliasedName, false, - type: DriftSqlType.int, - requiredDuringInsert: true, + type: DriftSqlType.string, + requiredDuringInsert: false, + clientDefault: () => ps.uuid.v4(), ); static const VerificationMeta _planIdMeta = const VerificationMeta('planId'); @override - late final GeneratedColumn planId = GeneratedColumn( + late final GeneratedColumn planId = GeneratedColumn( 'plan_id', aliasedName, false, - type: DriftSqlType.int, + type: DriftSqlType.string, requiredDuringInsert: true, defaultConstraints: GeneratedColumn.constraintIsAlways( 'REFERENCES nutrition_nutritionplan (id)', @@ -7381,7 +7380,8 @@ class $MealTableTable extends MealTable with TableInfo<$MealTableTable, Meal> { aliasedName, false, type: DriftSqlType.int, - requiredDuringInsert: true, + requiredDuringInsert: false, + defaultValue: const Constant(1), ); @override late final GeneratedColumnWithTypeConverter time = GeneratedColumn( @@ -7417,8 +7417,6 @@ class $MealTableTable extends MealTable with TableInfo<$MealTableTable, Meal> { final data = instance.toColumns(true); if (data.containsKey('id')) { context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); - } else if (isInserting) { - context.missing(_idMeta); } if (data.containsKey('plan_id')) { context.handle( @@ -7433,8 +7431,6 @@ class $MealTableTable extends MealTable with TableInfo<$MealTableTable, Meal> { _orderMeta, order.isAcceptableOrUnknown(data['order']!, _orderMeta), ); - } else if (isInserting) { - context.missing(_orderMeta); } if (data.containsKey('name')) { context.handle( @@ -7452,11 +7448,11 @@ class $MealTableTable extends MealTable with TableInfo<$MealTableTable, Meal> { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; return Meal.fromDrift( id: attachedDatabase.typeMapping.read( - DriftSqlType.int, + DriftSqlType.string, data['${effectivePrefix}id'], )!, planId: attachedDatabase.typeMapping.read( - DriftSqlType.int, + DriftSqlType.string, data['${effectivePrefix}plan_id'], )!, order: attachedDatabase.typeMapping.read( @@ -7488,8 +7484,8 @@ class $MealTableTable extends MealTable with TableInfo<$MealTableTable, Meal> { } class MealTableCompanion extends UpdateCompanion { - final Value id; - final Value planId; + final Value id; + final Value planId; final Value order; final Value time; final Value name; @@ -7503,18 +7499,16 @@ class MealTableCompanion extends UpdateCompanion { this.rowid = const Value.absent(), }); MealTableCompanion.insert({ - required int id, - required int planId, - required int order, + this.id = const Value.absent(), + required String planId, + this.order = const Value.absent(), this.time = const Value.absent(), this.name = const Value.absent(), this.rowid = const Value.absent(), - }) : id = Value(id), - planId = Value(planId), - order = Value(order); + }) : planId = Value(planId); static Insertable custom({ - Expression? id, - Expression? planId, + Expression? id, + Expression? planId, Expression? order, Expression? time, Expression? name, @@ -7531,8 +7525,8 @@ class MealTableCompanion extends UpdateCompanion { } MealTableCompanion copyWith({ - Value? id, - Value? planId, + Value? id, + Value? planId, Value? order, Value? time, Value? name, @@ -7552,10 +7546,10 @@ class MealTableCompanion extends UpdateCompanion { Map toColumns(bool nullToAbsent) { final map = {}; if (id.present) { - map['id'] = Variable(id.value); + map['id'] = Variable(id.value); } if (planId.present) { - map['plan_id'] = Variable(planId.value); + map['plan_id'] = Variable(planId.value); } if (order.present) { map['order'] = Variable(order.value); @@ -7595,20 +7589,21 @@ class $MealItemTableTable extends MealItemTable with TableInfo<$MealItemTableTab $MealItemTableTable(this.attachedDatabase, [this._alias]); static const VerificationMeta _idMeta = const VerificationMeta('id'); @override - late final GeneratedColumn id = GeneratedColumn( + late final GeneratedColumn id = GeneratedColumn( 'id', aliasedName, false, - type: DriftSqlType.int, - requiredDuringInsert: true, + type: DriftSqlType.string, + requiredDuringInsert: false, + clientDefault: () => ps.uuid.v4(), ); static const VerificationMeta _mealIdMeta = const VerificationMeta('mealId'); @override - late final GeneratedColumn mealId = GeneratedColumn( + late final GeneratedColumn mealId = GeneratedColumn( 'meal_id', aliasedName, false, - type: DriftSqlType.int, + type: DriftSqlType.string, requiredDuringInsert: true, defaultConstraints: GeneratedColumn.constraintIsAlways( 'REFERENCES nutrition_meal (id)', @@ -7646,7 +7641,8 @@ class $MealItemTableTable extends MealItemTable with TableInfo<$MealItemTableTab aliasedName, false, type: DriftSqlType.int, - requiredDuringInsert: true, + requiredDuringInsert: false, + defaultValue: const Constant(1), ); static const VerificationMeta _amountMeta = const VerificationMeta('amount'); @override @@ -7680,8 +7676,6 @@ class $MealItemTableTable extends MealItemTable with TableInfo<$MealItemTableTab final data = instance.toColumns(true); if (data.containsKey('id')) { context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); - } else if (isInserting) { - context.missing(_idMeta); } if (data.containsKey('meal_id')) { context.handle( @@ -7716,8 +7710,6 @@ class $MealItemTableTable extends MealItemTable with TableInfo<$MealItemTableTab _orderMeta, order.isAcceptableOrUnknown(data['order']!, _orderMeta), ); - } else if (isInserting) { - context.missing(_orderMeta); } if (data.containsKey('amount')) { context.handle( @@ -7737,11 +7729,11 @@ class $MealItemTableTable extends MealItemTable with TableInfo<$MealItemTableTab final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; return MealItem.fromDrift( id: attachedDatabase.typeMapping.read( - DriftSqlType.int, + DriftSqlType.string, data['${effectivePrefix}id'], )!, mealId: attachedDatabase.typeMapping.read( - DriftSqlType.int, + DriftSqlType.string, data['${effectivePrefix}meal_id'], )!, ingredientId: attachedDatabase.typeMapping.read( @@ -7770,8 +7762,8 @@ class $MealItemTableTable extends MealItemTable with TableInfo<$MealItemTableTab } class MealItemTableCompanion extends UpdateCompanion { - final Value id; - final Value mealId; + final Value id; + final Value mealId; final Value ingredientId; final Value weightUnitId; final Value order; @@ -7787,21 +7779,19 @@ class MealItemTableCompanion extends UpdateCompanion { this.rowid = const Value.absent(), }); MealItemTableCompanion.insert({ - required int id, - required int mealId, + this.id = const Value.absent(), + required String mealId, required int ingredientId, this.weightUnitId = const Value.absent(), - required int order, + this.order = const Value.absent(), required double amount, this.rowid = const Value.absent(), - }) : id = Value(id), - mealId = Value(mealId), + }) : mealId = Value(mealId), ingredientId = Value(ingredientId), - order = Value(order), amount = Value(amount); static Insertable custom({ - Expression? id, - Expression? mealId, + Expression? id, + Expression? mealId, Expression? ingredientId, Expression? weightUnitId, Expression? order, @@ -7820,8 +7810,8 @@ class MealItemTableCompanion extends UpdateCompanion { } MealItemTableCompanion copyWith({ - Value? id, - Value? mealId, + Value? id, + Value? mealId, Value? ingredientId, Value? weightUnitId, Value? order, @@ -7843,10 +7833,10 @@ class MealItemTableCompanion extends UpdateCompanion { Map toColumns(bool nullToAbsent) { final map = {}; if (id.present) { - map['id'] = Variable(id.value); + map['id'] = Variable(id.value); } if (mealId.present) { - map['meal_id'] = Variable(mealId.value); + map['meal_id'] = Variable(mealId.value); } if (ingredientId.present) { map['ingredient_id'] = Variable(ingredientId.value); @@ -7898,11 +7888,11 @@ class $LogItemTableTable extends LogItemTable with TableInfo<$LogItemTableTable, ); static const VerificationMeta _planIdMeta = const VerificationMeta('planId'); @override - late final GeneratedColumn planId = GeneratedColumn( + late final GeneratedColumn planId = GeneratedColumn( 'plan_id', aliasedName, false, - type: DriftSqlType.int, + type: DriftSqlType.string, requiredDuringInsert: true, defaultConstraints: GeneratedColumn.constraintIsAlways( 'REFERENCES nutrition_nutritionplan (id)', @@ -7910,11 +7900,11 @@ class $LogItemTableTable extends LogItemTable with TableInfo<$LogItemTableTable, ); static const VerificationMeta _mealIdMeta = const VerificationMeta('mealId'); @override - late final GeneratedColumn mealId = GeneratedColumn( + late final GeneratedColumn mealId = GeneratedColumn( 'meal_id', aliasedName, true, - type: DriftSqlType.int, + type: DriftSqlType.string, requiredDuringInsert: false, ); static const VerificationMeta _ingredientIdMeta = const VerificationMeta( @@ -8069,7 +8059,7 @@ class $LogItemTableTable extends LogItemTable with TableInfo<$LogItemTableTable, data['${effectivePrefix}id'], )!, mealId: attachedDatabase.typeMapping.read( - DriftSqlType.int, + DriftSqlType.string, data['${effectivePrefix}meal_id'], ), ingredientId: attachedDatabase.typeMapping.read( @@ -8085,7 +8075,7 @@ class $LogItemTableTable extends LogItemTable with TableInfo<$LogItemTableTable, data['${effectivePrefix}amount'], )!, planId: attachedDatabase.typeMapping.read( - DriftSqlType.int, + DriftSqlType.string, data['${effectivePrefix}plan_id'], )!, datetime: attachedDatabase.typeMapping.read( @@ -8107,8 +8097,8 @@ class $LogItemTableTable extends LogItemTable with TableInfo<$LogItemTableTable, class LogItemTableCompanion extends UpdateCompanion { final Value id; - final Value planId; - final Value mealId; + final Value planId; + final Value mealId; final Value ingredientId; final Value weightUnitId; final Value datetime; @@ -8128,7 +8118,7 @@ class LogItemTableCompanion extends UpdateCompanion { }); LogItemTableCompanion.insert({ this.id = const Value.absent(), - required int planId, + required String planId, this.mealId = const Value.absent(), required int ingredientId, this.weightUnitId = const Value.absent(), @@ -8142,8 +8132,8 @@ class LogItemTableCompanion extends UpdateCompanion { amount = Value(amount); static Insertable custom({ Expression? id, - Expression? planId, - Expression? mealId, + Expression? planId, + Expression? mealId, Expression? ingredientId, Expression? weightUnitId, Expression? datetime, @@ -8166,8 +8156,8 @@ class LogItemTableCompanion extends UpdateCompanion { LogItemTableCompanion copyWith({ Value? id, - Value? planId, - Value? mealId, + Value? planId, + Value? mealId, Value? ingredientId, Value? weightUnitId, Value? datetime, @@ -8195,10 +8185,10 @@ class LogItemTableCompanion extends UpdateCompanion { map['id'] = Variable(id.value); } if (planId.present) { - map['plan_id'] = Variable(planId.value); + map['plan_id'] = Variable(planId.value); } if (mealId.present) { - map['meal_id'] = Variable(mealId.value); + map['meal_id'] = Variable(mealId.value); } if (ingredientId.present) { map['ingredient_id'] = Variable(ingredientId.value); @@ -15246,7 +15236,7 @@ typedef $$RoutineWeightUnitTableTableProcessedTableManager = >; typedef $$NutritionalPlanTableTableCreateCompanionBuilder = NutritionalPlanTableCompanion Function({ - required int id, + Value id, required String description, required DateTime creationDate, required DateTime startDate, @@ -15262,7 +15252,7 @@ typedef $$NutritionalPlanTableTableCreateCompanionBuilder = }); typedef $$NutritionalPlanTableTableUpdateCompanionBuilder = NutritionalPlanTableCompanion Function({ - Value id, + Value id, Value description, Value creationDate, Value startDate, @@ -15299,7 +15289,7 @@ final class $$NutritionalPlanTableTableReferences final manager = $$MealTableTableTableManager( $_db, $_db.mealTable, - ).filter((f) => f.planId.id.sqlEquals($_itemColumn('id')!)); + ).filter((f) => f.planId.id.sqlEquals($_itemColumn('id')!)); final cache = $_typedResult.readTableOrNull(_mealTableRefsTable($_db)); return ProcessedTableManager( @@ -15321,7 +15311,7 @@ final class $$NutritionalPlanTableTableReferences final manager = $$LogItemTableTableTableManager( $_db, $_db.logItemTable, - ).filter((f) => f.planId.id.sqlEquals($_itemColumn('id')!)); + ).filter((f) => f.planId.id.sqlEquals($_itemColumn('id')!)); final cache = $_typedResult.readTableOrNull(_logItemTableRefsTable($_db)); return ProcessedTableManager( @@ -15339,7 +15329,7 @@ class $$NutritionalPlanTableTableFilterComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - ColumnFilters get id => $composableBuilder( + ColumnFilters get id => $composableBuilder( column: $table.id, builder: (column) => ColumnFilters(column), ); @@ -15457,7 +15447,7 @@ class $$NutritionalPlanTableTableOrderingComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - ColumnOrderings get id => $composableBuilder( + ColumnOrderings get id => $composableBuilder( column: $table.id, builder: (column) => ColumnOrderings(column), ); @@ -15527,7 +15517,8 @@ class $$NutritionalPlanTableTableAnnotationComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - GeneratedColumn get id => $composableBuilder(column: $table.id, builder: (column) => column); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); GeneratedColumn get description => $composableBuilder( column: $table.description, @@ -15659,7 +15650,7 @@ class $$NutritionalPlanTableTableTableManager ), updateCompanionCallback: ({ - Value id = const Value.absent(), + Value id = const Value.absent(), Value description = const Value.absent(), Value creationDate = const Value.absent(), Value startDate = const Value.absent(), @@ -15689,7 +15680,7 @@ class $$NutritionalPlanTableTableTableManager ), createCompanionCallback: ({ - required int id, + Value id = const Value.absent(), required String description, required DateTime creationDate, required DateTime startDate, @@ -17491,17 +17482,17 @@ typedef $$IngredientWeightUnitTableTableProcessedTableManager = >; typedef $$MealTableTableCreateCompanionBuilder = MealTableCompanion Function({ - required int id, - required int planId, - required int order, + Value id, + required String planId, + Value order, Value time, Value name, Value rowid, }); typedef $$MealTableTableUpdateCompanionBuilder = MealTableCompanion Function({ - Value id, - Value planId, + Value id, + Value planId, Value order, Value time, Value name, @@ -17518,7 +17509,7 @@ final class $$MealTableTableReferences ); $$NutritionalPlanTableTableProcessedTableManager get planId { - final $_column = $_itemColumn('plan_id')!; + final $_column = $_itemColumn('plan_id')!; final manager = $$NutritionalPlanTableTableTableManager( $_db, @@ -17545,7 +17536,7 @@ final class $$MealTableTableReferences final manager = $$MealItemTableTableTableManager( $_db, $_db.mealItemTable, - ).filter((f) => f.mealId.id.sqlEquals($_itemColumn('id')!)); + ).filter((f) => f.mealId.id.sqlEquals($_itemColumn('id')!)); final cache = $_typedResult.readTableOrNull(_mealItemTableRefsTable($_db)); return ProcessedTableManager( @@ -17562,7 +17553,7 @@ class $$MealTableTableFilterComposer extends Composer<_$DriftPowersyncDatabase, super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - ColumnFilters get id => $composableBuilder( + ColumnFilters get id => $composableBuilder( column: $table.id, builder: (column) => ColumnFilters(column), ); @@ -17637,7 +17628,7 @@ class $$MealTableTableOrderingComposer extends Composer<_$DriftPowersyncDatabase super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - ColumnOrderings get id => $composableBuilder( + ColumnOrderings get id => $composableBuilder( column: $table.id, builder: (column) => ColumnOrderings(column), ); @@ -17689,7 +17680,8 @@ class $$MealTableTableAnnotationComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - GeneratedColumn get id => $composableBuilder(column: $table.id, builder: (column) => column); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); GeneratedColumn get order => $composableBuilder(column: $table.order, builder: (column) => column); @@ -17775,8 +17767,8 @@ class $$MealTableTableTableManager $$MealTableTableAnnotationComposer($db: db, $table: table), updateCompanionCallback: ({ - Value id = const Value.absent(), - Value planId = const Value.absent(), + Value id = const Value.absent(), + Value planId = const Value.absent(), Value order = const Value.absent(), Value time = const Value.absent(), Value name = const Value.absent(), @@ -17791,9 +17783,9 @@ class $$MealTableTableTableManager ), createCompanionCallback: ({ - required int id, - required int planId, - required int order, + Value id = const Value.absent(), + required String planId, + Value order = const Value.absent(), Value time = const Value.absent(), Value name = const Value.absent(), Value rowid = const Value.absent(), @@ -17887,18 +17879,18 @@ typedef $$MealTableTableProcessedTableManager = >; typedef $$MealItemTableTableCreateCompanionBuilder = MealItemTableCompanion Function({ - required int id, - required int mealId, + Value id, + required String mealId, required int ingredientId, Value weightUnitId, - required int order, + Value order, required double amount, Value rowid, }); typedef $$MealItemTableTableUpdateCompanionBuilder = MealItemTableCompanion Function({ - Value id, - Value mealId, + Value id, + Value mealId, Value ingredientId, Value weightUnitId, Value order, @@ -17919,7 +17911,7 @@ final class $$MealItemTableTableReferences ); $$MealTableTableProcessedTableManager get mealId { - final $_column = $_itemColumn('meal_id')!; + final $_column = $_itemColumn('meal_id')!; final manager = $$MealTableTableTableManager( $_db, @@ -17962,7 +17954,7 @@ class $$MealItemTableTableFilterComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - ColumnFilters get id => $composableBuilder( + ColumnFilters get id => $composableBuilder( column: $table.id, builder: (column) => ColumnFilters(column), ); @@ -18036,7 +18028,7 @@ class $$MealItemTableTableOrderingComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - ColumnOrderings get id => $composableBuilder( + ColumnOrderings get id => $composableBuilder( column: $table.id, builder: (column) => ColumnOrderings(column), ); @@ -18110,7 +18102,8 @@ class $$MealItemTableTableAnnotationComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - GeneratedColumn get id => $composableBuilder(column: $table.id, builder: (column) => column); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); GeneratedColumn get weightUnitId => $composableBuilder( column: $table.weightUnitId, @@ -18197,8 +18190,8 @@ class $$MealItemTableTableTableManager $$MealItemTableTableAnnotationComposer($db: db, $table: table), updateCompanionCallback: ({ - Value id = const Value.absent(), - Value mealId = const Value.absent(), + Value id = const Value.absent(), + Value mealId = const Value.absent(), Value ingredientId = const Value.absent(), Value weightUnitId = const Value.absent(), Value order = const Value.absent(), @@ -18215,11 +18208,11 @@ class $$MealItemTableTableTableManager ), createCompanionCallback: ({ - required int id, - required int mealId, + Value id = const Value.absent(), + required String mealId, required int ingredientId, Value weightUnitId = const Value.absent(), - required int order, + Value order = const Value.absent(), required double amount, Value rowid = const Value.absent(), }) => MealItemTableCompanion.insert( @@ -18314,8 +18307,8 @@ typedef $$MealItemTableTableProcessedTableManager = typedef $$LogItemTableTableCreateCompanionBuilder = LogItemTableCompanion Function({ Value id, - required int planId, - Value mealId, + required String planId, + Value mealId, required int ingredientId, Value weightUnitId, required DateTime datetime, @@ -18326,8 +18319,8 @@ typedef $$LogItemTableTableCreateCompanionBuilder = typedef $$LogItemTableTableUpdateCompanionBuilder = LogItemTableCompanion Function({ Value id, - Value planId, - Value mealId, + Value planId, + Value mealId, Value ingredientId, Value weightUnitId, Value datetime, @@ -18349,7 +18342,7 @@ final class $$LogItemTableTableReferences ); $$NutritionalPlanTableTableProcessedTableManager get planId { - final $_column = $_itemColumn('plan_id')!; + final $_column = $_itemColumn('plan_id')!; final manager = $$NutritionalPlanTableTableTableManager( $_db, @@ -18397,7 +18390,7 @@ class $$LogItemTableTableFilterComposer builder: (column) => ColumnFilters(column), ); - ColumnFilters get mealId => $composableBuilder( + ColumnFilters get mealId => $composableBuilder( column: $table.mealId, builder: (column) => ColumnFilters(column), ); @@ -18481,7 +18474,7 @@ class $$LogItemTableTableOrderingComposer builder: (column) => ColumnOrderings(column), ); - ColumnOrderings get mealId => $composableBuilder( + ColumnOrderings get mealId => $composableBuilder( column: $table.mealId, builder: (column) => ColumnOrderings(column), ); @@ -18563,7 +18556,7 @@ class $$LogItemTableTableAnnotationComposer GeneratedColumn get id => $composableBuilder(column: $table.id, builder: (column) => column); - GeneratedColumn get mealId => + GeneratedColumn get mealId => $composableBuilder(column: $table.mealId, builder: (column) => column); GeneratedColumn get weightUnitId => $composableBuilder( @@ -18654,8 +18647,8 @@ class $$LogItemTableTableTableManager updateCompanionCallback: ({ Value id = const Value.absent(), - Value planId = const Value.absent(), - Value mealId = const Value.absent(), + Value planId = const Value.absent(), + Value mealId = const Value.absent(), Value ingredientId = const Value.absent(), Value weightUnitId = const Value.absent(), Value datetime = const Value.absent(), @@ -18676,8 +18669,8 @@ class $$LogItemTableTableTableManager createCompanionCallback: ({ Value id = const Value.absent(), - required int planId, - Value mealId = const Value.absent(), + required String planId, + Value mealId = const Value.absent(), required int ingredientId, Value weightUnitId = const Value.absent(), required DateTime datetime, diff --git a/lib/database/powersync/tables/nutrition.dart b/lib/database/powersync/tables/nutrition.dart index 80d559aa0..1d71820c9 100644 --- a/lib/database/powersync/tables/nutrition.dart +++ b/lib/database/powersync/tables/nutrition.dart @@ -31,7 +31,7 @@ class NutritionalPlanTable extends Table { @override String get tableName => 'nutrition_nutritionplan'; - IntColumn get id => integer()(); + TextColumn get id => text().clientDefault(() => ps.uuid.v4())(); TextColumn get description => text()(); DateTimeColumn get creationDate => dateTime().named('creation_date')(); DateTimeColumn get startDate => dateTime().named('start')(); @@ -73,8 +73,8 @@ class LogItemTable extends Table { String get tableName => 'nutrition_logitem'; TextColumn get id => text().clientDefault(() => ps.uuid.v4())(); - IntColumn get planId => integer().named('plan_id').references(NutritionalPlanTable, #id)(); - IntColumn get mealId => integer().nullable().named('meal_id')(); + TextColumn get planId => text().named('plan_id').references(NutritionalPlanTable, #id)(); + TextColumn get mealId => text().nullable().named('meal_id')(); IntColumn get ingredientId => integer().named('ingredient_id').references(IngredientTable, #id)(); IntColumn get weightUnitId => integer().nullable().named('weight_unit_id')(); DateTimeColumn get datetime => dateTime()(); @@ -85,8 +85,8 @@ class LogItemTable extends Table { const PowersyncLogItemTable = ps.Table( 'nutrition_logitem', [ - ps.Column.integer('plan_id'), - ps.Column.integer('meal_id'), + ps.Column.text('plan_id'), + ps.Column.text('meal_id'), ps.Column.integer('ingredient_id'), ps.Column.integer('weight_unit_id'), ps.Column.text('datetime'), @@ -101,18 +101,17 @@ const PowersyncLogItemTable = ps.Table( /// A meal inside a nutritional plan (`nutrition_meal`). /// -/// Creation goes via REST (server assigns the integer PK and the `order` -/// field), edits and deletes flow through PowerSync. The `time` is -/// stored as a `HH:MM:SS` string and translated to/from [TimeOfDay] via -/// [TimeOfDayConverter]. +/// Identified by uuid client-side; creation, edits and deletes all flow +/// through PowerSync. The `time` is stored as a `HH:MM:SS` string and +/// translated to/from [TimeOfDay] via [TimeOfDayConverter]. @UseRowClass(Meal, constructor: 'fromDrift') class MealTable extends Table { @override String get tableName => 'nutrition_meal'; - IntColumn get id => integer()(); - IntColumn get planId => integer().named('plan_id').references(NutritionalPlanTable, #id)(); - IntColumn get order => integer()(); + TextColumn get id => text().clientDefault(() => ps.uuid.v4())(); + TextColumn get planId => text().named('plan_id').references(NutritionalPlanTable, #id)(); + IntColumn get order => integer().withDefault(const Constant(1))(); TextColumn get time => text().map(const TimeOfDayConverter()).nullable()(); TextColumn get name => text().withDefault(const Constant(''))(); } @@ -120,7 +119,7 @@ class MealTable extends Table { const PowersyncMealTable = ps.Table( 'nutrition_meal', [ - ps.Column.integer('plan_id'), + ps.Column.text('plan_id'), ps.Column.integer('order'), ps.Column.text('time'), ps.Column.text('name'), @@ -132,26 +131,27 @@ const PowersyncMealTable = ps.Table( /// A single ingredient + amount inside a meal (`nutrition_mealitem`). /// -/// Creation via REST, edits and deletes via PowerSync. `amount` is -/// a `DecimalField(decimal_places=2, max_digits=6)` server-side, stored here +/// Identified by uuid client-side; the `meal_id` FK is the parent meal's +/// uuid (not the server-side integer PK). `amount` is a +/// `DecimalField(decimal_places=2, max_digits=6)` server-side, stored here /// as REAL — the rounding happens implicitly when DRF coerces back. @UseRowClass(MealItem, constructor: 'fromDrift') class MealItemTable extends Table { @override String get tableName => 'nutrition_mealitem'; - IntColumn get id => integer()(); - IntColumn get mealId => integer().named('meal_id').references(MealTable, #id)(); + TextColumn get id => text().clientDefault(() => ps.uuid.v4())(); + TextColumn get mealId => text().named('meal_id').references(MealTable, #id)(); IntColumn get ingredientId => integer().named('ingredient_id').references(IngredientTable, #id)(); IntColumn get weightUnitId => integer().named('weight_unit_id').nullable()(); - IntColumn get order => integer()(); + IntColumn get order => integer().withDefault(const Constant(1))(); RealColumn get amount => real()(); } const PowersyncMealItemTable = ps.Table( 'nutrition_mealitem', [ - ps.Column.integer('meal_id'), + ps.Column.text('meal_id'), ps.Column.integer('ingredient_id'), ps.Column.integer('weight_unit_id'), ps.Column.integer('order'), diff --git a/lib/helpers/consts.dart b/lib/helpers/consts.dart index 459ec84e1..dd7b75f86 100644 --- a/lib/helpers/consts.dart +++ b/lib/helpers/consts.dart @@ -111,8 +111,11 @@ enum EXERCISE_IMAGE_ART_STYLE { OTHER, } -/// Dummy ID for pseudo meals -const PSEUDO_MEAL_ID = -1; +/// Sentinel UUID for the synthetic "loose log entries" pseudo-meal. +/// +/// All-zero UUID is reserved by RFC 4122 (the "nil UUID") and won't collide +/// with any client-generated UUID v4. +const PSEUDO_MEAL_ID = '00000000-0000-0000-0000-000000000000'; /// Colors used for muscles const COLOR_MAIN_MUSCLES = Colors.red; diff --git a/lib/models/nutrition/log.dart b/lib/models/nutrition/log.dart index aa8d30d87..78370535e 100644 --- a/lib/models/nutrition/log.dart +++ b/lib/models/nutrition/log.dart @@ -37,8 +37,11 @@ class LogItem { /// the first persist; Drift fills it in via the table's `clientDefault`. String? id; - int planId; - int? mealId; + String planId; + + /// Optional parent meal (`null` for free-form diary entries that don't belong to a meal) + String? mealId; + int ingredientId; int? weightUnitId; late DateTime datetime; diff --git a/lib/models/nutrition/meal.dart b/lib/models/nutrition/meal.dart index cd3653b59..6477ca4e8 100644 --- a/lib/models/nutrition/meal.dart +++ b/lib/models/nutrition/meal.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -18,40 +18,29 @@ import 'package:drift/drift.dart' as drift; import 'package:flutter/material.dart'; -import 'package:json_annotation/json_annotation.dart'; import 'package:wger/database/powersync/database.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/date.dart'; -import 'package:wger/helpers/json.dart'; import 'package:wger/models/nutrition/log.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/models/nutrition/nutritional_values.dart'; -part 'meal.g.dart'; - -@JsonSerializable() class Meal { - @JsonKey(required: false) - late int? id; + String? id; - @JsonKey(name: 'plan') - late int planId; + /// FK to the parent plan + late String planId; - @JsonKey(toJson: timeToString, fromJson: stringToTimeNull) TimeOfDay? time; - @JsonKey(name: 'name') late String name; - /// Server-assigned ordering inside the plan. Not user-editable; we sync it - /// down so PowerSync can replicate the row, but never push changes back. - @JsonKey(includeToJson: false, defaultValue: 1) + /// Server-side ordering inside the plan. Replicated down for completeness; + /// the client computes new values as `MAX(order) + 1` on insert. int order = 1; - @JsonKey(includeFromJson: false, includeToJson: false, defaultValue: []) List mealItems = []; - @JsonKey(includeFromJson: false, includeToJson: false, defaultValue: []) List diaryEntries = []; List get diaryEntriesToday => @@ -59,7 +48,7 @@ class Meal { Meal({ this.id, - int? plan, + String? plan, this.time, String? name, List? mealItems, @@ -81,7 +70,7 @@ class Meal { /// by the repository hydration step. Meal.fromDrift({ this.id, - required int planId, + required String planId, required int order, this.time, required String name, @@ -93,8 +82,7 @@ class Meal { diaryEntries = []; } - /// Calculate total nutritional value - // This is already done on the server. It might be better to read it from there. + /// Total nutritional values across all child meal items. NutritionalValues get plannedNutritionalValues { return mealItems.fold(NutritionalValues(), (a, b) => a + b.nutritionalValues); } @@ -110,30 +98,28 @@ class Meal { return id != null && id != PSEUDO_MEAL_ID; } - // Boilerplate - factory Meal.fromJson(Map json) => _$MealFromJson(json); - - Map toJson() => _$MealToJson(this); - - /// Drift companion for updates against `nutrition_meal`. + /// Drift companion for inserts/updates against `nutrition_meal`. /// - /// `order` is intentionally absent — it's server-managed and read-only. - MealTableCompanion toCompanion() { + /// On insert, leave `id` absent so the table's `clientDefault` UUID kicks + /// in (or set [includeId] true if you've already generated it). For an + /// update, the row id must be present, we throw if it's missing. + MealTableCompanion toCompanion({bool includeId = true}) { final mealId = id; - if (mealId == null) { - throw StateError('Cannot persist meal without id (creation goes via REST)'); + if (includeId && mealId == null) { + throw StateError('Cannot persist meal without id'); } return MealTableCompanion( - id: drift.Value(mealId), + id: includeId && mealId != null ? drift.Value(mealId) : const drift.Value.absent(), planId: drift.Value(planId), + order: drift.Value(order), time: time == null ? const drift.Value.absent() : drift.Value(time!), name: drift.Value(name), ); } Meal copyWith({ - int? id, - int? planId, + String? id, + String? planId, TimeOfDay? time, String? name, List? mealItems, diff --git a/lib/models/nutrition/meal.g.dart b/lib/models/nutrition/meal.g.dart deleted file mode 100644 index d4b3f1c4f..000000000 --- a/lib/models/nutrition/meal.g.dart +++ /dev/null @@ -1,23 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'meal.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -Meal _$MealFromJson(Map json) => - Meal( - id: (json['id'] as num?)?.toInt(), - time: stringToTimeNull(json['time'] as String?), - name: json['name'] as String?, - ) - ..planId = (json['plan'] as num).toInt() - ..order = (json['order'] as num?)?.toInt() ?? 1; - -Map _$MealToJson(Meal instance) => { - 'id': instance.id, - 'plan': instance.planId, - 'time': timeToString(instance.time), - 'name': instance.name, -}; diff --git a/lib/models/nutrition/meal_item.dart b/lib/models/nutrition/meal_item.dart index 56eb03f75..837bf773e 100644 --- a/lib/models/nutrition/meal_item.dart +++ b/lib/models/nutrition/meal_item.dart @@ -17,45 +17,36 @@ */ import 'package:drift/drift.dart' as drift; -import 'package:json_annotation/json_annotation.dart'; import 'package:wger/database/powersync/database.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/nutritional_values.dart'; -part 'meal_item.g.dart'; - -@JsonSerializable() class MealItem { - @JsonKey(required: true) - int? id; + /// Client-generated UUID. `null` only for instances built in-memory before + /// the first persist; Drift fills it in via the table's `clientDefault`. + String? id; - @JsonKey(required: false, name: 'meal') - late int mealId; + /// FK to the parent meal — the meal's UUID, not the server-side integer PK. + late String mealId; - @JsonKey(required: false, name: 'ingredient') late int ingredientId; - @JsonKey(includeFromJson: false, includeToJson: false) late Ingredient ingredient; - @JsonKey(required: false, name: 'weight_unit') int? weightUnitId; - @JsonKey(includeFromJson: false, includeToJson: false) IngredientWeightUnit? weightUnitObj; - @JsonKey(required: true, fromJson: stringToNum, toJson: numToString) late num amount; - /// Server-assigned ordering inside the meal. Not user-editable. - @JsonKey(includeToJson: false, defaultValue: 1) + /// Server-side ordering inside the meal. Replicated down for completeness; + /// the client computes new values as `MAX(order) + 1` on insert. int order = 1; MealItem({ this.id, - int? mealId, + String? mealId, required this.ingredientId, this.weightUnitId, required this.amount, @@ -78,7 +69,7 @@ class MealItem { /// after a JOIN; instances built here have only the FK ids set. MealItem.fromDrift({ this.id, - required int mealId, + required String mealId, required int ingredientId, this.weightUnitId, required int order, @@ -90,24 +81,21 @@ class MealItem { this.order = order; } - // Boilerplate - factory MealItem.fromJson(Map json) => _$MealItemFromJson(json); - - Map toJson() => _$MealItemToJson(this); - - /// Drift companion for updates against `nutrition_mealitem`. + /// Drift companion for inserts/updates against `nutrition_mealitem`. /// - /// `order` is intentionally absent — it's server-managed and read-only. - MealItemTableCompanion toCompanion() { + /// On insert, leave `id` absent so the table's `clientDefault` UUID kicks + /// in (or set [includeId] true if you've already generated it). + MealItemTableCompanion toCompanion({bool includeId = true}) { final itemId = id; - if (itemId == null) { - throw StateError('Cannot persist meal item without id (creation goes via REST)'); + if (includeId && itemId == null) { + throw StateError('Cannot persist meal item without id'); } return MealItemTableCompanion( - id: drift.Value(itemId), + id: includeId && itemId != null ? drift.Value(itemId) : const drift.Value.absent(), mealId: drift.Value(mealId), ingredientId: drift.Value(ingredientId), weightUnitId: weightUnitId == null ? const drift.Value.absent() : drift.Value(weightUnitId!), + order: drift.Value(order), amount: drift.Value(amount.toDouble()), ); } @@ -120,8 +108,8 @@ class MealItem { } MealItem copyWith({ - int? id, - int? mealId, + String? id, + String? mealId, int? ingredientId, int? weightUnitId, num? amount, diff --git a/lib/models/nutrition/meal_item.g.dart b/lib/models/nutrition/meal_item.g.dart deleted file mode 100644 index 2e5155b24..000000000 --- a/lib/models/nutrition/meal_item.g.dart +++ /dev/null @@ -1,26 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'meal_item.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -MealItem _$MealItemFromJson(Map json) { - $checkKeys(json, requiredKeys: const ['id', 'amount']); - return MealItem( - id: (json['id'] as num?)?.toInt(), - mealId: (json['meal'] as num?)?.toInt(), - ingredientId: (json['ingredient'] as num).toInt(), - weightUnitId: (json['weight_unit'] as num?)?.toInt(), - amount: stringToNum(json['amount'] as String?), - )..order = (json['order'] as num?)?.toInt() ?? 1; -} - -Map _$MealItemToJson(MealItem instance) => { - 'id': instance.id, - 'meal': instance.mealId, - 'ingredient': instance.ingredientId, - 'weight_unit': instance.weightUnitId, - 'amount': numToString(instance.amount), -}; diff --git a/lib/models/nutrition/nutritional_plan.dart b/lib/models/nutrition/nutritional_plan.dart index 01a938aba..ce9065baa 100644 --- a/lib/models/nutrition/nutritional_plan.dart +++ b/lib/models/nutrition/nutritional_plan.dart @@ -19,11 +19,9 @@ import 'package:collection/collection.dart'; import 'package:drift/drift.dart' as drift; import 'package:flutter/widgets.dart'; -import 'package:json_annotation/json_annotation.dart'; import 'package:logging/logging.dart'; import 'package:wger/database/powersync/database.dart'; import 'package:wger/helpers/consts.dart'; -import 'package:wger/helpers/json.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/log.dart'; import 'package:wger/models/nutrition/meal.dart'; @@ -31,57 +29,37 @@ import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/models/nutrition/nutritional_goals.dart'; import 'package:wger/models/nutrition/nutritional_values.dart'; -part 'nutritional_plan.g.dart'; - -@JsonSerializable(explicitToJson: true) class NutritionalPlan { final _logger = Logger('NutritionalPlan Model'); - @JsonKey(required: true) - int? id; + /// `null` only for instances built in-memory before the first persist; + /// Drift fills it in via the table's `clientDefault`. + String? id; - @JsonKey(required: true) late String description; - @JsonKey( - required: true, - name: 'creation_date', - fromJson: utcIso8601ToLocalDate, - toJson: dateToUtcIso8601, - ) late DateTime creationDate; - @JsonKey(required: true, name: 'start', toJson: dateToYYYYMMDD) late DateTime startDate; - @JsonKey(required: true, name: 'end', toJson: dateToYYYYMMDD) late DateTime? endDate; - @JsonKey(required: true, name: 'only_logging') late bool onlyLogging; - @JsonKey(required: true, name: 'goal_energy') late num? goalEnergy; - @JsonKey(required: true, name: 'goal_protein') late num? goalProtein; - @JsonKey(required: true, name: 'goal_carbohydrates') late num? goalCarbohydrates; - @JsonKey(required: true, name: 'goal_fat') late num? goalFat; - @JsonKey(required: true, name: 'goal_fiber') late num? goalFiber; - @JsonKey(name: 'has_goal_calories', defaultValue: false) late bool hasGoalCalories; - @JsonKey(includeFromJson: false, includeToJson: false, defaultValue: []) List meals = []; - @JsonKey(includeFromJson: false, includeToJson: false, defaultValue: []) List diaryEntries = []; NutritionalPlan({ @@ -126,18 +104,18 @@ class NutritionalPlan { goalFat = null; } - // Boilerplate - factory NutritionalPlan.fromJson(Map json) => _$NutritionalPlanFromJson(json); - - Map toJson() => _$NutritionalPlanToJson(this); - - NutritionalPlanTableCompanion toCompanion() { + /// Drift companion for inserts/updates against `nutrition_nutritionplan`. + /// + /// On insert, leave `id` absent so the table's `clientDefault` UUID kicks + /// in (or set [includeId] true if you've already generated it). For an + /// update, the row id must be present — we throw if it's missing. + NutritionalPlanTableCompanion toCompanion({bool includeId = true}) { final planId = id; - if (planId == null) { - throw StateError('Cannot persist nutritional plan without id (creation goes via REST)'); + if (includeId && planId == null) { + throw StateError('Cannot persist nutritional plan without id'); } return NutritionalPlanTableCompanion( - id: drift.Value(planId), + id: includeId && planId != null ? drift.Value(planId) : const drift.Value.absent(), description: drift.Value(description), creationDate: drift.Value(creationDate.toUtc()), // `start`/`end` are `DateField` server-side diff --git a/lib/models/nutrition/nutritional_plan.g.dart b/lib/models/nutrition/nutritional_plan.g.dart deleted file mode 100644 index 60c590f96..000000000 --- a/lib/models/nutrition/nutritional_plan.g.dart +++ /dev/null @@ -1,55 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'nutritional_plan.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -NutritionalPlan _$NutritionalPlanFromJson(Map json) { - $checkKeys( - json, - requiredKeys: const [ - 'id', - 'description', - 'creation_date', - 'start', - 'end', - 'only_logging', - 'goal_energy', - 'goal_protein', - 'goal_carbohydrates', - 'goal_fat', - 'goal_fiber', - ], - ); - return NutritionalPlan( - id: (json['id'] as num?)?.toInt(), - description: json['description'] as String, - creationDate: utcIso8601ToLocalDate(json['creation_date'] as String), - startDate: DateTime.parse(json['start'] as String), - endDate: json['end'] == null ? null : DateTime.parse(json['end'] as String), - onlyLogging: json['only_logging'] as bool? ?? false, - hasGoalCalories: json['has_goal_calories'] as bool? ?? false, - goalEnergy: json['goal_energy'] as num?, - goalProtein: json['goal_protein'] as num?, - goalCarbohydrates: json['goal_carbohydrates'] as num?, - goalFat: json['goal_fat'] as num?, - goalFiber: json['goal_fiber'] as num?, - ); -} - -Map _$NutritionalPlanToJson(NutritionalPlan instance) => { - 'id': instance.id, - 'description': instance.description, - 'creation_date': dateToUtcIso8601(instance.creationDate), - 'start': dateToYYYYMMDD(instance.startDate), - 'end': dateToYYYYMMDD(instance.endDate), - 'only_logging': instance.onlyLogging, - 'goal_energy': instance.goalEnergy, - 'goal_protein': instance.goalProtein, - 'goal_carbohydrates': instance.goalCarbohydrates, - 'goal_fat': instance.goalFat, - 'goal_fiber': instance.goalFiber, - 'has_goal_calories': instance.hasGoalCalories, -}; diff --git a/lib/providers/nutrition_notifier.dart b/lib/providers/nutrition_notifier.dart index 1c8f756c4..3201bafdf 100644 --- a/lib/providers/nutrition_notifier.dart +++ b/lib/providers/nutrition_notifier.dart @@ -17,7 +17,7 @@ */ import 'package:collection/collection.dart'; -import 'package:logging/logging.dart'; +import 'package:powersync/powersync.dart' as ps; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:stream_transform/stream_transform.dart'; import 'package:wger/core/exceptions/no_such_entry_exception.dart'; @@ -25,7 +25,6 @@ import 'package:wger/models/nutrition/log.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/ingredient_repository.dart'; import 'package:wger/providers/nutrition_repository.dart'; part 'nutrition_notifier.g.dart'; @@ -60,14 +59,14 @@ class NutritionState { } /// Throws [NoSuchEntryException] if no plan with the given id exists. - NutritionalPlan findById(int id) { + NutritionalPlan findById(String id) { return plans.firstWhere( (plan) => plan.id == id, orElse: () => throw const NoSuchEntryException(), ); } - Meal? findMealById(int id) { + Meal? findMealById(String id) { for (final plan in plans) { final meal = plan.meals.firstWhereOrNull((m) => m.id == id); if (meal != null) { @@ -80,224 +79,131 @@ class NutritionState { @Riverpod(keepAlive: true) class NutritionNotifier extends _$NutritionNotifier { - final _logger = Logger('NutritionNotifier'); - @override Stream build() { - _logger.fine('Building NutritionNotifier'); ref.keepAlive(); - // Top-level plans and diary entries both come from synced tables. The - // hierarchy in between meals and meal items still lives behind REST and - // is layered on top by callers via [fetchAndSetPlanFull]; we re-attach - // it from the previous state on every emission so a remote edit doesn't - // wipe locally-hydrated meals. - // - // [combineLatest] holds back the first emission until both streams have - // produced a value, so the resulting plans always carry coherent diary - // data + // We chain three streams via [combineLatest]: the first emission is held + // back until every source has produced a value, so the resulting plans + // always carry coherent meal/diary data. final repo = ref.read(nutritionRepositoryProvider); - return repo.watchAllDrift().combineLatest(repo.watchAllLogsHydrated(), (freshPlans, allLogs) { - final existing = state.value?.plans ?? const []; - for (final fresh in freshPlans) { - final old = existing.firstWhereOrNull((p) => p.id == fresh.id); - if (old != null) { - fresh.meals = old.meals; - } - fresh.diaryEntries = allLogs.where((l) => l.planId == fresh.id).toList(); - for (final meal in fresh.meals) { - meal.diaryEntries = fresh.diaryEntries.where((l) => l.mealId == meal.id).toList(); - } + return repo + .watchAllDrift() + .combineLatest( + repo.watchAllMealsHydrated(), + (plans, meals) => (plans, meals), + ) + .combineLatest(repo.watchAllLogsHydrated(), (acc, logs) { + final plans = acc.$1; + final meals = acc.$2; + return _assemble(plans, meals, logs); + }); + } + + NutritionState _assemble( + List plans, + List meals, + List logs, + ) { + final mealsByPlan = >{}; + for (final meal in meals) { + mealsByPlan.putIfAbsent(meal.planId, () => []).add(meal); + } + final logsByPlan = >{}; + final logsByMeal = >{}; + for (final log in logs) { + logsByPlan.putIfAbsent(log.planId, () => []).add(log); + if (log.mealId != null) { + logsByMeal.putIfAbsent(log.mealId!, () => []).add(log); } - return NutritionState(plans: freshPlans); - }); + } + for (final plan in plans) { + plan.meals = mealsByPlan[plan.id] ?? const []; + plan.diaryEntries = logsByPlan[plan.id] ?? const []; + for (final meal in plan.meals) { + meal.diaryEntries = logsByMeal[meal.id] ?? const []; + } + } + return NutritionState(plans: plans); } // --- Convenience accessors (delegate to state) --- - List get _plans => state.value?.plans ?? const []; - /// Throws [NoSuchEntryException] if no plan with the given id exists. - NutritionalPlan findById(int id) => (state.value ?? const NutritionState()).findById(id); + NutritionalPlan findById(String id) => (state.value ?? const NutritionState()).findById(id); - Meal? findMealById(int id) => (state.value ?? const NutritionState()).findMealById(id); + Meal? findMealById(String id) => (state.value ?? const NutritionState()).findMealById(id); NutritionalPlan? get currentPlan => (state.value ?? const NutritionState()).currentPlan; - /// Notifies listeners after in-place mutation on the plans list (e.g. when - /// meals or logs on a plan are mutated via object references). Equivalent to - /// the old `notifyListeners()`. - void _notifyAfterInPlaceMutation() { - state = AsyncData(NutritionState(plans: List.of(_plans))); - } - - /// Replaces the in-memory plan list. Used to apply optimistic updates that - /// are eventually overwritten by the next stream emission. - void _setPlans(List plans) { - state = AsyncData(NutritionState(plans: List.of(plans))); - } - // --- Plans --- - Future fetchAndSetPlanSparse(int planId) async { + /// Persists a new nutritional plan via Drift. The UUID is generated here so + /// callers can reference it immediately (e.g. to add meals in the same + /// flow); PowerSync replicates the row to the backend asynchronously. + Future addPlan(NutritionalPlan plan) async { final repo = ref.read(nutritionRepositoryProvider); - final data = await repo.fetchPlanSparse(planId); - final plan = NutritionalPlan.fromJson(data); - final plans = List.of(_plans)..add(plan); - // Match Django's `Meta.ordering = ['-start']`. - plans.sort((a, b) => b.startDate.compareTo(a.startDate)); - _setPlans(plans); + plan.id ??= ps.uuid.v4(); + await repo.addPlanLocalDrift(plan); return plan; } - /// Fetches a plan with meals, meal items, and log entries. - Future fetchAndSetPlanFull(int planId) async { - _logger.fine('Fetching full nutritional plan $planId'); - - final repo = ref.read(nutritionRepositoryProvider); - - NutritionalPlan plan; - try { - plan = findById(planId); - } on NoSuchEntryException { - plan = await fetchAndSetPlanSparse(planId); - } - - final fullPlanData = await repo.fetchPlanFull(planId); - final ingredientRepo = ref.read(ingredientRepositoryProvider); - - // Meals - final List meals = []; - for (final mealData in (fullPlanData['meals'] as List?) ?? const []) { - final meal = Meal.fromJson(mealData); - final List mealItemsData = (mealData['meal_items'] as List?) ?? const []; - - // Resolve all ingredients for this meal in parallel - final resolved = await Future.wait( - mealItemsData.map((data) async { - final mealItem = MealItem.fromJson(data); - final ingredient = await ingredientRepo - .watchById(mealItem.ingredientId) - .firstWhere((i) => i != null, orElse: () => null) - .timeout(const Duration(seconds: 5), onTimeout: () => null); - if (ingredient == null) { - _logger.warning( - 'Ingredient ${mealItem.ingredientId} not in local DB after 5s ' - 'wait, skipping meal item ${mealItem.id}', - ); - return null; - } - mealItem.ingredient = ingredient; - return mealItem; - }), - ); - meal.mealItems = resolved.whereType().toList(); - meals.add(meal); - } - plan.meals = meals; - - // Diary entries are streamed in by build() from PowerSync. Distribute - // the logs we already have onto the freshly-loaded meals so the UI sees - // them immediately, before the next stream tick. - for (final meal in meals) { - meal.diaryEntries = plan.diaryEntries.where((e) => e.mealId == meal.id).toList(); - } - - _notifyAfterInPlaceMutation(); - return plan; - } - - /// Creation still goes through REST. PowerSync will eventually replicate the - /// new row via the stream, but to avoid a perceptible UI lag we also inject - /// the freshly-created plan into state right away. When the stream later - /// re-emits the same row, build()'s sub-data preservation logic keeps things - /// stable. - Future addPlan(NutritionalPlan planData) async { - final repo = ref.read(nutritionRepositoryProvider); - final data = await repo.createPlan(planData.toJson()); - final plan = NutritionalPlan.fromJson(data); - final plans = List.of(_plans)..add(plan); - // Match Django's `Meta.ordering = ['-start']`. - plans.sort((a, b) => b.startDate.compareTo(a.startDate)); - _setPlans(plans); - return plan; - } - - /// Goes through PowerSync (Drift update → CRUD queue → backend). - /// Local state picks up the change on the next stream emission. Future editPlan(NutritionalPlan plan) async { final repo = ref.read(nutritionRepositoryProvider); await repo.editLocalDrift(plan); } - /// Goes through PowerSync (Drift delete → CRUD queue → backend), where /// Django's FK CASCADE removes any dependent meals/items/diary entries. /// Local state picks up the removal on the next stream emission. - Future deletePlan(int id) async { + Future deletePlan(String id) async { final repo = ref.read(nutritionRepositoryProvider); await repo.deleteLocalDrift(id); } // --- Meals --- - /// Creation still goes through REST. The freshly-saved meal is injected into - /// in-memory state so the UI sees it immediately, before PowerSync has - /// replicated the row down into the local Drift database. - Future addMeal(Meal meal, int planId) async { + /// Persists a new meal via Drift. The UUID is generated here so callers can + /// reference it immediately (e.g. to add meal items in the same flow); the + /// repository computes the next `order` value from existing rows. + Future addMeal(Meal meal, String planId) async { final repo = ref.read(nutritionRepositoryProvider); - final plan = findById(planId); meal.planId = planId; - final data = await repo.createMeal(meal.toJson()); - final saved = Meal.fromJson(data); - plan.meals.add(saved); - _notifyAfterInPlaceMutation(); - return saved; + meal.id ??= ps.uuid.v4(); + await repo.addMealLocalDrift(meal); + return meal; } - /// Goes through PowerSync (Drift update → CRUD queue → backend). Future editMeal(Meal meal) async { final repo = ref.read(nutritionRepositoryProvider); await repo.editMealLocalDrift(meal); - _notifyAfterInPlaceMutation(); } - /// Goes through PowerSync (Drift delete → CRUD queue → backend), where /// Django's FK CASCADE removes any dependent meal items. Future deleteMeal(Meal meal) async { final repo = ref.read(nutritionRepositoryProvider); - final plan = findById(meal.planId); - plan.meals.removeWhere((e) => e.id == meal.id); - _notifyAfterInPlaceMutation(); await repo.deleteMealLocalDrift(meal.id!); } // --- Meal items --- - /// Creation still goes through REST. The saved item is injected into the - /// meal's in-memory list so the UI sees it immediately. + /// Persists a new meal item Future addMealItem(MealItem mealItem, Meal meal) async { final repo = ref.read(nutritionRepositoryProvider); - final data = await repo.createMealItem(mealItem.toJson()); - final saved = MealItem.fromJson(data); - saved.ingredient = mealItem.ingredient; - meal.mealItems.add(saved); - _notifyAfterInPlaceMutation(); - return saved; + mealItem.mealId = meal.id!; + mealItem.id ??= ps.uuid.v4(); + await repo.addMealItemLocalDrift(mealItem); + return mealItem; } /// Goes through PowerSync (Drift update → CRUD queue → backend). Future editMealItem(MealItem mealItem) async { final repo = ref.read(nutritionRepositoryProvider); await repo.editMealItemLocalDrift(mealItem); - _notifyAfterInPlaceMutation(); } /// Goes through PowerSync (Drift delete → CRUD queue → backend). Future deleteMealItem(MealItem mealItem) async { final repo = ref.read(nutritionRepositoryProvider); - final meal = findMealById(mealItem.mealId)!; - meal.mealItems.removeWhere((e) => e.id == mealItem.id); - _notifyAfterInPlaceMutation(); await repo.deleteMealItemLocalDrift(mealItem.id!); } @@ -314,7 +220,7 @@ class NutritionNotifier extends _$NutritionNotifier { Future logIngredientToDiary( MealItem mealItem, - int planId, [ + String planId, [ DateTime? dateTime, ]) async { final repo = ref.read(nutritionRepositoryProvider); diff --git a/lib/providers/nutrition_notifier.g.dart b/lib/providers/nutrition_notifier.g.dart index 9858f7f76..394f9a187 100644 --- a/lib/providers/nutrition_notifier.g.dart +++ b/lib/providers/nutrition_notifier.g.dart @@ -33,7 +33,7 @@ final class NutritionNotifierProvider NutritionNotifier create() => NutritionNotifier(); } -String _$nutritionNotifierHash() => r'c38f221bd9b074fb5b59f2a6d3421f460a8c37dc'; +String _$nutritionNotifierHash() => r'32a0a26492f7a6794a53e36f2d8a30b3d9465494'; abstract class _$NutritionNotifier extends $StreamNotifier { Stream build(); diff --git a/lib/providers/nutrition_repository.dart b/lib/providers/nutrition_repository.dart index 600154567..4d14a0f86 100644 --- a/lib/providers/nutrition_repository.dart +++ b/lib/providers/nutrition_repository.dart @@ -37,50 +37,18 @@ final nutritionRepositoryProvider = Provider((ref) { }); /// Data access for nutrition-related entities. -/// -/// Creation paths still use HTTP (plans, meals, meal items — the server picks -/// the integer PK and the `order`). Edits and deletes for [NutritionalPlan], -/// [Meal], [MealItem] and the diary [LogItem] table all flow through the -/// local PowerSync-backed Drift database; see [editLocalDrift] / -/// [deleteLocalDrift] (plans), [editMealLocalDrift] / [deleteMealLocalDrift], -/// [editMealItemLocalDrift] / [deleteMealItemLocalDrift], and the log -/// methods. -/// -/// Ingredient searches (local + REST) live on [IngredientRepository]. class NutritionRepository { final _logger = Logger('NutritionRepository'); final WgerBaseProvider _base; final DriftPowersyncDatabase _db; - static const plansPath = 'nutritionplan'; - static const plansInfoPath = 'nutritionplaninfo'; - static const mealPath = 'meal'; - static const mealItemPath = 'mealitem'; - NutritionRepository(this._base, this._db); // --- Plans --- - Future> fetchPlanSparse(int planId) async { - _logger.fine('Fetching plan $planId (sparse)'); - final data = await _base.fetch(_base.makeUrl(plansPath, id: planId)); - return data as Map; - } - - Future> fetchPlanFull(int planId) async { - _logger.fine('Fetching plan $planId (full)'); - final data = await _base.fetch(_base.makeUrl(plansInfoPath, id: planId)); - return data as Map; - } - - Future> createPlan(Map data) async { - return _base.post(data, _base.makeUrl(plansPath)); - } - /// Streams all nutritional plans from the local PowerSync-backed Drift table. /// - /// Sort matches Django's `NutritionalPlan.Meta.ordering = ['-start']` so - /// that REST responses and PowerSync emissions agree on the row order. + /// Sort matches Django's `NutritionalPlan.Meta.ordering = ['-start']`. Stream> watchAllDrift() { _logger.finer('Watching all local nutritional plans'); return (_db.select( @@ -88,6 +56,16 @@ class NutritionRepository { )..orderBy([(t) => OrderingTerm.desc(t.startDate)])).watch(); } + /// Inserts a nutritional plan into the local Drift table. The caller must + /// have set [NutritionalPlan.id] (UUID) beforehand. + Future addPlanLocalDrift(NutritionalPlan plan) async { + if (plan.id == null) { + throw StateError('Cannot persist plan without id (caller must generate the UUID)'); + } + _logger.finer('Inserting local nutritional plan ${plan.id}'); + await _db.into(_db.nutritionalPlanTable).insert(plan.toCompanion()); + } + /// Updates a nutritional plan via the local Drift table. PowerSync's CRUD /// queue picks the change up and pushes it to the backend. Future editLocalDrift(NutritionalPlan plan) async { @@ -104,18 +82,118 @@ class NutritionRepository { /// Deletes a nutritional plan via the local Drift table. Deletion of children /// entities (meals, meal items, diary entries) is handled by the backend via /// FK CASCADE, so we don't have to worry about that here. - Future deleteLocalDrift(int id) async { + Future deleteLocalDrift(String id) async { _logger.finer('Deleting local nutritional plan $id'); await (_db.delete(_db.nutritionalPlanTable)..where((t) => t.id.equals(id))).go(); } // --- Meals --- - /// Creation still goes through REST: the server assigns the integer PK and - /// the `order` field, then PowerSync replicates the row down so subsequent - /// edits and deletes can target the local Drift row. - Future> createMeal(Map data) async { - return _base.post(data, _base.makeUrl(mealPath)); + /// Streams all meals (across every plan) with their meal items hydrated + /// from the same Drift database in one query. Re-emits whenever any of the + /// joined tables changes. + /// + /// Each [MealItem] has its [Ingredient] and optional [IngredientWeightUnit] + /// resolved via the same query + Stream> watchAllMealsHydrated() { + _logger.finer('Watching all local meals'); + final query = + _db.select(_db.mealTable).join([ + leftOuterJoin(_db.mealItemTable, _db.mealItemTable.mealId.equalsExp(_db.mealTable.id)), + leftOuterJoin( + _db.ingredientTable, + _db.ingredientTable.id.equalsExp(_db.mealItemTable.ingredientId), + ), + leftOuterJoin( + _db.ingredientImageTable, + _db.ingredientImageTable.ingredientId.equalsExp(_db.ingredientTable.id), + ), + leftOuterJoin( + _db.ingredientWeightUnitTable, + _db.ingredientWeightUnitTable.ingredientId.equalsExp(_db.ingredientTable.id), + ), + ])..orderBy([ + OrderingTerm.asc(_db.mealTable.planId), + OrderingTerm.asc(_db.mealTable.order), + OrderingTerm.asc(_db.mealTable.time), + ]); + + return query.watch().map(_hydrateMeals); + } + + /// Collapses cross-joined rows into hydrated [Meal]s with their child items. + List _hydrateMeals(Iterable rows) { + final meals = {}; + final itemsByMeal = >{}; + final ingredients = {}; + final weightUnitsByIngredient = >{}; + + for (final row in rows) { + final meal = row.readTable(_db.mealTable); + meals.putIfAbsent(meal.id!, () => meal); + + final mealItem = row.readTableOrNull(_db.mealItemTable); + if (mealItem == null) continue; + + final ingredient = row.readTableOrNull(_db.ingredientTable); + final image = row.readTableOrNull(_db.ingredientImageTable); + final wu = row.readTableOrNull(_db.ingredientWeightUnitTable); + + if (ingredient != null) { + final ingEntry = ingredients.putIfAbsent(ingredient.id, () => ingredient); + if (image != null) { + ingEntry.image = image; + } + if (wu != null) { + final list = weightUnitsByIngredient.putIfAbsent(ingredient.id, () => []); + if (!list.any((w) => w.id == wu.id)) { + list.add(wu); + } + } + } + + itemsByMeal.putIfAbsent(meal.id!, () => {}).putIfAbsent(mealItem.id!, () => mealItem); + } + + for (final ing in ingredients.values) { + ing.weightUnits = weightUnitsByIngredient[ing.id] ?? const []; + } + for (final entry in itemsByMeal.entries) { + final meal = meals[entry.key]!; + meal.mealItems = entry.value.values.toList()..sort((a, b) => a.order.compareTo(b.order)); + for (final item in meal.mealItems) { + final ing = ingredients[item.ingredientId]; + if (ing != null) { + item.ingredient = ing; + if (item.weightUnitId != null) { + item.weightUnitObj = ing.weightUnits.firstWhereOrNull( + (w) => w.id == item.weightUnitId, + ); + } + } + } + } + + return meals.values.toList(); + } + + /// Inserts a meal into the local Drift table. The caller must have set + /// [Meal.id] (UUID) and [Meal.planId] beforehand. The `order` is computed + /// here as `MAX(order) + 1` over the plan's existing meals so that newly + /// added meals land at the bottom of the ordering + Future addMealLocalDrift(Meal meal) async { + if (meal.id == null) { + throw StateError('Cannot persist meal without id (caller must generate the UUID)'); + } + final maxOrder = + await (_db.selectOnly(_db.mealTable) + ..addColumns([_db.mealTable.order.max()]) + ..where(_db.mealTable.planId.equals(meal.planId))) + .map((row) => row.read(_db.mealTable.order.max())) + .getSingleOrNull(); + meal.order = (maxOrder ?? 0) + 1; + _logger.finer('Inserting local meal ${meal.id} (order=${meal.order})'); + await _db.into(_db.mealTable).insert(meal.toCompanion()); } /// Updates a meal via the local Drift table. PowerSync's CRUD queue picks @@ -131,17 +209,29 @@ class NutritionRepository { /// Deletes a meal via the local Drift table. The backend cascades through /// to the dependent meal items. - Future deleteMealLocalDrift(int id) async { + Future deleteMealLocalDrift(String id) async { _logger.finer('Deleting local meal $id'); await (_db.delete(_db.mealTable)..where((t) => t.id.equals(id))).go(); } // --- Meal items --- - /// Creation still goes through REST (server-assigned PK and `order`); - /// PowerSync replicates the row down for subsequent local edits/deletes. - Future> createMealItem(Map data) async { - return _base.post(data, _base.makeUrl(mealItemPath)); + /// Inserts a meal item into the local Drift table. The caller must have set + /// [MealItem.id] (UUID) and [MealItem.mealId] (parent meal's UUID); `order` + /// is computed here as `MAX(order) + 1` over the meal's existing items. + Future addMealItemLocalDrift(MealItem item) async { + if (item.id == null) { + throw StateError('Cannot persist meal item without id (caller must generate the UUID)'); + } + final maxOrder = + await (_db.selectOnly(_db.mealItemTable) + ..addColumns([_db.mealItemTable.order.max()]) + ..where(_db.mealItemTable.mealId.equals(item.mealId))) + .map((row) => row.read(_db.mealItemTable.order.max())) + .getSingleOrNull(); + item.order = (maxOrder ?? 0) + 1; + _logger.finer('Inserting local meal item ${item.id} (order=${item.order})'); + await _db.into(_db.mealItemTable).insert(item.toCompanion()); } /// Updates a meal item via the local Drift table. PowerSync picks the @@ -156,7 +246,7 @@ class NutritionRepository { } /// Deletes a meal item via the local Drift table. - Future deleteMealItemLocalDrift(int id) async { + Future deleteMealItemLocalDrift(String id) async { _logger.finer('Deleting local meal item $id'); await (_db.delete(_db.mealItemTable)..where((t) => t.id.equals(id))).go(); } diff --git a/lib/screens/nutritional_plan_screen.dart b/lib/screens/nutritional_plan_screen.dart index 1016e0fc1..b1b2bd6ed 100644 --- a/lib/screens/nutritional_plan_screen.dart +++ b/lib/screens/nutritional_plan_screen.dart @@ -25,7 +25,6 @@ import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/log_meals_screen.dart'; -import 'package:wger/widgets/core/error.dart'; import 'package:wger/widgets/core/progress_indicator.dart'; import 'package:wger/widgets/nutrition/forms.dart'; import 'package:wger/widgets/nutrition/nutritional_plan_detail.dart'; @@ -45,22 +44,28 @@ class NutritionalPlanScreen extends ConsumerStatefulWidget { } class _NutritionalPlanScreenState extends ConsumerState { - Future? _planFuture; - late NutritionalPlan _nutritionalPlan; + late NutritionalPlan _argumentPlan; @override void didChangeDependencies() { super.didChangeDependencies(); - if (_planFuture == null) { - _nutritionalPlan = ModalRoute.of(context)!.settings.arguments as NutritionalPlan; - _planFuture = ref.read(nutritionProvider.notifier).fetchAndSetPlanFull(_nutritionalPlan.id!); - } + _argumentPlan = ModalRoute.of(context)!.settings.arguments as NutritionalPlan; } @override Widget build(BuildContext context) { const appBarForeground = Colors.white; final isOnline = ref.watch(networkStatusProvider); + // Resolve the freshest plan from state so meal/diary edits reflect + // immediately. Falls back to the route argument if state hasn't streamed + // yet (e.g. cold open, deep link). + final state = ref.watch(nutritionProvider).value; + final NutritionalPlan _nutritionalPlan = + state?.plans.firstWhere( + (p) => p.id == _argumentPlan.id, + orElse: () => _argumentPlan, + ) ?? + _argumentPlan; return Scaffold( //appBar: getAppBar(nutritionalPlan), floatingActionButton: Row( @@ -185,36 +190,10 @@ class _NutritionalPlanScreenState extends ConsumerState { ), ), ), - FutureBuilder( - future: _planFuture, - builder: (context, AsyncSnapshot snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) { - return SliverList( - delegate: SliverChildListDelegate( - [const BoxedProgressIndicator()], - ), - ); - } - if (snapshot.hasError) { - return SliverList( - delegate: SliverChildListDelegate( - [ - StreamErrorIndicator( - snapshot.error!, - stacktrace: snapshot.stackTrace, - ), - ], - ), - ); - } - return Consumer( - builder: (context, ref, child) { - ref.watch(nutritionProvider); - return NutritionalPlanDetailWidget(_nutritionalPlan); - }, - ); - }, - ), + if (state == null) + const SliverToBoxAdapter(child: BoxedProgressIndicator()) + else + NutritionalPlanDetailWidget(_nutritionalPlan), ], ), ); diff --git a/lib/widgets/nutrition/forms.dart b/lib/widgets/nutrition/forms.dart index 0a709c08f..e7a7d7f01 100644 --- a/lib/widgets/nutrition/forms.dart +++ b/lib/widgets/nutrition/forms.dart @@ -28,7 +28,6 @@ import 'package:wger/models/nutrition/log.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import 'package:wger/widgets/nutrition/helpers.dart'; @@ -37,7 +36,7 @@ import 'package:wger/widgets/nutrition/widgets.dart'; class MealForm extends ConsumerWidget { late final Meal _meal; - final int _planId; + final String _planId; final _form = GlobalKey(); final _timeController = TextEditingController(); @@ -51,11 +50,7 @@ class MealForm extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - // Creation still goes through REST (server-assigned PK + order); editing - // flows through PowerSync and is therefore offline-capable. final isCreating = _meal.id == null; - final isOnline = ref.watch(networkStatusProvider); - final canSubmit = !isCreating || isOnline; return Container( margin: const EdgeInsets.all(20), child: Form( @@ -95,19 +90,17 @@ class MealForm extends ConsumerWidget { ElevatedButton( key: const Key(SUBMIT_BUTTON_KEY_NAME), child: Text(AppLocalizations.of(context).save), - onPressed: canSubmit - ? () { - if (!_form.currentState!.validate()) { - return; - } - _form.currentState!.save(); + onPressed: () { + if (!_form.currentState!.validate()) { + return; + } + _form.currentState!.save(); - final notifier = ref.read(nutritionProvider.notifier); - isCreating ? notifier.addMeal(_meal, _planId) : notifier.editMeal(_meal); + final notifier = ref.read(nutritionProvider.notifier); + isCreating ? notifier.addMeal(_meal, _planId) : notifier.editMeal(_meal); - Navigator.of(context).pop(); - } - : null, + Navigator.of(context).pop(); + }, ), ], ), @@ -123,8 +116,9 @@ Widget getMealItemForm( bool? test, ]) { return IngredientForm( - // TODO we use planId 0 here cause we don't have one and we don't need it I think? - recent: recent.map((e) => LogItem.fromMealItem(e, 0, e.mealId)).toList(), + // The recent list is ephemeral display data — planId isn't used for + // persistence, so an empty sentinel is fine. + recent: recent.map((e) => LogItem.fromMealItem(e, '', e.mealId)).toList(), onSave: (BuildContext context, WidgetRef ref, MealItem mealItem, DateTime? dt) { mealItem.mealId = meal.id!; ref.read(nutritionProvider.notifier).addMealItem(mealItem, meal); @@ -549,11 +543,7 @@ class _PlanFormState extends ConsumerState { @override Widget build(BuildContext context) { final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode); - // Creation still goes through REST (server-assigned PK + creation_date); - // editing flows through PowerSync and is therefore offline-capable. final isCreating = widget._plan.id == null; - final isOnline = ref.watch(networkStatusProvider); - final canSubmit = !isCreating || isOnline; return Form( key: _form, @@ -765,33 +755,31 @@ class _PlanFormState extends ConsumerState { ElevatedButton( key: const Key(SUBMIT_BUTTON_KEY_NAME), child: Text(AppLocalizations.of(context).save), - onPressed: canSubmit - ? () async { - // Validate and save the current values to the plan - final isValid = _form.currentState!.validate(); - if (!isValid) { - return; - } - _form.currentState!.save(); + onPressed: () async { + // Validate and save the current values to the plan + final isValid = _form.currentState!.validate(); + if (!isValid) { + return; + } + _form.currentState!.save(); - // Save to DB - final notifier = ref.read(nutritionProvider.notifier); - if (!isCreating) { - await notifier.editPlan(widget._plan); - if (context.mounted) { - Navigator.of(context).pop(); - } - } else { - widget._plan = await notifier.addPlan(widget._plan); - if (context.mounted) { - Navigator.of(context).pushReplacementNamed( - NutritionalPlanScreen.routeName, - arguments: widget._plan, - ); - } - } - } - : null, + // Save to DB + final notifier = ref.read(nutritionProvider.notifier); + if (!isCreating) { + await notifier.editPlan(widget._plan); + if (context.mounted) { + Navigator.of(context).pop(); + } + } else { + widget._plan = await notifier.addPlan(widget._plan); + if (context.mounted) { + Navigator.of(context).pushReplacementNamed( + NutritionalPlanScreen.routeName, + arguments: widget._plan, + ); + } + } + }, ), ], ), diff --git a/test/measurements/measurement_entries_screen_test.mocks.dart b/test/measurements/measurement_entries_screen_test.mocks.dart index afbb079a6..536225912 100644 --- a/test/measurements/measurement_entries_screen_test.mocks.dart +++ b/test/measurements/measurement_entries_screen_test.mocks.dart @@ -123,36 +123,6 @@ class MockNutritionRepository extends _i1.Mock implements _i6.NutritionRepositor _i1.throwOnMissingStub(this); } - @override - _i3.Future> fetchPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanSparse, [planId]), - returnValue: _i3.Future>.value( - {}, - ), - ) - as _i3.Future>); - - @override - _i3.Future> fetchPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanFull, [planId]), - returnValue: _i3.Future>.value( - {}, - ), - ) - as _i3.Future>); - - @override - _i3.Future> createPlan(Map? data) => - (super.noSuchMethod( - Invocation.method(#createPlan, [data]), - returnValue: _i3.Future>.value( - {}, - ), - ) - as _i3.Future>); - @override _i3.Stream> watchAllDrift() => (super.noSuchMethod( @@ -161,6 +131,15 @@ class MockNutritionRepository extends _i1.Mock implements _i6.NutritionRepositor ) as _i3.Stream>); + @override + _i3.Future addPlanLocalDrift(_i7.NutritionalPlan? plan) => + (super.noSuchMethod( + Invocation.method(#addPlanLocalDrift, [plan]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future editLocalDrift(_i7.NutritionalPlan? plan) => (super.noSuchMethod( @@ -171,7 +150,7 @@ class MockNutritionRepository extends _i1.Mock implements _i6.NutritionRepositor as _i3.Future); @override - _i3.Future deleteLocalDrift(int? id) => + _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDrift, [id]), returnValue: _i3.Future.value(), @@ -180,14 +159,21 @@ class MockNutritionRepository extends _i1.Mock implements _i6.NutritionRepositor as _i3.Future); @override - _i3.Future> createMeal(Map? data) => + _i3.Stream> watchAllMealsHydrated() => (super.noSuchMethod( - Invocation.method(#createMeal, [data]), - returnValue: _i3.Future>.value( - {}, - ), + Invocation.method(#watchAllMealsHydrated, []), + returnValue: _i3.Stream>.empty(), ) - as _i3.Future>); + as _i3.Stream>); + + @override + _i3.Future addMealLocalDrift(_i8.Meal? meal) => + (super.noSuchMethod( + Invocation.method(#addMealLocalDrift, [meal]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future editMealLocalDrift(_i8.Meal? meal) => @@ -199,7 +185,7 @@ class MockNutritionRepository extends _i1.Mock implements _i6.NutritionRepositor as _i3.Future); @override - _i3.Future deleteMealLocalDrift(int? id) => + _i3.Future deleteMealLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealLocalDrift, [id]), returnValue: _i3.Future.value(), @@ -208,14 +194,13 @@ class MockNutritionRepository extends _i1.Mock implements _i6.NutritionRepositor as _i3.Future); @override - _i3.Future> createMealItem(Map? data) => + _i3.Future addMealItemLocalDrift(_i9.MealItem? item) => (super.noSuchMethod( - Invocation.method(#createMealItem, [data]), - returnValue: _i3.Future>.value( - {}, - ), + Invocation.method(#addMealItemLocalDrift, [item]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i3.Future>); + as _i3.Future); @override _i3.Future editMealItemLocalDrift(_i9.MealItem? item) => @@ -227,7 +212,7 @@ class MockNutritionRepository extends _i1.Mock implements _i6.NutritionRepositor as _i3.Future); @override - _i3.Future deleteMealItemLocalDrift(int? id) => + _i3.Future deleteMealItemLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealItemLocalDrift, [id]), returnValue: _i3.Future.value(), diff --git a/test/nutrition/nutrition_provider_test.dart b/test/nutrition/nutrition_provider_test.dart index 87b459580..9888d3827 100644 --- a/test/nutrition/nutrition_provider_test.dart +++ b/test/nutrition/nutrition_provider_test.dart @@ -16,13 +16,10 @@ * along with this program. If not, see . */ -import 'dart:convert'; - import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:wger/models/nutrition/ingredient.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; @@ -31,7 +28,6 @@ import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/providers/nutrition_repository.dart'; import '../fake_connectivity.dart'; -import '../fixtures/fixture_reader.dart'; import 'nutrition_provider_test.mocks.dart'; @GenerateMocks([NutritionRepository, IngredientRepository]) @@ -44,10 +40,6 @@ void main() { late MockNutritionRepository mockRepo; late MockIngredientRepository mockIngredientRepo; - late Map nutritionalPlanInfoResponse; - late Map nutritionalPlanDetailResponse; - late Map ingredient10065Response; - ProviderContainer makeContainer() { return ProviderContainer.test( overrides: [ @@ -83,56 +75,29 @@ void main() { when(mockRepo.watchAllLogsHydrated()).thenAnswer((_) => Stream.value(const [])); // Edit + delete now go through Drift instead of REST. + when(mockRepo.addPlanLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.editLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.deleteLocalDrift(any)).thenAnswer((_) async => Future.value()); + when(mockRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(const [])); + when(mockRepo.addMealLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.editMealLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.deleteMealLocalDrift(any)).thenAnswer((_) async => Future.value()); + when(mockRepo.addMealItemLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.editMealItemLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.deleteMealItemLocalDrift(any)).thenAnswer((_) async => Future.value()); - nutritionalPlanInfoResponse = jsonDecode( - fixture('nutrition/nutritional_plan_info_detail_response.json'), - ); - nutritionalPlanDetailResponse = jsonDecode( - fixture('nutrition/nutritional_plan_detail_response.json'), - ); - ingredient10065Response = jsonDecode( - fixture('nutrition/ingredientinfo_10065.json'), - ); - when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); }); - group('fetchAndSetPlanFull', () { - test('should correctly load a full nutritional plan', () async { - // arrange - when(mockRepo.fetchPlanSparse(1)).thenAnswer( - (_) async => nutritionalPlanDetailResponse, - ); - when(mockRepo.fetchPlanFull(1)).thenAnswer( - (_) async => nutritionalPlanInfoResponse, - ); - when(mockRepo.watchAllLogsHydrated()).thenAnswer((_) => Stream.value(const [])); - // Ingredient lookups now go through PowerSync — stub the local repo. - final ingredient = Ingredient.fromJson(ingredient10065Response); - when(mockIngredientRepo.getById(any)).thenAnswer((_) async => ingredient); - when(mockIngredientRepo.watchById(any)).thenAnswer((_) => Stream.value(ingredient)); - - final container = makeContainer(); - - // act - await container.read(nutritionProvider.notifier).fetchAndSetPlanFull(1); - - // assert - final plans = container.read(nutritionProvider).value?.plans ?? const []; - expect(plans.isEmpty, false); - }); - }); + const planUuid1 = 'cc000000-0000-4000-8000-000000000001'; + const planUuid2 = 'cc000000-0000-4000-8000-000000000002'; + const planUuidA = 'cc000000-0000-4000-8000-00000000000a'; + const planUuidB = 'cc000000-0000-4000-8000-00000000000b'; group('currentPlan', () { test('gibt den aktiven Plan zurück, wenn nur einer aktiv ist', () async { final plan = NutritionalPlan( - id: 1, + id: planUuid1, description: 'Aktiver Plan', startDate: now.subtract(const Duration(days: 1)), endDate: now.add(const Duration(days: 1)), @@ -147,14 +112,14 @@ void main() { test('gibt den neuesten aktiven Plan zurück, wenn mehrere aktiv sind', () async { final olderPlan = NutritionalPlan( - id: 1, + id: planUuid1, description: 'Älterer aktiver Plan', startDate: now.subtract(const Duration(days: 10)), endDate: now.add(const Duration(days: 10)), creationDate: now.subtract(const Duration(days: 10)), ); final newerPlan = NutritionalPlan( - id: 2, + id: planUuid2, description: 'Neuerer aktiver Plan', startDate: now.subtract(const Duration(days: 5)), endDate: now.add(const Duration(days: 5)), @@ -177,13 +142,13 @@ void main() { test('no active plan -> null', () async { final plans = [ NutritionalPlan( - id: 1, + id: planUuid1, description: 'plan 1', startDate: now.subtract(const Duration(days: 30)), endDate: now.subtract(const Duration(days: 5)), ), NutritionalPlan( - id: 2, + id: planUuid2, description: 'plan 2', startDate: now.add(const Duration(days: 100)), endDate: now.add(const Duration(days: 50)), @@ -195,7 +160,7 @@ void main() { test('active plan exists -> return it', () async { final plan = NutritionalPlan( - id: 42, + id: planUuidA, description: 'Active plan', startDate: now.subtract(const Duration(days: 10)), endDate: now.add(const Duration(days: 10)), @@ -209,13 +174,13 @@ void main() { test('inactive plans are ignored', () async { final inactivePlan = NutritionalPlan( - id: 10, + id: planUuidA, description: 'Inactive plan', startDate: now.subtract(const Duration(days: 10)), endDate: now.subtract(const Duration(days: 5)), ); final plan = NutritionalPlan( - id: 11, + id: planUuidB, description: 'Active plan', startDate: now.subtract(const Duration(days: 10)), endDate: now.add(const Duration(days: 10)), @@ -229,14 +194,14 @@ void main() { test('several active plans exists -> return newest', () async { final olderPlan = NutritionalPlan( - id: 100, + id: planUuidA, description: 'Old active plan', startDate: now.subtract(const Duration(days: 10)), endDate: now.add(const Duration(days: 10)), creationDate: now.subtract(const Duration(days: 10)), ); final newerPlan = NutritionalPlan( - id: 101, + id: planUuidB, description: 'Newer active plan', startDate: now.subtract(const Duration(days: 5)), endDate: now.add(const Duration(days: 5)), @@ -251,36 +216,24 @@ void main() { }); group('plan write operations', () { - test('addPlan calls repository (creation still goes via REST)', () async { + test('addPlan generates a UUID and delegates to addPlanLocalDrift', () async { final toAdd = NutritionalPlan( id: null, description: 'New plan', startDate: now, creationDate: now, ); - final created = NutritionalPlan( - id: 99, - description: 'New plan', - startDate: now, - creationDate: now, - ); - when(mockRepo.createPlan(any)).thenAnswer((_) async => created.toJson()); - // Default `Stream.empty()` from setUp leaves state in AsyncLoading, - // which addPlan promotes to AsyncData via its optimistic update. final container = makeContainer(); final result = await container.read(nutritionProvider.notifier).addPlan(toAdd); - verify(mockRepo.createPlan(any)).called(1); - expect(result.id, created.id); - // Optimistic state injection: the new plan is visible right away. - final plans = container.read(nutritionProvider).value?.plans ?? const []; - expect(plans.map((p) => p.id), contains(99)); + expect(result.id, isNotNull); + verify(mockRepo.addPlanLocalDrift(toAdd)).called(1); }); - test('editPlan delegates to editLocalDrift (PowerSync), not REST', () async { + test('editPlan delegates to editLocalDrift', () async { final plan = NutritionalPlan( - id: 1, + id: planUuid1, description: 'edit me', startDate: now, creationDate: now, @@ -292,18 +245,31 @@ void main() { verify(mockRepo.editLocalDrift(plan)).called(1); }); - test('deletePlan delegates to deleteLocalDrift (PowerSync), not REST', () async { + test('deletePlan delegates to deleteLocalDrift', () async { final container = makeContainer(); - await container.read(nutritionProvider.notifier).deletePlan(1); + await container.read(nutritionProvider.notifier).deletePlan(planUuid1); - verify(mockRepo.deleteLocalDrift(1)).called(1); + verify(mockRepo.deleteLocalDrift(planUuid1)).called(1); }); }); group('meal write operations', () { + const mealUuid = 'aa000000-0000-4000-8000-000000000001'; + + test('addMeal generates a UUID and delegates to addMealLocalDrift', () async { + final meal = Meal(plan: planUuid1, name: 'breakfast'); + final container = makeContainer(); + + final saved = await container.read(nutritionProvider.notifier).addMeal(meal, planUuid1); + + expect(saved.id, isNotNull); + expect(saved.planId, planUuid1); + verify(mockRepo.addMealLocalDrift(meal)).called(1); + }); + test('editMeal delegates to editMealLocalDrift (PowerSync), not REST', () async { - final meal = Meal(id: 5, plan: 1, name: 'breakfast'); + final meal = Meal(id: mealUuid, plan: planUuid1, name: 'breakfast'); final container = makeContainer(); await container.read(nutritionProvider.notifier).editMeal(meal); @@ -311,27 +277,34 @@ void main() { verify(mockRepo.editMealLocalDrift(meal)).called(1); }); - test('deleteMeal delegates to deleteMealLocalDrift and updates state', () async { - final meal = Meal(id: 5, plan: 7, name: 'breakfast'); - final plan = NutritionalPlan( - id: 7, - description: 'plan', - startDate: now, - creationDate: now, - )..meals = [meal]; - final container = await containerWithPlans([plan]); + test('deleteMeal delegates to deleteMealLocalDrift', () async { + final meal = Meal(id: mealUuid, plan: planUuid1, name: 'breakfast'); + final container = makeContainer(); await container.read(nutritionProvider.notifier).deleteMeal(meal); - verify(mockRepo.deleteMealLocalDrift(5)).called(1); - final plans = container.read(nutritionProvider).value?.plans ?? const []; - expect(plans.single.meals, isEmpty); + verify(mockRepo.deleteMealLocalDrift(mealUuid)).called(1); }); }); group('meal item write operations', () { + const mealUuid = 'aa000000-0000-4000-8000-000000000001'; + const itemUuid = 'bb000000-0000-4000-8000-000000000001'; + + test('addMealItem generates a UUID and delegates to addMealItemLocalDrift', () async { + final meal = Meal(id: mealUuid, plan: planUuid1, name: 'breakfast'); + final item = MealItem(ingredientId: 1, amount: 100); + final container = makeContainer(); + + final saved = await container.read(nutritionProvider.notifier).addMealItem(item, meal); + + expect(saved.id, isNotNull); + expect(saved.mealId, mealUuid); + verify(mockRepo.addMealItemLocalDrift(item)).called(1); + }); + test('editMealItem delegates to editMealItemLocalDrift (PowerSync)', () async { - final item = MealItem(id: 9, mealId: 5, ingredientId: 1, amount: 100); + final item = MealItem(id: itemUuid, mealId: mealUuid, ingredientId: 1, amount: 100); final container = makeContainer(); await container.read(nutritionProvider.notifier).editMealItem(item); @@ -339,22 +312,13 @@ void main() { verify(mockRepo.editMealItemLocalDrift(item)).called(1); }); - test('deleteMealItem delegates to deleteMealItemLocalDrift and updates state', () async { - final item = MealItem(id: 9, mealId: 5, ingredientId: 1, amount: 100); - final meal = Meal(id: 5, plan: 7, name: 'breakfast')..mealItems = [item]; - final plan = NutritionalPlan( - id: 7, - description: 'plan', - startDate: now, - creationDate: now, - )..meals = [meal]; - final container = await containerWithPlans([plan]); + test('deleteMealItem delegates to deleteMealItemLocalDrift', () async { + final item = MealItem(id: itemUuid, mealId: mealUuid, ingredientId: 1, amount: 100); + final container = makeContainer(); await container.read(nutritionProvider.notifier).deleteMealItem(item); - verify(mockRepo.deleteMealItemLocalDrift(9)).called(1); - final plans = container.read(nutritionProvider).value?.plans ?? const []; - expect(plans.single.meals.single.mealItems, isEmpty); + verify(mockRepo.deleteMealItemLocalDrift(itemUuid)).called(1); }); }); } diff --git a/test/nutrition/nutrition_provider_test.mocks.dart b/test/nutrition/nutrition_provider_test.mocks.dart index e92ff7bfb..6583f0e18 100644 --- a/test/nutrition/nutrition_provider_test.mocks.dart +++ b/test/nutrition/nutrition_provider_test.mocks.dart @@ -37,36 +37,6 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor _i1.throwOnMissingStub(this); } - @override - _i3.Future> fetchPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanSparse, [planId]), - returnValue: _i3.Future>.value( - {}, - ), - ) - as _i3.Future>); - - @override - _i3.Future> fetchPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanFull, [planId]), - returnValue: _i3.Future>.value( - {}, - ), - ) - as _i3.Future>); - - @override - _i3.Future> createPlan(Map? data) => - (super.noSuchMethod( - Invocation.method(#createPlan, [data]), - returnValue: _i3.Future>.value( - {}, - ), - ) - as _i3.Future>); - @override _i3.Stream> watchAllDrift() => (super.noSuchMethod( @@ -75,6 +45,15 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor ) as _i3.Stream>); + @override + _i3.Future addPlanLocalDrift(_i4.NutritionalPlan? plan) => + (super.noSuchMethod( + Invocation.method(#addPlanLocalDrift, [plan]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future editLocalDrift(_i4.NutritionalPlan? plan) => (super.noSuchMethod( @@ -85,7 +64,7 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future deleteLocalDrift(int? id) => + _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDrift, [id]), returnValue: _i3.Future.value(), @@ -94,14 +73,21 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future> createMeal(Map? data) => + _i3.Stream> watchAllMealsHydrated() => (super.noSuchMethod( - Invocation.method(#createMeal, [data]), - returnValue: _i3.Future>.value( - {}, - ), + Invocation.method(#watchAllMealsHydrated, []), + returnValue: _i3.Stream>.empty(), ) - as _i3.Future>); + as _i3.Stream>); + + @override + _i3.Future addMealLocalDrift(_i5.Meal? meal) => + (super.noSuchMethod( + Invocation.method(#addMealLocalDrift, [meal]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future editMealLocalDrift(_i5.Meal? meal) => @@ -113,7 +99,7 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future deleteMealLocalDrift(int? id) => + _i3.Future deleteMealLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealLocalDrift, [id]), returnValue: _i3.Future.value(), @@ -122,14 +108,13 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future> createMealItem(Map? data) => + _i3.Future addMealItemLocalDrift(_i6.MealItem? item) => (super.noSuchMethod( - Invocation.method(#createMealItem, [data]), - returnValue: _i3.Future>.value( - {}, - ), + Invocation.method(#addMealItemLocalDrift, [item]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i3.Future>); + as _i3.Future); @override _i3.Future editMealItemLocalDrift(_i6.MealItem? item) => @@ -141,7 +126,7 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future deleteMealItemLocalDrift(int? id) => + _i3.Future deleteMealItemLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealItemLocalDrift, [id]), returnValue: _i3.Future.value(), diff --git a/test/nutrition/nutrition_repository_test.dart b/test/nutrition/nutrition_repository_test.dart index a32f21038..98fb8f9c5 100644 --- a/test/nutrition/nutrition_repository_test.dart +++ b/test/nutrition/nutrition_repository_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2026 wger Team + * Copyright (c) 2026 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -19,7 +19,6 @@ import 'package:drift/drift.dart' as drift; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; import 'package:wger/database/powersync/database.dart'; import 'package:wger/models/nutrition/log.dart'; import 'package:wger/models/nutrition/meal.dart'; @@ -50,7 +49,7 @@ void main() { // ---- seed helpers --------------------------------------------------------- Future seedPlan({ - required int id, + required String id, String description = '', DateTime? startDate, }) async { @@ -58,7 +57,7 @@ void main() { .into(db.nutritionalPlanTable) .insert( NutritionalPlanTableCompanion.insert( - id: id, + id: drift.Value(id), description: description, creationDate: DateTime.utc(2024), startDate: startDate ?? DateTime.utc(2024, 1, 1), @@ -123,33 +122,39 @@ void main() { ); } - Future seedMeal({required int id, required int planId, String name = ''}) async { + Future seedMeal({ + required String id, + required String planId, + int order = 1, + String name = '', + }) async { await db .into(db.mealTable) .insert( MealTableCompanion.insert( - id: id, + id: drift.Value(id), planId: planId, - order: 1, + order: drift.Value(order), name: drift.Value(name), ), ); } Future seedMealItem({ - required int id, - required int mealId, + required String id, + required String mealId, required int ingredientId, + int order = 1, double amount = 100, }) async { await db .into(db.mealItemTable) .insert( MealItemTableCompanion.insert( - id: id, + id: drift.Value(id), mealId: mealId, ingredientId: ingredientId, - order: 1, + order: drift.Value(order), amount: amount, ), ); @@ -157,37 +162,9 @@ void main() { // --------------------------------------------------------------------------- - group('Plans — REST', () { - test('fetchPlanSparse hits /nutritionplan// and returns the body as a map', () async { - final uri = Uri.https('localhost', 'api/v2/nutritionplan/42/'); - when(mockBase.makeUrl('nutritionplan', id: 42)).thenReturn(uri); - when(mockBase.fetch(uri)).thenAnswer((_) async => {'id': 42, 'description': 'plan'}); - - final result = await repo.fetchPlanSparse(42); - - expect(result, {'id': 42, 'description': 'plan'}); - }); - - test('fetchPlanFull hits /nutritionplaninfo//', () async { - final uri = Uri.https('localhost', 'api/v2/nutritionplaninfo/42/'); - when(mockBase.makeUrl('nutritionplaninfo', id: 42)).thenReturn(uri); - when(mockBase.fetch(uri)).thenAnswer((_) async => {'id': 42}); - - final result = await repo.fetchPlanFull(42); - - expect(result['id'], 42); - }); - - test('createPlan POSTs the payload to /nutritionplan/', () async { - final uri = Uri.https('localhost', 'api/v2/nutritionplan/'); - when(mockBase.makeUrl('nutritionplan')).thenReturn(uri); - when(mockBase.post(any, uri)).thenAnswer((_) async => {'id': 1}); - - await repo.createPlan({'description': 'new plan'}); - - verify(mockBase.post({'description': 'new plan'}, uri)).called(1); - }); - }); + const planUuid1 = 'cc000000-0000-4000-8000-000000000001'; + const planUuid2 = 'cc000000-0000-4000-8000-000000000002'; + const planUuid3 = 'cc000000-0000-4000-8000-000000000003'; group('Plans — Drift', () { test('watchAllDrift emits an empty list when no plans exist', () async { @@ -195,17 +172,44 @@ void main() { }); test('watchAllDrift emits plans sorted by start desc', () async { - await seedPlan(id: 1, startDate: DateTime.utc(2024, 1, 1)); - await seedPlan(id: 2, startDate: DateTime.utc(2024, 6, 1)); - await seedPlan(id: 3, startDate: DateTime.utc(2024, 3, 1)); + await seedPlan(id: planUuid1, startDate: DateTime.utc(2024, 1, 1)); + await seedPlan(id: planUuid2, startDate: DateTime.utc(2024, 6, 1)); + await seedPlan(id: planUuid3, startDate: DateTime.utc(2024, 3, 1)); final emitted = await repo.watchAllDrift().first; - expect(emitted.map((p) => p.id).toList(), [2, 3, 1]); + expect(emitted.map((p) => p.id).toList(), [planUuid2, planUuid3, planUuid1]); + }); + + test('addPlanLocalDrift inserts the plan', () async { + final fresh = NutritionalPlan( + id: planUuid1, + description: 'fresh', + creationDate: DateTime.utc(2024), + startDate: DateTime.utc(2024, 1, 1), + onlyLogging: false, + ); + + await repo.addPlanLocalDrift(fresh); + + final emitted = await repo.watchAllDrift().first; + expect(emitted.single.id, planUuid1); + expect(emitted.single.description, 'fresh'); + }); + + test('addPlanLocalDrift throws StateError when id is null', () async { + final plan = NutritionalPlan( + description: 'no id', + creationDate: DateTime.utc(2024), + startDate: DateTime.utc(2024), + onlyLogging: false, + ); + + expect(() => repo.addPlanLocalDrift(plan), throwsStateError); }); test('editLocalDrift overwrites the plan with matching id', () async { - await seedPlan(id: 1, description: 'original'); + await seedPlan(id: planUuid1, description: 'original'); final plan = (await repo.watchAllDrift().first).single; plan.description = 'updated'; @@ -227,99 +231,155 @@ void main() { }); test('deleteLocalDrift removes the plan with matching id', () async { - await seedPlan(id: 1); - await seedPlan(id: 2); + await seedPlan(id: planUuid1); + await seedPlan(id: planUuid2); - await repo.deleteLocalDrift(1); + await repo.deleteLocalDrift(planUuid1); final emitted = await repo.watchAllDrift().first; - expect(emitted.map((p) => p.id), [2]); + expect(emitted.map((p) => p.id), [planUuid2]); }); }); group('Meals', () { - test('createMeal POSTs to /meal/', () async { - final uri = Uri.https('localhost', 'api/v2/meal/'); - when(mockBase.makeUrl('meal')).thenReturn(uri); - when(mockBase.post(any, uri)).thenAnswer((_) async => {'id': 1}); + const mealUuid1 = 'aa000000-0000-4000-8000-000000000001'; + const mealUuid2 = 'aa000000-0000-4000-8000-000000000002'; - await repo.createMeal({'name': 'breakfast'}); + test('addMealLocalDrift inserts the meal and computes order from existing rows', () async { + await seedPlan(id: planUuid1); + await seedMeal(id: mealUuid1, planId: planUuid1, order: 3); - verify(mockBase.post({'name': 'breakfast'}, uri)).called(1); + final fresh = Meal(id: mealUuid2, plan: planUuid1, name: 'lunch'); + await repo.addMealLocalDrift(fresh); + + final row = await (db.select( + db.mealTable, + )..where((t) => t.id.equals(mealUuid2))).getSingle(); + expect(row.name, 'lunch'); + expect(row.order, 4); + }); + + test('addMealLocalDrift throws StateError when id is null', () async { + final meal = Meal(plan: planUuid1, name: 'no id'); + expect(() => repo.addMealLocalDrift(meal), throwsStateError); }); test('editMealLocalDrift overwrites the meal with matching id', () async { - await seedPlan(id: 1); - await seedMeal(id: 5, planId: 1, name: 'breakfast'); + await seedPlan(id: planUuid1); + await seedMeal(id: mealUuid1, planId: planUuid1, name: 'breakfast'); - final updated = Meal(id: 5, plan: 1, name: 'lunch'); + final updated = Meal(id: mealUuid1, plan: planUuid1, name: 'lunch'); await repo.editMealLocalDrift(updated); final row = await (db.select( db.mealTable, - )..where((t) => t.id.equals(5))).getSingle(); + )..where((t) => t.id.equals(mealUuid1))).getSingle(); expect(row.name, 'lunch'); }); test('editMealLocalDrift throws StateError when id is null', () async { - final meal = Meal(plan: 1, name: 'no id'); + final meal = Meal(plan: planUuid1, name: 'no id'); expect(() => repo.editMealLocalDrift(meal), throwsStateError); }); test('deleteMealLocalDrift removes the meal with matching id', () async { - await seedPlan(id: 1); - await seedMeal(id: 5, planId: 1); - await seedMeal(id: 6, planId: 1); + await seedPlan(id: planUuid1); + await seedMeal(id: mealUuid1, planId: planUuid1); + await seedMeal(id: mealUuid2, planId: planUuid1); - await repo.deleteMealLocalDrift(5); + await repo.deleteMealLocalDrift(mealUuid1); final remaining = await db.select(db.mealTable).get(); - expect(remaining.map((m) => m.id), [6]); + expect(remaining.map((m) => m.id), [mealUuid2]); }); }); group('Meal items', () { - test('createMealItem POSTs to /mealitem/', () async { - final uri = Uri.https('localhost', 'api/v2/mealitem/'); - when(mockBase.makeUrl('mealitem')).thenReturn(uri); - when(mockBase.post(any, uri)).thenAnswer((_) async => {'id': 1}); + const mealUuid = 'aa000000-0000-4000-8000-000000000001'; + const itemUuid1 = 'bb000000-0000-4000-8000-000000000001'; + const itemUuid2 = 'bb000000-0000-4000-8000-000000000002'; - await repo.createMealItem({'meal': 1, 'amount': 100}); + test('addMealItemLocalDrift inserts and computes order from existing items', () async { + await seedPlan(id: planUuid1); + await seedMeal(id: mealUuid, planId: planUuid1); + await seedIngredient(id: 1, name: 'Apple'); + await seedMealItem(id: itemUuid1, mealId: mealUuid, ingredientId: 1, order: 5); - verify(mockBase.post({'meal': 1, 'amount': 100}, uri)).called(1); + final fresh = MealItem(id: itemUuid2, mealId: mealUuid, ingredientId: 1, amount: 200); + await repo.addMealItemLocalDrift(fresh); + + final row = await (db.select( + db.mealItemTable, + )..where((t) => t.id.equals(itemUuid2))).getSingle(); + expect(row.amount, 200); + expect(row.order, 6); + }); + + test('addMealItemLocalDrift throws StateError when id is null', () async { + final item = MealItem(mealId: mealUuid, ingredientId: 1, amount: 50); + expect(() => repo.addMealItemLocalDrift(item), throwsStateError); }); test('editMealItemLocalDrift overwrites the item with matching id', () async { - await seedPlan(id: 1); - await seedMeal(id: 1, planId: 1); + await seedPlan(id: planUuid1); + await seedMeal(id: mealUuid, planId: planUuid1); await seedIngredient(id: 1, name: 'Apple'); - await seedMealItem(id: 7, mealId: 1, ingredientId: 1, amount: 100); + await seedMealItem(id: itemUuid1, mealId: mealUuid, ingredientId: 1, amount: 100); - final updated = MealItem(id: 7, mealId: 1, ingredientId: 1, amount: 250); + final updated = MealItem(id: itemUuid1, mealId: mealUuid, ingredientId: 1, amount: 250); await repo.editMealItemLocalDrift(updated); final row = await (db.select( db.mealItemTable, - )..where((t) => t.id.equals(7))).getSingle(); + )..where((t) => t.id.equals(itemUuid1))).getSingle(); expect(row.amount, 250); }); test('editMealItemLocalDrift throws StateError when id is null', () async { - final item = MealItem(mealId: 1, ingredientId: 1, amount: 50); + final item = MealItem(mealId: mealUuid, ingredientId: 1, amount: 50); expect(() => repo.editMealItemLocalDrift(item), throwsStateError); }); test('deleteMealItemLocalDrift removes the item with matching id', () async { - await seedPlan(id: 1); - await seedMeal(id: 1, planId: 1); + await seedPlan(id: planUuid1); + await seedMeal(id: mealUuid, planId: planUuid1); await seedIngredient(id: 1, name: 'Apple'); - await seedMealItem(id: 7, mealId: 1, ingredientId: 1); - await seedMealItem(id: 8, mealId: 1, ingredientId: 1); + await seedMealItem(id: itemUuid1, mealId: mealUuid, ingredientId: 1); + await seedMealItem(id: itemUuid2, mealId: mealUuid, ingredientId: 1); - await repo.deleteMealItemLocalDrift(7); + await repo.deleteMealItemLocalDrift(itemUuid1); final remaining = await db.select(db.mealItemTable).get(); - expect(remaining.map((m) => m.id), [8]); + expect(remaining.map((m) => m.id), [itemUuid2]); + }); + }); + + group('Meals — watchAllMealsHydrated', () { + const mealUuid1 = 'aa000000-0000-4000-8000-000000000001'; + const mealUuid2 = 'aa000000-0000-4000-8000-000000000002'; + const itemUuid1 = 'bb000000-0000-4000-8000-000000000001'; + const itemUuid2 = 'bb000000-0000-4000-8000-000000000002'; + + test('emits empty when no meals exist', () async { + expect(await repo.watchAllMealsHydrated().first, isEmpty); + }); + + test('emits meals with their items hydrated and ingredients attached', () async { + await seedPlan(id: planUuid1); + await seedIngredient(id: 1, name: 'Apple'); + await seedMeal(id: mealUuid1, planId: planUuid1, name: 'breakfast'); + await seedMeal(id: mealUuid2, planId: planUuid1, name: 'lunch'); + await seedMealItem(id: itemUuid1, mealId: mealUuid1, ingredientId: 1, amount: 100); + await seedMealItem(id: itemUuid2, mealId: mealUuid1, ingredientId: 1, amount: 50); + + final emitted = await repo.watchAllMealsHydrated().first; + + expect(emitted, hasLength(2)); + final breakfast = emitted.firstWhere((m) => m.id == mealUuid1); + expect(breakfast.mealItems, hasLength(2)); + expect(breakfast.mealItems.first.ingredient.name, 'Apple'); + final lunch = emitted.firstWhere((m) => m.id == mealUuid2); + expect(lunch.mealItems, isEmpty); }); }); @@ -329,11 +389,11 @@ void main() { }); test('addLogLocalDrift inserts a log visible in watchAllLogsHydrated', () async { - await seedPlan(id: 1); + await seedPlan(id: planUuid1); await seedIngredient(id: 1, name: 'Apple'); final log = LogItem( - planId: 1, + planId: planUuid1, ingredientId: 1, amount: 100, datetime: DateTime.utc(2026, 4, 15), @@ -347,13 +407,13 @@ void main() { }); test('watchAllLogsHydrated attaches image and weight units to each ingredient', () async { - await seedPlan(id: 1); + await seedPlan(id: planUuid1); await seedIngredient(id: 1, name: 'Apple'); await seedIngredientImage(id: 10, ingredientId: 1); await seedIngredientWeightUnit(id: 100, ingredientId: 1); await repo.addLogLocalDrift( LogItem( - planId: 1, + planId: planUuid1, ingredientId: 1, amount: 100, datetime: DateTime.utc(2026, 4, 15), @@ -367,12 +427,12 @@ void main() { }); test('watchAllLogsHydrated resolves weightUnitObj on the log when set', () async { - await seedPlan(id: 1); + await seedPlan(id: planUuid1); await seedIngredient(id: 1, name: 'Apple'); await seedIngredientWeightUnit(id: 100, ingredientId: 1); await repo.addLogLocalDrift( LogItem( - planId: 1, + planId: planUuid1, ingredientId: 1, weightUnitId: 100, amount: 1, @@ -386,11 +446,11 @@ void main() { }); test('watchAllLogsHydrated leaves weightUnitObj null when log has no weightUnitId', () async { - await seedPlan(id: 1); + await seedPlan(id: planUuid1); await seedIngredient(id: 1, name: 'Apple'); await repo.addLogLocalDrift( LogItem( - planId: 1, + planId: planUuid1, ingredientId: 1, amount: 100, datetime: DateTime.utc(2026, 4, 15), @@ -403,10 +463,10 @@ void main() { }); test('deleteLogLocalDrift removes the log with matching id', () async { - await seedPlan(id: 1); + await seedPlan(id: planUuid1); await seedIngredient(id: 1, name: 'Apple'); final log = LogItem( - planId: 1, + planId: planUuid1, ingredientId: 1, amount: 100, datetime: DateTime.utc(2026, 4, 15), diff --git a/test/nutrition/nutritional_meal_form_test.dart b/test/nutrition/nutritional_meal_form_test.dart index 5b9967082..04370fbee 100644 --- a/test/nutrition/nutritional_meal_form_test.dart +++ b/test/nutrition/nutritional_meal_form_test.dart @@ -53,12 +53,13 @@ void main() { mockRepo = MockNutritionRepository(); mockIngredientRepo = MockIngredientRepository(); + when(mockRepo.addMealLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.editMealLocalDrift(any)).thenAnswer((_) async => Future.value()); - when(mockRepo.createMeal(any)).thenAnswer((_) async => Meal(id: 99, plan: 1).toJson()); - // NutritionNotifier.build() subscribes to two Drift streams (plans + - // diary entries) — emit the seed plan and an empty diary so the + // NutritionNotifier.build() subscribes to three Drift streams (plans, + // meals, diary entries) — emit the seed plan and empty meals/diary so the // combined stream produces a value. when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value([plan1])); + when(mockRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(plan1.meals)); when(mockRepo.watchAllLogsHydrated()).thenAnswer((_) => Stream.value(const [])); container = ProviderContainer( @@ -88,7 +89,7 @@ void main() { localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, navigatorKey: key, - home: Scaffold(body: MealForm(1, meal)), + home: Scaffold(body: MealForm(plan1.id!, meal)), routes: { NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), }, @@ -127,7 +128,7 @@ void main() { // Correct method was called verify(mockRepo.editMealLocalDrift(any)); - verifyNever(mockRepo.createMeal(any)); + verifyNever(mockRepo.addMealLocalDrift(any)); }); testWidgets('Test creating a new nutritional plan', (WidgetTester tester) async { @@ -166,17 +167,19 @@ void main() { // Correct method was called verifyNever(mockRepo.editMealLocalDrift(any)); - verify(mockRepo.createMeal(any)); + verify(mockRepo.addMealLocalDrift(any)); }); // Detail page // ... }); - testWidgets('Submit is disabled offline only when creating a new meal', ( + testWidgets('Submit stays enabled offline (PowerSync handles create/edit locally)', ( WidgetTester tester, ) async { - // Build a fresh container that overrides the network status to offline. + // Both create and edit now flow through PowerSync (Drift insert/update), + // so the meal form's submit button should never be disabled by network + // status. final offlineContainer = ProviderContainer( overrides: [ nutritionRepositoryProvider.overrideWithValue(mockRepo), @@ -186,7 +189,6 @@ void main() { ); addTearDown(offlineContainer.dispose); - // 1) Creating a new meal offline: button must be disabled (REST POST). final newMeal = Meal(time: const TimeOfDay(hour: 8, minute: 0)); await tester.pumpWidget( UncontrolledProviderScope( @@ -195,7 +197,7 @@ void main() { locale: const Locale('en'), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold(body: MealForm(1, newMeal)), + home: Scaffold(body: MealForm(plan1.id!, newMeal)), ), ), ); @@ -204,33 +206,6 @@ void main() { final createButton = tester.widget( find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), ); - expect(createButton.onPressed, isNull); - await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), warnIfMissed: false); - await tester.pump(); - verifyNever(mockRepo.createMeal(any)); - verifyNever(mockRepo.editMealLocalDrift(any)); - - // 2) Editing an existing meal offline: PowerSync handles it locally, - // so the button must remain enabled. - await tester.pumpWidget( - UncontrolledProviderScope( - container: offlineContainer, - child: MaterialApp( - locale: const Locale('en'), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold(body: MealForm(1, meal1)), - ), - ), - ); - await tester.pumpAndSettle(); - final editButton = tester.widget( - find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), - ); - expect(editButton.onPressed, isNotNull); - - await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); - await tester.pump(); - verify(mockRepo.editMealLocalDrift(any)).called(1); + expect(createButton.onPressed, isNotNull); }); } diff --git a/test/nutrition/nutritional_meal_item_form_test.dart b/test/nutrition/nutritional_meal_item_form_test.dart index e9d8ea703..cd6658e8c 100644 --- a/test/nutrition/nutritional_meal_item_form_test.dart +++ b/test/nutrition/nutritional_meal_item_form_test.dart @@ -97,11 +97,14 @@ void main() { plan1 = getNutritionalPlan(); meal1 = plan1.meals.first; final MealItem mealItem = MealItem( - id: 10, - mealId: 1, + id: 'bb000000-0000-4000-8000-000000000010', + mealId: 'aa000000-0000-4000-8000-000000000001', ingredientId: ingredient.id, amount: 2, ); + // Silence unused-local warning while we keep the fixture for documentation. + // ignore: unnecessary_statements + mealItem; mockRepo = MockNutritionRepository(); mockIngredientRepo = MockIngredientRepository(); @@ -128,15 +131,16 @@ void main() { (_) => Future.value([ingredient1, ingredient2]), ); - when(mockRepo.createMealItem(any)).thenAnswer((_) async => mealItem.toJson()); + when(mockRepo.addMealItemLocalDrift(any)).thenAnswer((_) async => Future.value()); // Ingredient lookups go through PowerSync. Weight units now travel with // the Ingredient (inlined by REST or JOINed by the repository), so no // separate stub is needed. when(mockIngredientRepo.getById(any)).thenAnswer((_) async => ingredient); - // NutritionNotifier.build() now subscribes to two Drift streams (plans - // + diary entries) — emit the seed plan and an empty diary so the - // combined stream produces a value. + // NutritionNotifier.build() subscribes to three Drift streams (plans, + // meals, diary entries) — emit the seed plan and meals so the combined + // stream produces a value. when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value([plan1])); + when(mockRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(plan1.meals)); when(mockRepo.watchAllLogsHydrated()).thenAnswer((_) => Stream.value(const [])); container = ProviderContainer( @@ -358,7 +362,7 @@ void main() { expect(formState.mealItem.amount, 2); - verify(mockRepo.createMealItem(any)); + verify(mockRepo.addMealItemLocalDrift(any)); }, ); }); diff --git a/test/nutrition/nutritional_plan_form_test.dart b/test/nutrition/nutritional_plan_form_test.dart index da94b4a0d..3a41f4678 100644 --- a/test/nutrition/nutritional_plan_form_test.dart +++ b/test/nutrition/nutritional_plan_form_test.dart @@ -36,8 +36,10 @@ void main() { late MockNutritionRepository mockRepo; late MockIngredientRepository mockIngredientRepo; + const planUuid1 = 'cc000000-0000-4000-8000-000000000001'; + final plan1 = NutritionalPlan( - id: 1, + id: planUuid1, creationDate: DateTime(2021, 1, 1), startDate: DateTime(2021, 1, 1), endDate: DateTime(2021, 2, 10), @@ -49,9 +51,10 @@ void main() { mockRepo = MockNutritionRepository(); mockIngredientRepo = MockIngredientRepository(); - when(mockRepo.createPlan(any)).thenAnswer((_) async => plan1.toJson()); + when(mockRepo.addPlanLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.editLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value(const [])); + when(mockRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(const [])); when(mockRepo.watchAllLogsHydrated()).thenAnswer((_) => Stream.value(const [])); }); @@ -98,7 +101,7 @@ void main() { // Correct method was called verify(mockRepo.editLocalDrift(any)); - verifyNever(mockRepo.createPlan(any)); + verifyNever(mockRepo.addPlanLocalDrift(any)); }); testWidgets('Test creating a new nutritional plan', (WidgetTester tester) async { @@ -116,6 +119,6 @@ void main() { // Correct method was called verifyNever(mockRepo.editLocalDrift(any)); - verify(mockRepo.createPlan(any)); + verify(mockRepo.addPlanLocalDrift(any)); }); } diff --git a/test/nutrition/nutritional_plan_form_test.mocks.dart b/test/nutrition/nutritional_plan_form_test.mocks.dart index b0e041445..539a24139 100644 --- a/test/nutrition/nutritional_plan_form_test.mocks.dart +++ b/test/nutrition/nutritional_plan_form_test.mocks.dart @@ -37,36 +37,6 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor _i1.throwOnMissingStub(this); } - @override - _i3.Future> fetchPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanSparse, [planId]), - returnValue: _i3.Future>.value( - {}, - ), - ) - as _i3.Future>); - - @override - _i3.Future> fetchPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanFull, [planId]), - returnValue: _i3.Future>.value( - {}, - ), - ) - as _i3.Future>); - - @override - _i3.Future> createPlan(Map? data) => - (super.noSuchMethod( - Invocation.method(#createPlan, [data]), - returnValue: _i3.Future>.value( - {}, - ), - ) - as _i3.Future>); - @override _i3.Stream> watchAllDrift() => (super.noSuchMethod( @@ -75,6 +45,15 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor ) as _i3.Stream>); + @override + _i3.Future addPlanLocalDrift(_i4.NutritionalPlan? plan) => + (super.noSuchMethod( + Invocation.method(#addPlanLocalDrift, [plan]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future editLocalDrift(_i4.NutritionalPlan? plan) => (super.noSuchMethod( @@ -85,7 +64,7 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future deleteLocalDrift(int? id) => + _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDrift, [id]), returnValue: _i3.Future.value(), @@ -94,14 +73,21 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future> createMeal(Map? data) => + _i3.Stream> watchAllMealsHydrated() => (super.noSuchMethod( - Invocation.method(#createMeal, [data]), - returnValue: _i3.Future>.value( - {}, - ), + Invocation.method(#watchAllMealsHydrated, []), + returnValue: _i3.Stream>.empty(), ) - as _i3.Future>); + as _i3.Stream>); + + @override + _i3.Future addMealLocalDrift(_i5.Meal? meal) => + (super.noSuchMethod( + Invocation.method(#addMealLocalDrift, [meal]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future editMealLocalDrift(_i5.Meal? meal) => @@ -113,7 +99,7 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future deleteMealLocalDrift(int? id) => + _i3.Future deleteMealLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealLocalDrift, [id]), returnValue: _i3.Future.value(), @@ -122,14 +108,13 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future> createMealItem(Map? data) => + _i3.Future addMealItemLocalDrift(_i6.MealItem? item) => (super.noSuchMethod( - Invocation.method(#createMealItem, [data]), - returnValue: _i3.Future>.value( - {}, - ), + Invocation.method(#addMealItemLocalDrift, [item]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i3.Future>); + as _i3.Future); @override _i3.Future editMealItemLocalDrift(_i6.MealItem? item) => @@ -141,7 +126,7 @@ class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepositor as _i3.Future); @override - _i3.Future deleteMealItemLocalDrift(int? id) => + _i3.Future deleteMealItemLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealItemLocalDrift, [id]), returnValue: _i3.Future.value(), diff --git a/test/nutrition/nutritional_plan_screen_test.dart b/test/nutrition/nutritional_plan_screen_test.dart index 34ca30136..303829d10 100644 --- a/test/nutrition/nutritional_plan_screen_test.dart +++ b/test/nutrition/nutritional_plan_screen_test.dart @@ -16,7 +16,6 @@ * along with this program. If not, see . */ -import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -52,8 +51,6 @@ void main() { late MockNutritionRepository mockNutritionRepo; late MockIngredientRepository mockIngredientRepo; - late Map nutritionalPlanInfoResponse; - late Map nutritionalPlanDetailResponse; late Ingredient fetchedIngredient; setUp(() { @@ -65,23 +62,17 @@ void main() { mockNutritionRepo = MockNutritionRepository(); mockIngredientRepo = MockIngredientRepository(); - when(mockNutritionRepo.watchAllDrift()).thenAnswer((_) => Stream.value(const [])); - - nutritionalPlanInfoResponse = jsonDecode( - fixture('nutrition/nutritional_plan_info_detail_response.json'), - ); - nutritionalPlanDetailResponse = jsonDecode( - fixture('nutrition/nutritional_plan_detail_response.json'), - ); fetchedIngredient = Ingredient.fromJson( jsonDecode(fixture('nutrition/ingredientinfo_10065.json')), ); + // Plans, meals and logs all stream in via Drift now. when( - mockNutritionRepo.fetchPlanSparse(any), - ).thenAnswer((_) async => nutritionalPlanDetailResponse); - when(mockNutritionRepo.fetchPlanFull(any)).thenAnswer((_) async => nutritionalPlanInfoResponse); - + mockNutritionRepo.watchAllDrift(), + ).thenAnswer((_) => Stream.value(const [])); + when( + mockNutritionRepo.watchAllMealsHydrated(), + ).thenAnswer((_) => Stream.value(const [])); when( mockNutritionRepo.watchAllLogsHydrated(), ).thenAnswer((_) => Stream.value(getTestNutritionLogs())); @@ -222,39 +213,4 @@ void main() { expect(find.textContaining('17:00'), findsOneWidget); }); - - testWidgets( - 'loading indicator does not reappear after popup menu tap', - (WidgetTester tester) async { - final completer = Completer>(); - - // Override the fetchPlanFull behavior so we can control when it completes - when(mockNutritionRepo.fetchPlanFull(any)).thenAnswer((_) => completer.future); - - final container = makeContainer(); - await tester.pumpWidget(createNutritionalPlan(container: container)); - await tester.tap(find.byType(TextButton)); - - // Two pumps: first for route transition, second for FutureBuilder waiting state - await tester.pump(); - await tester.pump(); - - // Future is still pending — spinner must be visible - expect(find.byType(CircularProgressIndicator), findsOneWidget); - - // Now resolve the future — simulates network response - completer.complete(nutritionalPlanInfoResponse); - await tester.pumpAndSettle(); - - // Spinner gone after successful load - expect(find.byType(CircularProgressIndicator), findsNothing); - - // Tap popup menu — this is the exact scenario that triggered the bug - await tester.tap(find.byIcon(Icons.more_vert)); - await tester.pump(); - - // Core assertion: spinner must NOT reappear after menu tap - expect(find.byType(CircularProgressIndicator), findsNothing); - }, - ); } diff --git a/test/nutrition/nutritional_plan_screen_test.mocks.dart b/test/nutrition/nutritional_plan_screen_test.mocks.dart index d2285a434..de12f36a5 100644 --- a/test/nutrition/nutritional_plan_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plan_screen_test.mocks.dart @@ -52,36 +52,6 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor _i1.throwOnMissingStub(this); } - @override - _i4.Future> fetchPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanSparse, [planId]), - returnValue: _i4.Future>.value( - {}, - ), - ) - as _i4.Future>); - - @override - _i4.Future> fetchPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanFull, [planId]), - returnValue: _i4.Future>.value( - {}, - ), - ) - as _i4.Future>); - - @override - _i4.Future> createPlan(Map? data) => - (super.noSuchMethod( - Invocation.method(#createPlan, [data]), - returnValue: _i4.Future>.value( - {}, - ), - ) - as _i4.Future>); - @override _i4.Stream> watchAllDrift() => (super.noSuchMethod( @@ -90,6 +60,15 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor ) as _i4.Stream>); + @override + _i4.Future addPlanLocalDrift(_i5.NutritionalPlan? plan) => + (super.noSuchMethod( + Invocation.method(#addPlanLocalDrift, [plan]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + @override _i4.Future editLocalDrift(_i5.NutritionalPlan? plan) => (super.noSuchMethod( @@ -100,7 +79,7 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future deleteLocalDrift(int? id) => + _i4.Future deleteLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDrift, [id]), returnValue: _i4.Future.value(), @@ -109,14 +88,21 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future> createMeal(Map? data) => + _i4.Stream> watchAllMealsHydrated() => (super.noSuchMethod( - Invocation.method(#createMeal, [data]), - returnValue: _i4.Future>.value( - {}, - ), + Invocation.method(#watchAllMealsHydrated, []), + returnValue: _i4.Stream>.empty(), ) - as _i4.Future>); + as _i4.Stream>); + + @override + _i4.Future addMealLocalDrift(_i6.Meal? meal) => + (super.noSuchMethod( + Invocation.method(#addMealLocalDrift, [meal]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future editMealLocalDrift(_i6.Meal? meal) => @@ -128,7 +114,7 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future deleteMealLocalDrift(int? id) => + _i4.Future deleteMealLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealLocalDrift, [id]), returnValue: _i4.Future.value(), @@ -137,14 +123,13 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future> createMealItem(Map? data) => + _i4.Future addMealItemLocalDrift(_i7.MealItem? item) => (super.noSuchMethod( - Invocation.method(#createMealItem, [data]), - returnValue: _i4.Future>.value( - {}, - ), + Invocation.method(#addMealItemLocalDrift, [item]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), ) - as _i4.Future>); + as _i4.Future); @override _i4.Future editMealItemLocalDrift(_i7.MealItem? item) => @@ -156,7 +141,7 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future deleteMealItemLocalDrift(int? id) => + _i4.Future deleteMealItemLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealItemLocalDrift, [id]), returnValue: _i4.Future.value(), diff --git a/test/nutrition/nutritional_plans_screen_test.dart b/test/nutrition/nutritional_plans_screen_test.dart index 63bba9ad6..5c8fc1b30 100644 --- a/test/nutrition/nutritional_plans_screen_test.dart +++ b/test/nutrition/nutritional_plans_screen_test.dart @@ -59,15 +59,18 @@ void main() { weightUnitStr: 'kg', ); + const planUuid1 = 'cc000000-0000-4000-8000-000000000001'; + const planUuid2 = 'cc000000-0000-4000-8000-000000000002'; + final plans = [ NutritionalPlan( - id: 1, + id: planUuid1, description: 'test plan 1', creationDate: DateTime(2021, 01, 01), startDate: DateTime(2021, 01, 01), ), NutritionalPlan( - id: 2, + id: planUuid2, description: 'test plan 2', creationDate: DateTime(2021, 01, 10), startDate: DateTime(2021, 01, 10), @@ -83,7 +86,7 @@ void main() { when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); when(mockNutritionRepo.watchAllDrift()).thenAnswer((_) => Stream.value(plans)); - // build() now combines plans + diary entries; default to an empty diary. + when(mockNutritionRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(const [])); when(mockNutritionRepo.watchAllLogsHydrated()).thenAnswer((_) => Stream.value(const [])); when(mockNutritionRepo.deleteLocalDrift(any)).thenAnswer((_) async => Future.value()); }); diff --git a/test/nutrition/nutritional_plans_screen_test.mocks.dart b/test/nutrition/nutritional_plans_screen_test.mocks.dart index 98fe246f2..f797823c3 100644 --- a/test/nutrition/nutritional_plans_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plans_screen_test.mocks.dart @@ -58,36 +58,6 @@ class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepositor _i1.throwOnMissingStub(this); } - @override - _i5.Future> fetchPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanSparse, [planId]), - returnValue: _i5.Future>.value( - {}, - ), - ) - as _i5.Future>); - - @override - _i5.Future> fetchPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanFull, [planId]), - returnValue: _i5.Future>.value( - {}, - ), - ) - as _i5.Future>); - - @override - _i5.Future> createPlan(Map? data) => - (super.noSuchMethod( - Invocation.method(#createPlan, [data]), - returnValue: _i5.Future>.value( - {}, - ), - ) - as _i5.Future>); - @override _i5.Stream> watchAllDrift() => (super.noSuchMethod( @@ -96,6 +66,15 @@ class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepositor ) as _i5.Stream>); + @override + _i5.Future addPlanLocalDrift(_i6.NutritionalPlan? plan) => + (super.noSuchMethod( + Invocation.method(#addPlanLocalDrift, [plan]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + @override _i5.Future editLocalDrift(_i6.NutritionalPlan? plan) => (super.noSuchMethod( @@ -106,7 +85,7 @@ class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepositor as _i5.Future); @override - _i5.Future deleteLocalDrift(int? id) => + _i5.Future deleteLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDrift, [id]), returnValue: _i5.Future.value(), @@ -115,14 +94,21 @@ class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepositor as _i5.Future); @override - _i5.Future> createMeal(Map? data) => + _i5.Stream> watchAllMealsHydrated() => (super.noSuchMethod( - Invocation.method(#createMeal, [data]), - returnValue: _i5.Future>.value( - {}, - ), + Invocation.method(#watchAllMealsHydrated, []), + returnValue: _i5.Stream>.empty(), ) - as _i5.Future>); + as _i5.Stream>); + + @override + _i5.Future addMealLocalDrift(_i7.Meal? meal) => + (super.noSuchMethod( + Invocation.method(#addMealLocalDrift, [meal]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future editMealLocalDrift(_i7.Meal? meal) => @@ -134,7 +120,7 @@ class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepositor as _i5.Future); @override - _i5.Future deleteMealLocalDrift(int? id) => + _i5.Future deleteMealLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealLocalDrift, [id]), returnValue: _i5.Future.value(), @@ -143,14 +129,13 @@ class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepositor as _i5.Future); @override - _i5.Future> createMealItem(Map? data) => + _i5.Future addMealItemLocalDrift(_i8.MealItem? item) => (super.noSuchMethod( - Invocation.method(#createMealItem, [data]), - returnValue: _i5.Future>.value( - {}, - ), + Invocation.method(#addMealItemLocalDrift, [item]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i5.Future>); + as _i5.Future); @override _i5.Future editMealItemLocalDrift(_i8.MealItem? item) => @@ -162,7 +147,7 @@ class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepositor as _i5.Future); @override - _i5.Future deleteMealItemLocalDrift(int? id) => + _i5.Future deleteMealItemLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealItemLocalDrift, [id]), returnValue: _i5.Future.value(), diff --git a/test/weight/weight_screen_test.mocks.dart b/test/weight/weight_screen_test.mocks.dart index 50c5443c7..512fe20cf 100644 --- a/test/weight/weight_screen_test.mocks.dart +++ b/test/weight/weight_screen_test.mocks.dart @@ -45,36 +45,6 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor _i1.throwOnMissingStub(this); } - @override - _i4.Future> fetchPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanSparse, [planId]), - returnValue: _i4.Future>.value( - {}, - ), - ) - as _i4.Future>); - - @override - _i4.Future> fetchPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchPlanFull, [planId]), - returnValue: _i4.Future>.value( - {}, - ), - ) - as _i4.Future>); - - @override - _i4.Future> createPlan(Map? data) => - (super.noSuchMethod( - Invocation.method(#createPlan, [data]), - returnValue: _i4.Future>.value( - {}, - ), - ) - as _i4.Future>); - @override _i4.Stream> watchAllDrift() => (super.noSuchMethod( @@ -83,6 +53,15 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor ) as _i4.Stream>); + @override + _i4.Future addPlanLocalDrift(_i5.NutritionalPlan? plan) => + (super.noSuchMethod( + Invocation.method(#addPlanLocalDrift, [plan]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + @override _i4.Future editLocalDrift(_i5.NutritionalPlan? plan) => (super.noSuchMethod( @@ -93,7 +72,7 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future deleteLocalDrift(int? id) => + _i4.Future deleteLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDrift, [id]), returnValue: _i4.Future.value(), @@ -102,14 +81,21 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future> createMeal(Map? data) => + _i4.Stream> watchAllMealsHydrated() => (super.noSuchMethod( - Invocation.method(#createMeal, [data]), - returnValue: _i4.Future>.value( - {}, - ), + Invocation.method(#watchAllMealsHydrated, []), + returnValue: _i4.Stream>.empty(), ) - as _i4.Future>); + as _i4.Stream>); + + @override + _i4.Future addMealLocalDrift(_i6.Meal? meal) => + (super.noSuchMethod( + Invocation.method(#addMealLocalDrift, [meal]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future editMealLocalDrift(_i6.Meal? meal) => @@ -121,7 +107,7 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future deleteMealLocalDrift(int? id) => + _i4.Future deleteMealLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealLocalDrift, [id]), returnValue: _i4.Future.value(), @@ -130,14 +116,13 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future> createMealItem(Map? data) => + _i4.Future addMealItemLocalDrift(_i7.MealItem? item) => (super.noSuchMethod( - Invocation.method(#createMealItem, [data]), - returnValue: _i4.Future>.value( - {}, - ), + Invocation.method(#addMealItemLocalDrift, [item]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), ) - as _i4.Future>); + as _i4.Future); @override _i4.Future editMealItemLocalDrift(_i7.MealItem? item) => @@ -149,7 +134,7 @@ class MockNutritionRepository extends _i1.Mock implements _i3.NutritionRepositor as _i4.Future); @override - _i4.Future deleteMealItemLocalDrift(int? id) => + _i4.Future deleteMealItemLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteMealItemLocalDrift, [id]), returnValue: _i4.Future.value(), diff --git a/test_data/nutritional_plans.dart b/test_data/nutritional_plans.dart index 7a8823c0e..34bd19f93 100644 --- a/test_data/nutritional_plans.dart +++ b/test_data/nutritional_plans.dart @@ -153,17 +153,39 @@ final cake = Ingredient( sodium: 0, ); +/// Stable UUIDs for the test plans and meals so cross-references +/// (Meal.planId, MealItem.mealId, LogItem.planId/mealId) line up across +/// fixtures and assertions. +const testPlanUuid1 = 'cc000000-0000-4000-8000-000000000001'; +const testMealUuid1 = 'aa000000-0000-4000-8000-000000000001'; +const testMealUuid2 = 'aa000000-0000-4000-8000-000000000002'; + /// Three diary entries matching the meals on [getNutritionalPlan]: 100 g of /// `ingredient1` (Water), 75 g of `ingredient2` (Burger soup), and 300 g of /// `ingredient3` (Broccoli cake). Useful as a pre-hydrated payload for /// `watchAllLogsHydrated` mocks. List getTestNutritionLogs() => [ - LogItem(planId: 1, mealId: 1, ingredientId: 1, amount: 100, datetime: DateTime(2021, 6, 1)) - ..ingredient = ingredient1, - LogItem(planId: 1, mealId: 1, ingredientId: 2, amount: 75, datetime: DateTime(2021, 6, 1)) - ..ingredient = ingredient2, - LogItem(planId: 1, mealId: 1, ingredientId: 3, amount: 300, datetime: DateTime(2021, 6, 10)) - ..ingredient = ingredient3, + LogItem( + planId: testPlanUuid1, + mealId: testMealUuid1, + ingredientId: 1, + amount: 100, + datetime: DateTime(2021, 6, 1), + )..ingredient = ingredient1, + LogItem( + planId: testPlanUuid1, + mealId: testMealUuid1, + ingredientId: 2, + amount: 75, + datetime: DateTime(2021, 6, 1), + )..ingredient = ingredient2, + LogItem( + planId: testPlanUuid1, + mealId: testMealUuid1, + ingredientId: 3, + amount: 300, + datetime: DateTime(2021, 6, 10), + )..ingredient = ingredient3, ]; NutritionalPlan getNutritionalPlan() { @@ -177,23 +199,23 @@ NutritionalPlan getNutritionalPlan() { mealItem3.ingredient = ingredient3; final meal1 = Meal( - id: 1, - plan: 1, + id: testMealUuid1, + plan: testPlanUuid1, time: const TimeOfDay(hour: 17, minute: 0), name: 'Initial Name 1', ); meal1.mealItems = [mealItem1, mealItem2]; final meal2 = Meal( - id: 2, - plan: 1, + id: testMealUuid2, + plan: testPlanUuid1, time: const TimeOfDay(hour: 22, minute: 5), name: 'Initial Name 2', ); meal2.mealItems = [mealItem3]; final NutritionalPlan plan = NutritionalPlan( - id: 1, + id: testPlanUuid1, description: 'Less fat, more protein', creationDate: DateTime(2021, 5, 23), startDate: DateTime(2021, 5, 23), @@ -212,23 +234,23 @@ NutritionalPlan getNutritionalPlanScreenshot() { final mealItem3 = MealItem(ingredientId: 3, amount: 100, ingredient: apple); final meal1 = Meal( - id: 1, - plan: 1, + id: testMealUuid1, + plan: testPlanUuid1, time: const TimeOfDay(hour: 8, minute: 30), name: 'Breakfast', mealItems: [mealItem1, mealItem2], ); final meal2 = Meal( - id: 2, - plan: 1, + id: testMealUuid2, + plan: testPlanUuid1, time: const TimeOfDay(hour: 11, minute: 0), name: 'Snack 1', mealItems: [mealItem3], ); final NutritionalPlan plan = NutritionalPlan( - id: 1, + id: testPlanUuid1, description: 'Diet', creationDate: DateTime(2021, 5, 23), startDate: DateTime(2021, 5, 23), @@ -236,9 +258,15 @@ NutritionalPlan getNutritionalPlanScreenshot() { ); // Add logs - plan.diaryEntries.add(LogItem.fromMealItem(mealItem1, 1, 1, DateTime.now())); - plan.diaryEntries.add(LogItem.fromMealItem(mealItem2, 1, 1, DateTime.now())); - plan.diaryEntries.add(LogItem.fromMealItem(mealItem3, 1, 1, DateTime.now())); + plan.diaryEntries.add( + LogItem.fromMealItem(mealItem1, testPlanUuid1, testMealUuid1, DateTime.now()), + ); + plan.diaryEntries.add( + LogItem.fromMealItem(mealItem2, testPlanUuid1, testMealUuid1, DateTime.now()), + ); + plan.diaryEntries.add( + LogItem.fromMealItem(mealItem3, testPlanUuid1, testMealUuid1, DateTime.now()), + ); for (final i in plan.diaryEntries) { i.datetime = DateTime.now();