diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig index ec97fc6f3..592ceee85 100644 --- a/ios/Flutter/Debug.xcconfig +++ b/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig index c4855bfe2..592ceee85 100644 --- a/ios/Flutter/Release.xcconfig +++ b/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 08bd47e13..006be35e8 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -77,7 +77,6 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, - BB0286322FD60C00014F981C /* Pods */, ); sourceTree = ""; }; @@ -105,13 +104,6 @@ path = Runner; sourceTree = ""; }; - BB0286322FD60C00014F981C /* Pods */ = { - isa = PBXGroup; - children = ( - ); - path = Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -295,7 +287,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -383,7 +375,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -432,7 +424,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; diff --git a/lib/core/widgets/dashboard/widgets/measurements.dart b/lib/core/widgets/dashboard/widgets/measurements.dart index 75eabbcb6..a178bda56 100644 --- a/lib/core/widgets/dashboard/widgets/measurements.dart +++ b/lib/core/widgets/dashboard/widgets/measurements.dart @@ -45,7 +45,10 @@ class _DashboardMeasurementWidgetState extends ConsumerState>( value: ref.watch(measurementProvider), loggerName: 'DashboardMeasurementWidget', - data: (categoriesList) { + data: (allCategories) { + // Children of multi-value groups are shown inside their parent's card + final categoriesList = allCategories.where((c) => c.parentId == null).toList(); + if (categoriesList.isEmpty) { return NothingFound( AppLocalizations.of(context).moreMeasurementEntries, diff --git a/lib/database/powersync/database.g.dart b/lib/database/powersync/database.g.dart index 473084017..c01662f61 100644 --- a/lib/database/powersync/database.g.dart +++ b/lib/database/powersync/database.g.dart @@ -4891,8 +4891,39 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable ).withConverter( $MeasurementCategoryTableTable.$convertermetricType, ); + static const VerificationMeta _parentIdMeta = const VerificationMeta( + 'parentId', + ); @override - List get $columns => [id, name, unit, metricType]; + late final GeneratedColumn parentId = GeneratedColumn( + 'parent_id', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + defaultConstraints: GeneratedColumn.constraintIsAlways( + 'REFERENCES measurements_category (id)', + ), + ); + static const VerificationMeta _orderMeta = const VerificationMeta('order'); + @override + late final GeneratedColumn order = GeneratedColumn( + 'order', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + defaultValue: const Constant(0), + ); + @override + List get $columns => [ + id, + name, + unit, + metricType, + parentId, + order, + ]; @override String get aliasedName => _alias ?? actualTableName; @override @@ -4924,6 +4955,18 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable } else if (isInserting) { context.missing(_unitMeta); } + if (data.containsKey('parent_id')) { + context.handle( + _parentIdMeta, + parentId.isAcceptableOrUnknown(data['parent_id']!, _parentIdMeta), + ); + } + if (data.containsKey('order')) { + context.handle( + _orderMeta, + order.isAcceptableOrUnknown(data['order']!, _orderMeta), + ); + } return context; } @@ -4951,6 +4994,14 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable data['${effectivePrefix}metric_type'], )!, ), + parentId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}parent_id'], + ), + order: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}order'], + )!, ); } @@ -4968,12 +5019,16 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion name; final Value unit; final Value metricType; + final Value parentId; + final Value order; final Value rowid; const MeasurementCategoryTableCompanion({ this.id = const Value.absent(), this.name = const Value.absent(), this.unit = const Value.absent(), this.metricType = const Value.absent(), + this.parentId = const Value.absent(), + this.order = const Value.absent(), this.rowid = const Value.absent(), }); MeasurementCategoryTableCompanion.insert({ @@ -4981,6 +5036,8 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion? name, Expression? unit, Expression? metricType, + Expression? parentId, + Expression? order, Expression? rowid, }) { return RawValuesInsertable({ @@ -4997,6 +5056,8 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion? name, Value? unit, Value? metricType, + Value? parentId, + Value? order, Value? rowid, }) { return MeasurementCategoryTableCompanion( @@ -5013,6 +5076,8 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion(parentId.value); + } + if (order.present) { + map['order'] = Variable(order.value); + } if (rowid.present) { map['rowid'] = Variable(rowid.value); } @@ -5049,6 +5120,8 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion parentId, + Value order, Value rowid, }); typedef $$MeasurementCategoryTableTableUpdateCompanionBuilder = @@ -16484,6 +16559,8 @@ typedef $$MeasurementCategoryTableTableUpdateCompanionBuilder = Value name, Value unit, Value metricType, + Value parentId, + Value order, Value rowid, }); @@ -16500,6 +16577,26 @@ final class $$MeasurementCategoryTableTableReferences super.$_typedResult, ); + static $MeasurementCategoryTableTable _parentIdTable( + _$DriftPowersyncDatabase db, + ) => db.measurementCategoryTable.createAlias( + 'measurements_category__parent_id__measurements_category__id', + ); + + $$MeasurementCategoryTableTableProcessedTableManager? get parentId { + final $_column = $_itemColumn('parent_id'); + if ($_column == null) return null; + final manager = $$MeasurementCategoryTableTableTableManager( + $_db, + $_db.measurementCategoryTable, + ).filter((f) => f.id.sqlEquals($_column)); + final item = $_typedResult.readTableOrNull(_parentIdTable($_db)); + if (item == null) return manager; + return ProcessedTableManager( + manager.$state.copyWith(prefetchedData: [item]), + ); + } + static MultiTypedResultKey<$MeasurementEntryTableTable, List> _measurementEntryTableRefsTable(_$DriftPowersyncDatabase db) => MultiTypedResultKey.fromTable( db.measurementEntryTable, @@ -16551,6 +16648,33 @@ class $$MeasurementCategoryTableTableFilterComposer builder: (column) => ColumnWithTypeConverterFilters(column), ); + ColumnFilters get order => $composableBuilder( + column: $table.order, + builder: (column) => ColumnFilters(column), + ); + + $$MeasurementCategoryTableTableFilterComposer get parentId { + final $$MeasurementCategoryTableTableFilterComposer composer = $composerBuilder( + composer: this, + getCurrentColumn: (t) => t.parentId, + referencedTable: $db.measurementCategoryTable, + getReferencedColumn: (t) => t.id, + builder: + ( + joinBuilder, { + $addJoinBuilderToRootComposer, + $removeJoinBuilderFromRootComposer, + }) => $$MeasurementCategoryTableTableFilterComposer( + $db: $db, + $table: $db.measurementCategoryTable, + $addJoinBuilderToRootComposer: $addJoinBuilderToRootComposer, + joinBuilder: joinBuilder, + $removeJoinBuilderFromRootComposer: $removeJoinBuilderFromRootComposer, + ), + ); + return composer; + } + Expression measurementEntryTableRefs( Expression Function($$MeasurementEntryTableTableFilterComposer f) f, ) { @@ -16604,6 +16728,33 @@ class $$MeasurementCategoryTableTableOrderingComposer column: $table.metricType, builder: (column) => ColumnOrderings(column), ); + + ColumnOrderings get order => $composableBuilder( + column: $table.order, + builder: (column) => ColumnOrderings(column), + ); + + $$MeasurementCategoryTableTableOrderingComposer get parentId { + final $$MeasurementCategoryTableTableOrderingComposer composer = $composerBuilder( + composer: this, + getCurrentColumn: (t) => t.parentId, + referencedTable: $db.measurementCategoryTable, + getReferencedColumn: (t) => t.id, + builder: + ( + joinBuilder, { + $addJoinBuilderToRootComposer, + $removeJoinBuilderFromRootComposer, + }) => $$MeasurementCategoryTableTableOrderingComposer( + $db: $db, + $table: $db.measurementCategoryTable, + $addJoinBuilderToRootComposer: $addJoinBuilderToRootComposer, + joinBuilder: joinBuilder, + $removeJoinBuilderFromRootComposer: $removeJoinBuilderFromRootComposer, + ), + ); + return composer; + } } class $$MeasurementCategoryTableTableAnnotationComposer @@ -16629,6 +16780,31 @@ class $$MeasurementCategoryTableTableAnnotationComposer builder: (column) => column, ); + GeneratedColumn get order => + $composableBuilder(column: $table.order, builder: (column) => column); + + $$MeasurementCategoryTableTableAnnotationComposer get parentId { + final $$MeasurementCategoryTableTableAnnotationComposer composer = $composerBuilder( + composer: this, + getCurrentColumn: (t) => t.parentId, + referencedTable: $db.measurementCategoryTable, + getReferencedColumn: (t) => t.id, + builder: + ( + joinBuilder, { + $addJoinBuilderToRootComposer, + $removeJoinBuilderFromRootComposer, + }) => $$MeasurementCategoryTableTableAnnotationComposer( + $db: $db, + $table: $db.measurementCategoryTable, + $addJoinBuilderToRootComposer: $addJoinBuilderToRootComposer, + joinBuilder: joinBuilder, + $removeJoinBuilderFromRootComposer: $removeJoinBuilderFromRootComposer, + ), + ); + return composer; + } + Expression measurementEntryTableRefs( Expression Function($$MeasurementEntryTableTableAnnotationComposer a) f, ) { @@ -16667,7 +16843,10 @@ class $$MeasurementCategoryTableTableTableManager $$MeasurementCategoryTableTableUpdateCompanionBuilder, (MeasurementCategory, $$MeasurementCategoryTableTableReferences), MeasurementCategory, - PrefetchHooks Function({bool measurementEntryTableRefs}) + PrefetchHooks Function({ + bool parentId, + bool measurementEntryTableRefs, + }) > { $$MeasurementCategoryTableTableTableManager( _$DriftPowersyncDatabase db, @@ -16694,12 +16873,16 @@ class $$MeasurementCategoryTableTableTableManager Value name = const Value.absent(), Value unit = const Value.absent(), Value metricType = const Value.absent(), + Value parentId = const Value.absent(), + Value order = const Value.absent(), Value rowid = const Value.absent(), }) => MeasurementCategoryTableCompanion( id: id, name: name, unit: unit, metricType: metricType, + parentId: parentId, + order: order, rowid: rowid, ), createCompanionCallback: @@ -16708,12 +16891,16 @@ class $$MeasurementCategoryTableTableTableManager required String name, required String unit, required MetricType metricType, + Value parentId = const Value.absent(), + Value order = const Value.absent(), Value rowid = const Value.absent(), }) => MeasurementCategoryTableCompanion.insert( id: id, name: name, unit: unit, metricType: metricType, + parentId: parentId, + order: order, rowid: rowid, ), withReferenceMapper: (p0) => p0 @@ -16724,13 +16911,44 @@ class $$MeasurementCategoryTableTableTableManager ), ) .toList(), - prefetchHooksCallback: ({measurementEntryTableRefs = false}) { + prefetchHooksCallback: ({parentId = false, measurementEntryTableRefs = false}) { return PrefetchHooks( db: db, explicitlyWatchedTables: [ if (measurementEntryTableRefs) db.measurementEntryTable, ], - addJoins: null, + addJoins: + < + T extends TableManagerState< + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic + > + >(state) { + if (parentId) { + state = + state.withJoin( + currentTable: table, + currentColumn: table.parentId, + referencedTable: $$MeasurementCategoryTableTableReferences + ._parentIdTable(db), + referencedColumn: $$MeasurementCategoryTableTableReferences + ._parentIdTable(db) + .id, + ) + as T; + } + + return state; + }, getPrefetchedDataCallback: (items) async { return [ if (measurementEntryTableRefs) @@ -16748,7 +16966,9 @@ class $$MeasurementCategoryTableTableTableManager p0, ).measurementEntryTableRefs, referencedItemsForCurrentItem: (item, referencedItems) => - referencedItems.where((e) => e.categoryId == item.id), + referencedItems.where( + (e) => e.categoryId == item.id, + ), typedResults: items, ), ]; @@ -16771,7 +16991,7 @@ typedef $$MeasurementCategoryTableTableProcessedTableManager = $$MeasurementCategoryTableTableUpdateCompanionBuilder, (MeasurementCategory, $$MeasurementCategoryTableTableReferences), MeasurementCategory, - PrefetchHooks Function({bool measurementEntryTableRefs}) + PrefetchHooks Function({bool parentId, bool measurementEntryTableRefs}) >; typedef $$MeasurementEntryTableTableCreateCompanionBuilder = MeasurementEntryTableCompanion Function({ diff --git a/lib/database/powersync/tables/measurements.dart b/lib/database/powersync/tables/measurements.dart index 7e6e0aee2..cd16325a6 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -34,7 +34,14 @@ class MeasurementCategoryTable extends Table { TextColumn get unit => text()(); TextColumn get metricType => text().named('metric_type').map(const MeasurementMetricTypeConverter())(); - IntColumn get order => integer().nullable()(); + + /// Multi-value groups: parent category id (max. one level of nesting; only + /// leaf categories carry entries). + TextColumn get parentId => + text().named('parent_id').nullable().references(MeasurementCategoryTable, #id)(); + + /// Position in the category list; for children, the position within the group + IntColumn get order => integer().withDefault(const Constant(0))(); } const PowersyncMeasurementCategoryTable = ps.Table( @@ -43,8 +50,12 @@ const PowersyncMeasurementCategoryTable = ps.Table( ps.Column.text('name'), ps.Column.text('unit'), ps.Column.text('metric_type'), + ps.Column.text('parent_id'), ps.Column.integer('order'), ], + indexes: [ + ps.Index('parent_idx', [ps.IndexedColumn('parent_id')]), + ], ); @UseRowClass(MeasurementEntry) diff --git a/lib/features/health/models/health_metric.dart b/lib/features/health/models/health_metric.dart index a4afdc9a4..a1e48102a 100644 --- a/lib/features/health/models/health_metric.dart +++ b/lib/features/health/models/health_metric.dart @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -import 'package:health/health.dart'; +import 'package:health_bridge/health.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; /// A body metric that can be imported from Apple Health / Health Connect into a diff --git a/lib/features/health/models/health_reading.dart b/lib/features/health/models/health_reading.dart index 1a6e52200..64101adf7 100644 --- a/lib/features/health/models/health_reading.dart +++ b/lib/features/health/models/health_reading.dart @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -import 'package:health/health.dart'; +import 'package:health_bridge/health.dart'; /// A single reading pulled from a health platform, reduced to the fields the /// importer needs. Keeps the `health` package's [HealthDataPoint] out of the diff --git a/lib/features/health/providers/health_repository.dart b/lib/features/health/providers/health_repository.dart index 95c6e8a6c..c70d8032b 100644 --- a/lib/features/health/providers/health_repository.dart +++ b/lib/features/health/providers/health_repository.dart @@ -19,7 +19,7 @@ import 'dart:io'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:health/health.dart'; +import 'package:health_bridge/health.dart'; import 'package:logging/logging.dart'; import 'package:wger/features/health/models/health_reading.dart'; diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index f0a5d1b74..b45c8edd0 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -17,7 +17,7 @@ */ import 'package:collection/collection.dart'; -import 'package:health/health.dart'; +import 'package:health_bridge/health.dart'; import 'package:logging/logging.dart'; import 'package:powersync/powersync.dart' as ps; import 'package:riverpod_annotation/riverpod_annotation.dart'; diff --git a/lib/features/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index 3bf552ffd..24eca5553 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -103,18 +103,36 @@ class MeasurementCategory with _$MeasurementCategory { @override final MetricType metricType; + /// Multi-value groups (e.g. blood pressure): id of the parent category, one + /// child per component. Max. one level of nesting; only leaf categories + /// (no children) carry entries. + @override + final String? parentId; + + /// Position in the category list; for children, the position within the group @override final int order; + /// Child categories (components) of this group. Populated by the repository + /// for display, never persisted directly. + @override + final List children; + MeasurementCategory({ this.id, this.name = '', this.unit = '', this.entries = const [], this.metricType = MetricType.custom, + this.parentId, this.order = 0, + this.children = const [], }); + /// `true` for group parents (blood pressure etc.), which hold no entries of + /// their own + bool get isGroup => children.isNotEmpty; + MeasurementEntry findEntryById(String id) { return entries.firstWhere( (entry) => entry.id == id, @@ -129,6 +147,7 @@ class MeasurementCategory with _$MeasurementCategory { name: Value(name), unit: Value(unit), metricType: Value(metricType), + parentId: Value(parentId), order: Value(order), ); } diff --git a/lib/features/measurements/models/measurement_category.freezed.dart b/lib/features/measurements/models/measurement_category.freezed.dart index 215a5e72c..d5137c0bb 100644 --- a/lib/features/measurements/models/measurement_category.freezed.dart +++ b/lib/features/measurements/models/measurement_category.freezed.dart @@ -17,7 +17,13 @@ mixin _$MeasurementCategory { /// Client-generated UUID, is `null` only before the first persist String? get id; String get name; String get unit; List get entries;/// Drives the health-platform mapping (and, later, default unit/aggregation/ /// chart). [MetricType.custom] for plain user-created categories. - MetricType get metricType; + MetricType get metricType;/// Multi-value groups (e.g. blood pressure): id of the parent category, one +/// child per component. Max. one level of nesting; only leaf categories +/// (no children) carry entries. + String? get parentId;/// Position in the category list; for children, the position within the group + int get order;/// Child categories (components) of this group. Populated by the repository +/// for display, never persisted directly. + List get children; /// Create a copy of MeasurementCategory /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -28,16 +34,16 @@ $MeasurementCategoryCopyWith get copyWith => _$MeasurementC @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is MeasurementCategory&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.unit, unit) || other.unit == unit)&&const DeepCollectionEquality().equals(other.entries, entries)&&(identical(other.metricType, metricType) || other.metricType == metricType)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is MeasurementCategory&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.unit, unit) || other.unit == unit)&&const DeepCollectionEquality().equals(other.entries, entries)&&(identical(other.metricType, metricType) || other.metricType == metricType)&&(identical(other.parentId, parentId) || other.parentId == parentId)&&(identical(other.order, order) || other.order == order)&&const DeepCollectionEquality().equals(other.children, children)); } @override -int get hashCode => Object.hash(runtimeType,id,name,unit,const DeepCollectionEquality().hash(entries),metricType); +int get hashCode => Object.hash(runtimeType,id,name,unit,const DeepCollectionEquality().hash(entries),metricType,parentId,order,const DeepCollectionEquality().hash(children)); @override String toString() { - return 'MeasurementCategory(id: $id, name: $name, unit: $unit, entries: $entries, metricType: $metricType)'; + return 'MeasurementCategory(id: $id, name: $name, unit: $unit, entries: $entries, metricType: $metricType, parentId: $parentId, order: $order, children: $children)'; } @@ -48,7 +54,7 @@ abstract mixin class $MeasurementCategoryCopyWith<$Res> { factory $MeasurementCategoryCopyWith(MeasurementCategory value, $Res Function(MeasurementCategory) _then) = _$MeasurementCategoryCopyWithImpl; @useResult $Res call({ - String? id, String name, String unit, List entries, MetricType metricType + String? id, String name, String unit, List entries, MetricType metricType, String? parentId, int order, List children }); @@ -65,14 +71,17 @@ class _$MeasurementCategoryCopyWithImpl<$Res> /// Create a copy of MeasurementCategory /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? id = freezed,Object? name = null,Object? unit = null,Object? entries = null,Object? metricType = null,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? id = freezed,Object? name = null,Object? unit = null,Object? entries = null,Object? metricType = null,Object? parentId = freezed,Object? order = null,Object? children = null,}) { return _then(MeasurementCategory( id: freezed == id ? _self.id : id // ignore: cast_nullable_to_non_nullable as String?,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable as String,unit: null == unit ? _self.unit : unit // ignore: cast_nullable_to_non_nullable as String,entries: null == entries ? _self.entries : entries // ignore: cast_nullable_to_non_nullable as List,metricType: null == metricType ? _self.metricType : metricType // ignore: cast_nullable_to_non_nullable -as MetricType, +as MetricType,parentId: freezed == parentId ? _self.parentId : parentId // ignore: cast_nullable_to_non_nullable +as String?,order: null == order ? _self.order : order // ignore: cast_nullable_to_non_nullable +as int,children: null == children ? _self.children : children // ignore: cast_nullable_to_non_nullable +as List, )); } diff --git a/lib/features/measurements/providers/measurement_notifier.dart b/lib/features/measurements/providers/measurement_notifier.dart index 59d8f4e6c..593020fd0 100644 --- a/lib/features/measurements/providers/measurement_notifier.dart +++ b/lib/features/measurements/providers/measurement_notifier.dart @@ -72,6 +72,12 @@ final class MeasurementNotifier extends _$MeasurementNotifier { await _repo.addLocalDrift(entry); } + /// Adds one reading of a multi-value group (one entry per component, + /// persisted atomically). + Future addGroupEntries(List entries) async { + await _repo.addLocalDriftGroupEntries(entries); + } + // --- MeasurementCategory operations (delegated to repository) --- Future deleteCategory(String id) async { await _repo.deleteLocalDriftCategory(id); diff --git a/lib/features/measurements/providers/measurement_notifier.g.dart b/lib/features/measurements/providers/measurement_notifier.g.dart index 598a5a4c9..270cb246e 100644 --- a/lib/features/measurements/providers/measurement_notifier.g.dart +++ b/lib/features/measurements/providers/measurement_notifier.g.dart @@ -33,7 +33,7 @@ final class MeasurementNotifierProvider MeasurementNotifier create() => MeasurementNotifier(); } -String _$measurementNotifierHash() => r'94978ed841f94d3481322dc144ef82da95cfb62c'; +String _$measurementNotifierHash() => r'397b6739b5d49e226b1ca3bb1837b2f16c55e0f7'; abstract class _$MeasurementNotifier extends $StreamNotifier> { Stream> build(); diff --git a/lib/features/measurements/providers/measurement_repository.dart b/lib/features/measurements/providers/measurement_repository.dart index 55216cb19..ae2ed4559 100644 --- a/lib/features/measurements/providers/measurement_repository.dart +++ b/lib/features/measurements/providers/measurement_repository.dart @@ -39,7 +39,11 @@ class MeasurementRepository { MeasurementRepository(this._db); - /// Watches all categories, populated with their appropriate entries + /// Watches all categories, populated with their appropriate entries. + /// + /// The list is flat (children of multi-value groups appear as regular items + /// with a non-null `parentId`), but group parents additionally get their + /// [MeasurementCategory.children] attached, sorted by their in-group order. Stream> watchAll() { _logger.finer('Watching all measurement categories with entries'); @@ -72,9 +76,16 @@ class MeasurementRepository { } } - return map.values + final categories = map.values .map((c) => c.copyWith(entries: List.from(c.entries))) .toList(); + + // Attach children to their group parents (rows are already sorted by + // order/name, so insertion order is the display order). + return categories.map((c) { + final children = categories.where((other) => other.parentId == c.id).toList(); + return children.isEmpty ? c : c.copyWith(children: children); + }).toList(); }); } @@ -103,10 +114,26 @@ class MeasurementRepository { await _db.into(_db.measurementEntryTable).insert(entry.toCompanion()); } + /// Inserts one reading of a multi-value group: one entry per component, + /// written in a single transaction so a reading is never half-persisted. + Future addLocalDriftGroupEntries(List entries) async { + _logger.finer('Adding ${entries.length} local measurement entries for a group reading'); + await _db.transaction(() async { + for (final entry in entries) { + await _db.into(_db.measurementEntryTable).insert(entry.toCompanion()); + } + }); + } + // Categories Future deleteLocalDriftCategory(String id) async { _logger.finer('Deleting local measurement category $id'); - await (_db.delete(_db.measurementCategoryTable)..where((t) => t.id.equals(id))).go(); + await _db.transaction(() async { + // Children of a multi-value group are meaningless without their parent; + // the server cascades the same way. + await (_db.delete(_db.measurementCategoryTable)..where((t) => t.parentId.equals(id))).go(); + await (_db.delete(_db.measurementCategoryTable)..where((t) => t.id.equals(id))).go(); + }); } Future updateLocalDriftCategory(MeasurementCategory category) async { diff --git a/lib/features/measurements/widgets/categories.dart b/lib/features/measurements/widgets/categories.dart index 585f6a631..319d5ff84 100644 --- a/lib/features/measurements/widgets/categories.dart +++ b/lib/features/measurements/widgets/categories.dart @@ -31,11 +31,17 @@ class CategoriesList extends ConsumerWidget { return AsyncValueWidget>( value: ref.watch(measurementProvider), loggerName: 'CategoriesList', - data: (categoriesList) => ListView.builder( - padding: const EdgeInsets.all(10.0), - itemCount: categoriesList.length, - itemBuilder: (context, index) => CategoriesCard(categoriesList[index]), - ), + data: (categoriesList) { + // Children of multi-value groups are rendered inside their parent's + // card, not as own list items + final topLevel = categoriesList.where((c) => c.parentId == null).toList(); + + return ListView.builder( + padding: const EdgeInsets.all(10.0), + itemCount: topLevel.length, + itemBuilder: (context, index) => CategoriesCard(topLevel[index]), + ); + }, ); } } diff --git a/lib/features/measurements/widgets/categories_card.dart b/lib/features/measurements/widgets/categories_card.dart index 47100bd00..3afff5ece 100644 --- a/lib/features/measurements/widgets/categories_card.dart +++ b/lib/features/measurements/widgets/categories_card.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:wger/core/form_screen.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; @@ -34,6 +35,10 @@ class CategoriesCard extends StatelessWidget { @override Widget build(BuildContext context) { + if (currentCategory.isGroup) { + return _buildGroupCard(context); + } + // sensibleRange() operates on raw (pre-aggregation) entries final (entriesAll, entries7dAvg) = sensibleRange( currentCategory.entries.map((e) => MeasurementChartEntry(e.value, e.date)).toList(), @@ -115,4 +120,62 @@ class CategoriesCard extends StatelessWidget { ), ); } + + /// Card for a multi-value group (e.g. blood pressure): one row per + /// component with its latest reading; new readings are entered for all + /// components at once. + Widget _buildGroupCard(BuildContext context) { + return Card( + elevation: elevation, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + child: Text( + currentCategory.name, + style: Theme.of(context).textTheme.titleLarge, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + ...currentCategory.children.map((child) { + // Entries arrive sorted by date descending, so first is the latest + final latest = child.entries.firstOrNull; + return ListTile( + dense: true, + title: Text(child.name), + trailing: Text( + latest != null ? '${latest.value} ${child.unit}' : '—', + style: Theme.of(context).textTheme.bodyLarge, + ), + onTap: () => Navigator.pushNamed( + context, + MeasurementEntriesScreen.routeName, + arguments: child.id, + ), + ); + }), + const Divider(), + Align( + alignment: Alignment.centerRight, + child: IconButton( + onPressed: () async { + await Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).newEntry, + GroupMeasurementEntryForm(currentCategory), + ), + ); + }, + icon: const Icon(Icons.add), + ), + ), + ], + ), + ); + } } diff --git a/lib/features/measurements/widgets/forms.dart b/lib/features/measurements/widgets/forms.dart index 697a10169..18ab82446 100644 --- a/lib/features/measurements/widgets/forms.dart +++ b/lib/features/measurements/widgets/forms.dart @@ -111,6 +111,53 @@ class _MeasurementCategoryFormState extends ConsumerState c.parentId == _draft.id); + if (hasChildren) { + return const SizedBox.shrink(); + } + + final candidates = categories + .where((c) => c.parentId == null && c.id != _draft.id && c.entries.isEmpty) + .toList(); + if (candidates.isEmpty) { + return const SizedBox.shrink(); + } + + final initialParent = candidates.any((c) => c.id == _draft.parentId) + ? _draft.parentId + : null; + + return DropdownButtonFormField( + initialValue: initialParent, + decoration: InputDecoration( + labelText: AppLocalizations.of(context).partOfGroup, + ), + items: [ + DropdownMenuItem( + value: null, + child: Text(AppLocalizations.of(context).noGroup), + ), + ...candidates.map( + (c) => DropdownMenuItem(value: c.id, child: Text(c.name)), + ), + ], + onChanged: (value) { + setState(() { + _draft = _draft.copyWith(parentId: value); + }); + }, + ); + }, + ), FormSubmitButton( label: AppLocalizations.of(context).save, onPressed: () async { @@ -288,3 +335,97 @@ class _MeasurementEntryFormState extends ConsumerState { ); } } + +/// Entry form for a multi-value group (e.g. blood pressure): one value field +/// per component, saved as one entry per component with a shared timestamp. +class GroupMeasurementEntryForm extends ConsumerStatefulWidget { + final MeasurementCategory _group; + + const GroupMeasurementEntryForm(this._group); + + @override + ConsumerState createState() => _GroupMeasurementEntryFormState(); +} + +class _GroupMeasurementEntryFormState extends ConsumerState { + final _form = GlobalKey(); + + DateTime _date = DateTime.now(); + late final Map _values = { + for (final child in widget._group.children) child.id!: null, + }; + + @override + Widget build(BuildContext context) { + return Form( + key: _form, + child: Column( + children: [ + // Date and time are shared by all components of the reading + DateInputWidget( + value: _date, + labelText: AppLocalizations.of(context).date, + firstDate: DateTime(DateTime.now().year - 10), + lastDate: DateTime.now(), + onChanged: (date) { + _date = _date.copyWith( + year: date.year, + month: date.month, + day: date.day, + ); + }, + ), + TimeInputWidget( + value: TimeOfDay.fromDateTime(_date), + labelText: AppLocalizations.of(context).time, + onChanged: (time) { + _date = _date.copyWith( + hour: time.hour, + minute: time.minute, + second: 0, + ); + }, + ), + + // One value field per component + for (final child in widget._group.children) + DecimalInputWidget( + value: _values[child.id], + labelText: child.name, + suffixText: child.unit.isNotEmpty ? child.unit : widget._group.unit, + isRequired: true, + min: MeasurementEntry.minValue, + max: MeasurementEntry.maxValue, + onChanged: (value) => _values[child.id!] = value, + ), + + FormSubmitButton( + label: AppLocalizations.of(context).save, + onPressed: () async { + if (!_form.currentState!.validate()) { + return; + } + _form.currentState!.save(); + + final entries = widget._group.children + .map( + (child) => MeasurementEntry( + categoryId: child.id!, + date: _date, + value: _values[child.id]!, + notes: '', + ), + ) + .toList(); + await ref.read(measurementProvider.notifier).addGroupEntries(entries); + + if (context.mounted) { + Navigator.of(context).pop(); + } + }, + ), + ], + ), + ); + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 90930f8f0..b45efdef0 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -592,6 +592,14 @@ }, "measurementEntriesHelpText": "The unit used to measure the category such as 'cm' or '%'", "@measurementEntriesHelpText": {}, + "partOfGroup": "Part of group", + "@partOfGroup": { + "description": "Dropdown label: makes a measurement category a component of a multi-value group (e.g. blood pressure)" + }, + "noGroup": "No group", + "@noGroup": { + "description": "Dropdown option for a measurement category that is not part of any group" + }, "date": "Date", "@date": { "description": "The date of a workout log or body weight entry" diff --git a/pubspec.lock b/pubspec.lock index 76fb0255c..224fca8d6 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -193,14 +193,6 @@ packages: url: "https://pub.dev" source: hosted version: "5.1.2" - carp_serializable: - dependency: transitive - description: - name: carp_serializable - sha256: f039f8ea22e9437aef13fe7e9743c3761c76d401288dcb702eadd273c3e4dcef - url: "https://pub.dev" - source: hosted - version: "2.0.1" change: dependency: transitive description: @@ -743,14 +735,15 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" - health: + health_bridge: dependency: "direct main" description: - name: health - sha256: "2d9e119f3a1d281139f93149b41032b9f80b759960875bc784c5a25dd3c17524" - url: "https://pub.dev" - source: hosted - version: "13.3.1" + path: "." + ref: "51a567db9a97ccb15a9c1138aa4bcbdaf3d6c7b1" + resolved-ref: "51a567db9a97ccb15a9c1138aa4bcbdaf3d6c7b1" + url: "https://github.com/ytsni/health_bridge.git" + source: git + version: "1.0.0" hooks: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 4567b8a03..8ddb61f9c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -51,7 +51,15 @@ dependencies: flutter_zxing: ^2.3.0 font_awesome_flutter: ^11.0.0 freezed_annotation: ^3.1.0 - health: ^13.3.1 + # Temporarily swap `health` with a fork with Swift Package Manager support. + # Once that is available on upstream (see e.g. https://github.com/carp-dk/carp-health-flutter/issues/480 ) + # we can switch back. Note that if this doesn't happen in the near future we + # can just re-activate the cocoapods infrastructure. + # health: ^13.3.1 + health_bridge: + git: + url: https://github.com/ytsni/health_bridge.git + ref: 51a567db9a97ccb15a9c1138aa4bcbdaf3d6c7b1 http: ^1.6.0 image_picker: ^1.2.2 intl: ^0.20.2 diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 067e74602..ac8462028 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -2151,6 +2151,28 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get partOfGroup => + (super.noSuchMethod( + Invocation.getter(#partOfGroup), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#partOfGroup), + ), + ) + as String); + + @override + String get noGroup => + (super.noSuchMethod( + Invocation.getter(#noGroup), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#noGroup), + ), + ) + as String); + @override String get date => (super.noSuchMethod( diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index 2f3b66864..5f94eaf73 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -18,7 +18,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:health/health.dart'; +import 'package:health_bridge/health.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; diff --git a/test/features/health/providers/health_sync_test.mocks.dart b/test/features/health/providers/health_sync_test.mocks.dart index 938babcd9..db9fef171 100644 --- a/test/features/health/providers/health_sync_test.mocks.dart +++ b/test/features/health/providers/health_sync_test.mocks.dart @@ -5,7 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; -import 'package:health/health.dart' as _i5; +import 'package:health_bridge/health.dart' as _i5; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i3; import 'package:wger/features/health/models/health_reading.dart' as _i6; @@ -146,6 +146,17 @@ class MockMeasurementRepository extends _i1.Mock implements _i7.MeasurementRepos ) as _i4.Future); + @override + _i4.Future addLocalDriftGroupEntries( + List<_i9.MeasurementEntry>? entries, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftGroupEntries, [entries]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + @override _i4.Future deleteLocalDriftCategory(String? id) => (super.noSuchMethod( diff --git a/test/features/measurements/providers/measurement_notifier_test.mocks.dart b/test/features/measurements/providers/measurement_notifier_test.mocks.dart index 5a502e6c9..baf6519c2 100644 --- a/test/features/measurements/providers/measurement_notifier_test.mocks.dart +++ b/test/features/measurements/providers/measurement_notifier_test.mocks.dart @@ -88,6 +88,17 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos ) as _i3.Future); + @override + _i3.Future addLocalDriftGroupEntries( + List<_i5.MeasurementEntry>? entries, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftGroupEntries, [entries]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future deleteLocalDriftCategory(String? id) => (super.noSuchMethod( diff --git a/test/features/measurements/providers/measurement_repository_test.dart b/test/features/measurements/providers/measurement_repository_test.dart index 89a508cd5..36ec5ab7e 100644 --- a/test/features/measurements/providers/measurement_repository_test.dart +++ b/test/features/measurements/providers/measurement_repository_test.dart @@ -222,4 +222,69 @@ void main() { expect(emitted.map((c) => c.id), ['c2']); }); }); + + group('multi-value groups', () { + Future seedBloodPressureGroup() async { + await repo.addLocalDriftCategory( + MeasurementCategory(id: 'bp', name: 'Blood pressure', unit: 'mmHg'), + ); + await repo.addLocalDriftCategory( + MeasurementCategory(id: 'sys', name: 'Systolic', unit: 'mmHg', parentId: 'bp', order: 0), + ); + await repo.addLocalDriftCategory( + MeasurementCategory(id: 'dia', name: 'Diastolic', unit: 'mmHg', parentId: 'bp', order: 1), + ); + } + + test('watchAll attaches children to their parent in group order', () async { + await seedBloodPressureGroup(); + + final emitted = await repo.watchAll().first; + + final parent = emitted.firstWhere((c) => c.id == 'bp'); + expect(parent.isGroup, isTrue); + expect(parent.children.map((c) => c.id), ['sys', 'dia']); + }); + + test('watchAll sorts categories by order before name', () async { + await repo.addLocalDriftCategory( + MeasurementCategory(id: 'c1', name: 'Aaa', unit: 'cm', order: 5), + ); + await repo.addLocalDriftCategory( + MeasurementCategory(id: 'c2', name: 'Zzz', unit: 'cm', order: 1), + ); + + final emitted = await repo.watchAll().first; + + expect(emitted.map((c) => c.id), ['c2', 'c1']); + }); + + test('addLocalDriftGroupEntries inserts one entry per component', () async { + await seedBloodPressureGroup(); + final date = DateTime.utc(2026, 7, 10, 14, 32); + + await repo.addLocalDriftGroupEntries([ + MeasurementEntry(id: 'e1', categoryId: 'sys', date: date, value: 120, notes: ''), + MeasurementEntry(id: 'e2', categoryId: 'dia', date: date, value: 80, notes: ''), + ]); + + final emitted = await repo.watchAll().first; + final parent = emitted.firstWhere((c) => c.id == 'bp'); + expect(parent.children.first.entries.single.value, 120); + expect(parent.children.last.entries.single.value, 80); + expect( + parent.children.first.entries.single.date, + parent.children.last.entries.single.date, + ); + }); + + test('deleteLocalDriftCategory removes children along with the parent', () async { + await seedBloodPressureGroup(); + + await repo.deleteLocalDriftCategory('bp'); + + final emitted = await repo.watchAll().first; + expect(emitted, isEmpty); + }); + }); } diff --git a/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart b/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart index 91c79d7fe..8fa32a7e8 100644 --- a/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart +++ b/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart @@ -88,6 +88,17 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos ) as _i3.Future); + @override + _i3.Future addLocalDriftGroupEntries( + List<_i5.MeasurementEntry>? entries, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftGroupEntries, [entries]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future deleteLocalDriftCategory(String? id) => (super.noSuchMethod( diff --git a/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart b/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart index 15b6f34b1..c31c80f05 100644 --- a/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart +++ b/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart @@ -97,6 +97,17 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos ) as _i3.Future); + @override + _i3.Future addLocalDriftGroupEntries( + List<_i5.MeasurementEntry>? entries, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftGroupEntries, [entries]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future deleteLocalDriftCategory(String? id) => (super.noSuchMethod( diff --git a/test/screenshots/screenshots_01_dashboard.mocks.dart b/test/screenshots/screenshots_01_dashboard.mocks.dart index f5c2b54c0..f0af1a51a 100644 --- a/test/screenshots/screenshots_01_dashboard.mocks.dart +++ b/test/screenshots/screenshots_01_dashboard.mocks.dart @@ -509,6 +509,17 @@ class MockMeasurementRepository extends _i1.Mock implements _i23.MeasurementRepo ) as _i10.Future); + @override + _i10.Future addLocalDriftGroupEntries( + List<_i25.MeasurementEntry>? entries, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftGroupEntries, [entries]), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); + @override _i10.Future deleteLocalDriftCategory(String? id) => (super.noSuchMethod( diff --git a/test/screenshots/screenshots_04_measurements.mocks.dart b/test/screenshots/screenshots_04_measurements.mocks.dart index 686d60878..ab8aa659f 100644 --- a/test/screenshots/screenshots_04_measurements.mocks.dart +++ b/test/screenshots/screenshots_04_measurements.mocks.dart @@ -88,6 +88,17 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos ) as _i3.Future); + @override + _i3.Future addLocalDriftGroupEntries( + List<_i5.MeasurementEntry>? entries, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftGroupEntries, [entries]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future deleteLocalDriftCategory(String? id) => (super.noSuchMethod(