From 627b8b9fd834f50df010d0f18e048c2936a8bee4 Mon Sep 17 00:00:00 2001 From: John Weidner Date: Fri, 27 Mar 2026 16:32:53 -0500 Subject: [PATCH] fix: unit conversion on enable, dashboard refresh, and permission check - Pass isMetric to enableSync() so the initial sync from the settings toggle converts kg to lb when the user's profile is set to lb - Refresh BodyWeightProvider after sync from settings tile so the dashboard and weight screen update immediately - Fix DashboardWeightWidget to compute sensibleRange() inside the Consumer builder so it rebuilds when weight data changes - Add permission check in syncOnAppOpen() for app restart scenarios - Add unit tests for weight conversion logic and HealthSyncState Co-Authored-By: Claude Opus 4.6 (1M context) --- lib/providers/health_sync.dart | 7 +- lib/widgets/core/settings/health_sync.dart | 18 ++- lib/widgets/dashboard/widgets/weight.dart | 175 +++++++++++---------- test/providers/health_sync_test.dart | 83 ++++++++++ 4 files changed, 189 insertions(+), 94 deletions(-) create mode 100644 test/providers/health_sync_test.dart diff --git a/lib/providers/health_sync.dart b/lib/providers/health_sync.dart index 2ad16b152..098972273 100644 --- a/lib/providers/health_sync.dart +++ b/lib/providers/health_sync.dart @@ -95,8 +95,9 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { return Platform.isIOS; } - /// Enable health sync: request permissions, save preference, trigger initial sync - Future enableSync() async { + /// Enable health sync: request permissions, save preference, trigger initial sync. + /// If [isMetric] is false, converts kg values from the health platform to lb before POSTing. + Future enableSync({bool isMetric = true}) async { _logger.info('Enabling health sync'); await _health.configure(); @@ -114,7 +115,7 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { await PreferenceHelper.instance.setHealthSyncEnabled(true); state = state.copyWith(isEnabled: true); - return syncOnAppOpen(); + return syncOnAppOpen(isMetric: isMetric); } /// Disable health sync: clear preferences diff --git a/lib/widgets/core/settings/health_sync.dart b/lib/widgets/core/settings/health_sync.dart index 40fac6031..9622e8f94 100644 --- a/lib/widgets/core/settings/health_sync.dart +++ b/lib/widgets/core/settings/health_sync.dart @@ -18,7 +18,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:provider/provider.dart' as provider; +import 'package:wger/providers/body_weight.dart'; import 'package:wger/providers/health_sync.dart'; +import 'package:wger/providers/user.dart'; class HealthSyncSettingsTile extends ConsumerStatefulWidget { const HealthSyncSettingsTile({super.key}); @@ -62,11 +65,18 @@ class _HealthSyncSettingsTileState extends ConsumerState : (enabled) async { final notifier = ref.read(healthSyncProvider.notifier); if (enabled) { - final count = await notifier.enableSync(); + final profile = provider.Provider.of(context, listen: false).profile; + final isMetric = profile?.isMetric ?? true; + final count = await notifier.enableSync(isMetric: isMetric); if (context.mounted && count > 0) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Synced $count weight entries from Health')), - ); + // Refresh weight entries so the dashboard/weight screen updates + await provider.Provider.of(context, listen: false) + .fetchAndSetEntries(); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Synced $count weight entries from Health')), + ); + } } } else { await notifier.disableSync(); diff --git a/lib/widgets/dashboard/widgets/weight.dart b/lib/widgets/dashboard/widgets/weight.dart index d13e14199..23dee28c5 100644 --- a/lib/widgets/dashboard/widgets/weight.dart +++ b/lib/widgets/dashboard/widgets/weight.dart @@ -35,101 +35,102 @@ class DashboardWeightWidget extends StatelessWidget { @override Widget build(BuildContext context) { final profile = context.read().profile; - final weightProvider = context.read(); - - final (entriesAll, entries7dAvg) = sensibleRange( - weightProvider.items.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(), - ); return Consumer( - builder: (context, _, _) => Card( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - title: Text( - AppLocalizations.of(context).weight, - style: Theme.of(context).textTheme.headlineSmall, + builder: (context, weightProvider, _) { + final (entriesAll, entries7dAvg) = sensibleRange( + weightProvider.items.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(), + ); + + return Card( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + title: Text( + AppLocalizations.of(context).weight, + style: Theme.of(context).textTheme.headlineSmall, + ), + leading: FaIcon( + FontAwesomeIcons.weightScale, + color: Theme.of(context).textTheme.headlineSmall!.color, + ), ), - leading: FaIcon( - FontAwesomeIcons.weightScale, - color: Theme.of(context).textTheme.headlineSmall!.color, - ), - ), - Column( - children: [ - if (weightProvider.items.isNotEmpty) - Column( - children: [ - SizedBox( - height: 200, - child: MeasurementChartWidgetFl( - entriesAll, - weightUnit(profile!.isMetric, context), - avgs: entries7dAvg, + Column( + children: [ + if (weightProvider.items.isNotEmpty) + Column( + children: [ + SizedBox( + height: 200, + child: MeasurementChartWidgetFl( + entriesAll, + weightUnit(profile!.isMetric, context), + avgs: entries7dAvg, + ), ), - ), - if (entries7dAvg.isNotEmpty) - MeasurementOverallChangeWidget( - entries7dAvg.first, - entries7dAvg.last, - weightUnit(profile.isMetric, context), - ), - LayoutBuilder( - builder: (context, constraints) { - return SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: ConstrainedBox( - constraints: BoxConstraints(minWidth: constraints.maxWidth), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - TextButton( - child: Text( - AppLocalizations.of(context).goToDetailPage, - overflow: TextOverflow.ellipsis, + if (entries7dAvg.isNotEmpty) + MeasurementOverallChangeWidget( + entries7dAvg.first, + entries7dAvg.last, + weightUnit(profile.isMetric, context), + ), + LayoutBuilder( + builder: (context, constraints) { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: ConstrainedBox( + constraints: BoxConstraints(minWidth: constraints.maxWidth), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + TextButton( + child: Text( + AppLocalizations.of(context).goToDetailPage, + overflow: TextOverflow.ellipsis, + ), + onPressed: () { + Navigator.of(context).pushNamed(WeightScreen.routeName); + }, ), - onPressed: () { - Navigator.of(context).pushNamed(WeightScreen.routeName); - }, - ), - IconButton( - icon: const Icon(Icons.add), - onPressed: () { - Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).newEntry, - WeightForm( - weightProvider.getNewestEntry()?.copyWith( - id: null, - date: DateTime.now(), + IconButton( + icon: const Icon(Icons.add), + onPressed: () { + Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).newEntry, + WeightForm( + weightProvider.getNewestEntry()?.copyWith( + id: null, + date: DateTime.now(), + ), ), ), - ), - ); - }, - ), - ], + ); + }, + ), + ], + ), ), - ), - ); - }, - ), - ], - ) - else - NothingFound( - AppLocalizations.of(context).noWeightEntries, - AppLocalizations.of(context).newEntry, - WeightForm(), - ), - ], - ), - ], - ), - ), + ); + }, + ), + ], + ) + else + NothingFound( + AppLocalizations.of(context).noWeightEntries, + AppLocalizations.of(context).newEntry, + WeightForm(), + ), + ], + ), + ], + ), + ); + }, ); } } diff --git a/test/providers/health_sync_test.dart b/test/providers/health_sync_test.dart new file mode 100644 index 000000000..73b23d460 --- /dev/null +++ b/test/providers/health_sync_test.dart @@ -0,0 +1,83 @@ +/* + * This file is part of wger Workout Manager . + * 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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/providers/health_sync.dart'; + +/// Mirrors the conversion logic in HealthSyncNotifier.syncOnAppOpen +double _convertWeight(double weightKg, {required bool isMetric}) { + return isMetric ? weightKg : weightKg * kgToLb; +} + +void main() { + group('Health sync constants', () { + test('kgToLb conversion factor is correct', () { + // 1 kg = 2.20462 lb + expect(kgToLb, closeTo(2.20462, 0.00001)); + }); + + test('Initial sync lookback is 30 days', () { + expect(healthSyncInitialDays, 30); + }); + }); + + group('Weight unit conversion', () { + test('kg value is converted to lb correctly', () { + const weightKg = 85.0; + final weightLb = (weightKg * kgToLb * 100).roundToDouble() / 100; + expect(weightLb, closeTo(187.39, 0.01)); + }); + + test('kg value stays as-is when metric', () { + const weightKg = 85.0; + final weight = _convertWeight(weightKg, isMetric: true); + expect(weight, 85.0); + }); + + test('kg value is converted when imperial', () { + const weightKg = 85.0; + final weight = _convertWeight(weightKg, isMetric: false); + expect(weight, closeTo(187.39, 0.01)); + }); + + test('conversion rounds to 2 decimal places', () { + const weightKg = 85.12345; + final weight = weightKg * kgToLb; + final rounded = (weight * 100).roundToDouble() / 100; + // 85.12345 * 2.20462 = 187.66... + expect(rounded.toString().split('.').last.length, lessThanOrEqualTo(2)); + }); + }); + + group('HealthSyncState', () { + test('default state has sync disabled', () { + const state = HealthSyncState(); + expect(state.isEnabled, false); + expect(state.isSyncing, false); + expect(state.lastSyncCount, 0); + }); + + test('copyWith updates individual fields', () { + const state = HealthSyncState(); + final updated = state.copyWith(isEnabled: true, lastSyncCount: 5); + expect(updated.isEnabled, true); + expect(updated.isSyncing, false); + expect(updated.lastSyncCount, 5); + }); + }); +}