diff --git a/lib/features/health/models/health_metric.dart b/lib/features/health/models/health_metric.dart index 663ff5d2a..3959f7723 100644 --- a/lib/features/health/models/health_metric.dart +++ b/lib/features/health/models/health_metric.dart @@ -32,6 +32,7 @@ class HealthMetric { required this.unit, required this.toCategoryValue, this.components = const [], + this.aggregateDaily = false, this.enabled = false, this.disabledReason, }); @@ -59,6 +60,11 @@ class HealthMetric { /// stays measurement-free. final List components; + /// High-frequency metrics are not stored as raw samples but as one entry + /// per calendar day: the day's average as the value, min/max/sample count + /// in extra_data. Re-reads update the day in place as new samples arrive. + final bool aggregateDaily; + /// Whether V1 imports this metric. Disabled ones are declared for visibility /// and blocked on further groundwork (see [disabledReason]). final bool enabled; @@ -151,7 +157,19 @@ const List healthMetrics = [ canonicalName: 'Heart rate', unit: 'bpm', toCategoryValue: _identity, - disabledReason: 'High-frequency; needs a per-day aggregation strategy.', + aggregateDaily: true, + enabled: true, + ), + HealthMetric( + // Both platforms compute this themselves and write (typically) one value + // per day, so it is imported raw: no aggregation on our side, and the + // platform record uuid stays available for dedup. + metricType: MetricType.restingHeartRate, + dataType: HealthDataType.RESTING_HEART_RATE, + canonicalName: 'Resting heart rate', + unit: 'bpm', + toCategoryValue: _identity, + enabled: true, ), HealthMetric( metricType: MetricType.steps, diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index 51eda5edb..6ce413e81 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -22,6 +22,7 @@ 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'; +import 'package:wger/core/consts.dart'; import 'package:wger/core/shared_preferences.dart'; import 'package:wger/features/health/models/health_metric.dart'; import 'package:wger/features/health/models/health_reading.dart'; @@ -173,12 +174,9 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { } for (final (category, metricReadings) in targets) { - final (importedCount, newest) = await _importReadings( - metric, - metricReadings, - category, - source, - ); + final (importedCount, newest) = metric.aggregateDaily + ? await _importDailyAggregates(metric, metricReadings, category, source) + : await _importReadings(metric, metricReadings, category, source); synced += importedCount; if (newest != null && (latest == null || newest.isAfter(latest))) { latest = newest; @@ -267,6 +265,66 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { return (synced, latest); } + /// Imports [metricReadings] as one entry per calendar day: the day's + /// average as the value, min/max/sample count in extra_data. Days are keyed + /// by a synthetic externalId (`day-YYYY-MM-DD`), so a re-read within the + /// overlap window updates the aggregate in place when late samples change + /// it (the current day keeps growing until midnight). Returns the number of + /// written entries and the newest processed sample date. + Future<(int, DateTime?)> _importDailyAggregates( + HealthMetric metric, + Iterable metricReadings, + MeasurementCategory category, + String source, + ) async { + var synced = 0; + DateTime? latest; + final byDay = groupBy( + metricReadings, + (r) => DateTime(r.date.year, r.date.month, r.date.day), + ); + + for (final MapEntry(key: day, value: samples) in byDay.entries) { + final values = samples.map((r) => metric.toCategoryValue(r.value)).toList(); + // Round like the raw import: the server stores Decimal with 2 places + final value = (values.average * 100).roundToDouble() / 100; + final extraData = { + 'min': values.min, + 'max': values.max, + 'sample_count': values.length, + 'record_type': metric.dataType.name, + }; + + final externalId = 'day-${DateFormatLists.format(day)}'; + final existing = category.entries.firstWhereOrNull((e) => e.externalId == externalId); + if (existing == null) { + await _measurements.addLocalDrift( + MeasurementEntry( + categoryId: category.id!, + date: day, + value: value, + notes: '', + source: source, + externalId: externalId, + extraData: extraData, + ), + ); + synced++; + } else if (existing.value != value || + !const MapEquality().equals(existing.extraData, extraData)) { + await _measurements.updateLocalDrift(existing.copyWith(value: value, extraData: extraData)); + synced++; + } + + for (final sample in samples) { + if (latest == null || sample.date.isAfter(latest)) { + latest = sample.date; + } + } + } + return (synced, latest); + } + /// Builds an imported entry's `extra_data` from the reading's provenance. /// /// `unit` is the only key with server semantics (kg|lb, validated for body diff --git a/lib/features/health/providers/health_sync.g.dart b/lib/features/health/providers/health_sync.g.dart index e529cb1fd..cdd3ee67d 100644 --- a/lib/features/health/providers/health_sync.g.dart +++ b/lib/features/health/providers/health_sync.g.dart @@ -56,7 +56,7 @@ final class HealthSyncNotifierProvider } } -String _$healthSyncNotifierHash() => r'f301d60a828e5af34058c6aa21e2c41f62ec558b'; +String _$healthSyncNotifierHash() => r'6f1925f4c1da0ef550ce724b78748f3f53e6818e'; /// Imports body metrics from Apple Health / Health Connect into measurement /// categories. Read-only: reads the platform (via [HealthRepository]), writes to diff --git a/lib/features/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index b5ab1278d..ba4200ceb 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -34,6 +34,7 @@ enum MetricType { height('height'), bloodPressure('blood_pressure'), heartRate('heart_rate'), + restingHeartRate('resting_heart_rate'), steps('steps'), distance('distance'), energy('energy'), @@ -76,6 +77,7 @@ extension MeasurementMetricTypeL10n on MetricType { MetricType.height => l10n.metricHeight, MetricType.bloodPressure => l10n.metricBloodPressure, MetricType.heartRate => l10n.metricHeartRate, + MetricType.restingHeartRate => l10n.metricRestingHeartRate, MetricType.steps => l10n.metricSteps, MetricType.distance => l10n.metricDistance, MetricType.energy => l10n.metricEnergy, diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 6a2cf2deb..d97ad2586 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1166,6 +1166,7 @@ "metricHeight": "Körpergröße", "metricBloodPressure": "Blutdruck", "metricHeartRate": "Herzfrequenz", + "metricRestingHeartRate": "Ruhepuls", "metricSteps": "Schritte", "metricDistance": "Distanz", "metricEnergy": "Energie", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index ced6ec65c..ea6bb8cab 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -638,6 +638,10 @@ "@metricHeartRate": { "description": "Label for heart rate measurement" }, + "metricRestingHeartRate": "Resting heart rate", + "@metricRestingHeartRate": { + "description": "Label for resting heart rate measurement" + }, "metricSteps": "Steps", "@metricSteps": { "description": "Label for step count measurement" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 2b7271508..48ea3db0e 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1205,6 +1205,7 @@ "metricHeight": "Altura", "metricBloodPressure": "Presión arterial", "metricHeartRate": "Frecuencia cardíaca", + "metricRestingHeartRate": "Frecuencia cardíaca en reposo", "metricSteps": "Pasos", "metricDistance": "Distancia", "metricEnergy": "Energía", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 829fb7932..443b6901b 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1176,6 +1176,7 @@ "metricHeight": "Taille", "metricBloodPressure": "Pression artérielle", "metricHeartRate": "Fréquence cardiaque", + "metricRestingHeartRate": "Fréquence cardiaque au repos", "metricSteps": "Pas", "metricDistance": "Distance", "metricEnergy": "Énergie", diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 728839e1c..5743a625b 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -2236,6 +2236,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get metricRestingHeartRate => + (super.noSuchMethod( + Invocation.getter(#metricRestingHeartRate), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#metricRestingHeartRate), + ), + ) + as String); + @override String get metricSteps => (super.noSuchMethod( diff --git a/test/features/health/models/health_metric_test.dart b/test/features/health/models/health_metric_test.dart index 4013aaec7..88820ec89 100644 --- a/test/features/health/models/health_metric_test.dart +++ b/test/features/health/models/health_metric_test.dart @@ -26,7 +26,7 @@ HealthMetric _metric(MetricType type) => healthMetrics.firstWhere((m) => m.metri void main() { group('Enabled metric set', () { - test('only body fat, height, body weight and blood pressure are imported in V1', () { + test('only the V1 sample metrics are imported', () { expect( enabledHealthMetrics.map((m) => m.metricType), containsAll([ @@ -34,9 +34,17 @@ void main() { MetricType.height, MetricType.bodyWeight, MetricType.bloodPressure, + MetricType.heartRate, + MetricType.restingHeartRate, ]), ); - expect(enabledHealthMetrics.length, 4); + expect(enabledHealthMetrics.length, 6); + }); + + test('only raw heart rate is aggregated per day', () { + expect(_metric(MetricType.heartRate).aggregateDaily, isTrue); + // The platforms compute the resting rate per day themselves + expect(_metric(MetricType.restingHeartRate).aggregateDaily, isFalse); }); test('blood pressure reads both component types', () { diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index 8517c6d45..fb78c6df3 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -48,6 +48,7 @@ void main() { when(health.ensureAuthorized(any)).thenAnswer((_) async => true); when(health.sourceName).thenReturn('apple'); when(measurements.addLocalDrift(any)).thenAnswer((_) async {}); + when(measurements.updateLocalDrift(any)).thenAnswer((_) async {}); when(measurements.addLocalDriftCategory(any)).thenAnswer((_) async {}); }); @@ -354,6 +355,195 @@ void main() { }); }); + test('aggregates heart rate into one entry per day', () async { + when(measurements.getAllOnce()).thenAnswer((_) async => []); + stubReadings([ + HealthReading( + type: HealthDataType.HEART_RATE, + value: 60, + date: DateTime(2026, 1, 1, 8), + externalId: 'hr-1', + ), + HealthReading( + type: HealthDataType.HEART_RATE, + value: 71, + date: DateTime(2026, 1, 1, 20), + externalId: 'hr-2', + ), + HealthReading( + type: HealthDataType.HEART_RATE, + value: 64, + date: DateTime(2026, 1, 2, 9), + externalId: 'hr-3', + ), + ]); + + final count = await createNotifier().syncOnAppOpen(); + + // Three samples become two daily entries + expect(count, 2); + final entries = verify( + measurements.addLocalDrift(captureAny), + ).captured.cast(); + expect(entries, hasLength(2)); + + final day1 = entries.firstWhere((e) => e.externalId == 'day-2026-01-01'); + expect(day1.date, DateTime(2026, 1, 1)); + expect(day1.value, 65.5); // (60 + 71) / 2 + expect(day1.extraData, { + 'min': 60, + 'max': 71, + 'sample_count': 2, + 'record_type': 'HEART_RATE', + }); + + final day2 = entries.firstWhere((e) => e.externalId == 'day-2026-01-02'); + expect(day2.value, 64); + expect(day2.extraData?['sample_count'], 1); + + // The watermark tracks the newest sample, not the aggregate's date + expect( + await PreferenceHelper.instance.getLastHealthSyncTimestamp(), + DateTime(2026, 1, 2, 9).toIso8601String(), + ); + }); + + test('keeps resting heart rate in its own category, imported raw', () async { + when(measurements.getAllOnce()).thenAnswer((_) async => []); + stubReadings([ + HealthReading( + type: HealthDataType.HEART_RATE, + value: 70, + date: DateTime(2026, 1, 1, 8), + externalId: 'hr-1', + ), + HealthReading( + type: HealthDataType.RESTING_HEART_RATE, + value: 52, + date: DateTime(2026, 1, 1, 4), + externalId: 'rhr-1', + ), + ]); + + await createNotifier().syncOnAppOpen(); + + final categories = verify( + measurements.addLocalDriftCategory(captureAny), + ).captured.cast(); + final heartRate = categories.firstWhere((c) => c.metricType == MetricType.heartRate); + final resting = categories.firstWhere((c) => c.metricType == MetricType.restingHeartRate); + expect(resting.id, isNot(heartRate.id)); + + final entries = verify( + measurements.addLocalDrift(captureAny), + ).captured.cast(); + final restingEntry = entries.firstWhere((e) => e.categoryId == resting.id); + // Raw import: the platform record uuid and timestamp are kept as-is, + // no day- key and no aggregate extra_data + expect(restingEntry.externalId, 'rhr-1'); + expect(restingEntry.date, DateTime(2026, 1, 1, 4)); + expect(restingEntry.value, 52); + expect(restingEntry.extraData, isNot(contains('sample_count'))); + }); + + test('updates a daily aggregate when later samples change it', () async { + final existing = MeasurementCategory( + id: 'cat-hr', + name: 'Heart rate', + unit: 'bpm', + metricType: MetricType.heartRate, + entries: [ + MeasurementEntry( + id: 'e1', + categoryId: 'cat-hr', + date: DateTime(2026, 1, 1), + value: 60, + notes: '', + externalId: 'day-2026-01-01', + extraData: const { + 'min': 60, + 'max': 60, + 'sample_count': 1, + 'record_type': 'HEART_RATE', + }, + ), + ], + ); + when(measurements.getAllOnce()).thenAnswer((_) async => [existing]); + stubReadings([ + HealthReading( + type: HealthDataType.HEART_RATE, + value: 60, + date: DateTime(2026, 1, 1, 8), + externalId: 'hr-1', + ), + // A sample that arrived after the previous sync + HealthReading( + type: HealthDataType.HEART_RATE, + value: 70, + date: DateTime(2026, 1, 1, 20), + externalId: 'hr-2', + ), + ]); + + final count = await createNotifier().syncOnAppOpen(); + + expect(count, 1); + verifyNever(measurements.addLocalDrift(any)); + final updated = + verify(measurements.updateLocalDrift(captureAny)).captured.single as MeasurementEntry; + expect(updated.id, 'e1'); + expect(updated.value, 65); + expect(updated.extraData, { + 'min': 60, + 'max': 70, + 'sample_count': 2, + 'record_type': 'HEART_RATE', + }); + }); + + test('leaves an unchanged daily aggregate alone', () async { + final existing = MeasurementCategory( + id: 'cat-hr', + name: 'Heart rate', + unit: 'bpm', + metricType: MetricType.heartRate, + entries: [ + MeasurementEntry( + id: 'e1', + categoryId: 'cat-hr', + date: DateTime(2026, 1, 1), + value: 60, + notes: '', + externalId: 'day-2026-01-01', + extraData: const { + 'min': 60, + 'max': 60, + 'sample_count': 1, + 'record_type': 'HEART_RATE', + }, + ), + ], + ); + when(measurements.getAllOnce()).thenAnswer((_) async => [existing]); + stubReadings([ + HealthReading( + type: HealthDataType.HEART_RATE, + value: 60, + date: DateTime(2026, 1, 1, 8), + externalId: 'hr-1', + ), + ]); + + // Re-reading the same samples within the overlap window must not queue + // a pointless sync upload + final count = await createNotifier().syncOnAppOpen(); + + expect(count, 0); + verifyNever(measurements.addLocalDrift(any)); + verifyNever(measurements.updateLocalDrift(any)); + }); + test('imports blood pressure into an existing group by in-group order', () async { // The user's own group with different names: components map onto the // children by their in-group position, not by name