From a92897b2f9b8e97b69b841fa05925e29e73bc277 Mon Sep 17 00:00:00 2001 From: John Weidner Date: Fri, 27 Mar 2026 14:12:49 -0500 Subject: [PATCH 001/484] feat: add automatic weight sync from Apple Health and Google Health Connect Import body weight data from Apple Health (iOS) and Google Health Connect (Android) into wger when the app is opened. Uses the Flutter `health` package for cross-platform access. Feature is opt-in via a settings toggle. Key changes: - Add HealthSyncNotifier (Riverpod) for sync orchestration - Add HealthSyncSettingsTile in settings page - Add health package dependency and platform permissions - Fix WeightEntry.copyWith parameter type (int? -> num?) - Fix BodyWeightProvider.findByDate() to use calendar-date comparison - Raise Android minSdkVersion to 26 (Health Connect requirement) - Change MainActivity to extend FlutterFragmentActivity Co-Authored-By: Claude Opus 4.6 (1M context) --- android/app/build.gradle | 2 +- android/app/src/main/AndroidManifest.xml | 24 ++ .../kotlin/de/wger/flutter/MainActivity.kt | 4 +- ios/Runner/Info.plist | 2 + ios/Runner/Runner.entitlements | 6 + lib/helpers/shared_preferences.dart | 26 ++ lib/models/body_weight/weight_entry.dart | 2 +- lib/models/body_weight/weight_entry.g.dart | 11 +- lib/providers/body_weight.dart | 7 +- lib/providers/health_sync.dart | 224 ++++++++++++++++++ lib/providers/health_sync.g.dart | 63 +++++ lib/screens/home_tabs_screen.dart | 10 + lib/widgets/core/settings.dart | 3 + lib/widgets/core/settings/health_sync.dart | 77 ++++++ pubspec.lock | 40 ++++ pubspec.yaml | 1 + test/core/settings_test.dart | 27 ++- test/weight/weight_model_test.dart | 14 ++ test/weight/weight_provider_test.dart | 17 ++ 19 files changed, 539 insertions(+), 21 deletions(-) create mode 100644 lib/providers/health_sync.dart create mode 100644 lib/providers/health_sync.g.dart create mode 100644 lib/widgets/core/settings/health_sync.dart diff --git a/android/app/build.gradle b/android/app/build.gradle index 1f912e63b..0ffb8cfdd 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -39,7 +39,7 @@ android { defaultConfig { // Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "de.wger.flutter" - minSdkVersion flutter.minSdkVersion + minSdkVersion 26 targetSdk = flutter.targetSdkVersion versionCode = flutter.versionCode versionName = flutter.versionName diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 4e50bad4a..2f8ef5362 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -9,11 +9,19 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/de/wger/flutter/MainActivity.kt b/android/app/src/main/kotlin/de/wger/flutter/MainActivity.kt index 421496c68..3e9f4cd14 100644 --- a/android/app/src/main/kotlin/de/wger/flutter/MainActivity.kt +++ b/android/app/src/main/kotlin/de/wger/flutter/MainActivity.kt @@ -1,6 +1,6 @@ package de.wger.flutter -import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.android.FlutterFragmentActivity -class MainActivity: FlutterActivity() { +class MainActivity: FlutterFragmentActivity() { } diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 9cec73d2b..aa101c62c 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -26,6 +26,8 @@ NSCameraUsageDescription Workout photos + NSHealthShareUsageDescription + wger uses your health data to automatically sync weight measurements from your smart scale UIApplicationSceneManifest UIApplicationSupportsMultipleScenes diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements index 903def2af..57cd45923 100644 --- a/ios/Runner/Runner.entitlements +++ b/ios/Runner/Runner.entitlements @@ -4,5 +4,11 @@ aps-environment development + com.apple.developer.healthkit + + com.apple.developer.healthkit.access + + health-records + diff --git a/lib/helpers/shared_preferences.dart b/lib/helpers/shared_preferences.dart index cdab8a537..9501a53ae 100644 --- a/lib/helpers/shared_preferences.dart +++ b/lib/helpers/shared_preferences.dart @@ -68,4 +68,30 @@ class PreferenceHelper { ); } } + + // Health sync + static const _healthSyncEnabledKey = 'healthSyncEnabled'; + static const _lastHealthSyncTimestampKey = 'lastHealthSyncTimestamp'; + + Future setHealthSyncEnabled(bool value) async { + await PreferenceHelper.asyncPref.setBool(_healthSyncEnabledKey, value); + } + + Future getHealthSyncEnabled() async { + final value = await PreferenceHelper.asyncPref.getBool(_healthSyncEnabledKey); + return value ?? false; + } + + Future setLastHealthSyncTimestamp(String value) async { + await PreferenceHelper.asyncPref.setString(_lastHealthSyncTimestampKey, value); + } + + Future getLastHealthSyncTimestamp() async { + return PreferenceHelper.asyncPref.getString(_lastHealthSyncTimestampKey); + } + + Future clearHealthSyncPreferences() async { + await PreferenceHelper.asyncPref.remove(_healthSyncEnabledKey); + await PreferenceHelper.asyncPref.remove(_lastHealthSyncTimestampKey); + } } diff --git a/lib/models/body_weight/weight_entry.dart b/lib/models/body_weight/weight_entry.dart index 8daada31c..46601af05 100644 --- a/lib/models/body_weight/weight_entry.dart +++ b/lib/models/body_weight/weight_entry.dart @@ -40,7 +40,7 @@ class WeightEntry { } } - WeightEntry copyWith({int? id, int? weight, DateTime? date}) => WeightEntry( + WeightEntry copyWith({int? id, num? weight, DateTime? date}) => WeightEntry( id: id, weight: weight ?? this.weight, date: date ?? this.date, diff --git a/lib/models/body_weight/weight_entry.g.dart b/lib/models/body_weight/weight_entry.g.dart index 286c98661..fbaaa9c68 100644 --- a/lib/models/body_weight/weight_entry.g.dart +++ b/lib/models/body_weight/weight_entry.g.dart @@ -15,8 +15,9 @@ WeightEntry _$WeightEntryFromJson(Map json) { ); } -Map _$WeightEntryToJson(WeightEntry instance) => { - 'id': instance.id, - 'weight': numToString(instance.weight), - 'date': dateToUtcIso8601(instance.date), -}; +Map _$WeightEntryToJson(WeightEntry instance) => + { + 'id': instance.id, + 'weight': numToString(instance.weight), + 'date': dateToUtcIso8601(instance.date), + }; diff --git a/lib/providers/body_weight.dart b/lib/providers/body_weight.dart index cc93f7c35..8af2f4b3c 100644 --- a/lib/providers/body_weight.dart +++ b/lib/providers/body_weight.dart @@ -58,7 +58,12 @@ class BodyWeightProvider with ChangeNotifier { WeightEntry? findByDate(DateTime date) { try { - return _entries.firstWhere((plan) => plan.date == date); + return _entries.firstWhere( + (entry) => + entry.date.year == date.year && + entry.date.month == date.month && + entry.date.day == date.day, + ); } on StateError { return null; } diff --git a/lib/providers/health_sync.dart b/lib/providers/health_sync.dart new file mode 100644 index 000000000..2bcfde48c --- /dev/null +++ b/lib/providers/health_sync.dart @@ -0,0 +1,224 @@ +/* + * 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 'dart:io'; + +import 'package:health/health.dart'; +import 'package:logging/logging.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:wger/helpers/shared_preferences.dart'; +import 'package:wger/models/body_weight/weight_entry.dart'; +import 'package:wger/providers/base_provider.dart'; +import 'package:wger/providers/wger_base_riverpod.dart'; + +part 'health_sync.g.dart'; + +class HealthSyncState { + final bool isEnabled; + final bool isSyncing; + final int lastSyncCount; + + const HealthSyncState({ + this.isEnabled = false, + this.isSyncing = false, + this.lastSyncCount = 0, + }); + + HealthSyncState copyWith({ + bool? isEnabled, + bool? isSyncing, + int? lastSyncCount, + }) { + return HealthSyncState( + isEnabled: isEnabled ?? this.isEnabled, + isSyncing: isSyncing ?? this.isSyncing, + lastSyncCount: lastSyncCount ?? this.lastSyncCount, + ); + } +} + +/// Initial sync lookback period +const int healthSyncInitialDays = 30; + +@Riverpod(keepAlive: true) +class HealthSyncNotifier extends _$HealthSyncNotifier { + final _logger = Logger('HealthSyncNotifier'); + late final Health _health; + late final WgerBaseProvider _baseProvider; + + static const _weightEntryUrl = 'weightentry'; + + @override + HealthSyncState build() { + _health = Health(); + _baseProvider = ref.read(wgerBaseProvider); + + // Load persisted sync preference on startup + _loadPersistedState(); + + return const HealthSyncState(); + } + + Future _loadPersistedState() async { + final enabled = await PreferenceHelper.instance.getHealthSyncEnabled(); + if (enabled) { + state = state.copyWith(isEnabled: true); + } + } + + /// Check if the health platform is available on this device + Future isAvailable() async { + if (Platform.isAndroid) { + await _health.configure(); + final status = await _health.getHealthConnectSdkStatus(); + return status == HealthConnectSdkStatus.sdkAvailable; + } + // iOS always has HealthKit available + return Platform.isIOS; + } + + /// Enable health sync: request permissions, save preference, trigger initial sync + Future enableSync() async { + _logger.info('Enabling health sync'); + + await _health.configure(); + + final authorized = await _health.requestAuthorization( + [HealthDataType.WEIGHT], + permissions: [HealthDataAccess.READ], + ); + + if (!authorized) { + _logger.warning('Health permissions not granted'); + return 0; + } + + await PreferenceHelper.instance.setHealthSyncEnabled(true); + state = state.copyWith(isEnabled: true); + + return syncOnAppOpen(); + } + + /// Disable health sync: clear preferences + Future disableSync() async { + _logger.info('Disabling health sync'); + await PreferenceHelper.instance.clearHealthSyncPreferences(); + state = const HealthSyncState(); + } + + /// Main sync method: read weight data from health platform, post new entries to backend + Future syncOnAppOpen({List? existingEntries}) async { + final prefs = PreferenceHelper.instance; + final enabled = await prefs.getHealthSyncEnabled(); + if (!enabled) { + return 0; + } + + if (state.isSyncing) { + return 0; + } + state = state.copyWith(isEnabled: true, isSyncing: true); + + try { + await _health.configure(); + + // Determine the start time for the query + final lastSyncStr = await prefs.getLastHealthSyncTimestamp(); + final DateTime startTime; + if (lastSyncStr != null) { + startTime = DateTime.parse(lastSyncStr); + } else { + startTime = DateTime.now().subtract(const Duration(days: healthSyncInitialDays)); + } + final endTime = DateTime.now(); + + _logger.info('Syncing weight data from $startTime to $endTime'); + + // Read weight data from health platform + List dataPoints = await _health.getHealthDataFromTypes( + types: [HealthDataType.WEIGHT], + startTime: startTime, + endTime: endTime, + ); + dataPoints = _health.removeDuplicates(dataPoints); + + if (dataPoints.isEmpty) { + _logger.info('No new weight data from health platform'); + state = state.copyWith(isSyncing: false, lastSyncCount: 0); + return 0; + } + + _logger.info('Found ${dataPoints.length} weight data points'); + + int syncedCount = 0; + DateTime? latestSynced; + + for (final point in dataPoints) { + try { + final value = (point.value as NumericHealthValue).numericValue; + final weightKg = (value * 100).roundToDouble() / 100; // Round to 2 decimal places + final timestamp = point.dateFrom; + + // Fallback dedup: skip if an entry with the same timestamp exists locally + if (existingEntries != null) { + final duplicate = existingEntries.any( + (e) => + e.date.year == timestamp.year && + e.date.month == timestamp.month && + e.date.day == timestamp.day && + e.date.hour == timestamp.hour && + e.date.minute == timestamp.minute, + ); + if (duplicate) { + _logger.fine('Skipping duplicate entry for $timestamp'); + continue; + } + } + + // POST to backend with original timestamp + final entry = WeightEntry(weight: weightKg, date: timestamp); + await _baseProvider.post( + entry.toJson(), + _baseProvider.makeUrl(_weightEntryUrl), + ); + + syncedCount++; + if (latestSynced == null || timestamp.isAfter(latestSynced)) { + latestSynced = timestamp; + } + } catch (e) { + _logger.warning('Failed to sync weight entry: $e'); + // Best-effort: continue with next entry + } + } + + // Update last sync timestamp to the latest successfully synced reading + if (latestSynced != null) { + await prefs.setLastHealthSyncTimestamp(latestSynced.toIso8601String()); + } + + _logger.info('Synced $syncedCount weight entries'); + state = state.copyWith(isSyncing: false, lastSyncCount: syncedCount); + return syncedCount; + } catch (e) { + _logger.warning('Health sync failed: $e'); + state = state.copyWith(isSyncing: false, lastSyncCount: 0); + return 0; + } + } +} diff --git a/lib/providers/health_sync.g.dart b/lib/providers/health_sync.g.dart new file mode 100644 index 000000000..a10c6cec2 --- /dev/null +++ b/lib/providers/health_sync.g.dart @@ -0,0 +1,63 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'health_sync.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(HealthSyncNotifier) +final healthSyncProvider = HealthSyncNotifierProvider._(); + +final class HealthSyncNotifierProvider + extends $NotifierProvider { + HealthSyncNotifierProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'healthSyncProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$healthSyncNotifierHash(); + + @$internal + @override + HealthSyncNotifier create() => HealthSyncNotifier(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(HealthSyncState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$healthSyncNotifierHash() => + r'7a0929b0b1660729da0f0fc3a9a1a70af71cf894'; + +abstract class _$HealthSyncNotifier extends $Notifier { + HealthSyncState build(); + @$mustCallSuper + @override + void runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + HealthSyncState, + Object?, + Object? + >; + element.handleCreate(ref, build); + } +} diff --git a/lib/screens/home_tabs_screen.dart b/lib/screens/home_tabs_screen.dart index 10de168f7..8371cd98c 100644 --- a/lib/screens/home_tabs_screen.dart +++ b/lib/screens/home_tabs_screen.dart @@ -28,6 +28,7 @@ import 'package:wger/providers/auth.dart'; import 'package:wger/providers/body_weight.dart'; import 'package:wger/providers/exercises.dart'; import 'package:wger/providers/gallery.dart'; +import 'package:wger/providers/health_sync.dart'; import 'package:wger/providers/measurement.dart'; import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/routines.dart'; @@ -147,6 +148,15 @@ class _HomeTabsScreenState extends ConsumerState } authProvider.dataInit = true; + + // Trigger health sync after weight entries are loaded (non-blocking) + final weightProviderForSync = context.read(); + final healthNotifier = ref.read(healthSyncProvider.notifier); + healthNotifier.syncOnAppOpen(existingEntries: weightProviderForSync.items).then((syncCount) { + if (syncCount > 0) { + weightProviderForSync.fetchAndSetEntries(); + } + }); } @override diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index 014b281d9..3469acd73 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -21,6 +21,7 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/screens/settings_plates_screen.dart'; import './settings/exercise_cache.dart'; +import './settings/health_sync.dart'; import './settings/ingredient_cache.dart'; import './settings/theme.dart'; @@ -42,6 +43,8 @@ class SettingsPage extends StatelessWidget { ), const SettingsExerciseCache(), const SettingsIngredientCache(), + ListTile(title: Text('Health', style: Theme.of(context).textTheme.headlineSmall)), + const HealthSyncSettingsTile(), ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)), const SettingsTheme(), ListTile( diff --git a/lib/widgets/core/settings/health_sync.dart b/lib/widgets/core/settings/health_sync.dart new file mode 100644 index 000000000..40fac6031 --- /dev/null +++ b/lib/widgets/core/settings/health_sync.dart @@ -0,0 +1,77 @@ +/* + * 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/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/providers/health_sync.dart'; + +class HealthSyncSettingsTile extends ConsumerStatefulWidget { + const HealthSyncSettingsTile({super.key}); + + @override + ConsumerState createState() => _HealthSyncSettingsTileState(); +} + +class _HealthSyncSettingsTileState extends ConsumerState { + bool? _isAvailable; + + @override + void initState() { + super.initState(); + _checkAvailability(); + } + + Future _checkAvailability() async { + final notifier = ref.read(healthSyncProvider.notifier); + final available = await notifier.isAvailable(); + if (mounted) { + setState(() => _isAvailable = available); + } + } + + @override + Widget build(BuildContext context) { + // Hide entirely if platform check hasn't completed or is unavailable + if (_isAvailable == null || _isAvailable == false) { + return const SizedBox.shrink(); + } + + final syncState = ref.watch(healthSyncProvider); + + return SwitchListTile( + title: const Text('Health sync'), + subtitle: const Text('Import weight from Apple Health or Health Connect'), + value: syncState.isEnabled, + onChanged: syncState.isSyncing + ? null + : (enabled) async { + final notifier = ref.read(healthSyncProvider.notifier); + if (enabled) { + final count = await notifier.enableSync(); + if (context.mounted && count > 0) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Synced $count weight entries from Health')), + ); + } + } else { + await notifier.disableSync(); + } + }, + ); + } +} diff --git a/pubspec.lock b/pubspec.lock index ab5661fdc..5a89f2a0e 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -153,6 +153,14 @@ 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: @@ -297,6 +305,22 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.3" + device_info_plus: + dependency: transitive + description: + name: device_info_plus + sha256: "4df8babf73058181227e18b08e6ea3520cf5fc5d796888d33b7cb0f33f984b7c" + url: "https://pub.dev" + source: hosted + version: "12.3.0" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f + url: "https://pub.dev" + source: hosted + version: "7.0.3" drift: dependency: "direct main" description: @@ -615,6 +639,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.2" + health: + dependency: "direct main" + description: + name: health + sha256: "2d9e119f3a1d281139f93149b41032b9f80b759960875bc784c5a25dd3c17524" + url: "https://pub.dev" + source: hosted + version: "13.3.1" hooks: dependency: transitive description: @@ -1649,6 +1681,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.15.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae" + url: "https://pub.dev" + source: hosted + version: "2.1.0" xdg_directories: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 036307e83..c99b5c904 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -50,6 +50,7 @@ dependencies: font_awesome_flutter: ^11.0.0 freezed_annotation: ^3.0.0 get_it: ^8.3.0 + health: ^13.3.1 http: ^1.6.0 image_picker: ^1.2.1 intl: ^0.20.0 diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index f4869b4e6..003fb7dee 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -17,6 +17,7 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -57,17 +58,21 @@ void main() { }); Widget createSettingsScreen({locale = 'en'}) { - return MultiProvider( - providers: [ - ChangeNotifierProvider(create: (context) => mockNutritionProvider), - ChangeNotifierProvider(create: (context) => mockExerciseProvider), - ChangeNotifierProvider(create: (context) => mockUserProvider), - ], - child: MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: const SettingsPage(), + return ProviderScope( + child: MultiProvider( + providers: [ + ChangeNotifierProvider( + create: (context) => mockNutritionProvider, + ), + ChangeNotifierProvider(create: (context) => mockExerciseProvider), + ChangeNotifierProvider(create: (context) => mockUserProvider), + ], + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const SettingsPage(), + ), ), ); } diff --git a/test/weight/weight_model_test.dart b/test/weight/weight_model_test.dart index ebc283246..e6e6eb0d1 100644 --- a/test/weight/weight_model_test.dart +++ b/test/weight/weight_model_test.dart @@ -59,5 +59,19 @@ void main() { expect(weightModel.weight, 80); expect(weightModel.date, DateTime.utc(2020, 10, 01)); }); + + test('copyWith preserves decimal weight values', () { + final entry = WeightEntry(id: 1, weight: 80.5, date: DateTime.utc(2020, 10, 01)); + final copied = entry.copyWith(weight: 81.3); + + expect(copied.weight, 81.3); + }); + + test('copyWith with null weight keeps original value', () { + final entry = WeightEntry(id: 1, weight: 80.5, date: DateTime.utc(2020, 10, 01)); + final copied = entry.copyWith(); + + expect(copied.weight, 80.5); + }); }); } diff --git a/test/weight/weight_provider_test.dart b/test/weight/weight_provider_test.dart index 61ceffe80..e21d22094 100644 --- a/test/weight/weight_provider_test.dart +++ b/test/weight/weight_provider_test.dart @@ -88,6 +88,23 @@ void main() { expect(weightEntryNew.weight, 80); }); + test('findByDate matches by calendar date regardless of time', () { + final provider = BodyWeightProvider(mockBaseProvider); + provider.items = [ + WeightEntry(id: 1, weight: 80, date: DateTime(2021, 3, 15, 7, 15)), + WeightEntry(id: 2, weight: 81, date: DateTime(2021, 3, 16, 20, 0)), + ]; + + // Same calendar date, different time + final found = provider.findByDate(DateTime(2021, 3, 15, 22, 30)); + expect(found, isNotNull); + expect(found!.id, 1); + + // No entry for this date + final notFound = provider.findByDate(DateTime(2021, 3, 17)); + expect(notFound, isNull); + }); + test('Test deleting an existing weight entry', () async { // Arrange final uri = Uri( From 7bab9b617ef44ae0765ec4a1e1b4891ea10c6b88 Mon Sep 17 00:00:00 2001 From: John Weidner Date: Fri, 27 Mar 2026 15:44:34 -0500 Subject: [PATCH 002/484] feat: add unit label to weight form and convert health sync values - Show "Weight (kg)" or "Weight (lb)" on the weight entry form based on the user's profile preference - Convert health sync values from kg to lb before POSTing when the user's profile is set to lb - Check/request health permissions on sync to handle app restart - Fix weight form tests to provide UserProvider mock Co-Authored-By: Claude Opus 4.6 (1M context) --- lib/providers/health_sync.dart | 33 +++- lib/screens/home_tabs_screen.dart | 6 +- lib/widgets/weight/forms.dart | 8 +- test/weight/weight_form_test.dart | 28 +++- test/weight/weight_form_test.mocks.dart | 211 ++++++++++++++++++++++++ 5 files changed, 275 insertions(+), 11 deletions(-) create mode 100644 test/weight/weight_form_test.mocks.dart diff --git a/lib/providers/health_sync.dart b/lib/providers/health_sync.dart index 2bcfde48c..2ad16b152 100644 --- a/lib/providers/health_sync.dart +++ b/lib/providers/health_sync.dart @@ -55,6 +55,9 @@ class HealthSyncState { /// Initial sync lookback period const int healthSyncInitialDays = 30; +/// Conversion factor from kg to lb +const double kgToLb = 2.20462; + @Riverpod(keepAlive: true) class HealthSyncNotifier extends _$HealthSyncNotifier { final _logger = Logger('HealthSyncNotifier'); @@ -121,8 +124,9 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { state = const HealthSyncState(); } - /// Main sync method: read weight data from health platform, post new entries to backend - Future syncOnAppOpen({List? existingEntries}) async { + /// Main sync method: read weight data from health platform, post new entries to backend. + /// If [isMetric] is false, converts kg values from the health platform to lb before POSTing. + Future syncOnAppOpen({List? existingEntries, bool isMetric = true}) async { final prefs = PreferenceHelper.instance; final enabled = await prefs.getHealthSyncEnabled(); if (!enabled) { @@ -137,6 +141,23 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { try { await _health.configure(); + // Ensure we have permission to read weight data + final hasPerms = await _health.hasPermissions( + [HealthDataType.WEIGHT], + permissions: [HealthDataAccess.READ], + ); + if (hasPerms != true) { + final authorized = await _health.requestAuthorization( + [HealthDataType.WEIGHT], + permissions: [HealthDataAccess.READ], + ); + if (!authorized) { + _logger.warning('Health permissions not granted during sync'); + state = state.copyWith(isSyncing: false); + return 0; + } + } + // Determine the start time for the query final lastSyncStr = await prefs.getLastHealthSyncTimestamp(); final DateTime startTime; @@ -171,9 +192,13 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { for (final point in dataPoints) { try { final value = (point.value as NumericHealthValue).numericValue; - final weightKg = (value * 100).roundToDouble() / 100; // Round to 2 decimal places + final weightKg = value.toDouble(); final timestamp = point.dateFrom; + // Convert to user's preferred unit + final weight = isMetric ? weightKg : weightKg * kgToLb; + final weightRounded = (weight * 100).roundToDouble() / 100; + // Fallback dedup: skip if an entry with the same timestamp exists locally if (existingEntries != null) { final duplicate = existingEntries.any( @@ -191,7 +216,7 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { } // POST to backend with original timestamp - final entry = WeightEntry(weight: weightKg, date: timestamp); + final entry = WeightEntry(weight: weightRounded, date: timestamp); await _baseProvider.post( entry.toJson(), _baseProvider.makeUrl(_weightEntryUrl), diff --git a/lib/screens/home_tabs_screen.dart b/lib/screens/home_tabs_screen.dart index 8371cd98c..7dc2c9787 100644 --- a/lib/screens/home_tabs_screen.dart +++ b/lib/screens/home_tabs_screen.dart @@ -151,8 +151,12 @@ class _HomeTabsScreenState extends ConsumerState // Trigger health sync after weight entries are loaded (non-blocking) final weightProviderForSync = context.read(); + final userProviderForSync = context.read(); + final isMetric = userProviderForSync.profile?.isMetric ?? true; final healthNotifier = ref.read(healthSyncProvider.notifier); - healthNotifier.syncOnAppOpen(existingEntries: weightProviderForSync.items).then((syncCount) { + healthNotifier + .syncOnAppOpen(existingEntries: weightProviderForSync.items, isMetric: isMetric) + .then((syncCount) { if (syncCount > 0) { weightProviderForSync.fetchAndSetEntries(); } diff --git a/lib/widgets/weight/forms.dart b/lib/widgets/weight/forms.dart index c3e182554..34eeffbb0 100644 --- a/lib/widgets/weight/forms.dart +++ b/lib/widgets/weight/forms.dart @@ -24,6 +24,8 @@ import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; import 'package:wger/providers/body_weight.dart'; +import 'package:wger/providers/user.dart'; +import 'package:wger/widgets/measurements/charts.dart'; class WeightForm extends StatelessWidget { final _form = GlobalKey(); @@ -41,6 +43,10 @@ class WeightForm extends StatelessWidget { final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode); final timeFormat = DateFormat.Hm(Localizations.localeOf(context).languageCode); + final profile = context.read().profile; + final unitLabel = profile != null + ? weightUnit(profile.isMetric, context) + : AppLocalizations.of(context).kg; if (weightController.text.isEmpty && _weightEntry.weight != 0) { weightController.text = numberFormat.format(_weightEntry.weight); @@ -127,7 +133,7 @@ class WeightForm extends StatelessWidget { TextFormField( key: const Key('weightInput'), decoration: InputDecoration( - labelText: AppLocalizations.of(context).weight, + labelText: '${AppLocalizations.of(context).weight} ($unitLabel)', prefix: Row( mainAxisSize: MainAxisSize.min, children: [ diff --git a/test/weight/weight_form_test.dart b/test/weight/weight_form_test.dart index 0a821a377..6e5a8140c 100644 --- a/test/weight/weight_form_test.dart +++ b/test/weight/weight_form_test.dart @@ -18,19 +18,37 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; +import 'package:wger/models/user/profile.dart'; +import 'package:wger/providers/user.dart'; import 'package:wger/widgets/weight/forms.dart'; import '../../test_data/body_weight.dart'; +import '../../test_data/profile.dart'; +import 'weight_form_test.mocks.dart'; +@GenerateMocks([UserProvider]) void main() { + late MockUserProvider mockUserProvider; + + setUp(() { + mockUserProvider = MockUserProvider(); + when(mockUserProvider.profile).thenReturn(tProfile1); + }); + Widget createWeightForm({locale = 'en', weightEntry = WeightEntry}) { - return MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold(body: WeightForm(weightEntry)), + return ChangeNotifierProvider.value( + value: mockUserProvider, + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: WeightForm(weightEntry)), + ), ); } diff --git a/test/weight/weight_form_test.mocks.dart b/test/weight/weight_form_test.mocks.dart new file mode 100644 index 000000000..a998889d4 --- /dev/null +++ b/test/weight/weight_form_test.mocks.dart @@ -0,0 +1,211 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/weight/weight_form_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i7; +import 'dart:ui' as _i8; + +import 'package:flutter/material.dart' as _i5; +import 'package:mockito/mockito.dart' as _i1; +import 'package:shared_preferences/shared_preferences.dart' as _i3; +import 'package:wger/models/user/profile.dart' as _i6; +import 'package:wger/providers/base_provider.dart' as _i2; +import 'package:wger/providers/user.dart' as _i4; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeWgerBaseProvider_0 extends _i1.SmartFake + implements _i2.WgerBaseProvider { + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeSharedPreferencesAsync_1 extends _i1.SmartFake + implements _i3.SharedPreferencesAsync { + _FakeSharedPreferencesAsync_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +/// A class which mocks [UserProvider]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockUserProvider extends _i1.Mock implements _i4.UserProvider { + MockUserProvider() { + _i1.throwOnMissingStub(this); + } + + @override + _i5.ThemeMode get themeMode => + (super.noSuchMethod( + Invocation.getter(#themeMode), + returnValue: _i5.ThemeMode.system, + ) + as _i5.ThemeMode); + + @override + _i2.WgerBaseProvider get baseProvider => + (super.noSuchMethod( + Invocation.getter(#baseProvider), + returnValue: _FakeWgerBaseProvider_0( + this, + Invocation.getter(#baseProvider), + ), + ) + as _i2.WgerBaseProvider); + + @override + _i3.SharedPreferencesAsync get prefs => + (super.noSuchMethod( + Invocation.getter(#prefs), + returnValue: _FakeSharedPreferencesAsync_1( + this, + Invocation.getter(#prefs), + ), + ) + as _i3.SharedPreferencesAsync); + + @override + List<_i4.DashboardWidget> get dashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#dashboardWidgets), + returnValue: <_i4.DashboardWidget>[], + ) + as List<_i4.DashboardWidget>); + + @override + List<_i4.DashboardWidget> get allDashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#allDashboardWidgets), + returnValue: <_i4.DashboardWidget>[], + ) + as List<_i4.DashboardWidget>); + + @override + set themeMode(_i5.ThemeMode? value) => super.noSuchMethod( + Invocation.setter(#themeMode, value), + returnValueForMissingStub: null, + ); + + @override + set prefs(_i3.SharedPreferencesAsync? value) => super.noSuchMethod( + Invocation.setter(#prefs, value), + returnValueForMissingStub: null, + ); + + @override + set profile(_i6.Profile? value) => super.noSuchMethod( + Invocation.setter(#profile, value), + returnValueForMissingStub: null, + ); + + @override + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); + + @override + void clear() => super.noSuchMethod( + Invocation.method(#clear, []), + returnValueForMissingStub: null, + ); + + @override + bool isDashboardWidgetVisible(_i4.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i7.Future setDashboardWidgetVisible( + _i4.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i7.Future.value(), + returnValueForMissingStub: _i7.Future.value(), + ) + as _i7.Future); + + @override + _i7.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i7.Future.value(), + returnValueForMissingStub: _i7.Future.value(), + ) + as _i7.Future); + + @override + void setThemeMode(_i5.ThemeMode? mode) => super.noSuchMethod( + Invocation.method(#setThemeMode, [mode]), + returnValueForMissingStub: null, + ); + + @override + _i7.Future fetchAndSetProfile() => + (super.noSuchMethod( + Invocation.method(#fetchAndSetProfile, []), + returnValue: _i7.Future.value(), + returnValueForMissingStub: _i7.Future.value(), + ) + as _i7.Future); + + @override + _i7.Future saveProfile() => + (super.noSuchMethod( + Invocation.method(#saveProfile, []), + returnValue: _i7.Future.value(), + returnValueForMissingStub: _i7.Future.value(), + ) + as _i7.Future); + + @override + _i7.Future verifyEmail() => + (super.noSuchMethod( + Invocation.method(#verifyEmail, []), + returnValue: _i7.Future.value(), + returnValueForMissingStub: _i7.Future.value(), + ) + as _i7.Future); + + @override + void addListener(_i8.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#addListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void removeListener(_i8.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#removeListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void dispose() => super.noSuchMethod( + Invocation.method(#dispose, []), + returnValueForMissingStub: null, + ); + + @override + void notifyListeners() => super.noSuchMethod( + Invocation.method(#notifyListeners, []), + returnValueForMissingStub: null, + ); +} From 627b8b9fd834f50df010d0f18e048c2936a8bee4 Mon Sep 17 00:00:00 2001 From: John Weidner Date: Fri, 27 Mar 2026 16:32:53 -0500 Subject: [PATCH 003/484] 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); + }); + }); +} From 2f10ee9a5d4d9847fb52d16e776d825980d6d068 Mon Sep 17 00:00:00 2001 From: John Weidner Date: Fri, 27 Mar 2026 16:38:48 -0500 Subject: [PATCH 004/484] refactor: simplify health sync code after review - Use existing isSameDayAs() extension in findByDate() instead of manual year/month/day comparison - Build a Set of existing timestamps for O(1) dedup lookups instead of O(n*m) .any() scan per data point - Simplify nullable bool check (_isAvailable != true) - Remove comments that restate the code Co-Authored-By: Claude Opus 4.6 (1M context) --- lib/providers/body_weight.dart | 6 ++-- lib/providers/health_sync.dart | 38 +++++++++++----------- lib/widgets/core/settings/health_sync.dart | 2 +- 3 files changed, 22 insertions(+), 24 deletions(-) diff --git a/lib/providers/body_weight.dart b/lib/providers/body_weight.dart index 8af2f4b3c..71c1dd5dc 100644 --- a/lib/providers/body_weight.dart +++ b/lib/providers/body_weight.dart @@ -20,6 +20,7 @@ import 'package:flutter/material.dart'; import 'package:logging/logging.dart'; import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/helpers/consts.dart'; +import 'package:wger/helpers/date.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; import 'package:wger/providers/base_provider.dart'; @@ -59,10 +60,7 @@ class BodyWeightProvider with ChangeNotifier { WeightEntry? findByDate(DateTime date) { try { return _entries.firstWhere( - (entry) => - entry.date.year == date.year && - entry.date.month == date.month && - entry.date.day == date.day, + (entry) => entry.date.isSameDayAs(date), ); } on StateError { return null; diff --git a/lib/providers/health_sync.dart b/lib/providers/health_sync.dart index 098972273..056fe0437 100644 --- a/lib/providers/health_sync.dart +++ b/lib/providers/health_sync.dart @@ -52,10 +52,7 @@ class HealthSyncState { } } -/// Initial sync lookback period const int healthSyncInitialDays = 30; - -/// Conversion factor from kg to lb const double kgToLb = 2.20462; @Riverpod(keepAlive: true) @@ -187,6 +184,14 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { _logger.info('Found ${dataPoints.length} weight data points'); + // Build a Set of existing timestamps for O(1) dedup lookups + final existingTimestamps = existingEntries != null + ? { + for (final e in existingEntries) + DateTime(e.date.year, e.date.month, e.date.day, e.date.hour, e.date.minute), + } + : {}; + int syncedCount = 0; DateTime? latestSynced; @@ -196,27 +201,22 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { final weightKg = value.toDouble(); final timestamp = point.dateFrom; - // Convert to user's preferred unit final weight = isMetric ? weightKg : weightKg * kgToLb; final weightRounded = (weight * 100).roundToDouble() / 100; - // Fallback dedup: skip if an entry with the same timestamp exists locally - if (existingEntries != null) { - final duplicate = existingEntries.any( - (e) => - e.date.year == timestamp.year && - e.date.month == timestamp.month && - e.date.day == timestamp.day && - e.date.hour == timestamp.hour && - e.date.minute == timestamp.minute, - ); - if (duplicate) { - _logger.fine('Skipping duplicate entry for $timestamp'); - continue; - } + // Skip if an entry with the same timestamp already exists locally + final normalizedTimestamp = DateTime( + timestamp.year, + timestamp.month, + timestamp.day, + timestamp.hour, + timestamp.minute, + ); + if (existingTimestamps.contains(normalizedTimestamp)) { + _logger.fine('Skipping duplicate entry for $timestamp'); + continue; } - // POST to backend with original timestamp final entry = WeightEntry(weight: weightRounded, date: timestamp); await _baseProvider.post( entry.toJson(), diff --git a/lib/widgets/core/settings/health_sync.dart b/lib/widgets/core/settings/health_sync.dart index 9622e8f94..e9902355d 100644 --- a/lib/widgets/core/settings/health_sync.dart +++ b/lib/widgets/core/settings/health_sync.dart @@ -50,7 +50,7 @@ class _HealthSyncSettingsTileState extends ConsumerState @override Widget build(BuildContext context) { // Hide entirely if platform check hasn't completed or is unavailable - if (_isAvailable == null || _isAvailable == false) { + if (_isAvailable != true) { return const SizedBox.shrink(); } From 86246ac947131d0b03d7f764b9b70979c44a4fb3 Mon Sep 17 00:00:00 2001 From: John Weidner Date: Fri, 27 Mar 2026 16:42:08 -0500 Subject: [PATCH 005/484] refactor: use l10n for health sync user-facing strings Add healthSync, healthSyncDescription, healthSyncSuccess, and health keys to app_en.arb and use AppLocalizations instead of hardcoded English strings in the settings tile and settings page. Co-Authored-By: Claude Opus 4.6 (1M context) --- lib/l10n/app_en.arb | 23 +++++++++++++++++++++- lib/widgets/core/settings.dart | 2 +- lib/widgets/core/settings/health_sync.dart | 9 ++++++--- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index d07fa2765..891a75dfa 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1180,5 +1180,26 @@ } }, "searchLanguageAll": "All languages", - "@searchLanguageAll": {} + "@searchLanguageAll": {}, + "healthSync": "Health sync", + "@healthSync": { + "description": "Title for the health platform sync setting" + }, + "healthSyncDescription": "Import weight from Apple Health or Health Connect", + "@healthSyncDescription": { + "description": "Subtitle for the health platform sync setting" + }, + "healthSyncSuccess": "Synced {count} weight entries from Health", + "@healthSyncSuccess": { + "description": "Snackbar message after successful health sync", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "health": "Health", + "@health": { + "description": "Section header for health-related settings" + } } diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index 3469acd73..d4208bdd1 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -43,7 +43,7 @@ class SettingsPage extends StatelessWidget { ), const SettingsExerciseCache(), const SettingsIngredientCache(), - ListTile(title: Text('Health', style: Theme.of(context).textTheme.headlineSmall)), + ListTile(title: Text(i18n.health, style: Theme.of(context).textTheme.headlineSmall)), const HealthSyncSettingsTile(), ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)), const SettingsTheme(), diff --git a/lib/widgets/core/settings/health_sync.dart b/lib/widgets/core/settings/health_sync.dart index e9902355d..da738923f 100644 --- a/lib/widgets/core/settings/health_sync.dart +++ b/lib/widgets/core/settings/health_sync.dart @@ -19,6 +19,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:provider/provider.dart' as provider; +import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/body_weight.dart'; import 'package:wger/providers/health_sync.dart'; import 'package:wger/providers/user.dart'; @@ -56,9 +57,11 @@ class _HealthSyncSettingsTileState extends ConsumerState final syncState = ref.watch(healthSyncProvider); + final i18n = AppLocalizations.of(context); + return SwitchListTile( - title: const Text('Health sync'), - subtitle: const Text('Import weight from Apple Health or Health Connect'), + title: Text(i18n.healthSync), + subtitle: Text(i18n.healthSyncDescription), value: syncState.isEnabled, onChanged: syncState.isSyncing ? null @@ -74,7 +77,7 @@ class _HealthSyncSettingsTileState extends ConsumerState .fetchAndSetEntries(); if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Synced $count weight entries from Health')), + SnackBar(content: Text(i18n.healthSyncSuccess(count))), ); } } From a4d03bcc46422ec903a9b1ae02dd6b74994dd330 Mon Sep 17 00:00:00 2001 From: John Weidner Date: Fri, 27 Mar 2026 16:44:43 -0500 Subject: [PATCH 006/484] feat: import all health history instead of last 30 days Remove the 30-day lookback limit on initial sync. Pull all available weight data from Health Connect on first enable. Add READ_HEALTH_DATA_HISTORY permission to AndroidManifest to allow reading data older than 30 days. Co-Authored-By: Claude Opus 4.6 (1M context) --- android/app/src/main/AndroidManifest.xml | 1 + lib/providers/health_sync.dart | 4 ++-- test/providers/health_sync_test.dart | 3 --- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 2f8ef5362..b23873870 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -11,6 +11,7 @@ + diff --git a/lib/providers/health_sync.dart b/lib/providers/health_sync.dart index 056fe0437..0ac784b55 100644 --- a/lib/providers/health_sync.dart +++ b/lib/providers/health_sync.dart @@ -52,7 +52,6 @@ class HealthSyncState { } } -const int healthSyncInitialDays = 30; const double kgToLb = 2.20462; @Riverpod(keepAlive: true) @@ -162,7 +161,8 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { if (lastSyncStr != null) { startTime = DateTime.parse(lastSyncStr); } else { - startTime = DateTime.now().subtract(const Duration(days: healthSyncInitialDays)); + // Pull all available history on first sync + startTime = DateTime(2000); } final endTime = DateTime.now(); diff --git a/test/providers/health_sync_test.dart b/test/providers/health_sync_test.dart index 73b23d460..1062a5688 100644 --- a/test/providers/health_sync_test.dart +++ b/test/providers/health_sync_test.dart @@ -31,9 +31,6 @@ void main() { expect(kgToLb, closeTo(2.20462, 0.00001)); }); - test('Initial sync lookback is 30 days', () { - expect(healthSyncInitialDays, 30); - }); }); group('Weight unit conversion', () { From e1968d0b2f87d95ed6481826b7dde250e0104019 Mon Sep 17 00:00:00 2001 From: John Weidner Date: Fri, 27 Mar 2026 16:53:49 -0500 Subject: [PATCH 007/484] fix: request historical data access from Health Connect Call requestHealthDataHistoryAuthorization() on Android after initial permission grant. Without this runtime request, Health Connect limits data access to the last 30 days regardless of the manifest permission. Co-Authored-By: Claude Opus 4.6 (1M context) --- lib/providers/health_sync.dart | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/providers/health_sync.dart b/lib/providers/health_sync.dart index 0ac784b55..1198ff54c 100644 --- a/lib/providers/health_sync.dart +++ b/lib/providers/health_sync.dart @@ -108,6 +108,11 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { return 0; } + // Request access to historical data (older than 30 days) on Android + if (Platform.isAndroid) { + await _health.requestHealthDataHistoryAuthorization(); + } + await PreferenceHelper.instance.setHealthSyncEnabled(true); state = state.copyWith(isEnabled: true); From 7001bca7396a461367eb930fe406117a24ccfcff Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Sat, 16 May 2026 16:18:28 +0545 Subject: [PATCH 008/484] feat(measurements): implement measurement groups, dynamic formula evaluation --- .../measurements/measurement_category.dart | 27 +- .../measurements/measurement_category.g.dart | 10 + .../measurements/measurement_group.dart | 37 ++ .../measurements/measurement_group.g.dart | 25 ++ lib/providers/measurement.dart | 117 ++++- .../measurement_categories_screen.dart | 47 +- lib/screens/measurement_entries_screen.dart | 30 +- lib/widgets/measurements/categories.dart | 12 +- lib/widgets/measurements/categories_card.dart | 59 ++- lib/widgets/measurements/entries.dart | 4 +- lib/widgets/measurements/forms.dart | 412 ++++++++++++------ 11 files changed, 617 insertions(+), 163 deletions(-) create mode 100644 lib/models/measurements/measurement_group.dart create mode 100644 lib/models/measurements/measurement_group.g.dart diff --git a/lib/models/measurements/measurement_category.dart b/lib/models/measurements/measurement_category.dart index 05d6ade02..eb268b0e5 100644 --- a/lib/models/measurements/measurement_category.dart +++ b/lib/models/measurements/measurement_category.dart @@ -2,6 +2,7 @@ import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:wger/core/exceptions/no_such_entry_exception.dart'; import 'package:wger/models/measurements/measurement_entry.dart'; +import 'package:wger/models/measurements/measurement_group.dart'; part 'measurement_category.g.dart'; @@ -16,6 +17,18 @@ class MeasurementCategory extends Equatable { @JsonKey(required: true) final String unit; + @JsonKey(name: 'group', includeToJson: true) + final int? groupId; + + @JsonKey(name: 'group_detail', includeToJson: false) + final MeasurementGroup? groupDetail; + + @JsonKey(name: 'formula', includeToJson: true) + final String? formula; + + @JsonKey(name: 'is_dynamic', includeToJson: false, defaultValue: false) + final bool isDynamic; + @JsonKey(defaultValue: [], toJson: _nullValue) final List entries; @@ -23,6 +36,10 @@ class MeasurementCategory extends Equatable { required this.id, required this.name, required this.unit, + this.groupId, + this.groupDetail, + this.formula, + this.isDynamic = false, this.entries = const [], }); @@ -30,12 +47,20 @@ class MeasurementCategory extends Equatable { int? id, String? name, String? unit, + int? groupId, + MeasurementGroup? groupDetail, + String? formula, + bool? isDynamic, List? entries, }) { return MeasurementCategory( id: id ?? this.id, name: name ?? this.name, unit: unit ?? this.unit, + groupId: groupId ?? this.groupId, + groupDetail: groupDetail ?? this.groupDetail, + formula: formula ?? this.formula, + isDynamic: isDynamic ?? this.isDynamic, entries: entries ?? this.entries, ); } @@ -54,7 +79,7 @@ class MeasurementCategory extends Equatable { Map toJson() => _$MeasurementCategoryToJson(this); @override - List get props => [id, name, unit, entries]; + List get props => [id, name, unit, groupId, formula, isDynamic, entries]; // Helper function which makes the entries list of the toJson output null, as it isn't needed static Null _nullValue(List _) => null; diff --git a/lib/models/measurements/measurement_category.g.dart b/lib/models/measurements/measurement_category.g.dart index e971c3884..8ead8e403 100644 --- a/lib/models/measurements/measurement_category.g.dart +++ b/lib/models/measurements/measurement_category.g.dart @@ -12,6 +12,14 @@ MeasurementCategory _$MeasurementCategoryFromJson(Map json) { id: (json['id'] as num?)?.toInt(), name: json['name'] as String, unit: json['unit'] as String, + groupId: (json['group'] as num?)?.toInt(), + groupDetail: json['group_detail'] == null + ? null + : MeasurementGroup.fromJson( + json['group_detail'] as Map, + ), + formula: json['formula'] as String?, + isDynamic: json['is_dynamic'] as bool? ?? false, entries: (json['entries'] as List?) ?.map((e) => MeasurementEntry.fromJson(e as Map)) @@ -26,5 +34,7 @@ Map _$MeasurementCategoryToJson( 'id': instance.id, 'name': instance.name, 'unit': instance.unit, + 'group': instance.groupId, + 'formula': instance.formula, 'entries': MeasurementCategory._nullValue(instance.entries), }; diff --git a/lib/models/measurements/measurement_group.dart b/lib/models/measurements/measurement_group.dart new file mode 100644 index 000000000..93fd211e5 --- /dev/null +++ b/lib/models/measurements/measurement_group.dart @@ -0,0 +1,37 @@ + +import 'package:equatable/equatable.dart'; +import 'package:json_annotation/json_annotation.dart'; + +part 'measurement_group.g.dart'; + +/// A named group linking related measurement categories together. +/// Example: "Blood Pressure" groups Systolic + Diastolic categories. +@JsonSerializable() +class MeasurementGroup extends Equatable { + @JsonKey(required: true) + final int id; + + @JsonKey(required: true) + final String uuid; + + @JsonKey(required: true) + final String name; + + @JsonKey(defaultValue: '') + final String description; + + const MeasurementGroup({ + required this.id, + required this.uuid, + required this.name, + this.description = '', + }); + + factory MeasurementGroup.fromJson(Map json) => + _$MeasurementGroupFromJson(json); + + Map toJson() => _$MeasurementGroupToJson(this); + + @override + List get props => [id, uuid, name, description]; +} \ No newline at end of file diff --git a/lib/models/measurements/measurement_group.g.dart b/lib/models/measurements/measurement_group.g.dart new file mode 100644 index 000000000..51fee1ae7 --- /dev/null +++ b/lib/models/measurements/measurement_group.g.dart @@ -0,0 +1,25 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'measurement_group.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +MeasurementGroup _$MeasurementGroupFromJson(Map json) { + $checkKeys(json, requiredKeys: const ['id', 'uuid', 'name']); + return MeasurementGroup( + id: (json['id'] as num).toInt(), + uuid: json['uuid'] as String, + name: json['name'] as String, + description: json['description'] as String? ?? '', + ); +} + +Map _$MeasurementGroupToJson(MeasurementGroup instance) => + { + 'id': instance.id, + 'uuid': instance.uuid, + 'name': instance.name, + 'description': instance.description, + }; diff --git a/lib/providers/measurement.dart b/lib/providers/measurement.dart index 6c0292f0d..213967177 100644 --- a/lib/providers/measurement.dart +++ b/lib/providers/measurement.dart @@ -23,6 +23,7 @@ import 'package:wger/core/exceptions/no_such_entry_exception.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/models/measurements/measurement_category.dart'; import 'package:wger/models/measurements/measurement_entry.dart'; +import 'package:wger/models/measurements/measurement_group.dart'; import 'package:wger/providers/base_provider.dart'; class MeasurementProvider with ChangeNotifier { @@ -30,18 +31,22 @@ class MeasurementProvider with ChangeNotifier { static const _categoryUrl = 'measurement-category'; static const _entryUrl = 'measurement'; - + static const _groupUrl = 'measurement-group'; + static const _dynamicValuesAction = 'dynamic-values'; final WgerBaseProvider baseProvider; List _categories = []; + List _groups = []; MeasurementProvider(this.baseProvider); List get categories => _categories; + List get groups => _groups; /// Clears all lists void clear() { _categories = []; + _groups = []; } /// Finds the category by ID @@ -69,6 +74,12 @@ class MeasurementProvider with ChangeNotifier { /// Fetches and sets the measurement entries for the given category Future fetchAndSetCategoryEntries(int id) async { final category = findCategoryById(id); + + if (category.isDynamic) { + await fetchDynamicCategoryEntries(id); + return; + } + final categoryIndex = _categories.indexOf(category); // Process the response @@ -87,10 +98,39 @@ class MeasurementProvider with ChangeNotifier { notifyListeners(); } + /// Fetches computed values for a dynamic (formula-based) category + /// and sets the measurement entries + Future fetchDynamicCategoryEntries(int categoryId) async { + final category = findCategoryById(categoryId); + if (!category.isDynamic) return; + + final categoryIndex = _categories.indexOf(category); + + final requestUrl = baseProvider.makeUrl( + '$_categoryUrl/$categoryId/$_dynamicValuesAction', + ); + + // The dynamic-values endpoint returns a plain list, not paginated. + final dynamic rawData = await baseProvider.fetch(requestUrl); + final List data = rawData is List ? rawData : (rawData['results'] ?? []); + + final List computedEntries = data + .map((e) => MeasurementEntry.fromJson(e as Map)) + .toList(); + + final MeasurementCategory editedCategory = category.copyWith( + entries: computedEntries, + ); + _categories.removeAt(categoryIndex); + _categories.insert(categoryIndex, editedCategory); + notifyListeners(); + } + /// Fetches and sets the measurement categories and their entries Future fetchAndSetAllCategoriesAndEntries() async { _logger.info('Fetching all measurement categories and entries'); + await fetchAndSetGroups(); await fetchAndSetCategories(); await Future.wait(_categories.map((e) => fetchAndSetCategoryEntries(e.id!)).toList()); } @@ -124,7 +164,15 @@ class MeasurementProvider with ChangeNotifier { /// Edits a measurement category /// Currently there isn't any fallback if the call to the api is unsuccessful, as WgerBaseProvider.patch only returns the response body and not the whole response - Future editCategory(int id, String? newName, String? newUnit) async { + Future editCategory( + int id, + String? newName, + String? newUnit, + int? newGroupId, + String? newFormula, { + bool clearGroup = false, + bool clearFormula = false, + }) async { final MeasurementCategory oldCategory = findCategoryById(id); final int categoryIndex = _categories.indexOf(oldCategory); final MeasurementCategory tempNewCategory = oldCategory.copyWith(name: newName, unit: newUnit); @@ -141,6 +189,71 @@ class MeasurementProvider with ChangeNotifier { notifyListeners(); } + // --- Measurement Groups --- + + /// Finds a group by ID + MeasurementGroup findGroupById(int id) { + return _groups.firstWhere( + (group) => group.id == id, + orElse: () => throw const NoSuchEntryException(), + ); + } + + /// Fetches and sets all measurement groups from the server. + Future fetchAndSetGroups() async { + final requestUrl = baseProvider.makeUrl(_groupUrl, query: {'limit': API_MAX_PAGE_SIZE}); + final data = await baseProvider.fetchPaginated(requestUrl); + _groups = data.map((e) => MeasurementGroup.fromJson(e)).toList(); + notifyListeners(); + } + + /// Adds a measurement group. + Future addGroup(MeasurementGroup group) async { + final Uri postUri = baseProvider.makeUrl(_groupUrl); + final Map newGroupMap = await baseProvider.post(group.toJson(), postUri); + final MeasurementGroup newGroup = MeasurementGroup.fromJson(newGroupMap); + _groups.add(newGroup); + _groups.sort((a, b) => a.name.compareTo(b.name)); + notifyListeners(); + } + + /// Edits a measurement group name/description. + Future editGroup(int id, String? newName, String? newDescription) async { + final MeasurementGroup oldGroup = findGroupById(id); + final int groupIndex = _groups.indexOf(oldGroup); + final MeasurementGroup tempNew = MeasurementGroup( + id: oldGroup.id, + uuid: oldGroup.uuid, + name: newName ?? oldGroup.name, + description: newDescription ?? oldGroup.description, + ); + final Map response = await baseProvider.patch( + tempNew.toJson(), + baseProvider.makeUrl(_groupUrl, id: id), + ); + final MeasurementGroup newGroup = MeasurementGroup.fromJson(response); + _groups.removeAt(groupIndex); + _groups.insert(groupIndex, newGroup); + notifyListeners(); + } + + /// Deletes a measurement group. + Future deleteGroup(int id) async { + final MeasurementGroup group = findGroupById(id); + final int groupIndex = _groups.indexOf(group); + _groups.remove(group); + notifyListeners(); + try { + await baseProvider.deleteRequest(_groupUrl, id); + } on WgerHttpException { + _groups.insert(groupIndex, group); + notifyListeners(); + rethrow; + } + } + + // --- Measurement Entries --- + /// Adds a measurement entry Future addEntry(MeasurementEntry entry) async { final Uri postUri = baseProvider.makeUrl(_entryUrl); diff --git a/lib/screens/measurement_categories_screen.dart b/lib/screens/measurement_categories_screen.dart index 6feffb47a..5aa28a2a2 100644 --- a/lib/screens/measurement_categories_screen.dart +++ b/lib/screens/measurement_categories_screen.dart @@ -25,11 +25,19 @@ import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/measurements/categories.dart'; import 'package:wger/widgets/measurements/forms.dart'; -class MeasurementCategoriesScreen extends StatelessWidget { +class MeasurementCategoriesScreen extends StatefulWidget { + const MeasurementCategoriesScreen(); static const routeName = '/measurement-categories'; + @override + State createState() => _MeasurementCategoriesScreenState(); +} + +class _MeasurementCategoriesScreenState extends State { + int? _selectedGroupId; + @override Widget build(BuildContext context) { return Scaffold( @@ -49,7 +57,42 @@ class MeasurementCategoriesScreen extends StatelessWidget { ), body: WidescreenWrapper( child: Consumer( - builder: (context, provider, child) => const CategoriesList(), + builder: (context, provider, child) { + + final groups = provider.groups; + if (groups.isEmpty) return const SizedBox.shrink(); + + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + children: [ + // clears group filter + FilterChip( + label: const Text('All'), + selected: _selectedGroupId == null, + onSelected: (_) => setState(() => _selectedGroupId = null), + ), + const SizedBox(width: 6), + // One chip per group + ...groups.map( + (group) => Padding( + padding: const EdgeInsets.only(right: 6), + child: FilterChip( + label: Text(group.name), + selected: _selectedGroupId == group.id, + onSelected: (_) => setState( + () => _selectedGroupId = + _selectedGroupId == group.id ? null : group.id, + ), + ), + ), + ), + CategoriesList(_selectedGroupId), + ], + ), + ); + } ), ), ); diff --git a/lib/screens/measurement_entries_screen.dart b/lib/screens/measurement_entries_screen.dart index 3f30ed3e3..b8a5728af 100644 --- a/lib/screens/measurement_entries_screen.dart +++ b/lib/screens/measurement_entries_screen.dart @@ -54,6 +54,32 @@ class MeasurementEntriesScreen extends StatelessWidget { return const SizedBox(); // Return empty widget until pop happens } + if (category.isDynamic) { + return Container( + margin: const EdgeInsets.all(8), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.blue.withValues(alpha: 0.3)), + ), + child: Row( + children: [ + const Icon(Icons.auto_graph, color: Colors.blue, size: 18), + const SizedBox(width: 8), + Expanded( + child: Text( + 'Values for this category are calculated automatically ' + 'using the "${category.formula}" formula. ' + 'You cannot add entries manually.', + style: const TextStyle(fontSize: 13), + ), + ), + ], + ), + ); + } + return Scaffold( appBar: AppBar( title: Text(category.name), @@ -68,7 +94,7 @@ class MeasurementEntriesScreen extends StatelessWidget { FormScreen.routeName, arguments: FormScreenArguments( AppLocalizations.of(context).edit, - MeasurementCategoryForm(category), + MeasurementCategoryForm(), ), ); break; @@ -145,7 +171,7 @@ class MeasurementEntriesScreen extends StatelessWidget { FormScreen.routeName, arguments: FormScreenArguments( AppLocalizations.of(context).newEntry, - MeasurementEntryForm(categoryId), + MeasurementEntryForm(categoryId: categoryId), ), ); }, diff --git a/lib/widgets/measurements/categories.dart b/lib/widgets/measurements/categories.dart index 32abf49e6..a00905175 100644 --- a/lib/widgets/measurements/categories.dart +++ b/lib/widgets/measurements/categories.dart @@ -23,17 +23,23 @@ import 'package:wger/providers/measurement.dart'; import 'categories_card.dart'; class CategoriesList extends StatelessWidget { - const CategoriesList(); + final int? _selectedGrouptID; + const CategoriesList(this._selectedGrouptID); + @override Widget build(BuildContext context) { final provider = Provider.of(context, listen: false); + final categories = provider.categories.where((cat) { + if (_selectedGrouptID == null) return true; + return cat.groupId == _selectedGrouptID; + }).toList(); return RefreshIndicator( onRefresh: () => provider.fetchAndSetAllCategoriesAndEntries(), child: ListView.builder( padding: const EdgeInsets.all(10.0), - itemCount: provider.categories.length, - itemBuilder: (context, index) => CategoriesCard(provider.categories[index]), + itemCount: categories.length, + itemBuilder: (context, index) => CategoriesCard(categories[index]), ), ); } diff --git a/lib/widgets/measurements/categories_card.dart b/lib/widgets/measurements/categories_card.dart index 27ef09df2..c31401eb4 100644 --- a/lib/widgets/measurements/categories_card.dart +++ b/lib/widgets/measurements/categories_card.dart @@ -33,6 +33,35 @@ class CategoriesCard extends StatelessWidget { style: Theme.of(context).textTheme.titleLarge, ), ), + // Group + if (currentCategory.groupDetail != null) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Chip( + avatar: const Icon(Icons.link, size: 14), + label: Text( + currentCategory.groupDetail!.name, + style: const TextStyle(fontSize: 11), + ), + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + ), + ), + // Dynamic + if (currentCategory.isDynamic) + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Chip( + avatar: const Icon(Icons.auto_graph, size: 14, color: Colors.blue), + label: const Text( + 'Auto-calculated', + style: TextStyle(fontSize: 11, color: Colors.blue), + ), + backgroundColor: Colors.blue.withValues(alpha: 0.1), + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + ), + ), Container( padding: const EdgeInsets.all(10), height: 220, @@ -68,19 +97,23 @@ class CategoriesCard extends StatelessWidget { ); }, ), - IconButton( - onPressed: () async { - await Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).newEntry, - MeasurementEntryForm(currentCategory.id!), - ), - ); - }, - icon: const Icon(Icons.add), - ), + // hide add-entry button for dynamic categories + if (!currentCategory.isDynamic) + IconButton( + onPressed: () async { + await Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).newEntry, + MeasurementEntryForm( + categoryId: currentCategory.id!, + ), + ), + ); + }, + icon: const Icon(Icons.add), + ), ], ), ), diff --git a/lib/widgets/measurements/entries.dart b/lib/widgets/measurements/entries.dart index 10220dbe9..6985a1bc4 100644 --- a/lib/widgets/measurements/entries.dart +++ b/lib/widgets/measurements/entries.dart @@ -80,8 +80,8 @@ class EntriesList extends StatelessWidget { arguments: FormScreenArguments( AppLocalizations.of(context).edit, MeasurementEntryForm( - currentEntry.category, - currentEntry, + categoryId: currentEntry.category, + entry: currentEntry, ), ), ), diff --git a/lib/widgets/measurements/forms.dart b/lib/widgets/measurements/forms.dart index 38734d2ac..b69f08015 100644 --- a/lib/widgets/measurements/forms.dart +++ b/lib/widgets/measurements/forms.dart @@ -23,33 +23,66 @@ import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/measurements/measurement_category.dart'; import 'package:wger/models/measurements/measurement_entry.dart'; +import 'package:wger/models/measurements/measurement_group.dart'; import 'package:wger/providers/measurement.dart'; -class MeasurementCategoryForm extends StatelessWidget { - final _form = GlobalKey(); - final nameController = TextEditingController(); - final unitController = TextEditingController(); +class MeasurementCategoryForm extends StatefulWidget { + final MeasurementCategory? category; - final Map categoryData = { - 'id': null, - 'name': '', - 'unit': '', + const MeasurementCategoryForm({ + super.key, + this.category, + }); + + @override + State createState() => _MeasurementCategoryFormState(); +} + +class _MeasurementCategoryFormState extends State { + final List _dummyGroups = [ + const MeasurementGroup(uuid: '1', id: 1, name: 'Dummy: Bodyweight'), + const MeasurementGroup(uuid: '2', id: 2, name: 'Dummy: Strength'), + ]; + + final _form = GlobalKey(); + late final TextEditingController nameController; + late final TextEditingController unitController; + + int? _categoryId; + + int? _selectedGroupId; + String? _selectedFormula; + bool _isSubmitting = false; + + static const Map _formulaLabels = { + 'bmi': 'Body Mass Index (BMI)', + 'lbm': 'Lean Body Mass', + '1rm_epley': '1RM — Epley formula', }; - MeasurementCategoryForm([MeasurementCategory? category]) { - //this._category = category ?? MeasurementCategory(); - if (category != null) { - categoryData['id'] = category.id; - categoryData['unit'] = category.unit; - categoryData['name'] = category.name; - } + @override + void initState() { + super.initState(); + final cat = widget.category; + _categoryId = cat?.id; + nameController = TextEditingController(text: cat?.name ?? ''); + unitController = TextEditingController(text: cat?.unit ?? ''); - unitController.text = categoryData['unit']!; - nameController.text = categoryData['name']!; + _selectedGroupId = cat?.groupId; + _selectedFormula = cat?.formula; + } + + @override + void dispose() { + nameController.dispose(); + unitController.dispose(); + super.dispose(); } @override Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + final groups = Provider.of(context, listen: false).groups; return Form( key: _form, child: Column( @@ -57,16 +90,13 @@ class MeasurementCategoryForm extends StatelessWidget { // Name TextFormField( decoration: InputDecoration( - labelText: AppLocalizations.of(context).name, - helperText: AppLocalizations.of(context).measurementCategoriesHelpText, + labelText: i18n.name, + helperText: i18n.measurementCategoriesHelpText, ), controller: nameController, - onSaved: (newValue) { - categoryData['name'] = newValue; - }, validator: (value) { - if (value!.isEmpty) { - return AppLocalizations.of(context).enterValue; + if (value == null || value.trim().isEmpty) { + return i18n.enterValue; } return null; }, @@ -75,53 +105,106 @@ class MeasurementCategoryForm extends StatelessWidget { // Unit TextFormField( decoration: InputDecoration( - labelText: AppLocalizations.of(context).unit, - helperText: AppLocalizations.of(context).measurementEntriesHelpText, + labelText: i18n.unit, + helperText: i18n.measurementEntriesHelpText, ), controller: unitController, - onSaved: (newValue) { - categoryData['unit'] = newValue; - }, validator: (value) { - if (value!.isEmpty) { - return AppLocalizations.of(context).enterValue; + if (value == null || value.trim().isEmpty) { + return i18n.enterValue; } return null; }, ), + + // Group dropdown + const SizedBox(height: 12), + DropdownButtonFormField( + initialValue: _selectedGroupId, + decoration: const InputDecoration( + labelText: 'Group (optional)', + helperText: 'Link this category to a group e.g. "Blood Pressure"', + ), + items: [ + const DropdownMenuItem( + value: null, + child: Text('- No group -'), + ), + ...groups.map( + (g) => DropdownMenuItem( + value: g.id, + child: Text(g.name), + ), + ), + ], + onChanged: (val) => setState(() => _selectedGroupId = val), + ), + + // Formula dropdown + const SizedBox(height: 12), + DropdownButtonFormField( + initialValue: _selectedFormula, + decoration: const InputDecoration( + labelText: 'Auto-calculate from formula (optional)', + helperText: 'values are computed automatically, no entry needed.', + ), + items: [ + const DropdownMenuItem( + value: null, + child: Text('- Manual entry -'), + ), + ..._formulaLabels.entries.map( + (e) => DropdownMenuItem( + value: e.key, + child: Text(e.value), + ), + ), + ], + onChanged: (val) => setState(() => _selectedFormula = val), + ), + + const SizedBox(height: 16), ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(i18n.save), onPressed: () async { // Validate and save the current values to the weightEntry - final isValid = _form.currentState!.validate(); + final isValid = _form.currentState?.validate() ?? false; if (!isValid) { return; } _form.currentState!.save(); + setState(() => _isSubmitting = true); + final measurementProvider = Provider.of(context, listen: false); // Save the entry on the server - categoryData['id'] == null - ? await Provider.of( - context, - listen: false, - ).addCategory( - MeasurementCategory( - id: categoryData['id'], - name: categoryData['name'], - unit: categoryData['unit'], - ), - ) - : await Provider.of( - context, - listen: false, - ).editCategory( - categoryData['id'], - categoryData['name'], - categoryData['unit'], - ); + try { + if (_categoryId == null) { + await measurementProvider.addCategory( + MeasurementCategory( + id: null, + name: nameController.text.trim(), + unit: unitController.text.trim(), + groupId: _selectedGroupId, + formula: _selectedFormula, + ), + ); + } else { + await measurementProvider.editCategory( + _categoryId!, + nameController.text.trim(), + unitController.text.trim(), + _selectedGroupId, + _selectedFormula, + clearGroup: _selectedGroupId == null, + clearFormula: _selectedFormula == null, + ); + } - if (context.mounted) { - Navigator.of(context).pop(); + if (context.mounted) { + Navigator.of(context).pop(); + } + } catch (e) { + setState(() => _isSubmitting = false); } }, ), @@ -131,41 +214,62 @@ class MeasurementCategoryForm extends StatelessWidget { } } -class MeasurementEntryForm extends StatelessWidget { +class MeasurementEntryForm extends StatefulWidget { + final int categoryId; + final MeasurementEntry? entry; + + const MeasurementEntryForm({ + super.key, + required this.categoryId, + this.entry, + }); + + @override + State createState() => _MeasurementEntryFormState(); +} + +class _MeasurementEntryFormState extends State { final _form = GlobalKey(); - final int _categoryId; - final _valueController = TextEditingController(); - final _dateController = TextEditingController(text: ''); - final _timeController = TextEditingController(text: ''); - final _notesController = TextEditingController(); + late final int _categoryId; + late final TextEditingController _valueController; + late final TextEditingController _dateController; + late final TextEditingController _timeController; + late final TextEditingController _notesController; - late final Map _entryData; + late DateTime _selectedDateTime; + late num _selectedValue; + late String _selectedNotes; + bool _isSubmitting = false; - MeasurementEntryForm(this._categoryId, [MeasurementEntry? entry]) { - _entryData = { - 'id': null, - 'category': _categoryId, - 'date': DateTime.now(), - 'value': '', - 'notes': '', - }; + @override + void initState() { + super.initState(); + _categoryId = widget.categoryId; + _selectedDateTime = widget.entry?.date ?? DateTime.now(); + _selectedValue = widget.entry?.value ?? 0; + _selectedNotes = widget.entry?.notes ?? ''; + _dateController = TextEditingController(); + _timeController = TextEditingController(); + _valueController = TextEditingController(); + _notesController = TextEditingController(text: widget.entry?.notes ?? ''); + } - if (entry != null) { - _entryData['id'] = entry.id; - _entryData['category'] = entry.category; - _entryData['value'] = entry.value; - _entryData['date'] = entry.date; - _entryData['notes'] = entry.notes; - } - - _valueController.text = ''; - _notesController.text = _entryData['notes']!; + @override + void dispose() { + _valueController.dispose(); + _dateController.dispose(); + _timeController.dispose(); + _notesController.dispose(); + super.dispose(); } @override Widget build(BuildContext context) { - final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode); - final timeFormat = DateFormat.Hm(Localizations.localeOf(context).languageCode); + final i18n = AppLocalizations.of(context); + final locale = Localizations.localeOf(context).toString(); + + final dateFormat = DateFormat.yMd(locale); + final timeFormat = DateFormat.Hm(locale); final measurementProvider = Provider.of(context, listen: false); final measurementCategory = measurementProvider.categories.firstWhere( @@ -173,17 +277,45 @@ class MeasurementEntryForm extends StatelessWidget { ); if (_dateController.text.isEmpty) { - _dateController.text = dateFormat.format(_entryData['date']); + _dateController.text = dateFormat.format(_selectedDateTime); } if (_timeController.text.isEmpty) { - _timeController.text = timeFormat.format(_entryData['date']); + _timeController.text = timeFormat.format(_selectedDateTime); } - final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); + final numberFormat = NumberFormat.decimalPattern(locale); // If the value is not empty, format it - if (_valueController.text.isEmpty && _entryData['value'] != null && _entryData['value'] != '') { - _valueController.text = numberFormat.format(_entryData['value']); + if (_valueController.text.isEmpty && widget.entry?.value != null) { + _valueController.text = numberFormat.format(widget.entry!.value); + } + + if (measurementCategory.isDynamic) { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.auto_graph, size: 48, color: Colors.blue), + const SizedBox(height: 12), + Text( + 'This measurement is calculated automatically.', // TODO: i18n + style: Theme.of(context).textTheme.titleMedium, + textAlign: TextAlign.center, + ), + const SizedBox(height: 6), + Text( + 'Formula: ${measurementCategory.formula ?? ''}', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 8), + Text( + 'To see computed values, open the category detail page.', + textAlign: TextAlign.center, + ), + ], + ), + ); } return Form( @@ -193,7 +325,7 @@ class MeasurementEntryForm extends StatelessWidget { // Date TextFormField( decoration: InputDecoration( - labelText: AppLocalizations.of(context).date, + labelText: i18n.date, suffixIcon: const Icon( Icons.calendar_today, key: Key('calendarIcon'), @@ -209,7 +341,7 @@ class MeasurementEntryForm extends StatelessWidget { // Show Date Picker Here final pickedDate = await showDatePicker( context: context, - initialDate: _entryData['date'], + initialDate: _selectedDateTime, firstDate: DateTime(DateTime.now().year - 10), lastDate: DateTime.now(), ); @@ -220,15 +352,15 @@ class MeasurementEntryForm extends StatelessWidget { }, onSaved: (newValue) { final date = dateFormat.parse(newValue!); - _entryData['date'] = (_entryData['date'] as DateTime).copyWith( + _selectedDateTime = (_selectedDateTime as DateTime).copyWith( year: date.year, month: date.month, day: date.day, ); }, validator: (value) { - if (value!.isEmpty) { - return AppLocalizations.of(context).enterValue; + if (value == null || value.isEmpty) { + return i18n.enterValue; } return null; }, @@ -237,7 +369,7 @@ class MeasurementEntryForm extends StatelessWidget { // Time TextFormField( decoration: InputDecoration( - labelText: AppLocalizations.of(context).time, + labelText: i18n.time, suffixIcon: const Icon( Icons.access_time_outlined, key: Key('clockIcon'), @@ -248,7 +380,7 @@ class MeasurementEntryForm extends StatelessWidget { onTap: () async { final pickedTime = await showTimePicker( context: context, - initialTime: TimeOfDay.fromDateTime(_entryData['date']), + initialTime: TimeOfDay.fromDateTime(_selectedDateTime), ); if (pickedTime != null) { @@ -266,7 +398,7 @@ class MeasurementEntryForm extends StatelessWidget { }, onSaved: (newValue) { final time = timeFormat.parse(newValue!); - _entryData['date'] = (_entryData['date'] as DateTime).copyWith( + _selectedDateTime = (_selectedDateTime as DateTime).copyWith( hour: time.hour, minute: time.minute, second: time.second, @@ -277,39 +409,39 @@ class MeasurementEntryForm extends StatelessWidget { // Value TextFormField( decoration: InputDecoration( - labelText: AppLocalizations.of(context).value, + labelText: i18n.value, suffixIcon: Text(measurementCategory.unit), suffixIconConstraints: const BoxConstraints(minWidth: 0, minHeight: 0), ), controller: _valueController, keyboardType: textInputTypeDecimal, validator: (value) { - if (value!.isEmpty) { - return AppLocalizations.of(context).enterValue; + if (value == null || value.isEmpty) { + return i18n.enterValue; } try { numberFormat.parse(value); } catch (error) { - return AppLocalizations.of(context).enterValidNumber; + return i18n.enterValidNumber; } return null; }, onSaved: (newValue) { - _entryData['value'] = numberFormat.parse(newValue!); + _selectedValue = numberFormat.parse(newValue!); }, ), // Notes TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).notes), + decoration: InputDecoration(labelText: i18n.notes), controller: _notesController, onSaved: (newValue) { - _entryData['notes'] = newValue; + _selectedNotes = newValue!; }, validator: (value) { const minLength = 0; const maxLength = 100; if (value!.isNotEmpty && (value.length < minLength || value.length > maxLength)) { - return AppLocalizations.of(context).enterCharacters( + return i18n.enterCharacters( minLength.toString(), maxLength.toString(), ); @@ -319,44 +451,48 @@ class MeasurementEntryForm extends StatelessWidget { ), ElevatedButton( - child: Text(AppLocalizations.of(context).save), - onPressed: () async { - // Validate and save the current values to the weightEntry - final isValid = _form.currentState!.validate(); - if (!isValid) { - return; - } - _form.currentState!.save(); + onPressed: _isSubmitting + ? null + : () async { + // Validate and save the current values to the weightEntry + final isValid = _form.currentState!.validate(); + if (!isValid) { + return; + } + setState(() => _isSubmitting = true); + _form.currentState!.save(); - // Save the entry on the server - _entryData['id'] == null - ? await Provider.of( - context, - listen: false, - ).addEntry( - MeasurementEntry( - id: _entryData['id'], - category: _entryData['category'], - date: _entryData['date'], - value: _entryData['value'], - notes: _entryData['notes'], - ), - ) - : await Provider.of( - context, - listen: false, - ).editEntry( - _entryData['id'], - _entryData['category'], - _entryData['value'], - _entryData['notes'], - _entryData['date'], - ); + final provider = Provider.of(context, listen: false); + try { + // Save the entry on the server + widget.entry == null + ? await provider.addEntry( + MeasurementEntry( + id: null, + category: _categoryId, + date: _selectedDateTime, + value: _selectedValue, + notes: _selectedNotes, + ), + ) + : await provider.editEntry( + widget.entry!.id!, + _categoryId, + _selectedValue, + _selectedNotes, + _selectedDateTime, + ); - if (context.mounted) { - Navigator.of(context).pop(); - } - }, + if (context.mounted) { + Navigator.of(context).pop(); + } + } catch (e) { + debugPrint('Save failed: $e'); + } finally { + setState(() => _isSubmitting = false); + } + }, + child: Text(i18n.save), ), ], ), From 38c0a168b3a6350a3860a54eb8f19912b88ce22e Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Tue, 19 May 2026 19:06:47 +0545 Subject: [PATCH 009/484] adjust code files as per backend measurement entryurl endpoint --- .../measurements/measurement_category.dart | 22 +- .../measurements/measurement_category.g.dart | 7 +- .../measurements/measurement_group.dart | 8 +- .../measurements/measurement_group.g.dart | 15 +- .../measurements/mock_measurement_data.dart | 238 ++++++++++++++++++ lib/providers/measurement.dart | 53 ++-- .../measurement_categories_screen.dart | 76 +++--- lib/screens/measurement_entries_screen.dart | 69 +++-- .../dashboard/widgets/measurements.dart | 186 +++++++------- lib/widgets/measurements/categories.dart | 29 ++- lib/widgets/measurements/entries.dart | 82 +++--- lib/widgets/measurements/forms.dart | 50 +--- 12 files changed, 531 insertions(+), 304 deletions(-) create mode 100644 lib/models/measurements/mock_measurement_data.dart diff --git a/lib/models/measurements/measurement_category.dart b/lib/models/measurements/measurement_category.dart index eb268b0e5..46692f93e 100644 --- a/lib/models/measurements/measurement_category.dart +++ b/lib/models/measurements/measurement_category.dart @@ -23,11 +23,11 @@ class MeasurementCategory extends Equatable { @JsonKey(name: 'group_detail', includeToJson: false) final MeasurementGroup? groupDetail; - @JsonKey(name: 'formula', includeToJson: true) + @JsonKey(name: 'dynamic_type', includeToJson: true) final String? formula; - @JsonKey(name: 'is_dynamic', includeToJson: false, defaultValue: false) - final bool isDynamic; + @JsonKey(name: 'dynamic_params', includeToJson: true, defaultValue: {}) + final Map dynamicParams; @JsonKey(defaultValue: [], toJson: _nullValue) final List entries; @@ -39,28 +39,32 @@ class MeasurementCategory extends Equatable { this.groupId, this.groupDetail, this.formula, - this.isDynamic = false, + this.dynamicParams = const {}, this.entries = const [], }); + bool get isDynamic => formula != null && formula != 'NONE'; + MeasurementCategory copyWith({ int? id, String? name, String? unit, int? groupId, + bool clearGroup = false, MeasurementGroup? groupDetail, + bool clearGroupDetail = false, String? formula, - bool? isDynamic, + Map? dynamicParams, List? entries, }) { return MeasurementCategory( id: id ?? this.id, name: name ?? this.name, unit: unit ?? this.unit, - groupId: groupId ?? this.groupId, - groupDetail: groupDetail ?? this.groupDetail, + groupId: clearGroup ? null : (groupId ?? this.groupId), + groupDetail: clearGroupDetail ? null : (groupDetail ?? this.groupDetail), formula: formula ?? this.formula, - isDynamic: isDynamic ?? this.isDynamic, + dynamicParams: dynamicParams ?? this.dynamicParams, entries: entries ?? this.entries, ); } @@ -79,7 +83,7 @@ class MeasurementCategory extends Equatable { Map toJson() => _$MeasurementCategoryToJson(this); @override - List get props => [id, name, unit, groupId, formula, isDynamic, entries]; + List get props => [id, name, unit, groupId, formula, dynamicParams, entries]; // Helper function which makes the entries list of the toJson output null, as it isn't needed static Null _nullValue(List _) => null; diff --git a/lib/models/measurements/measurement_category.g.dart b/lib/models/measurements/measurement_category.g.dart index 8ead8e403..e3b6b1df5 100644 --- a/lib/models/measurements/measurement_category.g.dart +++ b/lib/models/measurements/measurement_category.g.dart @@ -18,8 +18,8 @@ MeasurementCategory _$MeasurementCategoryFromJson(Map json) { : MeasurementGroup.fromJson( json['group_detail'] as Map, ), - formula: json['formula'] as String?, - isDynamic: json['is_dynamic'] as bool? ?? false, + formula: json['dynamic_type'] as String?, + dynamicParams: json['dynamic_params'] as Map? ?? {}, entries: (json['entries'] as List?) ?.map((e) => MeasurementEntry.fromJson(e as Map)) @@ -35,6 +35,7 @@ Map _$MeasurementCategoryToJson( 'name': instance.name, 'unit': instance.unit, 'group': instance.groupId, - 'formula': instance.formula, + 'dynamic_type': instance.formula, + 'dynamic_params': instance.dynamicParams, 'entries': MeasurementCategory._nullValue(instance.entries), }; diff --git a/lib/models/measurements/measurement_group.dart b/lib/models/measurements/measurement_group.dart index 93fd211e5..6dec86342 100644 --- a/lib/models/measurements/measurement_group.dart +++ b/lib/models/measurements/measurement_group.dart @@ -1,4 +1,3 @@ - import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; @@ -22,16 +21,15 @@ class MeasurementGroup extends Equatable { const MeasurementGroup({ required this.id, - required this.uuid, + this.uuid = '', required this.name, this.description = '', }); - factory MeasurementGroup.fromJson(Map json) => - _$MeasurementGroupFromJson(json); + factory MeasurementGroup.fromJson(Map json) => _$MeasurementGroupFromJson(json); Map toJson() => _$MeasurementGroupToJson(this); @override List get props => [id, uuid, name, description]; -} \ No newline at end of file +} diff --git a/lib/models/measurements/measurement_group.g.dart b/lib/models/measurements/measurement_group.g.dart index 51fee1ae7..59e4cfd1b 100644 --- a/lib/models/measurements/measurement_group.g.dart +++ b/lib/models/measurements/measurement_group.g.dart @@ -10,16 +10,15 @@ MeasurementGroup _$MeasurementGroupFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'uuid', 'name']); return MeasurementGroup( id: (json['id'] as num).toInt(), - uuid: json['uuid'] as String, + uuid: json['uuid'] as String? ?? '', name: json['name'] as String, description: json['description'] as String? ?? '', ); } -Map _$MeasurementGroupToJson(MeasurementGroup instance) => - { - 'id': instance.id, - 'uuid': instance.uuid, - 'name': instance.name, - 'description': instance.description, - }; +Map _$MeasurementGroupToJson(MeasurementGroup instance) => { + 'id': instance.id, + 'uuid': instance.uuid, + 'name': instance.name, + 'description': instance.description, +}; diff --git a/lib/models/measurements/mock_measurement_data.dart b/lib/models/measurements/mock_measurement_data.dart new file mode 100644 index 000000000..dcb9dac5a --- /dev/null +++ b/lib/models/measurements/mock_measurement_data.dart @@ -0,0 +1,238 @@ +import 'package:wger/models/measurements/measurement_category.dart'; +import 'package:wger/models/measurements/measurement_entry.dart'; +import 'package:wger/models/measurements/measurement_group.dart'; + +// ignore: avoid_classes_with_only_static_members +class MeasurementMockData { + static List get dummyGroups => [ + const MeasurementGroup( + id: 9901, + name: 'Body Composition (Mock)', + ), + const MeasurementGroup( + id: 9902, + name: 'Cardiovascular Metrics (Mock)', + ), + const MeasurementGroup( + id: 9903, + name: 'Strength Performance (Mock)', + ), + ]; + + static List get dummyCategories { + final now = DateTime.now(); + + return [ + MeasurementCategory( + id: 8801, + name: 'Weight (Mock)', + unit: 'kg', + groupId: 9901, + formula: 'NONE', + entries: [ + MeasurementEntry( + id: 7701, + category: 8801, + date: now.subtract(const Duration(days: 14)), + value: 89.5, + notes: 'Initial mock reading.', + ), + MeasurementEntry( + id: 7702, + category: 8801, + date: now.subtract(const Duration(days: 7)), + value: 88.8, + notes: 'Morning weight after fasting.', + ), + MeasurementEntry( + id: 7703, + category: 8801, + date: now.subtract(const Duration(days: 1)), + value: 88.2, + notes: 'Consistent drop tracked.', + ), + MeasurementEntry( + id: 7726, + category: 8801, + date: now.subtract(const Duration(days: 32)), + value: 88.4, + notes: 'Auto-generated mock reading 5.', + ), + MeasurementEntry( + id: 7725, + category: 8801, + date: now.subtract(const Duration(days: 30)), + value: 87.9, + notes: 'Auto-generated mock reading 6.', + ), + MeasurementEntry( + id: 7724, + category: 8801, + date: now.subtract(const Duration(days: 28)), + value: 87.5, + notes: 'Auto-generated mock reading 7.', + ), + MeasurementEntry( + id: 7723, + category: 8801, + date: now.subtract(const Duration(days: 26)), + value: 87.3, + notes: 'Auto-generated mock reading 8.', + ), + MeasurementEntry( + id: 7722, + category: 8801, + date: now.subtract(const Duration(days: 24)), + value: 87.1, + notes: 'Auto-generated mock reading 9.', + ), + MeasurementEntry( + id: 7721, + category: 8801, + date: now.subtract(const Duration(days: 22)), + value: 86.6, + notes: 'Auto-generated mock reading 10.', + ), + MeasurementEntry( + id: 7720, + category: 8801, + date: now.subtract(const Duration(days: 20)), + value: 86.4, + notes: 'Auto-generated mock reading 11.', + ), + MeasurementEntry( + id: 7719, + category: 8801, + date: now.subtract(const Duration(days: 18)), + value: 86.0, + notes: 'Auto-generated mock reading 12.', + ), + MeasurementEntry( + id: 7718, + category: 8801, + date: now.subtract(const Duration(days: 16)), + value: 85.7, + notes: 'Auto-generated mock reading 13.', + ), + MeasurementEntry( + id: 7717, + category: 8801, + date: now.subtract(const Duration(days: 14)), + value: 85.4, + notes: 'Auto-generated mock reading 14.', + ), + MeasurementEntry( + id: 7716, + category: 8801, + date: now.subtract(const Duration(days: 12)), + value: 85.3, + notes: 'Auto-generated mock reading 15.', + ), + MeasurementEntry( + id: 7715, + category: 8801, + date: now.subtract(const Duration(days: 10)), + value: 84.9, + notes: 'Auto-generated mock reading 16.', + ), + MeasurementEntry( + id: 7714, + category: 8801, + date: now.subtract(const Duration(days: 8)), + value: 84.8, + notes: 'Auto-generated mock reading 17.', + ), + MeasurementEntry( + id: 7713, + category: 8801, + date: now.subtract(const Duration(days: 6)), + value: 84.7, + notes: 'Auto-generated mock reading 18.', + ), + MeasurementEntry( + id: 7712, + category: 8801, + date: now.subtract(const Duration(days: 4)), + value: 84.2, + notes: 'Auto-generated mock reading 19.', + ), + MeasurementEntry( + id: 7711, + category: 8801, + date: now.subtract(const Duration(days: 2)), + value: 83.9, + notes: 'Auto-generated mock reading 20.', + ), + ], + ), + + // BMI + MeasurementCategory( + id: 8802, + name: 'Body Mass Index (Mock Formula)', + unit: 'index', + groupId: 9901, + formula: 'BMI', + entries: [ + MeasurementEntry( + id: 7704, + category: 8802, + date: now.subtract(const Duration(days: 14)), + value: 24.5, + notes: 'Computed dynamically from height/weight metrics.', + ), + MeasurementEntry( + id: 7705, + category: 8802, + date: now.subtract(const Duration(days: 7)), + value: 24.2, + notes: 'Auto-updated baseline entry.', + ), + ], + ), + + // Chest Circumference has No Assigned Group Link + MeasurementCategory( + id: 8803, + name: 'Chest Circumference (Mock)', + unit: 'cm', + groupId: null, + formula: 'NONE', + entries: [ + MeasurementEntry( + id: 7706, + category: 8803, + date: now.subtract(const Duration(days: 30)), + value: 104.0, + notes: 'Baseline measurement.', + ), + MeasurementEntry( + id: 7707, + category: 8803, + date: now, + value: 106.5, + notes: 'Hypertrophy progress visible.', + ), + ], + ), + + // Blood Pressure + MeasurementCategory( + id: 8804, + name: 'Systolic Blood Pressure (Mock)', + unit: 'mmHg', + groupId: 9902, + formula: 'NONE', + entries: [ + MeasurementEntry( + id: 7708, + category: 8804, + date: now.subtract(const Duration(days: 3)), + value: 120.0, + notes: 'Normal home rest conditions.', + ), + ], + ), + ]; + } +} diff --git a/lib/providers/measurement.dart b/lib/providers/measurement.dart index 213967177..a144b787b 100644 --- a/lib/providers/measurement.dart +++ b/lib/providers/measurement.dart @@ -24,6 +24,7 @@ import 'package:wger/helpers/consts.dart'; import 'package:wger/models/measurements/measurement_category.dart'; import 'package:wger/models/measurements/measurement_entry.dart'; import 'package:wger/models/measurements/measurement_group.dart'; +import 'package:wger/models/measurements/mock_measurement_data.dart'; import 'package:wger/providers/base_provider.dart'; class MeasurementProvider with ChangeNotifier { @@ -32,13 +33,16 @@ class MeasurementProvider with ChangeNotifier { static const _categoryUrl = 'measurement-category'; static const _entryUrl = 'measurement'; static const _groupUrl = 'measurement-group'; - static const _dynamicValuesAction = 'dynamic-values'; final WgerBaseProvider baseProvider; List _categories = []; List _groups = []; - MeasurementProvider(this.baseProvider); + MeasurementProvider(this.baseProvider) { + // TODO: REMOVE before merge — loads mock data for UI development + _groups = MeasurementMockData.dummyGroups; + _categories = MeasurementMockData.dummyCategories; + } List get categories => _categories; List get groups => _groups; @@ -75,11 +79,6 @@ class MeasurementProvider with ChangeNotifier { Future fetchAndSetCategoryEntries(int id) async { final category = findCategoryById(id); - if (category.isDynamic) { - await fetchDynamicCategoryEntries(id); - return; - } - final categoryIndex = _categories.indexOf(category); // Process the response @@ -98,34 +97,6 @@ class MeasurementProvider with ChangeNotifier { notifyListeners(); } - /// Fetches computed values for a dynamic (formula-based) category - /// and sets the measurement entries - Future fetchDynamicCategoryEntries(int categoryId) async { - final category = findCategoryById(categoryId); - if (!category.isDynamic) return; - - final categoryIndex = _categories.indexOf(category); - - final requestUrl = baseProvider.makeUrl( - '$_categoryUrl/$categoryId/$_dynamicValuesAction', - ); - - // The dynamic-values endpoint returns a plain list, not paginated. - final dynamic rawData = await baseProvider.fetch(requestUrl); - final List data = rawData is List ? rawData : (rawData['results'] ?? []); - - final List computedEntries = data - .map((e) => MeasurementEntry.fromJson(e as Map)) - .toList(); - - final MeasurementCategory editedCategory = category.copyWith( - entries: computedEntries, - ); - _categories.removeAt(categoryIndex); - _categories.insert(categoryIndex, editedCategory); - notifyListeners(); - } - /// Fetches and sets the measurement categories and their entries Future fetchAndSetAllCategoriesAndEntries() async { _logger.info('Fetching all measurement categories and entries'); @@ -175,8 +146,13 @@ class MeasurementProvider with ChangeNotifier { }) async { final MeasurementCategory oldCategory = findCategoryById(id); final int categoryIndex = _categories.indexOf(oldCategory); - final MeasurementCategory tempNewCategory = oldCategory.copyWith(name: newName, unit: newUnit); - + final MeasurementCategory tempNewCategory = oldCategory.copyWith( + name: newName, + unit: newUnit, + groupId: newGroupId, + clearGroup: clearGroup, + formula: newFormula, + ); final Map response = await baseProvider.patch( tempNewCategory.toJson(), baseProvider.makeUrl(_categoryUrl, id: id), @@ -288,8 +264,6 @@ class MeasurementProvider with ChangeNotifier { } /// Edits a measurement entry - /// Currently there isn't any fallback if the call to the api is unsuccessful, as - /// WgerBaseProvider.patch only returns the response body and not the whole response Future editEntry( int id, int categoryId, @@ -298,6 +272,7 @@ class MeasurementProvider with ChangeNotifier { DateTime? newDate, ) async { final MeasurementCategory category = findCategoryById(categoryId); + final MeasurementEntry oldEntry = category.findEntryById(id); final int entryIndex = category.entries.indexOf(oldEntry); final MeasurementEntry tempNewEntry = oldEntry.copyWith( diff --git a/lib/screens/measurement_categories_screen.dart b/lib/screens/measurement_categories_screen.dart index 5aa28a2a2..6934344c3 100644 --- a/lib/screens/measurement_categories_screen.dart +++ b/lib/screens/measurement_categories_screen.dart @@ -26,7 +26,6 @@ import 'package:wger/widgets/measurements/categories.dart'; import 'package:wger/widgets/measurements/forms.dart'; class MeasurementCategoriesScreen extends StatefulWidget { - const MeasurementCategoriesScreen(); static const routeName = '/measurement-categories'; @@ -37,7 +36,6 @@ class MeasurementCategoriesScreen extends StatefulWidget { class _MeasurementCategoriesScreenState extends State { int? _selectedGroupId; - @override Widget build(BuildContext context) { return Scaffold( @@ -50,7 +48,7 @@ class _MeasurementCategoriesScreenState extends State( builder: (context, provider, child) { - - final groups = provider.groups; - if (groups.isEmpty) return const SizedBox.shrink(); + final groups = provider.groups; - return SingleChildScrollView( - scrollDirection: Axis.horizontal, - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - child: Row( - children: [ - // clears group filter - FilterChip( - label: const Text('All'), - selected: _selectedGroupId == null, - onSelected: (_) => setState(() => _selectedGroupId = null), - ), - const SizedBox(width: 6), - // One chip per group - ...groups.map( - (group) => Padding( - padding: const EdgeInsets.only(right: 6), - child: FilterChip( - label: Text(group.name), - selected: _selectedGroupId == group.id, - onSelected: (_) => setState( - () => _selectedGroupId = - _selectedGroupId == group.id ? null : group.id, + return Column( + children: [ + // Group filter chips + if (groups.isNotEmpty) + SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + children: [ + FilterChip( + label: const Text('All'), + selected: _selectedGroupId == null, + onSelected: (_) => setState(() => _selectedGroupId = null), + ), + const SizedBox(width: 6), + ...groups.map( + (group) => Padding( + padding: const EdgeInsets.only(right: 6), + child: FilterChip( + label: Text(group.name), + selected: _selectedGroupId == group.id, + onSelected: (_) => setState( + () => _selectedGroupId = _selectedGroupId == group.id + ? null + : group.id, + ), + ), + ), + ), + ], + ), + ), + + Expanded( + child: CategoriesList(_selectedGroupId), ), - ), - ), - ), - CategoriesList(_selectedGroupId), - ], - ), - ); - } + ], + ); + }, ), ), ); diff --git a/lib/screens/measurement_entries_screen.dart b/lib/screens/measurement_entries_screen.dart index b8a5728af..43623f7bd 100644 --- a/lib/screens/measurement_entries_screen.dart +++ b/lib/screens/measurement_entries_screen.dart @@ -55,28 +55,54 @@ class MeasurementEntriesScreen extends StatelessWidget { } if (category.isDynamic) { - return Container( - margin: const EdgeInsets.all(8), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - decoration: BoxDecoration( - color: Colors.blue.withValues(alpha: 0.08), - borderRadius: BorderRadius.circular(8), - border: Border.all(color: Colors.blue.withValues(alpha: 0.3)), - ), - child: Row( - children: [ - const Icon(Icons.auto_graph, color: Colors.blue, size: 18), - const SizedBox(width: 8), - Expanded( - child: Text( - 'Values for this category are calculated automatically ' - 'using the "${category.formula}" formula. ' - 'You cannot add entries manually.', - style: const TextStyle(fontSize: 13), - ), + return Scaffold( + appBar: AppBar( + title: Text(category.name), + actions: [ + Chip( + avatar: const Icon(Icons.auto_awesome, size: 14), + label: const Text('Auto-calculated'), + backgroundColor: Colors.blue.withValues(alpha: 0.15), ), + const SizedBox(width: 8), ], ), + body: WidescreenWrapper( + child: SingleChildScrollView( + child: Column( + children: [ + // Info banner + Container( + margin: const EdgeInsets.all(12), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.blue.withValues(alpha: 0.3)), + ), + child: Row( + children: [ + const Icon(Icons.auto_graph, color: Colors.blue, size: 18), + const SizedBox(width: 8), + Expanded( + child: Text( + 'Values for this category are calculated automatically ' + 'using the "${category.formula == 'NONE' || category.formula == null ? 'formula' : category.formula!.toLowerCase()}" formula. ' + 'You cannot add entries manually.', + style: const TextStyle(fontSize: 13), + ), + ), + ], + ), + ), + // Show the computed entries read-only + Consumer( + builder: (context, provider, child) => EntriesList(category!), + ), + ], + ), + ), + ), ); } @@ -94,7 +120,7 @@ class MeasurementEntriesScreen extends StatelessWidget { FormScreen.routeName, arguments: FormScreenArguments( AppLocalizations.of(context).edit, - MeasurementCategoryForm(), + MeasurementCategoryForm(category: category), ), ); break; @@ -128,9 +154,8 @@ class MeasurementEntriesScreen extends StatelessWidget { // Close the popup Navigator.of(contextDialog).pop(); - Navigator.of(context).pop(); // Exit detail screen + Navigator.of(context).pop(); - // and inform the user ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( diff --git a/lib/widgets/dashboard/widgets/measurements.dart b/lib/widgets/dashboard/widgets/measurements.dart index 498028aae..a9794afe6 100644 --- a/lib/widgets/dashboard/widgets/measurements.dart +++ b/lib/widgets/dashboard/widgets/measurements.dart @@ -40,105 +40,107 @@ class _DashboardMeasurementWidgetState extends State @override Widget build(BuildContext context) { - final provider = Provider.of(context, listen: false); + // final provider = Provider.of(context, listen: false); - final items = provider.categories - .map((item) => CategoriesCard(item, elevation: 0)) - .toList(); - if (items.isNotEmpty) { - items.add( - NothingFound( - AppLocalizations.of(context).moreMeasurementEntries, - AppLocalizations.of(context).newEntry, - MeasurementCategoryForm(), - ), - ); - } return Consumer( - builder: (context, _, _) => Card( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - title: Text( - AppLocalizations.of(context).measurements, - style: Theme.of(context).textTheme.headlineSmall, - ), - leading: FaIcon( - FontAwesomeIcons.chartLine, - color: Theme.of(context).textTheme.headlineSmall!.color, - ), - // TODO: this icon feels out of place and inconsistent with all - // other dashboard widgets. - // maybe we should just add a "Go to all" at the bottom of the widget - trailing: IconButton( - icon: const Icon(Icons.arrow_forward), - onPressed: () => Navigator.pushNamed( - context, - MeasurementCategoriesScreen.routeName, + builder: (context, provider, _) { + final items = provider.categories + .map((item) => CategoriesCard(item, elevation: 0)) + .toList(); + if (items.isNotEmpty) { + items.add( + NothingFound( + AppLocalizations.of(context).moreMeasurementEntries, + AppLocalizations.of(context).newEntry, + MeasurementCategoryForm(), + ), + ); + } + return Card( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + title: Text( + AppLocalizations.of(context).measurements, + style: Theme.of(context).textTheme.headlineSmall, + ), + leading: FaIcon( + FontAwesomeIcons.chartLine, + color: Theme.of(context).textTheme.headlineSmall!.color, + ), + // TODO: this icon feels out of place and inconsistent with all + // other dashboard widgets. + // maybe we should just add a "Go to all" at the bottom of the widget + trailing: IconButton( + icon: const Icon(Icons.arrow_forward), + onPressed: () => Navigator.pushNamed( + context, + MeasurementCategoriesScreen.routeName, + ), ), ), - ), - Column( - children: [ - if (items.isNotEmpty) - Column( - children: [ - CarouselSlider( - items: items, - carouselController: _controller, - options: CarouselOptions( - autoPlay: false, - enlargeCenterPage: false, - viewportFraction: 1, - enableInfiniteScroll: false, - aspectRatio: 1.1, - onPageChanged: (index, reason) { - setState(() { - _current = index; - }); - }, + Column( + children: [ + if (items.isNotEmpty) + Column( + children: [ + CarouselSlider( + items: items, + carouselController: _controller, + options: CarouselOptions( + autoPlay: false, + enlargeCenterPage: false, + viewportFraction: 1, + enableInfiniteScroll: false, + aspectRatio: 1.1, + onPageChanged: (index, reason) { + setState(() { + _current = index; + }); + }, + ), ), - ), - Padding( - padding: const EdgeInsets.only(bottom: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: items.asMap().entries.map((entry) { - return GestureDetector( - onTap: () => _controller.animateToPage(entry.key), - child: Container( - width: 12.0, - height: 12.0, - margin: const EdgeInsets.symmetric( - vertical: 8.0, - horizontal: 4.0, + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: items.asMap().entries.map((entry) { + return GestureDetector( + onTap: () => _controller.animateToPage(entry.key), + child: Container( + width: 12.0, + height: 12.0, + margin: const EdgeInsets.symmetric( + vertical: 8.0, + horizontal: 4.0, + ), + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Theme.of(context).textTheme.headlineSmall!.color! + .withValues( + alpha: _current == entry.key ? 0.9 : 0.4, + ), + ), ), - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Theme.of(context).textTheme.headlineSmall!.color! - .withValues( - alpha: _current == entry.key ? 0.9 : 0.4, - ), - ), - ), - ); - }).toList(), + ); + }).toList(), + ), ), - ), - ], - ) - else - NothingFound( - AppLocalizations.of(context).noMeasurementEntries, - AppLocalizations.of(context).newEntry, - MeasurementCategoryForm(), - ), - ], - ), - ], - ), - ), + ], + ) + else + NothingFound( + AppLocalizations.of(context).noMeasurementEntries, + AppLocalizations.of(context).newEntry, + MeasurementCategoryForm(), + ), + ], + ), + ], + ), + ); + }, ); } } diff --git a/lib/widgets/measurements/categories.dart b/lib/widgets/measurements/categories.dart index a00905175..a8ead1a68 100644 --- a/lib/widgets/measurements/categories.dart +++ b/lib/widgets/measurements/categories.dart @@ -23,24 +23,31 @@ import 'package:wger/providers/measurement.dart'; import 'categories_card.dart'; class CategoriesList extends StatelessWidget { - final int? _selectedGrouptID; - const CategoriesList(this._selectedGrouptID); + final int? _selectedGroupID; + const CategoriesList([this._selectedGroupID]); @override Widget build(BuildContext context) { final provider = Provider.of(context, listen: false); - final categories = provider.categories.where((cat) { - if (_selectedGrouptID == null) return true; - return cat.groupId == _selectedGrouptID; - }).toList(); + // Filter by group if a chip is selected + final visibleCategories = _selectedGroupID == null + ? provider.categories + : provider.categories.where((c) => c.groupId == _selectedGroupID).toList(); return RefreshIndicator( onRefresh: () => provider.fetchAndSetAllCategoriesAndEntries(), - child: ListView.builder( - padding: const EdgeInsets.all(10.0), - itemCount: categories.length, - itemBuilder: (context, index) => CategoriesCard(categories[index]), - ), + child: visibleCategories.isEmpty + ? const Center( + child: Padding( + padding: EdgeInsets.all(32), + child: Text('No categories found.'), + ), + ) + : ListView.builder( + padding: const EdgeInsets.all(10.0), + itemCount: visibleCategories.length, + itemBuilder: (context, index) => CategoriesCard(visibleCategories[index]), + ), ); } } diff --git a/lib/widgets/measurements/entries.dart b/lib/widgets/measurements/entries.dart index 6985a1bc4..cb82b6d69 100644 --- a/lib/widgets/measurements/entries.dart +++ b/lib/widgets/measurements/entries.dart @@ -69,48 +69,54 @@ class EntriesList extends StatelessWidget { child: ListTile( title: Text('${numberFormat.format(currentEntry.value)} ${_category.unit}'), subtitle: Text(datetimeFormat.format(currentEntry.date)), - trailing: PopupMenuButton( - itemBuilder: (BuildContext context) { - return [ - PopupMenuItem( - child: Text(AppLocalizations.of(context).edit), - onTap: () => Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).edit, - MeasurementEntryForm( - categoryId: currentEntry.category, - entry: currentEntry, - ), - ), - ), - ), - PopupMenuItem( - child: Text(AppLocalizations.of(context).delete), - onTap: () async { - // Delete entry from DB - await provider.deleteEntry( - currentEntry.id!, - currentEntry.category, - ); - - // and inform the user - if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - AppLocalizations.of(context).successfullyDeleted, - textAlign: TextAlign.center, + // Hide edit/delete entry for Dynamic category + trailing: _category.isDynamic + ? const Tooltip( + message: 'Auto-calculated — cannot be edited or deleted', + child: Icon(Icons.auto_graph, size: 18, color: Colors.blue), + ) + : PopupMenuButton( + itemBuilder: (BuildContext context) { + return [ + PopupMenuItem( + child: Text(AppLocalizations.of(context).edit), + onTap: () => Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).edit, + MeasurementEntryForm( + categoryId: currentEntry.category, + entry: currentEntry, + ), ), ), - ); - } + ), + PopupMenuItem( + child: Text(AppLocalizations.of(context).delete), + onTap: () async { + // Delete entry from DB + await provider.deleteEntry( + currentEntry.id!, + currentEntry.category, + ); + + // and inform the user + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + AppLocalizations.of(context).successfullyDeleted, + textAlign: TextAlign.center, + ), + ), + ); + } + }, + ), + ]; }, ), - ]; - }, - ), ), ); }, diff --git a/lib/widgets/measurements/forms.dart b/lib/widgets/measurements/forms.dart index b69f08015..ff217e698 100644 --- a/lib/widgets/measurements/forms.dart +++ b/lib/widgets/measurements/forms.dart @@ -39,11 +39,6 @@ class MeasurementCategoryForm extends StatefulWidget { } class _MeasurementCategoryFormState extends State { - final List _dummyGroups = [ - const MeasurementGroup(uuid: '1', id: 1, name: 'Dummy: Bodyweight'), - const MeasurementGroup(uuid: '2', id: 2, name: 'Dummy: Strength'), - ]; - final _form = GlobalKey(); late final TextEditingController nameController; late final TextEditingController unitController; @@ -55,9 +50,9 @@ class _MeasurementCategoryFormState extends State { bool _isSubmitting = false; static const Map _formulaLabels = { - 'bmi': 'Body Mass Index (BMI)', - 'lbm': 'Lean Body Mass', - '1rm_epley': '1RM — Epley formula', + 'BMI': 'Body Mass Index (BMI)', + // 'LBM': 'Lean Body Mass', + // '1RM_EPLEY': '1RM — Epley formula', }; @override @@ -69,7 +64,7 @@ class _MeasurementCategoryFormState extends State { unitController = TextEditingController(text: cat?.unit ?? ''); _selectedGroupId = cat?.groupId; - _selectedFormula = cat?.formula; + _selectedFormula = (cat?.formula == null || cat?.formula == 'NONE') ? null : cat?.formula; } @override @@ -177,6 +172,7 @@ class _MeasurementCategoryFormState extends State { final measurementProvider = Provider.of(context, listen: false); // Save the entry on the server + final formulaToSave = _selectedFormula ?? 'NONE'; try { if (_categoryId == null) { await measurementProvider.addCategory( @@ -185,7 +181,7 @@ class _MeasurementCategoryFormState extends State { name: nameController.text.trim(), unit: unitController.text.trim(), groupId: _selectedGroupId, - formula: _selectedFormula, + formula: formulaToSave, ), ); } else { @@ -194,7 +190,7 @@ class _MeasurementCategoryFormState extends State { nameController.text.trim(), unitController.text.trim(), _selectedGroupId, - _selectedFormula, + formulaToSave, clearGroup: _selectedGroupId == null, clearFormula: _selectedFormula == null, ); @@ -290,34 +286,6 @@ class _MeasurementEntryFormState extends State { _valueController.text = numberFormat.format(widget.entry!.value); } - if (measurementCategory.isDynamic) { - return Padding( - padding: const EdgeInsets.all(16), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.auto_graph, size: 48, color: Colors.blue), - const SizedBox(height: 12), - Text( - 'This measurement is calculated automatically.', // TODO: i18n - style: Theme.of(context).textTheme.titleMedium, - textAlign: TextAlign.center, - ), - const SizedBox(height: 6), - Text( - 'Formula: ${measurementCategory.formula ?? ''}', - style: Theme.of(context).textTheme.bodySmall, - ), - const SizedBox(height: 8), - Text( - 'To see computed values, open the category detail page.', - textAlign: TextAlign.center, - ), - ], - ), - ); - } - return Form( key: _form, child: Column( @@ -352,7 +320,7 @@ class _MeasurementEntryFormState extends State { }, onSaved: (newValue) { final date = dateFormat.parse(newValue!); - _selectedDateTime = (_selectedDateTime as DateTime).copyWith( + _selectedDateTime = _selectedDateTime.copyWith( year: date.year, month: date.month, day: date.day, @@ -398,7 +366,7 @@ class _MeasurementEntryFormState extends State { }, onSaved: (newValue) { final time = timeFormat.parse(newValue!); - _selectedDateTime = (_selectedDateTime as DateTime).copyWith( + _selectedDateTime = _selectedDateTime.copyWith( hour: time.hour, minute: time.minute, second: time.second, From 51ad3520fa94c8c4d8104486d11582bf7c8c0efe Mon Sep 17 00:00:00 2001 From: John Mccaulley Date: Thu, 28 May 2026 15:22:31 -0400 Subject: [PATCH 010/484] initial code for profile usage --- lib/main.dart | 7 ++++--- lib/models/workouts/set_config_data.dart | 2 +- lib/models/workouts/set_config_data.g.dart | 2 +- lib/models/workouts/slot_entry.dart | 3 +-- lib/providers/routines.dart | 18 +++++++++++++----- lib/providers/user.dart | 20 +++++++++++++++----- lib/screens/home_tabs_screen.dart | 2 -- 7 files changed, 35 insertions(+), 19 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 1a7f61127..0dbe18ef7 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -163,14 +163,15 @@ class MainApp extends StatelessWidget { update: (context, base, previous) => previous ?? ExercisesProvider(WgerBaseProvider(base)), ), - ChangeNotifierProxyProvider2( + ChangeNotifierProxyProvider3( create: (context) => RoutinesProvider( WgerBaseProvider(Provider.of(context, listen: false)), Provider.of(context, listen: false), + Provider.of(context, listen: true), [], ), - update: (context, auth, exercises, previous) => - previous ?? RoutinesProvider(WgerBaseProvider(auth), exercises, []), + update: (context, auth, exercises, user, previous) => + previous ?? RoutinesProvider(WgerBaseProvider(auth), exercises, user, []), ), ChangeNotifierProxyProvider( create: (context) => NutritionPlansProvider( diff --git a/lib/models/workouts/set_config_data.dart b/lib/models/workouts/set_config_data.dart index 38b8e1520..47435945c 100644 --- a/lib/models/workouts/set_config_data.dart +++ b/lib/models/workouts/set_config_data.dart @@ -107,7 +107,7 @@ class SetConfigData { this.maxNrOfSets, this.weight, this.maxWeight, - this.weightUnitId = WEIGHT_UNIT_KG, + this.weightUnitId, this.weightRounding, this.repetitions, this.maxRepetitions, diff --git a/lib/models/workouts/set_config_data.g.dart b/lib/models/workouts/set_config_data.g.dart index e415005b7..eba87c76a 100644 --- a/lib/models/workouts/set_config_data.g.dart +++ b/lib/models/workouts/set_config_data.g.dart @@ -40,7 +40,7 @@ SetConfigData _$SetConfigDataFromJson(Map json) { maxNrOfSets: json['max_sets'] as num?, weight: stringToNumNull(json['weight'] as String?), maxWeight: stringToNumNull(json['max_weight'] as String?), - weightUnitId: (json['weight_unit'] as num?)?.toInt() ?? WEIGHT_UNIT_KG, + weightUnitId: (json['weight_unit'] as num?)?.toInt(), weightRounding: stringToNumNull(json['weight_rounding'] as String?), repetitions: stringToNumNull(json['repetitions'] as String?), maxRepetitions: stringToNumNull(json['max_repetitions'] as String?), diff --git a/lib/models/workouts/slot_entry.dart b/lib/models/workouts/slot_entry.dart index 47f87bd08..5e46bc3c1 100644 --- a/lib/models/workouts/slot_entry.dart +++ b/lib/models/workouts/slot_entry.dart @@ -192,7 +192,7 @@ class SlotEntry { int? order, SlotEntryType? type, required Exercise exercise, - int? weightUnitId, + this.weightUnitId, this.weightRounding, int? repetitionUnitId, this.repetitionRounding, @@ -203,7 +203,6 @@ class SlotEntry { this.type = type ?? SlotEntryType.normal; exerciseObj = exercise; exerciseId = exercise.id!; - this.weightUnitId = weightUnitId ?? WEIGHT_UNIT_KG; this.repetitionUnitId = repetitionUnitId ?? REP_UNIT_REPETITIONS_ID; } diff --git a/lib/providers/routines.dart b/lib/providers/routines.dart index 7072afe66..eba0081be 100644 --- a/lib/providers/routines.dart +++ b/lib/providers/routines.dart @@ -37,6 +37,7 @@ import 'package:wger/models/workouts/slot_entry.dart'; import 'package:wger/models/workouts/weight_unit.dart'; import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/exercises.dart'; +import 'package:wger/providers/user.dart'; class RoutinesProvider with ChangeNotifier { final _logger = Logger('RoutinesProvider'); @@ -67,6 +68,7 @@ class RoutinesProvider with ChangeNotifier { Routine? activeRoutine; final ExercisesProvider _exerciseProvider; final WgerBaseProvider baseProvider; + final UserProvider _userProvider; List _routines = []; List _weightUnits = []; List _repetitionUnits = []; @@ -74,6 +76,7 @@ class RoutinesProvider with ChangeNotifier { RoutinesProvider( this.baseProvider, this._exerciseProvider, + this._userProvider, List entries, { List? weightUnits, List? repetitionUnits, @@ -112,8 +115,9 @@ class RoutinesProvider with ChangeNotifier { } /// Return the default weight unit (kg) - WeightUnit get defaultWeightUnit { - return _weightUnits.firstWhere((element) => element.id == WEIGHT_UNIT_KG); + Future get defaultWeightUnit async { + final id = await _userProvider.isMetric() ? WEIGHT_UNIT_KG : WEIGHT_UNIT_LB; + return _weightUnits.firstWhere((element) => element.id == id); } WeightUnit findWeightUnitById(int id) => _weightUnits.firstWhere((element) => element.id == id); @@ -203,9 +207,13 @@ class RoutinesProvider with ChangeNotifier { (e) => e.id == setConfig.repetitionsUnitId, ); - setConfig.weightUnit = _weightUnits.firstWhere( - (e) => e.id == setConfig.weightUnitId, - ); + if (setConfig.weightUnitId != null) { + setConfig.weightUnit = _weightUnits.firstWhere( + (e) => e.id == setConfig.weightUnitId, + ); + } else { + setConfig.weightUnit = await defaultWeightUnit; + } } } } diff --git a/lib/providers/user.dart b/lib/providers/user.dart index 7659e841f..43f528ca4 100644 --- a/lib/providers/user.dart +++ b/lib/providers/user.dart @@ -244,7 +244,7 @@ class UserProvider with ChangeNotifier { } /// Fetch the current user's profile - Future fetchAndSetProfile() async { + Future _fetchAndSetProfile() async { final userData = await baseProvider.fetch(baseProvider.makeUrl(PROFILE_URL)); try { profile = Profile.fromJson(userData); @@ -255,10 +255,13 @@ class UserProvider with ChangeNotifier { /// Save the user's profile to the server Future saveProfile() async { - await baseProvider.post( - profile!.toJson(), - baseProvider.makeUrl(PROFILE_URL), - ); + final profile = this.profile; + if (profile != null) { + await baseProvider.post( + profile.toJson(), + baseProvider.makeUrl(PROFILE_URL), + ); + } } /// Verify the user's email @@ -271,4 +274,11 @@ class UserProvider with ChangeNotifier { ); //log(verificationData.toString()); } + + Future isMetric() async { + if (profile == null) { + await _fetchAndSetProfile(); + } + return profile?.isMetric ?? false; + } } diff --git a/lib/screens/home_tabs_screen.dart b/lib/screens/home_tabs_screen.dart index 10de168f7..61baa85da 100644 --- a/lib/screens/home_tabs_screen.dart +++ b/lib/screens/home_tabs_screen.dart @@ -93,14 +93,12 @@ class _HomeTabsScreenState extends ConsumerState final galleryProvider = context.read(); final weightProvider = context.read(); final measurementProvider = context.read(); - final userProvider = context.read(); // // Base data widget._logger.info('Loading base data'); await Future.wait([ authProvider.setServerVersion(), - userProvider.fetchAndSetProfile(), routinesProvider.fetchAndSetUnits(), nutritionPlansProvider.fetchIngredientsFromCache(), exercisesProvider.fetchAndSetInitialData(), From fb599a488987c8381bf0f928802f5322758d4d79 Mon Sep 17 00:00:00 2001 From: John Mccaulley Date: Thu, 28 May 2026 15:38:27 -0400 Subject: [PATCH 011/484] updating tests to pass --- test/routine/routine_screen_test.dart | 5 +- test/routine/routine_screen_test.mocks.dart | 245 +++++++++- test/routine/routines_provider_test.dart | 16 +- .../routine/routines_provider_test.mocks.dart | 441 +++++++++++++----- test/routine/routines_screen_test.dart | 5 +- test/routine/routines_screen_test.mocks.dart | 245 +++++++++- test/user/provider_test.dart | 6 +- 7 files changed, 794 insertions(+), 169 deletions(-) diff --git a/test/routine/routine_screen_test.dart b/test/routine/routine_screen_test.dart index 9d46b1d26..97fb78574 100644 --- a/test/routine/routine_screen_test.dart +++ b/test/routine/routine_screen_test.dart @@ -28,14 +28,16 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/exercises.dart'; import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/user.dart'; import 'package:wger/screens/routine_screen.dart'; import '../../test_data/routines.dart'; import 'routine_screen_test.mocks.dart'; -@GenerateMocks([WgerBaseProvider]) +@GenerateMocks([WgerBaseProvider, UserProvider]) void main() { final mockBaseProvider = MockWgerBaseProvider(); + final mockUserProvider = MockUserProvider(); final exercisesProvider = ExercisesProvider( mockBaseProvider, database: ExerciseDatabase.inMemory(NativeDatabase.memory()), @@ -48,6 +50,7 @@ void main() { create: (context) => RoutinesProvider( mockBaseProvider, exercisesProvider, + mockUserProvider, [getTestRoutine()], ), child: MaterialApp( diff --git a/test/routine/routine_screen_test.mocks.dart b/test/routine/routine_screen_test.mocks.dart index aac1c9eac..166b4a5e8 100644 --- a/test/routine/routine_screen_test.mocks.dart +++ b/test/routine/routine_screen_test.mocks.dart @@ -3,12 +3,17 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i5; +import 'dart:async' as _i6; +import 'dart:ui' as _i9; +import 'package:flutter/material.dart' as _i8; import 'package:http/http.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; +import 'package:shared_preferences/shared_preferences.dart' as _i5; +import 'package:wger/models/user/profile.dart' as _i10; import 'package:wger/providers/auth.dart' as _i2; import 'package:wger/providers/base_provider.dart' as _i4; +import 'package:wger/providers/user.dart' as _i7; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -26,19 +31,35 @@ import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: invalid_use_of_internal_member class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeWgerBaseProvider_4 extends _i1.SmartFake + implements _i4.WgerBaseProvider { + _FakeWgerBaseProvider_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeSharedPreferencesAsync_5 extends _i1.SmartFake + implements _i5.SharedPreferencesAsync { + _FakeSharedPreferencesAsync_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -116,7 +137,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch( + _i6.Future fetch( Uri? uri, { int? maxRetries = 3, Duration? initialDelay = const Duration(milliseconds: 250), @@ -134,12 +155,12 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { #language: language, }, ), - returnValue: _i5.Future.value(), + returnValue: _i6.Future.value(), ) - as _i5.Future); + as _i6.Future); @override - _i5.Future> fetchPaginated( + _i6.Future> fetchPaginated( Uri? uri, { String? language, Duration? timeout = const Duration(seconds: 15), @@ -150,43 +171,227 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { [uri], {#language: language, #timeout: timeout}, ), - returnValue: _i5.Future>.value([]), + returnValue: _i6.Future>.value([]), ) - as _i5.Future>); + as _i6.Future>); @override - _i5.Future> post(Map? data, Uri? uri) => + _i6.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( Invocation.method(#post, [data, uri]), - returnValue: _i5.Future>.value( + returnValue: _i6.Future>.value( {}, ), ) - as _i5.Future>); + as _i6.Future>); @override - _i5.Future> patch( + _i6.Future> patch( Map? data, Uri? uri, ) => (super.noSuchMethod( Invocation.method(#patch, [data, uri]), - returnValue: _i5.Future>.value( + returnValue: _i6.Future>.value( {}, ), ) - as _i5.Future>); + as _i6.Future>); @override - _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => + _i6.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( Invocation.method(#deleteRequest, [url, id]), - returnValue: _i5.Future<_i3.Response>.value( + returnValue: _i6.Future<_i3.Response>.value( _FakeResponse_3( this, Invocation.method(#deleteRequest, [url, id]), ), ), ) - as _i5.Future<_i3.Response>); + as _i6.Future<_i3.Response>); +} + +/// A class which mocks [UserProvider]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockUserProvider extends _i1.Mock implements _i7.UserProvider { + MockUserProvider() { + _i1.throwOnMissingStub(this); + } + + @override + _i8.ThemeMode get themeMode => + (super.noSuchMethod( + Invocation.getter(#themeMode), + returnValue: _i8.ThemeMode.system, + ) + as _i8.ThemeMode); + + @override + _i4.WgerBaseProvider get baseProvider => + (super.noSuchMethod( + Invocation.getter(#baseProvider), + returnValue: _FakeWgerBaseProvider_4( + this, + Invocation.getter(#baseProvider), + ), + ) + as _i4.WgerBaseProvider); + + @override + _i5.SharedPreferencesAsync get prefs => + (super.noSuchMethod( + Invocation.getter(#prefs), + returnValue: _FakeSharedPreferencesAsync_5( + this, + Invocation.getter(#prefs), + ), + ) + as _i5.SharedPreferencesAsync); + + @override + List<_i7.DashboardWidget> get dashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#dashboardWidgets), + returnValue: <_i7.DashboardWidget>[], + ) + as List<_i7.DashboardWidget>); + + @override + List<_i7.DashboardWidget> get allDashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#allDashboardWidgets), + returnValue: <_i7.DashboardWidget>[], + ) + as List<_i7.DashboardWidget>); + + @override + set themeMode(_i8.ThemeMode? value) => super.noSuchMethod( + Invocation.setter(#themeMode, value), + returnValueForMissingStub: null, + ); + + @override + set userLocale(_i9.Locale? value) => super.noSuchMethod( + Invocation.setter(#userLocale, value), + returnValueForMissingStub: null, + ); + + @override + set prefs(_i5.SharedPreferencesAsync? value) => super.noSuchMethod( + Invocation.setter(#prefs, value), + returnValueForMissingStub: null, + ); + + @override + set profile(_i10.Profile? value) => super.noSuchMethod( + Invocation.setter(#profile, value), + returnValueForMissingStub: null, + ); + + @override + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); + + @override + void clear() => super.noSuchMethod( + Invocation.method(#clear, []), + returnValueForMissingStub: null, + ); + + @override + bool isDashboardWidgetVisible(_i7.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i6.Future setDashboardWidgetVisible( + _i7.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + _i6.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + void setThemeMode(_i8.ThemeMode? mode) => super.noSuchMethod( + Invocation.method(#setThemeMode, [mode]), + returnValueForMissingStub: null, + ); + + @override + _i6.Future setUserLocale(_i9.Locale? locale) => + (super.noSuchMethod( + Invocation.method(#setUserLocale, [locale]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + _i6.Future saveProfile() => + (super.noSuchMethod( + Invocation.method(#saveProfile, []), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + _i6.Future verifyEmail() => + (super.noSuchMethod( + Invocation.method(#verifyEmail, []), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + _i6.Future isMetric() => + (super.noSuchMethod( + Invocation.method(#isMetric, []), + returnValue: _i6.Future.value(false), + ) + as _i6.Future); + + @override + void addListener(_i9.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#addListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void removeListener(_i9.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#removeListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void dispose() => super.noSuchMethod( + Invocation.method(#dispose, []), + returnValueForMissingStub: null, + ); + + @override + void notifyListeners() => super.noSuchMethod( + Invocation.method(#notifyListeners, []), + returnValueForMissingStub: null, + ); } diff --git a/test/routine/routines_provider_test.dart b/test/routine/routines_provider_test.dart index 4679985c5..15e401439 100644 --- a/test/routine/routines_provider_test.dart +++ b/test/routine/routines_provider_test.dart @@ -35,15 +35,17 @@ import 'package:wger/models/workouts/weight_unit.dart'; import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/exercises.dart'; import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/user.dart'; import '../../test_data/exercises.dart'; import '../../test_data/routines.dart'; import '../fixtures/fixture_reader.dart'; import 'routines_provider_test.mocks.dart'; -@GenerateMocks([WgerBaseProvider, ExercisesProvider]) +@GenerateMocks([WgerBaseProvider, ExercisesProvider, UserProvider]) void main() { final mockBaseProvider = MockWgerBaseProvider(); + final mockUserProvider = MockUserProvider(); /// Replacement for SharedPreferences.setMockInitialValues() SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); @@ -74,7 +76,7 @@ void main() { ); // Load the entries - final provider = RoutinesProvider(mockBaseProvider, exercisesProvider, []); + final provider = RoutinesProvider(mockBaseProvider, exercisesProvider, mockUserProvider, []); final plan = await provider.fetchAndSetRoutineSparse(325397); final plans = provider.getPlans(); @@ -102,7 +104,7 @@ void main() { ); // Load the entries - final provider = RoutinesProvider(mockBaseProvider, exercisesProvider, []); + final provider = RoutinesProvider(mockBaseProvider, exercisesProvider, mockUserProvider, []); await provider.fetchAndSetRoutineSparse(325397); await provider.deleteRoutine(325397); @@ -121,7 +123,7 @@ void main() { ).thenAnswer((_) => Future.value(tRepetitionUnits['results'])); // Load the entries - final provider = RoutinesProvider(mockBaseProvider, exercisesProvider, []); + final provider = RoutinesProvider(mockBaseProvider, exercisesProvider, mockUserProvider, []); await provider.fetchAndSetRepetitionUnits(); final repetitionUnits = provider.repetitionUnits; @@ -139,7 +141,7 @@ void main() { final ExercisesProvider testExercisesProvider = ExercisesProvider(mockBaseProvider); // Load the entries - final provider = RoutinesProvider(mockBaseProvider, testExercisesProvider, []); + final provider = RoutinesProvider(mockBaseProvider, testExercisesProvider, mockUserProvider, []); await provider.fetchAndSetWeightUnits(); final weightUnits = provider.weightUnits; @@ -168,7 +170,7 @@ void main() { final prefs = PreferenceHelper.asyncPref; // Load the entries - final provider = RoutinesProvider(mockBaseProvider, exercisesProvider, []); + final provider = RoutinesProvider(mockBaseProvider, exercisesProvider, mockUserProvider, []); await provider.fetchAndSetUnits(); final prefsJson = jsonDecode((await prefs.getString(PREFS_WORKOUT_UNITS))!); @@ -229,7 +231,7 @@ void main() { (_) async => Future.value(testCrunches), ); - final provider = RoutinesProvider(mockBaseProvider, mockExercisesProvider, []); + final provider = RoutinesProvider(mockBaseProvider, mockExercisesProvider, mockUserProvider, []); provider.repetitionUnits = testRepetitionUnits; provider.weightUnits = testWeightUnits; diff --git a/test/routine/routines_provider_test.mocks.dart b/test/routine/routines_provider_test.mocks.dart index c07f47e1c..b3362c3cb 100644 --- a/test/routine/routines_provider_test.mocks.dart +++ b/test/routine/routines_provider_test.mocks.dart @@ -3,22 +3,26 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i11; -import 'dart:ui' as _i15; +import 'dart:async' as _i12; +import 'dart:ui' as _i16; +import 'package:flutter/material.dart' as _i18; import 'package:http/http.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; +import 'package:shared_preferences/shared_preferences.dart' as _i11; import 'package:wger/database/exercises/exercise_database.dart' as _i5; -import 'package:wger/models/core/search_options.dart' as _i13; +import 'package:wger/models/core/search_options.dart' as _i14; import 'package:wger/models/exercises/category.dart' as _i7; import 'package:wger/models/exercises/equipment.dart' as _i8; import 'package:wger/models/exercises/exercise.dart' as _i6; -import 'package:wger/models/exercises/exercise_filters.dart' as _i14; +import 'package:wger/models/exercises/exercise_filters.dart' as _i15; import 'package:wger/models/exercises/language.dart' as _i10; import 'package:wger/models/exercises/muscle.dart' as _i9; +import 'package:wger/models/user/profile.dart' as _i19; import 'package:wger/providers/auth.dart' as _i2; import 'package:wger/providers/base_provider.dart' as _i4; -import 'package:wger/providers/exercises.dart' as _i12; +import 'package:wger/providers/exercises.dart' as _i13; +import 'package:wger/providers/user.dart' as _i17; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -36,50 +40,67 @@ import 'package:wger/providers/exercises.dart' as _i12; // ignore_for_file: invalid_use_of_internal_member class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeWgerBaseProvider_4 extends _i1.SmartFake implements _i4.WgerBaseProvider { +class _FakeWgerBaseProvider_4 extends _i1.SmartFake + implements _i4.WgerBaseProvider { _FakeWgerBaseProvider_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeExerciseDatabase_5 extends _i1.SmartFake implements _i5.ExerciseDatabase { +class _FakeExerciseDatabase_5 extends _i1.SmartFake + implements _i5.ExerciseDatabase { _FakeExerciseDatabase_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeExercise_6 extends _i1.SmartFake implements _i6.Exercise { - _FakeExercise_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeExercise_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeExerciseCategory_7 extends _i1.SmartFake implements _i7.ExerciseCategory { +class _FakeExerciseCategory_7 extends _i1.SmartFake + implements _i7.ExerciseCategory { _FakeExerciseCategory_7(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeEquipment_8 extends _i1.SmartFake implements _i8.Equipment { - _FakeEquipment_8(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeEquipment_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMuscle_9 extends _i1.SmartFake implements _i9.Muscle { - _FakeMuscle_9(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeMuscle_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeLanguage_10 extends _i1.SmartFake implements _i10.Language { - _FakeLanguage_10(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeLanguage_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeSharedPreferencesAsync_11 extends _i1.SmartFake + implements _i11.SharedPreferencesAsync { + _FakeSharedPreferencesAsync_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -157,7 +178,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i11.Future fetch( + _i12.Future fetch( Uri? uri, { int? maxRetries = 3, Duration? initialDelay = const Duration(milliseconds: 250), @@ -175,12 +196,12 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { #language: language, }, ), - returnValue: _i11.Future.value(), + returnValue: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future> fetchPaginated( + _i12.Future> fetchPaginated( Uri? uri, { String? language, Duration? timeout = const Duration(seconds: 15), @@ -191,54 +212,54 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { [uri], {#language: language, #timeout: timeout}, ), - returnValue: _i11.Future>.value([]), + returnValue: _i12.Future>.value([]), ) - as _i11.Future>); + as _i12.Future>); @override - _i11.Future> post( + _i12.Future> post( Map? data, Uri? uri, ) => (super.noSuchMethod( Invocation.method(#post, [data, uri]), - returnValue: _i11.Future>.value( + returnValue: _i12.Future>.value( {}, ), ) - as _i11.Future>); + as _i12.Future>); @override - _i11.Future> patch( + _i12.Future> patch( Map? data, Uri? uri, ) => (super.noSuchMethod( Invocation.method(#patch, [data, uri]), - returnValue: _i11.Future>.value( + returnValue: _i12.Future>.value( {}, ), ) - as _i11.Future>); + as _i12.Future>); @override - _i11.Future<_i3.Response> deleteRequest(String? url, int? id) => + _i12.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( Invocation.method(#deleteRequest, [url, id]), - returnValue: _i11.Future<_i3.Response>.value( + returnValue: _i12.Future<_i3.Response>.value( _FakeResponse_3( this, Invocation.method(#deleteRequest, [url, id]), ), ), ) - as _i11.Future<_i3.Response>); + as _i12.Future<_i3.Response>); } /// A class which mocks [ExercisesProvider]. /// /// See the documentation for Mockito's code generation for more information. -class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { +class MockExercisesProvider extends _i1.Mock implements _i13.ExercisesProvider { MockExercisesProvider() { _i1.throwOnMissingStub(this); } @@ -334,10 +355,11 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { ); @override - set filteredExercises(List<_i6.Exercise>? newFilteredExercises) => super.noSuchMethod( - Invocation.setter(#filteredExercises, newFilteredExercises), - returnValueForMissingStub: null, - ); + set filteredExercises(List<_i6.Exercise>? newFilteredExercises) => + super.noSuchMethod( + Invocation.setter(#filteredExercises, newFilteredExercises), + returnValueForMissingStub: null, + ); @override set languages(List<_i10.Language>? languages) => super.noSuchMethod( @@ -347,16 +369,17 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override bool get hasListeners => - (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override - _i11.Future setFilters(_i12.Filters? newFilters) => + _i12.Future setFilters(_i13.Filters? newFilters) => (super.noSuchMethod( Invocation.method(#setFilters, [newFilters]), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override void initFilters() => super.noSuchMethod( @@ -365,13 +388,13 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { ); @override - _i11.Future findByFilters() => + _i12.Future findByFilters() => (super.noSuchMethod( Invocation.method(#findByFilters, []), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override void clear() => super.noSuchMethod( @@ -450,60 +473,60 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { as _i10.Language); @override - _i11.Future fetchAndSetCategoriesFromApi() => + _i12.Future fetchAndSetCategoriesFromApi() => (super.noSuchMethod( Invocation.method(#fetchAndSetCategoriesFromApi, []), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future fetchAndSetMusclesFromApi() => + _i12.Future fetchAndSetMusclesFromApi() => (super.noSuchMethod( Invocation.method(#fetchAndSetMusclesFromApi, []), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future fetchAndSetEquipmentsFromApi() => + _i12.Future fetchAndSetEquipmentsFromApi() => (super.noSuchMethod( Invocation.method(#fetchAndSetEquipmentsFromApi, []), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future fetchAndSetLanguagesFromApi() => + _i12.Future fetchAndSetLanguagesFromApi() => (super.noSuchMethod( Invocation.method(#fetchAndSetLanguagesFromApi, []), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future fetchAndSetAllExercises() => + _i12.Future fetchAndSetAllExercises() => (super.noSuchMethod( Invocation.method(#fetchAndSetAllExercises, []), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future<_i6.Exercise?> fetchAndSetExercise(int? exerciseId) => + _i12.Future<_i6.Exercise?> fetchAndSetExercise(int? exerciseId) => (super.noSuchMethod( Invocation.method(#fetchAndSetExercise, [exerciseId]), - returnValue: _i11.Future<_i6.Exercise?>.value(), + returnValue: _i12.Future<_i6.Exercise?>.value(), ) - as _i11.Future<_i6.Exercise?>); + as _i12.Future<_i6.Exercise?>); @override - _i11.Future<_i6.Exercise> handleUpdateExerciseFromApi( + _i12.Future<_i6.Exercise> handleUpdateExerciseFromApi( _i5.ExerciseDatabase? database, int? exerciseId, ) => @@ -512,7 +535,7 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { database, exerciseId, ]), - returnValue: _i11.Future<_i6.Exercise>.value( + returnValue: _i12.Future<_i6.Exercise>.value( _FakeExercise_6( this, Invocation.method(#handleUpdateExerciseFromApi, [ @@ -522,39 +545,39 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { ), ), ) - as _i11.Future<_i6.Exercise>); + as _i12.Future<_i6.Exercise>); @override - _i11.Future initCacheTimesLocalPrefs({bool? forceInit = false}) => + _i12.Future initCacheTimesLocalPrefs({bool? forceInit = false}) => (super.noSuchMethod( Invocation.method(#initCacheTimesLocalPrefs, [], { #forceInit: forceInit, }), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future clearAllCachesAndPrefs() => + _i12.Future clearAllCachesAndPrefs() => (super.noSuchMethod( Invocation.method(#clearAllCachesAndPrefs, []), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future fetchAndSetInitialData() => + _i12.Future fetchAndSetInitialData() => (super.noSuchMethod( Invocation.method(#fetchAndSetInitialData, []), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future setExercisesFromDatabase( + _i12.Future setExercisesFromDatabase( _i5.ExerciseDatabase? database, { bool? forceDeleteCache = false, }) => @@ -564,58 +587,58 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { [database], {#forceDeleteCache: forceDeleteCache}, ), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future updateExerciseCache(_i5.ExerciseDatabase? database) => + _i12.Future updateExerciseCache(_i5.ExerciseDatabase? database) => (super.noSuchMethod( Invocation.method(#updateExerciseCache, [database]), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future fetchAndSetMuscles(_i5.ExerciseDatabase? database) => + _i12.Future fetchAndSetMuscles(_i5.ExerciseDatabase? database) => (super.noSuchMethod( Invocation.method(#fetchAndSetMuscles, [database]), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future fetchAndSetCategories(_i5.ExerciseDatabase? database) => + _i12.Future fetchAndSetCategories(_i5.ExerciseDatabase? database) => (super.noSuchMethod( Invocation.method(#fetchAndSetCategories, [database]), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future fetchAndSetLanguages(_i5.ExerciseDatabase? database) => + _i12.Future fetchAndSetLanguages(_i5.ExerciseDatabase? database) => (super.noSuchMethod( Invocation.method(#fetchAndSetLanguages, [database]), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future fetchAndSetEquipments(_i5.ExerciseDatabase? database) => + _i12.Future fetchAndSetEquipments(_i5.ExerciseDatabase? database) => (super.noSuchMethod( Invocation.method(#fetchAndSetEquipments, [database]), - returnValue: _i11.Future.value(), - returnValueForMissingStub: _i11.Future.value(), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), ) - as _i11.Future); + as _i12.Future); @override - _i11.Future> searchExercise( + _i12.Future> searchExercise( String? name, { String? languageCode = 'en', bool? searchEnglish = false, @@ -626,18 +649,18 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { [name], {#languageCode: languageCode, #searchEnglish: searchEnglish}, ), - returnValue: _i11.Future>.value( + returnValue: _i12.Future>.value( <_i6.Exercise>[], ), ) - as _i11.Future>); + as _i12.Future>); @override - _i11.Future> searchExerciseWithSearchMode( + _i12.Future> searchExerciseWithSearchMode( String? name, { String? languageCode = 'en', - _i13.SearchLanguage? searchLanguage = _i13.SearchLanguage.currentAndEnglish, - _i14.ExerciseSearchMode? searchMode = _i14.ExerciseSearchMode.fulltext, + _i14.SearchLanguage? searchLanguage = _i14.SearchLanguage.currentAndEnglish, + _i15.ExerciseSearchMode? searchMode = _i15.ExerciseSearchMode.fulltext, Set<_i7.ExerciseCategory>? categories = const {}, }) => (super.noSuchMethod( @@ -651,20 +674,204 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { #categories: categories, }, ), - returnValue: _i11.Future>.value( + returnValue: _i12.Future>.value( <_i6.Exercise>[], ), ) - as _i11.Future>); + as _i12.Future>); @override - void addListener(_i15.VoidCallback? listener) => super.noSuchMethod( + void addListener(_i16.VoidCallback? listener) => super.noSuchMethod( Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override - void removeListener(_i15.VoidCallback? listener) => super.noSuchMethod( + void removeListener(_i16.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#removeListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void dispose() => super.noSuchMethod( + Invocation.method(#dispose, []), + returnValueForMissingStub: null, + ); + + @override + void notifyListeners() => super.noSuchMethod( + Invocation.method(#notifyListeners, []), + returnValueForMissingStub: null, + ); +} + +/// A class which mocks [UserProvider]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockUserProvider extends _i1.Mock implements _i17.UserProvider { + MockUserProvider() { + _i1.throwOnMissingStub(this); + } + + @override + _i18.ThemeMode get themeMode => + (super.noSuchMethod( + Invocation.getter(#themeMode), + returnValue: _i18.ThemeMode.system, + ) + as _i18.ThemeMode); + + @override + _i4.WgerBaseProvider get baseProvider => + (super.noSuchMethod( + Invocation.getter(#baseProvider), + returnValue: _FakeWgerBaseProvider_4( + this, + Invocation.getter(#baseProvider), + ), + ) + as _i4.WgerBaseProvider); + + @override + _i11.SharedPreferencesAsync get prefs => + (super.noSuchMethod( + Invocation.getter(#prefs), + returnValue: _FakeSharedPreferencesAsync_11( + this, + Invocation.getter(#prefs), + ), + ) + as _i11.SharedPreferencesAsync); + + @override + List<_i17.DashboardWidget> get dashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#dashboardWidgets), + returnValue: <_i17.DashboardWidget>[], + ) + as List<_i17.DashboardWidget>); + + @override + List<_i17.DashboardWidget> get allDashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#allDashboardWidgets), + returnValue: <_i17.DashboardWidget>[], + ) + as List<_i17.DashboardWidget>); + + @override + set themeMode(_i18.ThemeMode? value) => super.noSuchMethod( + Invocation.setter(#themeMode, value), + returnValueForMissingStub: null, + ); + + @override + set userLocale(_i16.Locale? value) => super.noSuchMethod( + Invocation.setter(#userLocale, value), + returnValueForMissingStub: null, + ); + + @override + set prefs(_i11.SharedPreferencesAsync? value) => super.noSuchMethod( + Invocation.setter(#prefs, value), + returnValueForMissingStub: null, + ); + + @override + set profile(_i19.Profile? value) => super.noSuchMethod( + Invocation.setter(#profile, value), + returnValueForMissingStub: null, + ); + + @override + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); + + @override + void clear() => super.noSuchMethod( + Invocation.method(#clear, []), + returnValueForMissingStub: null, + ); + + @override + bool isDashboardWidgetVisible(_i17.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i12.Future setDashboardWidgetVisible( + _i17.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), + ) + as _i12.Future); + + @override + _i12.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), + ) + as _i12.Future); + + @override + void setThemeMode(_i18.ThemeMode? mode) => super.noSuchMethod( + Invocation.method(#setThemeMode, [mode]), + returnValueForMissingStub: null, + ); + + @override + _i12.Future setUserLocale(_i16.Locale? locale) => + (super.noSuchMethod( + Invocation.method(#setUserLocale, [locale]), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), + ) + as _i12.Future); + + @override + _i12.Future saveProfile() => + (super.noSuchMethod( + Invocation.method(#saveProfile, []), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), + ) + as _i12.Future); + + @override + _i12.Future verifyEmail() => + (super.noSuchMethod( + Invocation.method(#verifyEmail, []), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), + ) + as _i12.Future); + + @override + _i12.Future isMetric() => + (super.noSuchMethod( + Invocation.method(#isMetric, []), + returnValue: _i12.Future.value(false), + ) + as _i12.Future); + + @override + void addListener(_i16.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#addListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void removeListener(_i16.VoidCallback? listener) => super.noSuchMethod( Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); diff --git a/test/routine/routines_screen_test.dart b/test/routine/routines_screen_test.dart index 6c7740588..3a4465143 100644 --- a/test/routine/routines_screen_test.dart +++ b/test/routine/routines_screen_test.dart @@ -29,6 +29,7 @@ import 'package:wger/models/workouts/routine.dart'; import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/exercises.dart'; import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/user.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/routine_list_screen.dart'; import 'package:wger/widgets/nutrition/forms.dart'; @@ -36,9 +37,10 @@ import 'package:wger/widgets/routines/forms/routine.dart'; import 'routines_screen_test.mocks.dart'; -@GenerateMocks([WgerBaseProvider]) +@GenerateMocks([WgerBaseProvider, UserProvider]) void main() { var mockBaseProvider = MockWgerBaseProvider(); + var mockUserProvider = MockUserProvider(); final testExercisesProvider = ExercisesProvider( mockBaseProvider, database: ExerciseDatabase.inMemory(NativeDatabase.memory()), @@ -61,6 +63,7 @@ void main() { create: (context) => RoutinesProvider( mockBaseProvider, testExercisesProvider, + mockUserProvider, [ Routine( id: 1, diff --git a/test/routine/routines_screen_test.mocks.dart b/test/routine/routines_screen_test.mocks.dart index e76067c8f..88c113d15 100644 --- a/test/routine/routines_screen_test.mocks.dart +++ b/test/routine/routines_screen_test.mocks.dart @@ -3,12 +3,17 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i5; +import 'dart:async' as _i6; +import 'dart:ui' as _i9; +import 'package:flutter/material.dart' as _i8; import 'package:http/http.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; +import 'package:shared_preferences/shared_preferences.dart' as _i5; +import 'package:wger/models/user/profile.dart' as _i10; import 'package:wger/providers/auth.dart' as _i2; import 'package:wger/providers/base_provider.dart' as _i4; +import 'package:wger/providers/user.dart' as _i7; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -26,19 +31,35 @@ import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: invalid_use_of_internal_member class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeWgerBaseProvider_4 extends _i1.SmartFake + implements _i4.WgerBaseProvider { + _FakeWgerBaseProvider_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeSharedPreferencesAsync_5 extends _i1.SmartFake + implements _i5.SharedPreferencesAsync { + _FakeSharedPreferencesAsync_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -116,7 +137,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch( + _i6.Future fetch( Uri? uri, { int? maxRetries = 3, Duration? initialDelay = const Duration(milliseconds: 250), @@ -134,12 +155,12 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { #language: language, }, ), - returnValue: _i5.Future.value(), + returnValue: _i6.Future.value(), ) - as _i5.Future); + as _i6.Future); @override - _i5.Future> fetchPaginated( + _i6.Future> fetchPaginated( Uri? uri, { String? language, Duration? timeout = const Duration(seconds: 15), @@ -150,43 +171,227 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { [uri], {#language: language, #timeout: timeout}, ), - returnValue: _i5.Future>.value([]), + returnValue: _i6.Future>.value([]), ) - as _i5.Future>); + as _i6.Future>); @override - _i5.Future> post(Map? data, Uri? uri) => + _i6.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( Invocation.method(#post, [data, uri]), - returnValue: _i5.Future>.value( + returnValue: _i6.Future>.value( {}, ), ) - as _i5.Future>); + as _i6.Future>); @override - _i5.Future> patch( + _i6.Future> patch( Map? data, Uri? uri, ) => (super.noSuchMethod( Invocation.method(#patch, [data, uri]), - returnValue: _i5.Future>.value( + returnValue: _i6.Future>.value( {}, ), ) - as _i5.Future>); + as _i6.Future>); @override - _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => + _i6.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( Invocation.method(#deleteRequest, [url, id]), - returnValue: _i5.Future<_i3.Response>.value( + returnValue: _i6.Future<_i3.Response>.value( _FakeResponse_3( this, Invocation.method(#deleteRequest, [url, id]), ), ), ) - as _i5.Future<_i3.Response>); + as _i6.Future<_i3.Response>); +} + +/// A class which mocks [UserProvider]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockUserProvider extends _i1.Mock implements _i7.UserProvider { + MockUserProvider() { + _i1.throwOnMissingStub(this); + } + + @override + _i8.ThemeMode get themeMode => + (super.noSuchMethod( + Invocation.getter(#themeMode), + returnValue: _i8.ThemeMode.system, + ) + as _i8.ThemeMode); + + @override + _i4.WgerBaseProvider get baseProvider => + (super.noSuchMethod( + Invocation.getter(#baseProvider), + returnValue: _FakeWgerBaseProvider_4( + this, + Invocation.getter(#baseProvider), + ), + ) + as _i4.WgerBaseProvider); + + @override + _i5.SharedPreferencesAsync get prefs => + (super.noSuchMethod( + Invocation.getter(#prefs), + returnValue: _FakeSharedPreferencesAsync_5( + this, + Invocation.getter(#prefs), + ), + ) + as _i5.SharedPreferencesAsync); + + @override + List<_i7.DashboardWidget> get dashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#dashboardWidgets), + returnValue: <_i7.DashboardWidget>[], + ) + as List<_i7.DashboardWidget>); + + @override + List<_i7.DashboardWidget> get allDashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#allDashboardWidgets), + returnValue: <_i7.DashboardWidget>[], + ) + as List<_i7.DashboardWidget>); + + @override + set themeMode(_i8.ThemeMode? value) => super.noSuchMethod( + Invocation.setter(#themeMode, value), + returnValueForMissingStub: null, + ); + + @override + set userLocale(_i9.Locale? value) => super.noSuchMethod( + Invocation.setter(#userLocale, value), + returnValueForMissingStub: null, + ); + + @override + set prefs(_i5.SharedPreferencesAsync? value) => super.noSuchMethod( + Invocation.setter(#prefs, value), + returnValueForMissingStub: null, + ); + + @override + set profile(_i10.Profile? value) => super.noSuchMethod( + Invocation.setter(#profile, value), + returnValueForMissingStub: null, + ); + + @override + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); + + @override + void clear() => super.noSuchMethod( + Invocation.method(#clear, []), + returnValueForMissingStub: null, + ); + + @override + bool isDashboardWidgetVisible(_i7.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i6.Future setDashboardWidgetVisible( + _i7.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + _i6.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + void setThemeMode(_i8.ThemeMode? mode) => super.noSuchMethod( + Invocation.method(#setThemeMode, [mode]), + returnValueForMissingStub: null, + ); + + @override + _i6.Future setUserLocale(_i9.Locale? locale) => + (super.noSuchMethod( + Invocation.method(#setUserLocale, [locale]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + _i6.Future saveProfile() => + (super.noSuchMethod( + Invocation.method(#saveProfile, []), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + _i6.Future verifyEmail() => + (super.noSuchMethod( + Invocation.method(#verifyEmail, []), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + _i6.Future isMetric() => + (super.noSuchMethod( + Invocation.method(#isMetric, []), + returnValue: _i6.Future.value(false), + ) + as _i6.Future); + + @override + void addListener(_i9.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#addListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void removeListener(_i9.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#removeListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void dispose() => super.noSuchMethod( + Invocation.method(#dispose, []), + returnValueForMissingStub: null, + ); + + @override + void notifyListeners() => super.noSuchMethod( + Invocation.method(#notifyListeners, []), + returnValueForMissingStub: null, + ); } diff --git a/test/user/provider_test.dart b/test/user/provider_test.dart index cc83fea6d..2187968a5 100644 --- a/test/user/provider_test.dart +++ b/test/user/provider_test.dart @@ -70,7 +70,7 @@ void main() { group('house keeping', () { test('should clear the profile list with clear()', () async { // arrange - await userProvider.fetchAndSetProfile(); + await userProvider.isMetric(); // assert expect(userProvider.profile, isNot(null)); @@ -87,7 +87,7 @@ void main() { group('profile', () { test('Loading the profile from the server works', () async { // arrange - await userProvider.fetchAndSetProfile(); + await userProvider.isMetric(); // assert expect(userProvider.profile!.username, 'admin'); @@ -98,7 +98,7 @@ void main() { test('Sending the verify email works', () async { // arrange - await userProvider.fetchAndSetProfile(); + await userProvider.isMetric(); await userProvider.verifyEmail(); // assert From 8fe43409497123da5daaed5d201f50ae7b69bf80 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 19 Jun 2026 15:17:59 +0200 Subject: [PATCH 012/484] Properly load and set the unit from the profile --- lib/models/workouts/log.dart | 4 +- .../helpers/routine_form_test_overrides.dart | 14 ++++- test/routine/models/log_test.dart | 21 ++++++- test/routine/routines_provider_test.dart | 59 +++++++++++++++++++ 4 files changed, 93 insertions(+), 5 deletions(-) diff --git a/lib/models/workouts/log.dart b/lib/models/workouts/log.dart index 18503fb29..291c41fcc 100644 --- a/lib/models/workouts/log.dart +++ b/lib/models/workouts/log.dart @@ -93,7 +93,9 @@ class Log { weight = setConfig.weight; weightTarget = setConfig.weight; - weightUnitId = setConfig.weightUnitId ?? WEIGHT_UNIT_KG; + // Fall back to the resolved unit object (set during routine hydration from + // the user's metric preference) when the config carries no explicit unit. + weightUnitId = setConfig.weightUnitId ?? setConfig.weightUnit?.id ?? WEIGHT_UNIT_KG; weightUnitObj = setConfig.weightUnit; repetitions = setConfig.repetitions; diff --git a/test/routine/helpers/routine_form_test_overrides.dart b/test/routine/helpers/routine_form_test_overrides.dart index 739d2110b..5d9cf6147 100644 --- a/test/routine/helpers/routine_form_test_overrides.dart +++ b/test/routine/helpers/routine_form_test_overrides.dart @@ -32,7 +32,7 @@ import 'package:wger/providers/workout_session_repository.dart'; import 'routine_form_test_overrides.mocks.dart'; export 'routine_form_test_overrides.mocks.dart' - show MockExerciseRepository, MockWorkoutSessionRepository; + show MockExerciseRepository, MockWorkoutSessionRepository, MockUserProfileRepository; @GenerateMocks([ExerciseRepository, WorkoutSessionRepository, UserProfileRepository]) /// Repository overrides for the two reference-data notifiers that @@ -47,6 +47,7 @@ export 'routine_form_test_overrides.mocks.dart' List exerciseAndSessionRepoOverrides({ MockExerciseRepository? exercise, MockWorkoutSessionRepository? session, + MockUserProfileRepository? userProfile, }) { final exerciseRepo = exercise ?? _emptyExerciseRepoMock(); final sessionRepo = session ?? _emptySessionRepoMock(); @@ -55,7 +56,9 @@ List exerciseAndSessionRepoOverrides({ workoutSessionRepositoryProvider.overrideWithValue(sessionRepo), // RoutinesRiverpod.build listens to the user profile to pick the default // weight unit; stub it so the real Drift-backed repo isn't pulled in. - userProfileRepositoryProvider.overrideWithValue(_emptyUserProfileRepoMock()), + // Defaults to a null (metric) profile; pass [userProfile] to exercise the + // imperial default-unit path. + userProfileRepositoryProvider.overrideWithValue(userProfile ?? _emptyUserProfileRepoMock()), ]; } @@ -90,10 +93,15 @@ MockWorkoutSessionRepository _emptySessionRepoMock() { List routineFormAmbientOverrides({ MockExerciseRepository? exercise, MockWorkoutSessionRepository? session, + MockUserProfileRepository? userProfile, List repetitionUnits = const [], List weightUnits = const [], }) => [ - ...exerciseAndSessionRepoOverrides(exercise: exercise, session: session), + ...exerciseAndSessionRepoOverrides( + exercise: exercise, + session: session, + userProfile: userProfile, + ), routineRepetitionUnitProvider.overrideWith( (ref) => Stream>.value(repetitionUnits), ), diff --git a/test/routine/models/log_test.dart b/test/routine/models/log_test.dart index c979b6ae4..f2b72c946 100644 --- a/test/routine/models/log_test.dart +++ b/test/routine/models/log_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, 2025 wger Team + * Copyright (c) 2020 - 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 @@ -22,6 +22,7 @@ import 'package:wger/models/exercises/category.dart'; import 'package:wger/models/exercises/exercise.dart'; import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/set_config_data.dart'; +import 'package:wger/models/workouts/weight_unit.dart'; void main() { group('Log.volume', () { @@ -178,6 +179,24 @@ void main() { expect(log.repetitionsUnitId, REP_UNIT_TILL_FAILURE_ID); }); + test('derives the unit ID from the resolved unit object when no explicit ID is set', () { + // Imperial users: routine hydration leaves weightUnitId null and only + // resolves the weightUnit object (lb) from the profile. The log must pick + // up lb for *both* the ID and the object + const lb = WeightUnit(id: WEIGHT_UNIT_LB, name: 'lb'); + final setConfig = SetConfigData( + exerciseId: 1, + slotEntryId: 1, + exercise: exercise, + weightUnit: lb, + ); + + final log = Log.fromSetConfigData(setConfig); + + expect(log.weightUnitId, WEIGHT_UNIT_LB); + expect(log.weightUnitObj, lb); + }); + test('copies weight and repetitions values', () { final setConfig = SetConfigData( exerciseId: 1, diff --git a/test/routine/routines_provider_test.dart b/test/routine/routines_provider_test.dart index 5a509bc8f..61f27d65e 100644 --- a/test/routine/routines_provider_test.dart +++ b/test/routine/routines_provider_test.dart @@ -22,15 +22,20 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:wger/models/exercises/exercise.dart'; +import 'package:wger/models/user/user_profile.dart'; import 'package:wger/models/workouts/day.dart'; +import 'package:wger/models/workouts/day_data.dart'; import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/routine.dart'; import 'package:wger/models/workouts/session.dart'; +import 'package:wger/models/workouts/set_config_data.dart'; import 'package:wger/models/workouts/slot.dart'; +import 'package:wger/models/workouts/slot_data.dart'; import 'package:wger/models/workouts/slot_entry.dart'; import 'package:wger/providers/exercises_notifier.dart'; import 'package:wger/providers/routines_notifier.dart'; import 'package:wger/providers/routines_repository.dart'; +import 'package:wger/providers/user_profile_notifier.dart'; import '../../test_data/exercises.dart'; import '../../test_data/routines.dart'; @@ -359,6 +364,60 @@ void main() { // Assert: `_fullFetchInFlight` collapses them into a single roundtrip. verify(mockRepo.fetchAndSetRoutineFullServer(101)).called(1); }); + + test('resolves the default weight unit from an imperial profile', () async { + // A set config without an explicit weight unit must inherit the unit + // implied by the profile: lb (id 2) for an imperial user, not kg. + overrideStreams(mockExerciseRepo); + final setConfig = SetConfigData( + exerciseId: 1, + slotEntryId: 1, + exercise: getTestExercises()[0], + // No weightUnit / weightUnitId: the server omits it, the default applies. + ); + final routine = Routine(id: 101, name: 'Test routine') + ..dayDataGym = [ + DayData( + iteration: 1, + date: DateTime(2024, 11, 1), + label: '', + day: Day(id: 1, routineId: 101, name: 'Test', order: 1), + slots: [ + SlotData(comment: '', isSuperset: false, exerciseIds: [1], setConfigs: [setConfig]), + ], + ), + ]; + when(mockRepo.fetchAndSetRoutineFullServer(101)).thenAnswer((_) async => routine); + + final imperialProfileRepo = MockUserProfileRepository(); + when( + imperialProfileRepo.watchDrift(), + ).thenAnswer((_) => Stream.value(UserProfile(id: 1, weightUnitStr: 'lb'))); + + final container = ProviderContainer.test( + overrides: [ + routinesRepositoryProvider.overrideWithValue(mockRepo), + ...routineFormAmbientOverrides( + exercise: mockExerciseRepo, + session: mockSessionRepo, + userProfile: imperialProfileRepo, + repetitionUnits: testRepetitionUnits, + weightUnits: testWeightUnits, + ), + ], + ); + + // fetchAndSetRoutineFull doesn't await the profile, so keep it alive and + // let its stream emit before hydration reads it (post-sync steady state). + container.listen(userProfileProvider, (_, _) {}); + await pumpEventQueue(); + final notifier = container.read(routinesRiverpodProvider.notifier); + final result = await notifier.fetchAndSetRoutineFull(101); + + // testWeightUnit2 has id 2 == WEIGHT_UNIT_LB. + final hydratedConfig = result.dayDataGym[0].slots[0].setConfigs[0]; + expect(hydratedConfig.weightUnit, testWeightUnit2); + }); }); group('routineHydration family', () { From 65995c666afec2dcc494b281684650869e527053 Mon Sep 17 00:00:00 2001 From: bhavit04 Date: Sun, 21 Jun 2026 12:30:39 +0530 Subject: [PATCH 013/484] feat(auth): allow connecting to servers with self-signed certificates Self-hosted instances served behind a self-signed (or otherwise invalid) TLS certificate could not be reached from the app: both the API client and image loading failed certificate validation. Add an opt-in "Allow self-signed certificates" toggle to the advanced sign-in sheet, shown only when a self-hosted server is selected. When enabled it installs an HttpOverrides.global that skips certificate validation, which transparently covers the http-package API client and the dart:io HttpClient used by NetworkImage / extended_image. The preference is persisted in AppSettings and re-applied on startup before the first request, and applied immediately when toggled so the next login already trusts the certificate. The override is a no-op on web, where dart:io networking does not apply. Native media players (the video_player plugin) use their own networking stack and are not affected by this override. Closes #116 Co-Authored-By: Claude Opus 4.8 --- lib/helpers/consts.dart | 7 +++ lib/helpers/http_overrides.dart | 49 +++++++++++++++++++ lib/l10n/app_en.arb | 4 ++ lib/main.dart | 9 ++++ lib/providers/app_settings_notifier.dart | 27 ++++++++++ .../app_settings_notifier.freezed.dart | 43 +++++++++------- lib/providers/app_settings_notifier.g.dart | 3 +- lib/widgets/auth/advanced_sheet.dart | 27 ++++++++-- lib/widgets/auth/auth_card.dart | 16 +++++- test/auth/auth_screen_test.dart | 32 ++++++++++++ test/core/settings_test.dart | 43 ++++++++++++++++ test/helpers/http_overrides_test.dart | 45 +++++++++++++++++ 12 files changed, 282 insertions(+), 23 deletions(-) create mode 100644 lib/helpers/http_overrides.dart create mode 100644 test/helpers/http_overrides_test.dart diff --git a/lib/helpers/consts.dart b/lib/helpers/consts.dart index 30136fdd7..aee6c1eda 100644 --- a/lib/helpers/consts.dart +++ b/lib/helpers/consts.dart @@ -79,6 +79,13 @@ const PREFS_DB_OWNER_USER_ID = 'dbOwnerUserId'; const PREFS_KEEP_DATA_ON_LOGOUT = 'keepDataOnLogout'; const KEEP_DATA_ON_LOGOUT_DEFAULT = true; +/// User preference: trust self-signed/invalid TLS certificates so the app can +/// connect to self-hosted instances behind a self-signed cert. Off by default +/// since it disables certificate validation. Defaults to +/// [ALLOW_SELF_SIGNED_CERTS_DEFAULT]. +const PREFS_ALLOW_SELF_SIGNED_CERTS = 'allowSelfSignedCerts'; +const ALLOW_SELF_SIGNED_CERTS_DEFAULT = false; + /// Secure-storage key for the headless refresh token. const SECURE_STORAGE_REFRESH_TOKEN = 'wger_refresh_token'; diff --git a/lib/helpers/http_overrides.dart b/lib/helpers/http_overrides.dart new file mode 100644 index 000000000..1a6263212 --- /dev/null +++ b/lib/helpers/http_overrides.dart @@ -0,0 +1,49 @@ +/* + * This file is part of wger Workout Manager . + * 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 + * 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 'dart:io'; + +import 'package:flutter/foundation.dart'; + +/// [HttpOverrides] that accepts self-signed / otherwise invalid TLS +/// certificates. +/// +/// Installing this as [HttpOverrides.global] makes *every* `dart:io` +/// `HttpClient` skip certificate validation, which transparently covers both +/// the `http` package client used for API calls and the `HttpClient` that +/// `NetworkImage` / `extended_image` use to load images. Native media players +/// (e.g. the `video_player` plugin on Android/iOS) use their own networking +/// stack and are not affected by this override. +class WgerHttpOverrides extends HttpOverrides { + @override + HttpClient createHttpClient(SecurityContext? context) { + return super.createHttpClient(context) + ..badCertificateCallback = (X509Certificate cert, String host, int port) => true; + } +} + +/// Installs or removes [WgerHttpOverrides] based on [allow]. +/// +/// No-op on the web, where `dart:io` networking (and thus [HttpOverrides]) does +/// not apply. Passing `false` restores the default certificate validation. +void applySelfSignedCertOverride(bool allow) { + if (kIsWeb) { + return; + } + HttpOverrides.global = allow ? WgerHttpOverrides() : null; +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b185a7107..3ef67dc4a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -132,6 +132,10 @@ "@serverOptionSelfHostedTitle": {}, "serverOptionSelfHostedDetail": "Connect to your own instance", "@serverOptionSelfHostedDetail": {}, + "allowSelfSignedCertsTitle": "Allow self-signed certificates", + "@allowSelfSignedCertsTitle": {}, + "allowSelfSignedCertsDetail": "Disables TLS certificate validation. Only enable this for a server you trust.", + "@allowSelfSignedCertsDetail": {}, "authOptionPasswordTitle": "Username and password", "@authOptionPasswordTitle": {}, "signInWithToken": "Sign in with token", diff --git a/lib/main.dart b/lib/main.dart index a210da338..a425f1dd7 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -25,7 +25,9 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:wger/core/error_dialogs.dart'; import 'package:wger/core/keys.dart'; +import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/errors.dart'; +import 'package:wger/helpers/http_overrides.dart'; import 'package:wger/helpers/locale.dart'; import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -108,6 +110,13 @@ void main() async { // SharedPreferences to SharedPreferencesAsync migration function await PreferenceHelper.instance.migrationSupportFunctionForSharedPreferences(); + // Install the self-signed certificate override before any network request + // (e.g. the auto-login probe) is made, based on the persisted preference. + final allowSelfSignedCerts = + await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS) ?? + ALLOW_SELF_SIGNED_CERTS_DEFAULT; + applySelfSignedCertOverride(allowSelfSignedCerts); + // Catch errors from Flutter itself (widget build, layout, paint, etc.) FlutterError.onError = (FlutterErrorDetails details) { final stack = details.stack ?? StackTrace.empty; diff --git a/lib/providers/app_settings_notifier.dart b/lib/providers/app_settings_notifier.dart index fc808e119..7b1ae7468 100644 --- a/lib/providers/app_settings_notifier.dart +++ b/lib/providers/app_settings_notifier.dart @@ -25,6 +25,7 @@ import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/helpers/consts.dart'; +import 'package:wger/helpers/http_overrides.dart'; import 'package:wger/helpers/locale.dart'; import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -82,6 +83,10 @@ sealed class AppSettings with _$AppSettings { /// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. @Default(KEEP_DATA_ON_LOGOUT_DEFAULT) bool keepDataOnLogout, + + /// When true, TLS certificate validation is disabled so the app can + /// connect to self-hosted instances using a self-signed certificate. + @Default(ALLOW_SELF_SIGNED_CERTS_DEFAULT) bool allowSelfSignedCerts, }) = _AppSettings; } @@ -101,11 +106,13 @@ class AppSettingsNotifier extends _$AppSettingsNotifier { final userLocale = await _loadUserLocale(); final items = await _loadDashboardItems(); final keepDataOnLogout = await _loadKeepDataOnLogout(); + final allowSelfSignedCerts = await _loadAllowSelfSignedCerts(); return AppSettings( themeMode: themeMode, userLocale: userLocale, dashboardItems: items, keepDataOnLogout: keepDataOnLogout, + allowSelfSignedCerts: allowSelfSignedCerts, ); } @@ -191,6 +198,26 @@ class AppSettingsNotifier extends _$AppSettingsNotifier { await _prefs.setBool(PREFS_KEEP_DATA_ON_LOGOUT, value); } + // + // Allow self-signed certificates + // + + Future _loadAllowSelfSignedCerts() async { + final value = + (await _prefs.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS)) ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT; + // Keep the global override in sync with the persisted value so the very + // first HTTP request after build() honours the setting. + applySelfSignedCertOverride(value); + return value; + } + + Future setAllowSelfSignedCerts(bool value) async { + final current = state.asData?.value ?? const AppSettings(); + state = AsyncData(current.copyWith(allowSelfSignedCerts: value)); + applySelfSignedCertOverride(value); + await _prefs.setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, value); + } + // // Dashboard config // diff --git a/lib/providers/app_settings_notifier.freezed.dart b/lib/providers/app_settings_notifier.freezed.dart index 16b0f1020..31ec0b079 100644 --- a/lib/providers/app_settings_notifier.freezed.dart +++ b/lib/providers/app_settings_notifier.freezed.dart @@ -17,7 +17,9 @@ mixin _$AppSettings { ThemeMode get themeMode; List get dashboardItems;/// Locale override. Null means the app follows the system locale. Locale? get userLocale;/// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. - bool get keepDataOnLogout; + bool get keepDataOnLogout;/// When true, TLS certificate validation is disabled so the app can +/// connect to self-hosted instances using a self-signed certificate. + bool get allowSelfSignedCerts; /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -28,16 +30,16 @@ $AppSettingsCopyWith get copyWith => _$AppSettingsCopyWithImpl Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(dashboardItems),userLocale,keepDataOnLogout); +int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(dashboardItems),userLocale,keepDataOnLogout,allowSelfSignedCerts); @override String toString() { - return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale, keepDataOnLogout: $keepDataOnLogout)'; + return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale, keepDataOnLogout: $keepDataOnLogout, allowSelfSignedCerts: $allowSelfSignedCerts)'; } @@ -48,7 +50,7 @@ abstract mixin class $AppSettingsCopyWith<$Res> { factory $AppSettingsCopyWith(AppSettings value, $Res Function(AppSettings) _then) = _$AppSettingsCopyWithImpl; @useResult $Res call({ - ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout + ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts }); @@ -65,12 +67,13 @@ class _$AppSettingsCopyWithImpl<$Res> /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,Object? keepDataOnLogout = null,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,Object? keepDataOnLogout = null,Object? allowSelfSignedCerts = null,}) { return _then(_self.copyWith( themeMode: null == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable as ThemeMode,dashboardItems: null == dashboardItems ? _self.dashboardItems : dashboardItems // ignore: cast_nullable_to_non_nullable as List,userLocale: freezed == userLocale ? _self.userLocale : userLocale // ignore: cast_nullable_to_non_nullable as Locale?,keepDataOnLogout: null == keepDataOnLogout ? _self.keepDataOnLogout : keepDataOnLogout // ignore: cast_nullable_to_non_nullable +as bool,allowSelfSignedCerts: null == allowSelfSignedCerts ? _self.allowSelfSignedCerts : allowSelfSignedCerts // ignore: cast_nullable_to_non_nullable as bool, )); } @@ -153,10 +156,10 @@ return $default(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen(TResult Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout)? $default,{required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen(TResult Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts)? $default,{required TResult orElse(),}) {final _that = this; switch (_that) { case _AppSettings() when $default != null: -return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout);case _: +return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout,_that.allowSelfSignedCerts);case _: return orElse(); } @@ -174,10 +177,10 @@ return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keep /// } /// ``` -@optionalTypeArgs TResult when(TResult Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout) $default,) {final _that = this; +@optionalTypeArgs TResult when(TResult Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts) $default,) {final _that = this; switch (_that) { case _AppSettings(): -return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout);} +return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout,_that.allowSelfSignedCerts);} } /// A variant of `when` that fallback to returning `null` /// @@ -191,10 +194,10 @@ return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keep /// } /// ``` -@optionalTypeArgs TResult? whenOrNull(TResult? Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout)? $default,) {final _that = this; +@optionalTypeArgs TResult? whenOrNull(TResult? Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts)? $default,) {final _that = this; switch (_that) { case _AppSettings() when $default != null: -return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout);case _: +return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout,_that.allowSelfSignedCerts);case _: return null; } @@ -206,7 +209,7 @@ return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keep class _AppSettings implements AppSettings { - const _AppSettings({this.themeMode = ThemeMode.system, final List dashboardItems = const [], this.userLocale, this.keepDataOnLogout = KEEP_DATA_ON_LOGOUT_DEFAULT}): _dashboardItems = dashboardItems; + const _AppSettings({this.themeMode = ThemeMode.system, final List dashboardItems = const [], this.userLocale, this.keepDataOnLogout = KEEP_DATA_ON_LOGOUT_DEFAULT, this.allowSelfSignedCerts = ALLOW_SELF_SIGNED_CERTS_DEFAULT}): _dashboardItems = dashboardItems; @override@JsonKey() final ThemeMode themeMode; @@ -222,6 +225,9 @@ class _AppSettings implements AppSettings { /// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. @override@JsonKey() final bool keepDataOnLogout; +/// When true, TLS certificate validation is disabled so the app can +/// connect to self-hosted instances using a self-signed certificate. +@override@JsonKey() final bool allowSelfSignedCerts; /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. @@ -233,16 +239,16 @@ _$AppSettingsCopyWith<_AppSettings> get copyWith => __$AppSettingsCopyWithImpl<_ @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other._dashboardItems, _dashboardItems)&&(identical(other.userLocale, userLocale) || other.userLocale == userLocale)&&(identical(other.keepDataOnLogout, keepDataOnLogout) || other.keepDataOnLogout == keepDataOnLogout)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other._dashboardItems, _dashboardItems)&&(identical(other.userLocale, userLocale) || other.userLocale == userLocale)&&(identical(other.keepDataOnLogout, keepDataOnLogout) || other.keepDataOnLogout == keepDataOnLogout)&&(identical(other.allowSelfSignedCerts, allowSelfSignedCerts) || other.allowSelfSignedCerts == allowSelfSignedCerts)); } @override -int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(_dashboardItems),userLocale,keepDataOnLogout); +int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(_dashboardItems),userLocale,keepDataOnLogout,allowSelfSignedCerts); @override String toString() { - return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale, keepDataOnLogout: $keepDataOnLogout)'; + return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale, keepDataOnLogout: $keepDataOnLogout, allowSelfSignedCerts: $allowSelfSignedCerts)'; } @@ -253,7 +259,7 @@ abstract mixin class _$AppSettingsCopyWith<$Res> implements $AppSettingsCopyWith factory _$AppSettingsCopyWith(_AppSettings value, $Res Function(_AppSettings) _then) = __$AppSettingsCopyWithImpl; @override @useResult $Res call({ - ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout + ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts }); @@ -270,12 +276,13 @@ class __$AppSettingsCopyWithImpl<$Res> /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. -@override @pragma('vm:prefer-inline') $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,Object? keepDataOnLogout = null,}) { +@override @pragma('vm:prefer-inline') $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,Object? keepDataOnLogout = null,Object? allowSelfSignedCerts = null,}) { return _then(_AppSettings( themeMode: null == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable as ThemeMode,dashboardItems: null == dashboardItems ? _self._dashboardItems : dashboardItems // ignore: cast_nullable_to_non_nullable as List,userLocale: freezed == userLocale ? _self.userLocale : userLocale // ignore: cast_nullable_to_non_nullable as Locale?,keepDataOnLogout: null == keepDataOnLogout ? _self.keepDataOnLogout : keepDataOnLogout // ignore: cast_nullable_to_non_nullable +as bool,allowSelfSignedCerts: null == allowSelfSignedCerts ? _self.allowSelfSignedCerts : allowSelfSignedCerts // ignore: cast_nullable_to_non_nullable as bool, )); } diff --git a/lib/providers/app_settings_notifier.g.dart b/lib/providers/app_settings_notifier.g.dart index 2a729d42a..85fb2bb6d 100644 --- a/lib/providers/app_settings_notifier.g.dart +++ b/lib/providers/app_settings_notifier.g.dart @@ -33,7 +33,8 @@ final class AppSettingsNotifierProvider AppSettingsNotifier create() => AppSettingsNotifier(); } -String _$appSettingsNotifierHash() => r'fe24b3b36a74af66268086628fe377141e52c8ff'; +String _$appSettingsNotifierHash() => + r'2ba0d53f1a48ba6876571c965e9e804c04be5645'; abstract class _$AppSettingsNotifier extends $AsyncNotifier { FutureOr build(); diff --git a/lib/widgets/auth/advanced_sheet.dart b/lib/widgets/auth/advanced_sheet.dart index 175680e1c..63d9999b4 100644 --- a/lib/widgets/auth/advanced_sheet.dart +++ b/lib/widgets/auth/advanced_sheet.dart @@ -29,9 +29,11 @@ Future showAdvancedSheet({ required BuildContext context, required bool initialHideCustomServer, required bool initialUsePassword, + required bool initialAllowSelfSignedCerts, required bool loginMode, required TextEditingController serverUrlController, - required void Function(bool hideCustomServer, bool usePassword) onChanged, + required void Function(bool hideCustomServer, bool usePassword, bool allowSelfSignedCerts) + onChanged, }) { return showModalBottomSheet( context: context, @@ -40,6 +42,7 @@ Future showAdvancedSheet({ builder: (_) => AdvancedSheet( initialHideCustomServer: initialHideCustomServer, initialUsePassword: initialUsePassword, + initialAllowSelfSignedCerts: initialAllowSelfSignedCerts, loginMode: loginMode, serverUrlController: serverUrlController, onChanged: onChanged, @@ -50,13 +53,15 @@ Future showAdvancedSheet({ class AdvancedSheet extends StatefulWidget { final bool initialHideCustomServer; final bool initialUsePassword; + final bool initialAllowSelfSignedCerts; final bool loginMode; final TextEditingController serverUrlController; - final void Function(bool hideCustomServer, bool usePassword) onChanged; + final void Function(bool hideCustomServer, bool usePassword, bool allowSelfSignedCerts) onChanged; const AdvancedSheet({ required this.initialHideCustomServer, required this.initialUsePassword, + required this.initialAllowSelfSignedCerts, required this.loginMode, required this.serverUrlController, required this.onChanged, @@ -70,6 +75,7 @@ class AdvancedSheet extends StatefulWidget { class _AdvancedSheetState extends State { late bool _hideCustomServer; late bool _usePassword; + late bool _allowSelfSignedCerts; final _formKey = GlobalKey(); @override @@ -77,11 +83,12 @@ class _AdvancedSheetState extends State { super.initState(); _hideCustomServer = widget.initialHideCustomServer; _usePassword = widget.initialUsePassword; + _allowSelfSignedCerts = widget.initialAllowSelfSignedCerts; } void _set(VoidCallback change) { setState(change); - widget.onChanged(_hideCustomServer, _usePassword); + widget.onChanged(_hideCustomServer, _usePassword, _allowSelfSignedCerts); } @override @@ -151,6 +158,20 @@ class _AdvancedSheetState extends State { padding: const EdgeInsets.only(top: 2, bottom: 4), child: ServerField(controller: widget.serverUrlController), ), + if (!_hideCustomServer) + SwitchListTile( + key: const Key('allowSelfSignedCertsSwitch'), + contentPadding: EdgeInsets.zero, + title: Text(i18n.allowSelfSignedCertsTitle), + subtitle: Text( + i18n.allowSelfSignedCertsDetail, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + value: _allowSelfSignedCerts, + onChanged: (value) => _set(() => _allowSelfSignedCerts = value), + ), if (widget.loginMode) ...[ _SectionLabel(text: i18n.signInMethodSectionLabel), _OptionRow( diff --git a/lib/widgets/auth/auth_card.dart b/lib/widgets/auth/auth_card.dart index bd1a08c2d..e7d706488 100644 --- a/lib/widgets/auth/auth_card.dart +++ b/lib/widgets/auth/auth_card.dart @@ -27,6 +27,7 @@ import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/errors.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/app_link_router.dart'; +import 'package:wger/providers/app_settings_notifier.dart'; import 'package:wger/providers/auth_notifier.dart'; import 'package:wger/providers/auth_state.dart'; import 'package:wger/providers/network_provider.dart'; @@ -69,6 +70,7 @@ class _AuthCardState extends ConsumerState { bool _autoValidate = false; bool _hideCustomServer = true; bool _useUsernameAndPassword = true; + bool _allowSelfSignedCerts = ALLOW_SELF_SIGNED_CERTS_DEFAULT; var _isLoading = false; final _usernameController = TextEditingController(); @@ -105,6 +107,13 @@ class _AuthCardState extends ConsumerState { } }); + // Surface the persisted self-signed-cert preference in the advanced sheet. + ref.read(appSettingsProvider.future).then((settings) { + if (mounted) { + setState(() => _allowSelfSignedCerts = settings.allowSelfSignedCerts); + } + }); + _preFillTextFields(); } @@ -252,13 +261,18 @@ class _AuthCardState extends ConsumerState { context: context, initialHideCustomServer: _hideCustomServer, initialUsePassword: _useUsernameAndPassword, + initialAllowSelfSignedCerts: _allowSelfSignedCerts, loginMode: _authMode == AuthMode.login, serverUrlController: _serverUrlController, - onChanged: (hideCustomServer, usePassword) { + onChanged: (hideCustomServer, usePassword, allowSelfSignedCerts) { setState(() { _hideCustomServer = hideCustomServer; _useUsernameAndPassword = usePassword; + _allowSelfSignedCerts = allowSelfSignedCerts; }); + // Persist immediately and install the override so the next login + // request (still made from this screen) trusts the self-signed cert. + ref.read(appSettingsProvider.notifier).setAllowSelfSignedCerts(allowSelfSignedCerts); }, ).then((_) { if (mounted) { diff --git a/test/auth/auth_screen_test.dart b/test/auth/auth_screen_test.dart index 02a1218ee..12572215f 100644 --- a/test/auth/auth_screen_test.dart +++ b/test/auth/auth_screen_test.dart @@ -17,6 +17,7 @@ */ import 'dart:convert'; +import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -544,6 +545,37 @@ void main() { expect(find.text('http://localhost:8000'), findsNothing); }); + testWidgets('Self-hosted exposes the self-signed-cert toggle and persists it', ( + WidgetTester tester, + ) async { + // Toggling the switch installs a global HttpOverrides; undo it so the + // override does not leak into later tests in this isolate. + addTearDown(() => HttpOverrides.global = null); + + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + tester.view.devicePixelRatio = 1.0; + await tester.pumpWidget(getWidget()); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + + // The toggle only exists once a self-hosted server is selected. + final toggle = find.byKey(const Key('allowSelfSignedCertsSwitch')); + expect(toggle, findsNothing); + await tester.tap(find.text('Self-hosted')); + await tester.pumpAndSettle(); + expect(toggle, findsOneWidget); + + await tester.tap(toggle); + await tester.pumpAndSettle(); + + expect( + await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + isTrue, + ); + }); + testWidgets('Sheet pre-selects Self-hosted for a custom last-used server', ( WidgetTester tester, ) async { diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index 2de004f31..a1ee7dec4 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -167,6 +167,49 @@ void main() { }); }); + group('Allow-self-signed-certs (AppSettingsNotifier)', () { + riverpod.ProviderContainer makeContainer() { + final container = riverpod.ProviderContainer( + overrides: [ + appSettingsPrefsProvider.overrideWithValue(mockSharedPreferences), + ], + ); + addTearDown(container.dispose); + return container; + } + + test('defaults to false', () async { + when( + mockSharedPreferences.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + ).thenAnswer((_) async => null); + + final settings = await makeContainer().read(appSettingsProvider.future); + expect(settings.allowSelfSignedCerts, false); + }); + + test('loads true from prefs', () async { + when( + mockSharedPreferences.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + ).thenAnswer((_) async => true); + + final settings = await makeContainer().read(appSettingsProvider.future); + expect(settings.allowSelfSignedCerts, true); + }); + + test('persists the toggle', () async { + when( + mockSharedPreferences.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + ).thenAnswer((_) async => null); + final container = makeContainer(); + + await container.read(appSettingsProvider.future); + await container.read(appSettingsProvider.notifier).setAllowSelfSignedCerts(true); + + expect(container.read(appSettingsProvider).requireValue.allowSelfSignedCerts, true); + verify(mockSharedPreferences.setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, true)).called(1); + }); + }); + group('Language switcher', () { testWidgets('shows system option when no override set', (WidgetTester tester) async { await tester.pumpWidget(createSettingsScreen()); diff --git a/test/helpers/http_overrides_test.dart b/test/helpers/http_overrides_test.dart new file mode 100644 index 000000000..563184909 --- /dev/null +++ b/test/helpers/http_overrides_test.dart @@ -0,0 +1,45 @@ +/* + * This file is part of wger Workout Manager . + * 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 + * 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 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/helpers/http_overrides.dart'; + +void main() { + // Restore the default networking after each test so we don't leak the + // certificate override into other tests sharing the same isolate. + final HttpOverrides? original = HttpOverrides.current; + tearDown(() => HttpOverrides.global = original); + + test('applySelfSignedCertOverride(true) installs WgerHttpOverrides', () { + applySelfSignedCertOverride(true); + expect(HttpOverrides.current, isA()); + }); + + test('applySelfSignedCertOverride(false) removes the override', () { + applySelfSignedCertOverride(true); + applySelfSignedCertOverride(false); + expect(HttpOverrides.current, isNull); + }); + + test('WgerHttpOverrides creates a usable HttpClient', () { + final client = WgerHttpOverrides().createHttpClient(null); + expect(client, isA()); + }); +} From f9b9885de75756f483a66598a9b98c821d70b539 Mon Sep 17 00:00:00 2001 From: bhavit04 Date: Wed, 24 Jun 2026 16:45:41 +0530 Subject: [PATCH 014/484] feat(weight): add time-range selector to body weight chart The body weight chart always plotted the entire history, which becomes hard to read for users with a lot of entries going back a long time. Add a segmented selector above the chart with "All" / "Last year" / "Last 3 months" options (the approach suggested in the issue) that restricts the plotted range. "All" is the default, so the existing behaviour is unchanged unless the user opts in. The range filtering is applied to the weight overview only; the shared getOverviewWidgetsSeries helper gains an optional mainChartTitle so the header reflects the selected range, leaving the measurements call site untouched. Closes #148 Co-Authored-By: Claude Opus 4.8 --- lib/l10n/app_en.arb | 32 ++++++++++++ lib/widgets/measurements/helpers.dart | 7 +-- lib/widgets/weight/weight_overview.dart | 68 +++++++++++++++++++++++-- test/weight/weight_screen_test.dart | 27 ++++++++++ 4 files changed, 126 insertions(+), 8 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b185a7107..47d955f6f 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -534,6 +534,38 @@ } } }, + "chartLastYearTitle": "{name} last year", + "@chartLastYearTitle": { + "description": "last year chart of 'name' (e.g. 'weight', 'body fat' etc.)", + "type": "text", + "placeholders": { + "name": { + "type": "String" + } + } + }, + "chartLast3MonthsTitle": "{name} last 3 months", + "@chartLast3MonthsTitle": { + "description": "last 3 months chart of 'name' (e.g. 'weight', 'body fat' etc.)", + "type": "text", + "placeholders": { + "name": { + "type": "String" + } + } + }, + "chartRangeAll": "All", + "@chartRangeAll": { + "description": "Label for the chart time-range selector option showing all data" + }, + "chartRangeLastYear": "Last year", + "@chartRangeLastYear": { + "description": "Label for the chart time-range selector option showing the last year" + }, + "chartRangeLast3Months": "Last 3 months", + "@chartRangeLast3Months": { + "description": "Label for the chart time-range selector option showing the last 3 months" + }, "measurement": "Measurement", "@measurement": {}, "measurements": "Measurements", diff --git a/lib/widgets/measurements/helpers.dart b/lib/widgets/measurements/helpers.dart index 00369b06d..67c75f891 100644 --- a/lib/widgets/measurements/helpers.dart +++ b/lib/widgets/measurements/helpers.dart @@ -42,12 +42,13 @@ List getOverviewWidgetsSeries( List entries7dAvg, List plans, String unit, - BuildContext context, -) { + BuildContext context, { + String? mainChartTitle, +}) { final monthAgo = DateTime.now().subtract(const Duration(days: 30)); return [ ...getOverviewWidgets( - AppLocalizations.of(context).chartAllTimeTitle(name), + mainChartTitle ?? AppLocalizations.of(context).chartAllTimeTitle(name), entriesAll, entries7dAvg, unit, diff --git a/lib/widgets/weight/weight_overview.dart b/lib/widgets/weight/weight_overview.dart index 53ef5db4a..0533860f5 100644 --- a/lib/widgets/weight/weight_overview.dart +++ b/lib/widgets/weight/weight_overview.dart @@ -19,6 +19,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; import 'package:intl/intl.dart'; +import 'package:wger/helpers/measurements.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; import 'package:wger/providers/body_weight_notifier.dart'; @@ -31,11 +32,22 @@ import 'package:wger/widgets/measurements/charts.dart'; import 'package:wger/widgets/measurements/helpers.dart'; import 'package:wger/widgets/weight/forms.dart'; -class WeightOverview extends riverpod.ConsumerWidget { +/// Time range the user can pick to limit how far back the weight chart goes. +enum WeightChartRange { all, lastYear, last3Months } + +class WeightOverview extends riverpod.ConsumerStatefulWidget { const WeightOverview(); @override - Widget build(BuildContext context, riverpod.WidgetRef ref) { + riverpod.ConsumerState createState() => _WeightOverviewState(); +} + +class _WeightOverviewState extends riverpod.ConsumerState { + WeightChartRange _range = WeightChartRange.all; + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); final profileAsync = ref.watch(userProfileProvider); final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); final plans = ref.watch(nutritionProvider).value?.plans ?? const []; @@ -54,17 +66,63 @@ class WeightOverview extends riverpod.ConsumerWidget { final entriesAll = entriesList.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(); final entries7dAvg = moving7dAverage(entriesAll); + // Restrict the data to the selected range. The average is computed over + // the full history first and only filtered afterwards, matching how the + // per-plan and 30-day sub-charts are built. + final (DateTime? cutoff, String? mainChartTitle) = switch (_range) { + WeightChartRange.all => (null, null), + WeightChartRange.lastYear => ( + DateTime.now().subtract(const Duration(days: 365)), + i18n.chartLastYearTitle(i18n.weight), + ), + WeightChartRange.last3Months => ( + DateTime.now().subtract(const Duration(days: 90)), + i18n.chartLast3MonthsTitle(i18n.weight), + ), + }; + final entriesRange = cutoff == null ? entriesAll : entriesAll.whereDate(cutoff, null); + final entries7dAvgRange = + cutoff == null ? entries7dAvg : entries7dAvg.whereDate(cutoff, null); + final unit = weightUnit(profile.isMetric, context); return Column( children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 15), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SegmentedButton( + key: const ValueKey('weightChartRangeSelector'), + showSelectedIcon: false, + segments: [ + ButtonSegment( + value: WeightChartRange.all, + label: Text(i18n.chartRangeAll), + ), + ButtonSegment( + value: WeightChartRange.lastYear, + label: Text(i18n.chartRangeLastYear), + ), + ButtonSegment( + value: WeightChartRange.last3Months, + label: Text(i18n.chartRangeLast3Months), + ), + ], + selected: {_range}, + onSelectionChanged: (selection) => + setState(() => _range = selection.first), + ), + ), + ), ...getOverviewWidgetsSeries( - AppLocalizations.of(context).weight, - entriesAll, - entries7dAvg, + i18n.weight, + entriesRange, + entries7dAvgRange, plans, unit, context, + mainChartTitle: mainChartTitle, ), TextButton( onPressed: () => Navigator.pushNamed( diff --git a/test/weight/weight_screen_test.dart b/test/weight/weight_screen_test.dart index d6391e31e..22e15953d 100644 --- a/test/weight/weight_screen_test.dart +++ b/test/weight/weight_screen_test.dart @@ -94,6 +94,33 @@ void main() { expect(find.byType(ListTile), findsNWidgets(2)); }); + testWidgets('Weight chart range selector filters the data', (WidgetTester tester) async { + await tester.pumpWidget(createWeightScreen()); + await tester.pumpAndSettle(); + + // The range selector is shown with the three options + expect(find.byKey(const ValueKey('weightChartRangeSelector')), findsOneWidget); + expect(find.text('All'), findsOneWidget); + expect(find.text('Last year'), findsOneWidget); + expect(find.text('Last 3 months'), findsOneWidget); + + // By default (all time) the chart is shown for the seeded entries + expect(find.byType(MeasurementChartWidgetFl), findsOneWidget); + + // Restricting to the last 3 months excludes the (old) seeded data + await tester.ensureVisible(find.text('Last 3 months')); + await tester.tap(find.text('Last 3 months')); + await tester.pumpAndSettle(); + expect(find.byType(MeasurementChartWidgetFl), findsNothing); + expect(find.text('No data available'), findsOneWidget); + + // Switching back to all time restores the chart + await tester.ensureVisible(find.text('All')); + await tester.tap(find.text('All')); + await tester.pumpAndSettle(); + expect(find.byType(MeasurementChartWidgetFl), findsOneWidget); + }); + testWidgets('Test deleting an item using the Delete button', (WidgetTester tester) async { // Arrange await tester.pumpWidget(createWeightScreen()); From ec115096566d81e6be3ba9163f430ba64f420fde Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Wed, 1 Jul 2026 09:13:19 +0545 Subject: [PATCH 015/484] refactor(models): update workout session time tracking to DateTime - Convert timeStart and timeEnd from TimeOfDay to DateTime for better precision and easier duration calculation. - Includes overnight session detection logic - Limits active session fetching to a new sessionMaxDuration constant (5 hours). - Relates to: wger-project/wger#2379 --- lib/helpers/routines/validators.dart | 4 +- lib/models/workouts/session.dart | 43 ++++++++++++------- lib/providers/gym_state.dart | 8 ++-- lib/widgets/dashboard/calendar.dart | 3 +- lib/widgets/routines/forms/session.dart | 33 ++++++++++++-- .../routines/gym_mode/session_page.dart | 9 +++- 6 files changed, 71 insertions(+), 29 deletions(-) diff --git a/lib/helpers/routines/validators.dart b/lib/helpers/routines/validators.dart index 5e79191f2..9867c1818 100644 --- a/lib/helpers/routines/validators.dart +++ b/lib/helpers/routines/validators.dart @@ -39,8 +39,8 @@ String? validateWorkoutLogCrossField({ /// - [timeStart] and [timeEnd] must both be set or both be empty, /// - if both are set, [timeStart] must not be after [timeEnd]. String? validateWorkoutSessionTimes({ - required TimeOfDay? timeStart, - required TimeOfDay? timeEnd, + required DateTime? timeStart, + required DateTime? timeEnd, required AppLocalizations i18n, }) { if ((timeStart == null) != (timeEnd == null)) { diff --git a/lib/models/workouts/session.dart b/lib/models/workouts/session.dart index 864f596f6..2f7e266b0 100644 --- a/lib/models/workouts/session.dart +++ b/lib/models/workouts/session.dart @@ -54,6 +54,8 @@ extension WorkoutImpressionL10n on WorkoutImpression { } } +const sessionMaxDuration = Duration(hours: 5); + class WorkoutSession { /// Inclusive upper bound for [notes] static const maxNotesChars = 1000; @@ -65,10 +67,10 @@ class WorkoutSession { DateTime date; WorkoutImpression impression; late String? notes; - late TimeOfDay? timeStart; - late TimeOfDay? timeEnd; + DateTime? timeStart; + DateTime? timeEnd; - List logs = []; + List logs; WorkoutSession({ this.id, @@ -87,28 +89,34 @@ class WorkoutSession { id: id != null ? drift.Value(id!) : const drift.Value.absent(), routineId: routineId != null ? drift.Value(routineId) : const drift.Value.absent(), dayId: dayId != null ? drift.Value(dayId) : const drift.Value.absent(), - // Server-side `date` is a `DateField` (no time, no TZ). We send here the - // calendar day the user picked, packaged as midnight-UTC so it round-trips + // Server-side `date` is a `DateTimeField`. It round-trips // through PowerSync's ISO8601 wire format and lands on the right day on // the server. date: drift.Value(DateTime.utc(date.year, date.month, date.day)), notes: drift.Value(notes), impression: drift.Value(impression), - timeStart: timeStart != null ? drift.Value(timeStart) : const drift.Value.absent(), - timeEnd: timeEnd != null ? drift.Value(timeEnd) : const drift.Value.absent(), + timeStart: timeStart != null + ? drift.Value(TimeOfDay.fromDateTime(timeStart!)) + : const drift.Value.absent(), + timeEnd: timeEnd != null + ? drift.Value(TimeOfDay.fromDateTime(timeEnd!)) + : const drift.Value.absent(), ); } + /// Calculates the duration between [timeStart] and [timeEnd]. + /// Returns null if either is missing. Duration? get duration { - if (timeStart == null || timeEnd == null) { + final start = timeStart; + final end = timeEnd; + if (start == null || end == null) { return null; } - final now = DateTime.now(); - final startDate = DateTime(now.year, now.month, now.day, timeStart!.hour, timeStart!.minute); - final endDate = DateTime(now.year, now.month, now.day, timeEnd!.hour, timeEnd!.minute); - return endDate.difference(startDate); + + return end.difference(start); } + /// Returns a localized string representation of the duration (e.g., "2h 30m"). String durationTxt(BuildContext context) { final duration = this.duration; if (duration == null) { @@ -119,14 +127,17 @@ class WorkoutSession { ).durationHoursMinutes(duration.inHours, duration.inMinutes.remainder(60)); } + /// Returns a formatted string: "2h 30m (09:00 AM - 11:30 AM)". String durationTxtWithStartEnd(BuildContext context) { - final duration = this.duration; - if (duration == null) { + final start = timeStart; + final end = timeEnd; + if (end == null || start == null) { return '-/-'; } - final startTime = MaterialLocalizations.of(context).formatTimeOfDay(timeStart!); - final endTime = MaterialLocalizations.of(context).formatTimeOfDay(timeEnd!); + final localizations = MaterialLocalizations.of(context); + final startTime = localizations.formatTimeOfDay(TimeOfDay.fromDateTime(start)); + final endTime = localizations.formatTimeOfDay(TimeOfDay.fromDateTime(end)); return '${durationTxt(context)} ($startTime - $endTime)'; } diff --git a/lib/providers/gym_state.dart b/lib/providers/gym_state.dart index 44644b3e2..1a5e9388e 100644 --- a/lib/providers/gym_state.dart +++ b/lib/providers/gym_state.dart @@ -168,7 +168,7 @@ class GymModeState { final List pages; final int currentPage; - final TimeOfDay startTime; + final DateTime startTime; final DateTime validUntil; // User settings @@ -199,9 +199,9 @@ class GymModeState { Routine? routine, DateTime? validUntil, - TimeOfDay? startTime, + DateTime? startTime, }) : validUntil = validUntil ?? clock.now().add(DEFAULT_DURATION), - startTime = startTime ?? TimeOfDay.fromDateTime(clock.now()) { + startTime = startTime ?? clock.now() { if (dayId != null) { this.dayId = dayId; } @@ -225,7 +225,7 @@ class GymModeState { int? dayId, int? iteration, DateTime? validUntil, - TimeOfDay? startTime, + DateTime? startTime, Routine? routine, // User settings diff --git a/lib/widgets/dashboard/calendar.dart b/lib/widgets/dashboard/calendar.dart index b60927ac2..9f0e3c534 100644 --- a/lib/widgets/dashboard/calendar.dart +++ b/lib/widgets/dashboard/calendar.dart @@ -111,7 +111,8 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState []); var time = ''; if (session.timeStart != null && session.timeEnd != null) { - time = '(${timeToString(session.timeStart)} - ${timeToString(session.timeEnd)})'; + time = + '(${timeToString(TimeOfDay.fromDateTime(session.timeStart!))} - ${timeToString(TimeOfDay.fromDateTime(session.timeEnd!))})'; } events[date]!.add( Event( diff --git a/lib/widgets/routines/forms/session.dart b/lib/widgets/routines/forms/session.dart index d41dc0f7d..bba147c73 100644 --- a/lib/widgets/routines/forms/session.dart +++ b/lib/widgets/routines/forms/session.dart @@ -120,19 +120,44 @@ class _SessionFormState extends ConsumerState { Flexible( child: TimeInputWidget( key: const ValueKey('time-start'), - value: widget._session.timeStart, + value: widget._session.timeStart != null + ? TimeOfDay.fromDateTime(widget._session.timeStart!) + : null, labelText: AppLocalizations.of(context).timeStart, onCleared: () => widget._session.timeStart = null, - onChanged: (time) => widget._session.timeStart = time, + + onChanged: (time) { + final now = clock.now(); + widget._session.timeStart = (widget._session.timeStart ?? now).copyWith( + hour: time.hour, + minute: time.minute, + ); + }, ), ), Flexible( child: TimeInputWidget( key: const ValueKey('time-end'), - value: widget._session.timeEnd, + value: widget._session.timeEnd != null + ? TimeOfDay.fromDateTime(widget._session.timeEnd!) + : null, labelText: AppLocalizations.of(context).timeEnd, onCleared: () => widget._session.timeEnd = null, - onChanged: (time) => widget._session.timeEnd = time, + + onChanged: (time) { + final now = clock.now(); + final start = widget._session.timeStart ?? now; + final end = (widget._session.timeEnd ?? now).copyWith( + hour: time.hour, + minute: time.minute, + ); + + if (end.isBefore(start)) { + widget._session.timeEnd = end.add(const Duration(days: 1)); + } else { + widget._session.timeEnd = end; + } + }, ), ), ], diff --git a/lib/widgets/routines/gym_mode/session_page.dart b/lib/widgets/routines/gym_mode/session_page.dart index 6180cbbe7..d58d33408 100644 --- a/lib/widgets/routines/gym_mode/session_page.dart +++ b/lib/widgets/routines/gym_mode/session_page.dart @@ -52,14 +52,19 @@ class _SessionPageState extends ConsumerState { value: ref.watch(workoutSessionProvider), loggerName: 'SessionPage', data: (sessions) { + final nowDt = clock.now(); + final start = gymState.startTime; final session = sessions.firstWhere( - (s) => s.date.isSameDayAs(clock.now()) && s.routineId == gymState.routine.id, + (s) => + s.timeEnd == null && + s.routineId == gymState.routine.id && + nowDt.difference(s.timeStart!) <= sessionMaxDuration, orElse: () => WorkoutSession( dayId: gymState.dayId, date: clock.now(), routineId: gymState.routine.id, timeStart: gymState.startTime, - timeEnd: TimeOfDay.fromDateTime(clock.now()), + timeEnd: nowDt, ), ); From 13218a2dd6eb5c2b2b5ef7ccfce60589d6951602 Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Wed, 1 Jul 2026 19:58:09 +0545 Subject: [PATCH 016/484] feat(database): upgrade session time tracking to full DateTime Refactors WorkoutSession storage from TimeOfDay to DateTime to enable accurate cross-midnight session tracking. - Adds DateTimeTextConverter to handle ISO8601 serialization/deserialization. - Updates WorkoutSessionTable to use the new DateTime converter. - Refactors WorkoutLogRepository to use UTC ISO8601 strings for time range queries in Drift. - Improves lazy session creation logic to handle closed vs. open session states. --- .../converters/date_only_text_converter.dart | 19 +++++++++++++ lib/database/powersync/tables/routines.dart | 5 ++-- lib/models/workouts/session.dart | 8 ++---- lib/providers/workout_logs_repository.dart | 27 ++++++++++++++++--- 4 files changed, 47 insertions(+), 12 deletions(-) diff --git a/lib/database/converters/date_only_text_converter.dart b/lib/database/converters/date_only_text_converter.dart index 7507c216b..62cdbe910 100644 --- a/lib/database/converters/date_only_text_converter.dart +++ b/lib/database/converters/date_only_text_converter.dart @@ -42,3 +42,22 @@ class DateOnlyTextConverter extends TypeConverter { '${value.month.toString().padLeft(2, '0')}-' '${value.day.toString().padLeft(2, '0')}'; } + +class DateTimeTextConverter extends TypeConverter { + const DateTimeTextConverter(); + + @override + DateTime fromSql(String fromDb) { + final day = DateTime.parse(fromDb.substring(0, 19)); + return DateTime.utc(day.year, day.month, day.day, day.hour, day.minute, day.second); + } + + @override + String toSql(DateTime value) => + '${value.year.toString().padLeft(4, '0')}-' + '${value.month.toString().padLeft(2, '0')}-' + '${value.day.toString().padLeft(2, '0')}T' + '${value.hour.toString().padLeft(2, '0')}:' + '${value.minute.toString().padLeft(2, '0')}:' + '${value.second.toString().padLeft(2, '0')}'; +} diff --git a/lib/database/powersync/tables/routines.dart b/lib/database/powersync/tables/routines.dart index 21cbf322e..3438ca354 100644 --- a/lib/database/powersync/tables/routines.dart +++ b/lib/database/powersync/tables/routines.dart @@ -124,8 +124,9 @@ class WorkoutSessionTable extends Table { TextColumn get notes => text().nullable()(); TextColumn get impression => text().map(const WorkoutImpressionConverter())(); TextColumn get timeStart => - text().named('time_start').nullable().map(const TimeOfDayConverter())(); - TextColumn get timeEnd => text().named('time_end').nullable().map(const TimeOfDayConverter())(); + text().named('time_start').nullable().map(const DateTimeTextConverter())(); + TextColumn get timeEnd => + text().named('time_end').nullable().map(const DateTimeTextConverter())(); } const PowersyncWorkoutSessionTable = ps.Table( diff --git a/lib/models/workouts/session.dart b/lib/models/workouts/session.dart index 2f7e266b0..74af5ee8e 100644 --- a/lib/models/workouts/session.dart +++ b/lib/models/workouts/session.dart @@ -95,12 +95,8 @@ class WorkoutSession { date: drift.Value(DateTime.utc(date.year, date.month, date.day)), notes: drift.Value(notes), impression: drift.Value(impression), - timeStart: timeStart != null - ? drift.Value(TimeOfDay.fromDateTime(timeStart!)) - : const drift.Value.absent(), - timeEnd: timeEnd != null - ? drift.Value(TimeOfDay.fromDateTime(timeEnd!)) - : const drift.Value.absent(), + timeStart: timeStart != null ? drift.Value(timeStart) : const drift.Value.absent(), + timeEnd: timeEnd != null ? drift.Value(timeEnd) : const drift.Value.absent(), ); } diff --git a/lib/providers/workout_logs_repository.dart b/lib/providers/workout_logs_repository.dart index a667fb5b0..d81065e0e 100644 --- a/lib/providers/workout_logs_repository.dart +++ b/lib/providers/workout_logs_repository.dart @@ -23,6 +23,7 @@ import 'package:drift/drift.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; +import 'package:wger/helpers/json.dart'; import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/session.dart'; @@ -110,18 +111,22 @@ class WorkoutLogRepository { await _db.transaction(() async { if (log.sessionId == null) { final dayMidnightUtc = DateTime.utc(log.date.year, log.date.month, log.date.day); + final windowStart = log.date.subtract(sessionMaxDuration); final existing = await (_db.select(_db.workoutSessionTable) ..where( - (t) => t.routineId.equals(log.routineId) & t.date.equalsValue(dayMidnightUtc), + (t) => + t.routineId.equals(log.routineId) & + t.timeStart.isBiggerOrEqualValue(dateToUtcIso8601(windowStart)) & + t.timeStart.isSmallerOrEqualValue(dateToUtcIso8601(log.date)), ) + ..orderBy([(t) => OrderingTerm.desc(t.timeStart)]) ..limit(1)) .getSingleOrNull(); - if (existing != null) { - log.sessionId = existing.id; - } else { + if (existing == null) { + // No session at all -> create new session final newSession = WorkoutSession( routineId: log.routineId, date: dayMidnightUtc, @@ -131,6 +136,20 @@ class WorkoutLogRepository { .insertReturning(newSession.toCompanion()); log.sessionId = inserted.id; _logger.finer('Created lazy session ${inserted.id} for log'); + } else if (existing.timeEnd != null && log.date.isAfter(existing.timeEnd!)) { + // Session found but already closed -> create new session + final newSession = WorkoutSession( + routineId: log.routineId, + date: dayMidnightUtc, + ); + final inserted = await _db + .into(_db.workoutSessionTable) + .insertReturning(newSession.toCompanion()); + log.sessionId = inserted.id; + _logger.finer('Created lazy session ${inserted.id} for log'); + } else { + // Session is open and within window -> reuse it + log.sessionId = existing.id; } } From 18b745f3654f26f1b71d14f85e05077d82926ffb Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 2 Jul 2026 21:45:53 +0200 Subject: [PATCH 017/484] Start reworking the sync logic We don't just want to sync the weight entries --- android/app/src/main/AndroidManifest.xml | 5 +- ios/Runner/Runner.entitlements | 4 - lib/core/home_tabs_screen.dart | 10 +- lib/database/powersync/database.g.dart | 168 +++++++++++- .../powersync/tables/measurements.dart | 15 ++ .../account/widgets/settings/health_sync.dart | 13 +- lib/features/health/models/health_metric.dart | 134 ++++++++++ .../health/providers/health_sync.dart | 250 ++++++++++++++++++ .../providers/health_sync.g.dart | 19 +- .../models/measurement_category.dart | 7 + .../models/measurement_category.freezed.dart | 17 +- .../models/measurement_entry.dart | 14 + .../models/measurement_entry.freezed.dart | 20 +- .../providers/measurement_repository.dart | 3 + .../weight/providers/health_sync.dart | 249 ----------------- lib/l10n/app_en.arb | 4 +- lib/powersync/connector.dart | 5 +- .../account/widgets/settings_test.dart | 2 +- .../health/models/health_metric_test.dart | 79 ++++++ .../providers/health_sync_test.dart | 42 +-- .../measurement_notifier_test.mocks.dart | 10 + ...surement_categories_screen_test.mocks.dart | 10 + ...measurement_entries_screen_test.mocks.dart | 10 + test/powersync/connector_test.dart | 10 + .../screenshots_01_dashboard.mocks.dart | 10 + .../screenshots_04_measurements.mocks.dart | 10 + 26 files changed, 787 insertions(+), 333 deletions(-) create mode 100644 lib/features/health/models/health_metric.dart create mode 100644 lib/features/health/providers/health_sync.dart rename lib/features/{weight => health}/providers/health_sync.g.dart (56%) delete mode 100644 lib/features/weight/providers/health_sync.dart create mode 100644 test/features/health/models/health_metric_test.dart rename test/features/{weight => health}/providers/health_sync_test.dart (50%) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 1b01bfd55..2016766b4 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -9,8 +9,9 @@ - - + + + diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements index 57cd45923..c77f75e0e 100644 --- a/ios/Runner/Runner.entitlements +++ b/ios/Runner/Runner.entitlements @@ -6,9 +6,5 @@ development com.apple.developer.healthkit - com.apple.developer.healthkit.access - - health-records - diff --git a/lib/core/home_tabs_screen.dart b/lib/core/home_tabs_screen.dart index 5f17f24dd..3ba7f6498 100644 --- a/lib/core/home_tabs_screen.dart +++ b/lib/core/home_tabs_screen.dart @@ -21,12 +21,10 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:wger/core/dashboard.dart'; import 'package:wger/core/material.dart'; -import 'package:wger/features/account/providers/user_profile_notifier.dart'; import 'package:wger/features/gallery/screens/gallery_screen.dart'; +import 'package:wger/features/health/providers/health_sync.dart'; import 'package:wger/features/nutrition/screens/nutritional_plans_screen.dart'; import 'package:wger/features/routines/screens/routine_list_screen.dart'; -import 'package:wger/features/weight/providers/body_weight_notifier.dart'; -import 'package:wger/features/weight/providers/health_sync.dart'; import 'package:wger/features/weight/screens/weight_screen.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -54,11 +52,7 @@ class _HomeTabsScreenState extends ConsumerState if (!mounted) { return; } - final existingEntries = ref.read(weightEntryProvider).value ?? []; - final isMetric = ref.read(userProfileProvider).value?.isMetric ?? true; - ref - .read(healthSyncProvider.notifier) - .syncOnAppOpen(existingEntries: existingEntries, isMetric: isMetric); + ref.read(healthSyncProvider.notifier).syncOnAppOpen(); }); } diff --git a/lib/database/powersync/database.g.dart b/lib/database/powersync/database.g.dart index e09e93822..b594929e2 100644 --- a/lib/database/powersync/database.g.dart +++ b/lib/database/powersync/database.g.dart @@ -4880,8 +4880,19 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable type: DriftSqlType.string, requiredDuringInsert: true, ); + static const VerificationMeta _metricTypeMeta = const VerificationMeta( + 'metricType', + ); @override - List get $columns => [id, name, unit]; + late final GeneratedColumn metricType = GeneratedColumn( + 'metric_type', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); + @override + List get $columns => [id, name, unit, metricType]; @override String get aliasedName => _alias ?? actualTableName; @override @@ -4913,6 +4924,12 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable } else if (isInserting) { context.missing(_unitMeta); } + if (data.containsKey('metric_type')) { + context.handle( + _metricTypeMeta, + metricType.isAcceptableOrUnknown(data['metric_type']!, _metricTypeMeta), + ); + } return context; } @@ -4934,6 +4951,10 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable DriftSqlType.string, data['${effectivePrefix}unit'], )!, + metricType: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}metric_type'], + ), ); } @@ -4947,17 +4968,20 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion id; final Value name; final Value unit; + final Value metricType; 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.rowid = const Value.absent(), }); MeasurementCategoryTableCompanion.insert({ this.id = const Value.absent(), required String name, required String unit, + this.metricType = const Value.absent(), this.rowid = const Value.absent(), }) : name = Value(name), unit = Value(unit); @@ -4965,12 +4989,14 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion? id, Expression? name, Expression? unit, + Expression? metricType, Expression? rowid, }) { return RawValuesInsertable({ if (id != null) 'id': id, if (name != null) 'name': name, if (unit != null) 'unit': unit, + if (metricType != null) 'metric_type': metricType, if (rowid != null) 'rowid': rowid, }); } @@ -4979,12 +5005,14 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion? id, Value? name, Value? unit, + Value? metricType, Value? rowid, }) { return MeasurementCategoryTableCompanion( id: id ?? this.id, name: name ?? this.name, unit: unit ?? this.unit, + metricType: metricType ?? this.metricType, rowid: rowid ?? this.rowid, ); } @@ -5001,6 +5029,9 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion(unit.value); } + if (metricType.present) { + map['metric_type'] = Variable(metricType.value); + } if (rowid.present) { map['rowid'] = Variable(rowid.value); } @@ -5013,6 +5044,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion get $columns => [id, categoryId, date, value, notes]; + late final GeneratedColumn source = GeneratedColumn( + 'source', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: false, + defaultValue: const Constant('manual'), + ); + static const VerificationMeta _externalIdMeta = const VerificationMeta( + 'externalId', + ); + @override + late final GeneratedColumn externalId = GeneratedColumn( + 'external_id', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); + @override + List get $columns => [ + id, + categoryId, + date, + value, + notes, + source, + externalId, + ]; @override String get aliasedName => _alias ?? actualTableName; @override @@ -5116,6 +5177,18 @@ class $MeasurementEntryTableTable extends MeasurementEntryTable } else if (isInserting) { context.missing(_notesMeta); } + if (data.containsKey('source')) { + context.handle( + _sourceMeta, + source.isAcceptableOrUnknown(data['source']!, _sourceMeta), + ); + } + if (data.containsKey('external_id')) { + context.handle( + _externalIdMeta, + externalId.isAcceptableOrUnknown(data['external_id']!, _externalIdMeta), + ); + } return context; } @@ -5147,6 +5220,14 @@ class $MeasurementEntryTableTable extends MeasurementEntryTable DriftSqlType.string, data['${effectivePrefix}notes'], )!, + source: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}source'], + )!, + externalId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}external_id'], + ), ); } @@ -5164,6 +5245,8 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { final Value date; final Value value; final Value notes; + final Value source; + final Value externalId; final Value rowid; const MeasurementEntryTableCompanion({ this.id = const Value.absent(), @@ -5171,6 +5254,8 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { this.date = const Value.absent(), this.value = const Value.absent(), this.notes = const Value.absent(), + this.source = const Value.absent(), + this.externalId = const Value.absent(), this.rowid = const Value.absent(), }); MeasurementEntryTableCompanion.insert({ @@ -5179,6 +5264,8 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { required DateTime date, required double value, required String notes, + this.source = const Value.absent(), + this.externalId = const Value.absent(), this.rowid = const Value.absent(), }) : categoryId = Value(categoryId), date = Value(date), @@ -5190,6 +5277,8 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { Expression? date, Expression? value, Expression? notes, + Expression? source, + Expression? externalId, Expression? rowid, }) { return RawValuesInsertable({ @@ -5198,6 +5287,8 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { if (date != null) 'date': date, if (value != null) 'value': value, if (notes != null) 'notes': notes, + if (source != null) 'source': source, + if (externalId != null) 'external_id': externalId, if (rowid != null) 'rowid': rowid, }); } @@ -5208,6 +5299,8 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { Value? date, Value? value, Value? notes, + Value? source, + Value? externalId, Value? rowid, }) { return MeasurementEntryTableCompanion( @@ -5216,6 +5309,8 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { date: date ?? this.date, value: value ?? this.value, notes: notes ?? this.notes, + source: source ?? this.source, + externalId: externalId ?? this.externalId, rowid: rowid ?? this.rowid, ); } @@ -5240,6 +5335,12 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { if (notes.present) { map['notes'] = Variable(notes.value); } + if (source.present) { + map['source'] = Variable(source.value); + } + if (externalId.present) { + map['external_id'] = Variable(externalId.value); + } if (rowid.present) { map['rowid'] = Variable(rowid.value); } @@ -5254,6 +5355,8 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { ..write('date: $date, ') ..write('value: $value, ') ..write('notes: $notes, ') + ..write('source: $source, ') + ..write('externalId: $externalId, ') ..write('rowid: $rowid') ..write(')')) .toString(); @@ -16368,6 +16471,7 @@ typedef $$MeasurementCategoryTableTableCreateCompanionBuilder = Value id, required String name, required String unit, + Value metricType, Value rowid, }); typedef $$MeasurementCategoryTableTableUpdateCompanionBuilder = @@ -16375,6 +16479,7 @@ typedef $$MeasurementCategoryTableTableUpdateCompanionBuilder = Value id, Value name, Value unit, + Value metricType, Value rowid, }); @@ -16436,6 +16541,11 @@ class $$MeasurementCategoryTableTableFilterComposer builder: (column) => ColumnFilters(column), ); + ColumnFilters get metricType => $composableBuilder( + column: $table.metricType, + builder: (column) => ColumnFilters(column), + ); + Expression measurementEntryTableRefs( Expression Function($$MeasurementEntryTableTableFilterComposer f) f, ) { @@ -16484,6 +16594,11 @@ class $$MeasurementCategoryTableTableOrderingComposer column: $table.unit, builder: (column) => ColumnOrderings(column), ); + + ColumnOrderings get metricType => $composableBuilder( + column: $table.metricType, + builder: (column) => ColumnOrderings(column), + ); } class $$MeasurementCategoryTableTableAnnotationComposer @@ -16504,6 +16619,11 @@ class $$MeasurementCategoryTableTableAnnotationComposer GeneratedColumn get unit => $composableBuilder(column: $table.unit, builder: (column) => column); + GeneratedColumn get metricType => $composableBuilder( + column: $table.metricType, + builder: (column) => column, + ); + Expression measurementEntryTableRefs( Expression Function($$MeasurementEntryTableTableAnnotationComposer a) f, ) { @@ -16568,11 +16688,13 @@ class $$MeasurementCategoryTableTableTableManager Value id = const Value.absent(), Value name = const Value.absent(), Value unit = const Value.absent(), + Value metricType = const Value.absent(), Value rowid = const Value.absent(), }) => MeasurementCategoryTableCompanion( id: id, name: name, unit: unit, + metricType: metricType, rowid: rowid, ), createCompanionCallback: @@ -16580,11 +16702,13 @@ class $$MeasurementCategoryTableTableTableManager Value id = const Value.absent(), required String name, required String unit, + Value metricType = const Value.absent(), Value rowid = const Value.absent(), }) => MeasurementCategoryTableCompanion.insert( id: id, name: name, unit: unit, + metricType: metricType, rowid: rowid, ), withReferenceMapper: (p0) => p0 @@ -16651,6 +16775,8 @@ typedef $$MeasurementEntryTableTableCreateCompanionBuilder = required DateTime date, required double value, required String notes, + Value source, + Value externalId, Value rowid, }); typedef $$MeasurementEntryTableTableUpdateCompanionBuilder = @@ -16660,6 +16786,8 @@ typedef $$MeasurementEntryTableTableUpdateCompanionBuilder = Value date, Value value, Value notes, + Value source, + Value externalId, Value rowid, }); @@ -16722,6 +16850,16 @@ class $$MeasurementEntryTableTableFilterComposer builder: (column) => ColumnFilters(column), ); + ColumnFilters get source => $composableBuilder( + column: $table.source, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get externalId => $composableBuilder( + column: $table.externalId, + builder: (column) => ColumnFilters(column), + ); + $$MeasurementCategoryTableTableFilterComposer get categoryId { final $$MeasurementCategoryTableTableFilterComposer composer = $composerBuilder( composer: this, @@ -16774,6 +16912,16 @@ class $$MeasurementEntryTableTableOrderingComposer builder: (column) => ColumnOrderings(column), ); + ColumnOrderings get source => $composableBuilder( + column: $table.source, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get externalId => $composableBuilder( + column: $table.externalId, + builder: (column) => ColumnOrderings(column), + ); + $$MeasurementCategoryTableTableOrderingComposer get categoryId { final $$MeasurementCategoryTableTableOrderingComposer composer = $composerBuilder( composer: this, @@ -16818,6 +16966,14 @@ class $$MeasurementEntryTableTableAnnotationComposer GeneratedColumn get notes => $composableBuilder(column: $table.notes, builder: (column) => column); + GeneratedColumn get source => + $composableBuilder(column: $table.source, builder: (column) => column); + + GeneratedColumn get externalId => $composableBuilder( + column: $table.externalId, + builder: (column) => column, + ); + $$MeasurementCategoryTableTableAnnotationComposer get categoryId { final $$MeasurementCategoryTableTableAnnotationComposer composer = $composerBuilder( composer: this, @@ -16882,6 +17038,8 @@ class $$MeasurementEntryTableTableTableManager Value date = const Value.absent(), Value value = const Value.absent(), Value notes = const Value.absent(), + Value source = const Value.absent(), + Value externalId = const Value.absent(), Value rowid = const Value.absent(), }) => MeasurementEntryTableCompanion( id: id, @@ -16889,6 +17047,8 @@ class $$MeasurementEntryTableTableTableManager date: date, value: value, notes: notes, + source: source, + externalId: externalId, rowid: rowid, ), createCompanionCallback: @@ -16898,6 +17058,8 @@ class $$MeasurementEntryTableTableTableManager required DateTime date, required double value, required String notes, + Value source = const Value.absent(), + Value externalId = const Value.absent(), Value rowid = const Value.absent(), }) => MeasurementEntryTableCompanion.insert( id: id, @@ -16905,6 +17067,8 @@ class $$MeasurementEntryTableTableTableManager date: date, value: value, notes: notes, + source: source, + externalId: externalId, rowid: rowid, ), withReferenceMapper: (p0) => p0 diff --git a/lib/database/powersync/tables/measurements.dart b/lib/database/powersync/tables/measurements.dart index cb9f2d247..743114daa 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -31,6 +31,9 @@ class MeasurementCategoryTable extends Table { TextColumn get name => text()(); TextColumn get unit => text()(); + + /// `null` for plain user-created ("custom") categories. + TextColumn get metricType => text().named('metric_type').nullable()(); } const PowersyncMeasurementCategoryTable = ps.Table( @@ -38,6 +41,7 @@ const PowersyncMeasurementCategoryTable = ps.Table( [ ps.Column.text('name'), ps.Column.text('unit'), + ps.Column.text('metric_type'), ], ); @@ -53,6 +57,14 @@ class MeasurementEntryTable extends Table { DateTimeColumn get date => dateTime().map(const UtcDateTimeConverter())(); RealColumn get value => real()(); TextColumn get notes => text()(); + + /// Where the reading came from: `manual` or a health platform + /// (`apple_health`, `health_connect`). + TextColumn get source => text().withDefault(const Constant('manual'))(); + + /// Platform record UUID, used to deduplicate re-imports. `null` for manual + /// entries. + TextColumn get externalId => text().named('external_id').nullable()(); } const PowersyncMeasurementEntryTable = ps.Table( @@ -62,8 +74,11 @@ const PowersyncMeasurementEntryTable = ps.Table( ps.Column.text('date'), ps.Column.real('value'), ps.Column.text('notes'), + ps.Column.text('source'), + ps.Column.text('external_id'), ], indexes: [ ps.Index('category_idx', [ps.IndexedColumn('category_id')]), + ps.Index('external_id_idx', [ps.IndexedColumn('external_id')]), ], ); diff --git a/lib/features/account/widgets/settings/health_sync.dart b/lib/features/account/widgets/settings/health_sync.dart index 66d5a3d9c..91d3528d2 100644 --- a/lib/features/account/widgets/settings/health_sync.dart +++ b/lib/features/account/widgets/settings/health_sync.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 @@ -18,8 +18,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:wger/features/account/providers/user_profile_notifier.dart'; -import 'package:wger/features/weight/providers/health_sync.dart'; +import 'package:wger/features/health/providers/health_sync.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; class HealthSyncSettingsTile extends ConsumerStatefulWidget { @@ -66,11 +65,9 @@ class _HealthSyncSettingsTileState extends ConsumerState : (enabled) async { final notifier = ref.read(healthSyncProvider.notifier); if (enabled) { - final profile = ref.read(userProfileProvider).value; - final isMetric = profile?.isMetric ?? true; - final count = await notifier.enableSync(isMetric: isMetric); - // Synced entries land in the local Drift DB and surface through - // the weight stream automatically, so no manual refresh is needed. + final count = await notifier.enableSync(); + // Imported entries land in the local Drift DB and surface through + // the measurement stream automatically, so no manual refresh is needed. if (context.mounted && count > 0) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(i18n.healthSyncSuccess(count))), diff --git a/lib/features/health/models/health_metric.dart b/lib/features/health/models/health_metric.dart new file mode 100644 index 000000000..f0b224152 --- /dev/null +++ b/lib/features/health/models/health_metric.dart @@ -0,0 +1,134 @@ +/* + * 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:health/health.dart'; + +/// A body metric that can be imported from Apple Health / Health Connect into a +/// measurement category. +/// +/// [metricType] mirrors the server's planned `metric_type` enum and is stored +/// on the created category; it drives the mapping back to a category on the +/// next import. +class HealthMetric { + const HealthMetric({ + required this.metricType, + required this.dataType, + required this.canonicalName, + required this.unit, + required this.toCategoryValue, + this.enabled = false, + this.disabledReason, + }); + + /// Value of the server `metric_type` enum, e.g. `body_fat`. + final String metricType; + + /// Health platform type this metric reads. + final HealthDataType dataType; + + /// Stable, non-localized category name. Used to find-or-create the category, + /// and as the fallback match after a sync round-trip nulls [metricType] + /// (the server does not persist it yet). + final String canonicalName; + + /// Unit the value is stored in on the category. + final String unit; + + /// Converts the platform's numeric value (in its native unit) into [unit]. + final double Function(double raw) toCategoryValue; + + /// Whether V1 imports this metric. Disabled ones are declared for visibility + /// and blocked on further groundwork (see [disabledReason]). + final bool enabled; + + /// Why a declared metric is not imported yet. + final String? disabledReason; +} + +/// Apple Health / Health Connect report body fat as a fraction on iOS (0.15) +/// but as a percentage on Health Connect (15). A real body fat percentage is +/// never below ~1.5, and a fraction is always below 1, so the magnitude tells +/// the two apart without branching on platform. +double _bodyFatToPercent(double raw) => raw <= 1.5 ? raw * 100 : raw; + +/// Height is reported in meters on both platforms (~1.75). Guard against a +/// value that already arrived in centimeters. +double _heightToCm(double raw) => raw < 3 ? raw * 100 : raw; + +double _identity(double raw) => raw; + +/// The V1 metric set (see `plan-measurements-health-v27.md`). +/// +/// Only [HealthMetric.enabled] entries are imported. The rest are declared so +/// the mapping is visible in one place; each is blocked on groundwork noted in +/// its [HealthMetric.disabledReason]. +const List healthMetrics = [ + HealthMetric( + metricType: 'body_fat', + dataType: HealthDataType.BODY_FAT_PERCENTAGE, + canonicalName: 'Body fat', + unit: '%', + toCategoryValue: _bodyFatToPercent, + enabled: true, + ), + HealthMetric( + metricType: 'height', + dataType: HealthDataType.HEIGHT, + canonicalName: 'Height', + unit: 'cm', + toCategoryValue: _heightToCm, + enabled: true, + ), + HealthMetric( + metricType: 'body_weight', + dataType: HealthDataType.WEIGHT, + canonicalName: 'Weight', + unit: 'kg', + toCategoryValue: _identity, + disabledReason: + 'Body weight lives in its own feature until the ' + 'weight/measurements merge (metric_type=body_weight).', + ), + HealthMetric( + metricType: 'blood_pressure', + dataType: HealthDataType.BLOOD_PRESSURE_SYSTOLIC, + canonicalName: 'Blood pressure', + unit: 'mmHg', + toCategoryValue: _identity, + disabledReason: 'Needs measurement grouping to pair systolic/diastolic.', + ), + HealthMetric( + metricType: 'heart_rate', + dataType: HealthDataType.HEART_RATE, + canonicalName: 'Heart rate', + unit: 'bpm', + toCategoryValue: _identity, + disabledReason: 'High-frequency; needs a per-day aggregation strategy.', + ), + HealthMetric( + metricType: 'steps', + dataType: HealthDataType.STEPS, + canonicalName: 'Steps', + unit: 'count', + toCategoryValue: _identity, + disabledReason: 'High-volume cumulative type, parked behind a load test.', + ), +]; + +/// The enabled subset that the importer actually pulls. +List get enabledHealthMetrics => healthMetrics.where((m) => m.enabled).toList(); diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart new file mode 100644 index 000000000..e0e1a1971 --- /dev/null +++ b/lib/features/health/providers/health_sync.dart @@ -0,0 +1,250 @@ +/* + * 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 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:health/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/shared_preferences.dart'; +import 'package:wger/features/health/models/health_metric.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/models/measurement_entry.dart'; +import 'package:wger/features/measurements/providers/measurement_repository.dart'; + +part 'health_sync.g.dart'; + +class HealthSyncState { + final bool isEnabled; + final bool isSyncing; + final int lastSyncCount; + + const HealthSyncState({ + this.isEnabled = false, + this.isSyncing = false, + this.lastSyncCount = 0, + }); + + HealthSyncState copyWith({bool? isEnabled, bool? isSyncing, int? lastSyncCount}) { + return HealthSyncState( + isEnabled: isEnabled ?? this.isEnabled, + isSyncing: isSyncing ?? this.isSyncing, + lastSyncCount: lastSyncCount ?? this.lastSyncCount, + ); + } +} + +/// Imports body metrics from Apple Health / Health Connect into measurement +/// categories. Read-only: reads the platform, writes to the local Drift DB, and +/// lets PowerSync push the rows up. Re-imports are deduplicated via each +/// measurement's [MeasurementEntry.externalId] (the platform record UUID). +@Riverpod(keepAlive: true) +class HealthSyncNotifier extends _$HealthSyncNotifier { + final _logger = Logger('HealthSyncNotifier'); + late final Health _health; + late final MeasurementRepository _repo; + + List get _types => enabledHealthMetrics.map((m) => m.dataType).toList(); + + List get _readAccess => List.filled(_types.length, HealthDataAccess.READ); + + String get _sourceName => Platform.isIOS ? 'apple_health' : 'health_connect'; + + @override + HealthSyncState build() { + _health = Health(); + _repo = ref.read(measurementRepositoryProvider); + _loadPersistedState(); + return const HealthSyncState(); + } + + Future _loadPersistedState() async { + if (await PreferenceHelper.instance.getHealthSyncEnabled()) { + state = state.copyWith(isEnabled: true); + } + } + + /// Whether a health platform is available on this device. + Future isAvailable() async { + if (Platform.isAndroid) { + await _health.configure(); + final status = await _health.getHealthConnectSdkStatus(); + return status == HealthConnectSdkStatus.sdkAvailable; + } + return Platform.isIOS; + } + + /// Requests permissions, persists the preference, and runs an initial import. + Future enableSync() async { + _logger.info('Enabling health sync'); + await _health.configure(); + + final authorized = await _health.requestAuthorization(_types, permissions: _readAccess); + if (!authorized) { + _logger.warning('Health permissions not granted'); + return 0; + } + + if (Platform.isAndroid) { + await _health.requestHealthDataHistoryAuthorization(); + } + + await PreferenceHelper.instance.setHealthSyncEnabled(true); + state = state.copyWith(isEnabled: true); + + return syncOnAppOpen(); + } + + /// Clears the preference and disables importing. + Future disableSync() async { + _logger.info('Disabling health sync'); + await PreferenceHelper.instance.clearHealthSyncPreferences(); + state = const HealthSyncState(); + } + + /// Reads the enabled metrics from the health platform and writes any new + /// readings to the matching measurement categories. Returns the number of + /// imported entries. A no-op unless the user enabled sync. + Future syncOnAppOpen() async { + final prefs = PreferenceHelper.instance; + if (!await prefs.getHealthSyncEnabled()) { + return 0; + } + if (state.isSyncing) { + return 0; + } + state = state.copyWith(isEnabled: true, isSyncing: true); + + try { + await _health.configure(); + + final hasPerms = await _health.hasPermissions(_types, permissions: _readAccess); + if (hasPerms != true) { + final authorized = await _health.requestAuthorization(_types, permissions: _readAccess); + if (!authorized) { + _logger.warning('Health permissions not granted during sync'); + state = state.copyWith(isSyncing: false); + return 0; + } + } + + final lastSyncStr = await prefs.getLastHealthSyncTimestamp(); + final startTime = lastSyncStr != null ? DateTime.parse(lastSyncStr) : DateTime(2000); + final endTime = DateTime.now(); + _logger.info('Syncing health data from $startTime to $endTime'); + + var points = await _health.getHealthDataFromTypes( + types: _types, + startTime: startTime, + endTime: endTime, + ); + points = _health.removeDuplicates(points); + if (points.isEmpty) { + _logger.info('No new health data'); + state = state.copyWith(isSyncing: false, lastSyncCount: 0); + return 0; + } + + final categories = await _repo.getAllOnce(); + var synced = 0; + DateTime? latest; + + for (final metric in enabledHealthMetrics) { + final metricPoints = points.where((p) => p.type == metric.dataType); + if (metricPoints.isEmpty) { + continue; + } + + final category = await _findOrCreateCategory(metric, categories); + final seen = { + for (final e in category.entries) + if (e.externalId != null) e.externalId!, + }; + + for (final point in metricPoints) { + final value = point.value; + if (value is! NumericHealthValue) { + continue; + } + final uuid = point.uuid; + if (uuid.isNotEmpty && seen.contains(uuid)) { + continue; + } + + await _repo.addLocalDrift( + MeasurementEntry( + categoryId: category.id!, + date: point.dateFrom, + value: metric.toCategoryValue(value.numericValue.toDouble()), + notes: '', + source: _sourceName, + externalId: uuid.isEmpty ? null : uuid, + ), + ); + + if (uuid.isNotEmpty) { + seen.add(uuid); + } + synced++; + if (latest == null || point.dateFrom.isAfter(latest)) { + latest = point.dateFrom; + } + } + } + + if (latest != null) { + await prefs.setLastHealthSyncTimestamp(latest.toIso8601String()); + } + _logger.info('Imported $synced health measurements'); + state = state.copyWith(isSyncing: false, lastSyncCount: synced); + return synced; + } catch (e) { + _logger.warning('Health sync failed: $e'); + state = state.copyWith(isSyncing: false, lastSyncCount: 0); + return 0; + } + } + + /// Finds the category for [metric] (by `metric_type`, falling back to the + /// canonical name once the server has nulled `metric_type` on a round-trip) + /// or creates it. The created category is appended to [categories] so a later + /// metric in the same run reuses it. + Future _findOrCreateCategory( + HealthMetric metric, + List categories, + ) async { + final existing = categories.firstWhereOrNull( + (c) => c.metricType == metric.metricType || c.name == metric.canonicalName, + ); + if (existing != null) { + return existing; + } + + final category = MeasurementCategory( + id: ps.uuid.v7(), + name: metric.canonicalName, + unit: metric.unit, + metricType: metric.metricType, + ); + await _repo.addLocalDriftCategory(category); + categories.add(category); + return category; + } +} diff --git a/lib/features/weight/providers/health_sync.g.dart b/lib/features/health/providers/health_sync.g.dart similarity index 56% rename from lib/features/weight/providers/health_sync.g.dart rename to lib/features/health/providers/health_sync.g.dart index 5c161334d..768adca84 100644 --- a/lib/features/weight/providers/health_sync.g.dart +++ b/lib/features/health/providers/health_sync.g.dart @@ -8,12 +8,24 @@ part of 'health_sync.dart'; // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint, type=warning +/// Imports body metrics from Apple Health / Health Connect into measurement +/// categories. Read-only: reads the platform, writes to the local Drift DB, and +/// lets PowerSync push the rows up. Re-imports are deduplicated via each +/// measurement's [MeasurementEntry.externalId] (the platform record UUID). @ProviderFor(HealthSyncNotifier) final healthSyncProvider = HealthSyncNotifierProvider._(); +/// Imports body metrics from Apple Health / Health Connect into measurement +/// categories. Read-only: reads the platform, writes to the local Drift DB, and +/// lets PowerSync push the rows up. Re-imports are deduplicated via each +/// measurement's [MeasurementEntry.externalId] (the platform record UUID). final class HealthSyncNotifierProvider extends $NotifierProvider { + /// Imports body metrics from Apple Health / Health Connect into measurement + /// categories. Read-only: reads the platform, writes to the local Drift DB, and + /// lets PowerSync push the rows up. Re-imports are deduplicated via each + /// measurement's [MeasurementEntry.externalId] (the platform record UUID). HealthSyncNotifierProvider._() : super( from: null, @@ -41,7 +53,12 @@ final class HealthSyncNotifierProvider } } -String _$healthSyncNotifierHash() => r'451a05716a24477f7626a266aaac6a29c1707ab2'; +String _$healthSyncNotifierHash() => r'9efca0080b2dd104a3e409f1c81a9976ec0e635c'; + +/// Imports body metrics from Apple Health / Health Connect into measurement +/// categories. Read-only: reads the platform, writes to the local Drift DB, and +/// lets PowerSync push the rows up. Re-imports are deduplicated via each +/// measurement's [MeasurementEntry.externalId] (the platform record UUID). abstract class _$HealthSyncNotifier extends $Notifier { HealthSyncState build(); diff --git a/lib/features/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index 3dd72751e..45683827a 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -45,11 +45,17 @@ class MeasurementCategory with _$MeasurementCategory { @override final List entries; + /// Drives the health-platform mapping (and, later, default unit/aggregation/ + /// chart). `null` for plain user-created ("custom") categories. + @override + final String? metricType; + MeasurementCategory({ this.id, this.name = '', this.unit = '', this.entries = const [], + this.metricType, }); MeasurementEntry findEntryById(String id) { @@ -65,6 +71,7 @@ class MeasurementCategory with _$MeasurementCategory { id: id != null ? Value(id!) : const Value.absent(), name: Value(name), unit: Value(unit), + metricType: Value(metricType), ); } } diff --git a/lib/features/measurements/models/measurement_category.freezed.dart b/lib/features/measurements/models/measurement_category.freezed.dart index 4d6754060..252d17ce7 100644 --- a/lib/features/measurements/models/measurement_category.freezed.dart +++ b/lib/features/measurements/models/measurement_category.freezed.dart @@ -15,7 +15,9 @@ T _$identity(T value) => value; mixin _$MeasurementCategory { /// Client-generated UUID, is `null` only before the first persist - String? get id; String get name; String get unit; List get entries; + String? get id; String get name; String get unit; List get entries;/// Drives the health-platform mapping (and, later, default unit/aggregation/ +/// chart). `null` for plain user-created ("custom") categories. + String? get metricType; /// Create a copy of MeasurementCategory /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -26,16 +28,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)); + 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)); } @override -int get hashCode => Object.hash(runtimeType,id,name,unit,const DeepCollectionEquality().hash(entries)); +int get hashCode => Object.hash(runtimeType,id,name,unit,const DeepCollectionEquality().hash(entries),metricType); @override String toString() { - return 'MeasurementCategory(id: $id, name: $name, unit: $unit, entries: $entries)'; + return 'MeasurementCategory(id: $id, name: $name, unit: $unit, entries: $entries, metricType: $metricType)'; } @@ -46,7 +48,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 + String? id, String name, String unit, List entries, String? metricType }); @@ -63,13 +65,14 @@ 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,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? id = freezed,Object? name = null,Object? unit = null,Object? entries = null,Object? metricType = freezed,}) { 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, +as List,metricType: freezed == metricType ? _self.metricType : metricType // ignore: cast_nullable_to_non_nullable +as String?, )); } diff --git a/lib/features/measurements/models/measurement_entry.dart b/lib/features/measurements/models/measurement_entry.dart index 2d5e8f636..717408547 100644 --- a/lib/features/measurements/models/measurement_entry.dart +++ b/lib/features/measurements/models/measurement_entry.dart @@ -43,12 +43,24 @@ class MeasurementEntry with _$MeasurementEntry { @override final String notes; + /// Where the reading came from: `manual` or a health platform + /// (`apple_health`, `health_connect`). + @override + final String source; + + /// Platform record UUID, used to deduplicate re-imports. `null` for manual + /// entries. + @override + final String? externalId; + MeasurementEntry({ this.id, required this.categoryId, required this.date, required this.value, required this.notes, + this.source = 'manual', + this.externalId, }); // Boilerplate @@ -59,6 +71,8 @@ class MeasurementEntry with _$MeasurementEntry { date: Value(date), value: Value(value.toDouble()), notes: Value(notes), + source: Value(source), + externalId: Value(externalId), ); } } diff --git a/lib/features/measurements/models/measurement_entry.freezed.dart b/lib/features/measurements/models/measurement_entry.freezed.dart index e4423aa6a..4f0b855f7 100644 --- a/lib/features/measurements/models/measurement_entry.freezed.dart +++ b/lib/features/measurements/models/measurement_entry.freezed.dart @@ -15,7 +15,11 @@ T _$identity(T value) => value; mixin _$MeasurementEntry { /// Client-generated UUID, is `null` only before the first persist - String? get id; String get categoryId; DateTime get date; num get value; String get notes; + String? get id; String get categoryId; DateTime get date; num get value; String get notes;/// Where the reading came from: `manual` or a health platform +/// (`apple_health`, `health_connect`). + String get source;/// Platform record UUID, used to deduplicate re-imports. `null` for manual +/// entries. + String? get externalId; /// Create a copy of MeasurementEntry /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -26,16 +30,16 @@ $MeasurementEntryCopyWith get copyWith => _$MeasurementEntryCo @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is MeasurementEntry&&(identical(other.id, id) || other.id == id)&&(identical(other.categoryId, categoryId) || other.categoryId == categoryId)&&(identical(other.date, date) || other.date == date)&&(identical(other.value, value) || other.value == value)&&(identical(other.notes, notes) || other.notes == notes)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is MeasurementEntry&&(identical(other.id, id) || other.id == id)&&(identical(other.categoryId, categoryId) || other.categoryId == categoryId)&&(identical(other.date, date) || other.date == date)&&(identical(other.value, value) || other.value == value)&&(identical(other.notes, notes) || other.notes == notes)&&(identical(other.source, source) || other.source == source)&&(identical(other.externalId, externalId) || other.externalId == externalId)); } @override -int get hashCode => Object.hash(runtimeType,id,categoryId,date,value,notes); +int get hashCode => Object.hash(runtimeType,id,categoryId,date,value,notes,source,externalId); @override String toString() { - return 'MeasurementEntry(id: $id, categoryId: $categoryId, date: $date, value: $value, notes: $notes)'; + return 'MeasurementEntry(id: $id, categoryId: $categoryId, date: $date, value: $value, notes: $notes, source: $source, externalId: $externalId)'; } @@ -46,7 +50,7 @@ abstract mixin class $MeasurementEntryCopyWith<$Res> { factory $MeasurementEntryCopyWith(MeasurementEntry value, $Res Function(MeasurementEntry) _then) = _$MeasurementEntryCopyWithImpl; @useResult $Res call({ - String? id, String categoryId, DateTime date, num value, String notes + String? id, String categoryId, DateTime date, num value, String notes, String source, String? externalId }); @@ -63,14 +67,16 @@ class _$MeasurementEntryCopyWithImpl<$Res> /// Create a copy of MeasurementEntry /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? id = freezed,Object? categoryId = null,Object? date = null,Object? value = null,Object? notes = null,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? id = freezed,Object? categoryId = null,Object? date = null,Object? value = null,Object? notes = null,Object? source = null,Object? externalId = freezed,}) { return _then(MeasurementEntry( id: freezed == id ? _self.id : id // ignore: cast_nullable_to_non_nullable as String?,categoryId: null == categoryId ? _self.categoryId : categoryId // ignore: cast_nullable_to_non_nullable as String,date: null == date ? _self.date : date // ignore: cast_nullable_to_non_nullable as DateTime,value: null == value ? _self.value : value // ignore: cast_nullable_to_non_nullable as num,notes: null == notes ? _self.notes : notes // ignore: cast_nullable_to_non_nullable -as String, +as String,source: null == source ? _self.source : source // ignore: cast_nullable_to_non_nullable +as String,externalId: freezed == externalId ? _self.externalId : externalId // ignore: cast_nullable_to_non_nullable +as String?, )); } diff --git a/lib/features/measurements/providers/measurement_repository.dart b/lib/features/measurements/providers/measurement_repository.dart index 5763e6e03..06ce035fd 100644 --- a/lib/features/measurements/providers/measurement_repository.dart +++ b/lib/features/measurements/providers/measurement_repository.dart @@ -82,6 +82,9 @@ class MeasurementRepository { return watchAll().map((categories) => categories.firstWhereOrNull((c) => c.id == id)); } + /// One-shot snapshot of all categories with their entries. + Future> getAllOnce() => watchAll().first; + // Entries Future deleteLocalDrift(String id) async { _logger.finer('Deleting local measurement entry $id'); diff --git a/lib/features/weight/providers/health_sync.dart b/lib/features/weight/providers/health_sync.dart deleted file mode 100644 index 1604e1b0a..000000000 --- a/lib/features/weight/providers/health_sync.dart +++ /dev/null @@ -1,249 +0,0 @@ -/* - * 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 'dart:io'; - -import 'package:health/health.dart'; -import 'package:logging/logging.dart'; -import 'package:riverpod_annotation/riverpod_annotation.dart'; -import 'package:wger/core/shared_preferences.dart'; -import 'package:wger/features/weight/models/weight_entry.dart'; -import 'package:wger/features/weight/providers/body_weight_repository.dart'; - -part 'health_sync.g.dart'; - -class HealthSyncState { - final bool isEnabled; - final bool isSyncing; - final int lastSyncCount; - - const HealthSyncState({ - this.isEnabled = false, - this.isSyncing = false, - this.lastSyncCount = 0, - }); - - HealthSyncState copyWith({ - bool? isEnabled, - bool? isSyncing, - int? lastSyncCount, - }) { - return HealthSyncState( - isEnabled: isEnabled ?? this.isEnabled, - isSyncing: isSyncing ?? this.isSyncing, - lastSyncCount: lastSyncCount ?? this.lastSyncCount, - ); - } -} - -const double kgToLb = 2.20462; - -@Riverpod(keepAlive: true) -class HealthSyncNotifier extends _$HealthSyncNotifier { - final _logger = Logger('HealthSyncNotifier'); - late final Health _health; - late final BodyWeightRepository _repo; - - @override - HealthSyncState build() { - _health = Health(); - _repo = ref.read(bodyWeightRepositoryProvider); - - // Load persisted sync preference on startup - _loadPersistedState(); - - return const HealthSyncState(); - } - - Future _loadPersistedState() async { - final enabled = await PreferenceHelper.instance.getHealthSyncEnabled(); - if (enabled) { - state = state.copyWith(isEnabled: true); - } - } - - /// Check if the health platform is available on this device - Future isAvailable() async { - if (Platform.isAndroid) { - await _health.configure(); - final status = await _health.getHealthConnectSdkStatus(); - return status == HealthConnectSdkStatus.sdkAvailable; - } - // iOS always has HealthKit available - return Platform.isIOS; - } - - /// 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(); - - final authorized = await _health.requestAuthorization( - [HealthDataType.WEIGHT], - permissions: [HealthDataAccess.READ], - ); - - if (!authorized) { - _logger.warning('Health permissions not granted'); - return 0; - } - - // Request access to historical data (older than 30 days) on Android - if (Platform.isAndroid) { - await _health.requestHealthDataHistoryAuthorization(); - } - - await PreferenceHelper.instance.setHealthSyncEnabled(true); - state = state.copyWith(isEnabled: true); - - return syncOnAppOpen(isMetric: isMetric); - } - - /// Disable health sync: clear preferences - Future disableSync() async { - _logger.info('Disabling health sync'); - await PreferenceHelper.instance.clearHealthSyncPreferences(); - state = const HealthSyncState(); - } - - /// Main sync method: read weight data from health platform, post new entries to backend. - /// If [isMetric] is false, converts kg values from the health platform to lb before POSTing. - Future syncOnAppOpen({List? existingEntries, bool isMetric = true}) async { - final prefs = PreferenceHelper.instance; - final enabled = await prefs.getHealthSyncEnabled(); - if (!enabled) { - return 0; - } - - if (state.isSyncing) { - return 0; - } - state = state.copyWith(isEnabled: true, isSyncing: true); - - try { - await _health.configure(); - - // Ensure we have permission to read weight data - final hasPerms = await _health.hasPermissions( - [HealthDataType.WEIGHT], - permissions: [HealthDataAccess.READ], - ); - if (hasPerms != true) { - final authorized = await _health.requestAuthorization( - [HealthDataType.WEIGHT], - permissions: [HealthDataAccess.READ], - ); - if (!authorized) { - _logger.warning('Health permissions not granted during sync'); - state = state.copyWith(isSyncing: false); - return 0; - } - } - - // Determine the start time for the query - final lastSyncStr = await prefs.getLastHealthSyncTimestamp(); - final DateTime startTime; - if (lastSyncStr != null) { - startTime = DateTime.parse(lastSyncStr); - } else { - // Pull all available history on first sync - startTime = DateTime(2000); - } - final endTime = DateTime.now(); - - _logger.info('Syncing weight data from $startTime to $endTime'); - - // Read weight data from health platform - List dataPoints = await _health.getHealthDataFromTypes( - types: [HealthDataType.WEIGHT], - startTime: startTime, - endTime: endTime, - ); - dataPoints = _health.removeDuplicates(dataPoints); - - if (dataPoints.isEmpty) { - _logger.info('No new weight data from health platform'); - state = state.copyWith(isSyncing: false, lastSyncCount: 0); - return 0; - } - - _logger.info('Found ${dataPoints.length} weight data points'); - - // Build a Set of existing timestamps for O(1) dedup lookups - final existingTimestamps = existingEntries != null - ? { - for (final e in existingEntries) - DateTime(e.date.year, e.date.month, e.date.day, e.date.hour, e.date.minute), - } - : {}; - - int syncedCount = 0; - DateTime? latestSynced; - - for (final point in dataPoints) { - try { - final value = (point.value as NumericHealthValue).numericValue; - final weightKg = value.toDouble(); - final timestamp = point.dateFrom; - - final weight = isMetric ? weightKg : weightKg * kgToLb; - final weightRounded = (weight * 100).roundToDouble() / 100; - - // Skip if an entry with the same timestamp already exists locally - final normalizedTimestamp = DateTime( - timestamp.year, - timestamp.month, - timestamp.day, - timestamp.hour, - timestamp.minute, - ); - if (existingTimestamps.contains(normalizedTimestamp)) { - _logger.fine('Skipping duplicate entry for $timestamp'); - continue; - } - - final entry = WeightEntry(weight: weightRounded, date: timestamp); - await _repo.addLocalDrift(entry); - - syncedCount++; - if (latestSynced == null || timestamp.isAfter(latestSynced)) { - latestSynced = timestamp; - } - } catch (e) { - _logger.warning('Failed to sync weight entry: $e'); - // Best-effort: continue with next entry - } - } - - // Update last sync timestamp to the latest successfully synced reading - if (latestSynced != null) { - await prefs.setLastHealthSyncTimestamp(latestSynced.toIso8601String()); - } - - _logger.info('Synced $syncedCount weight entries'); - state = state.copyWith(isSyncing: false, lastSyncCount: syncedCount); - return syncedCount; - } catch (e) { - _logger.warning('Health sync failed: $e'); - state = state.copyWith(isSyncing: false, lastSyncCount: 0); - return 0; - } - } -} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 0ec1bab34..3cc494838 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1439,11 +1439,11 @@ "@healthSync": { "description": "Title for the health platform sync setting" }, - "healthSyncDescription": "Import weight from Apple Health or Health Connect", + "healthSyncDescription": "Import body measurements from Apple Health or Health Connect", "@healthSyncDescription": { "description": "Subtitle for the health platform sync setting" }, - "healthSyncSuccess": "Synced {count} weight entries from Health", + "healthSyncSuccess": "Imported {count} measurements from Health", "@healthSyncSuccess": { "description": "Snackbar message after successful health sync", "placeholders": { diff --git a/lib/powersync/connector.dart b/lib/powersync/connector.dart index 532c15b74..17424003c 100644 --- a/lib/powersync/connector.dart +++ b/lib/powersync/connector.dart @@ -157,7 +157,10 @@ class DjangoConnector extends PowerSyncBackendConnector { if (k == 'id') { return; } - final key = k.endsWith('_id') ? k.substring(0, k.length - 3) : k; + // Trailing `_id` marks a foreign key, which Django exposes without the + // suffix (`category_id` -> `category`). `external_id` is a plain value + // column, not an FK, so it keeps its name. + final key = (k.endsWith('_id') && k != 'external_id') ? k.substring(0, k.length - 3) : k; out[key] = (dateFields.contains(key) && v is String && v.length >= 10) ? v.substring(0, 10) : v; diff --git a/test/features/account/widgets/settings_test.dart b/test/features/account/widgets/settings_test.dart index debe599e6..d6bce6230 100644 --- a/test/features/account/widgets/settings_test.dart +++ b/test/features/account/widgets/settings_test.dart @@ -25,7 +25,7 @@ import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/core/app_settings_notifier.dart'; import 'package:wger/core/consts.dart'; import 'package:wger/features/account/widgets/settings.dart'; -import 'package:wger/features/weight/providers/health_sync.dart'; +import 'package:wger/features/health/providers/health_sync.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'settings_test.mocks.dart'; diff --git a/test/features/health/models/health_metric_test.dart b/test/features/health/models/health_metric_test.dart new file mode 100644 index 000000000..2557e11ba --- /dev/null +++ b/test/features/health/models/health_metric_test.dart @@ -0,0 +1,79 @@ +/* + * 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:collection/collection.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/health/models/health_metric.dart'; + +HealthMetric _metric(String type) => healthMetrics.firstWhere((m) => m.metricType == type); + +void main() { + group('Enabled metric set', () { + test('only body fat and height are imported in V1', () { + expect( + enabledHealthMetrics.map((m) => m.metricType), + containsAll(['body_fat', 'height']), + ); + expect(enabledHealthMetrics.length, 2); + }); + + test('every disabled metric explains why', () { + final disabled = healthMetrics.where((m) => !m.enabled); + expect(disabled, isNotEmpty); + expect(disabled.every((m) => m.disabledReason != null), isTrue); + }); + + test('metric types are unique', () { + final types = healthMetrics.map((m) => m.metricType).toList(); + expect(types.length, types.toSet().length); + }); + }); + + group('Body fat conversion', () { + final bodyFat = _metric('body_fat'); + + test('iOS fraction is scaled to a percentage', () { + expect(bodyFat.toCategoryValue(0.15), closeTo(15, 0.001)); + }); + + test('Health Connect percentage is kept as-is', () { + expect(bodyFat.toCategoryValue(15), closeTo(15, 0.001)); + }); + }); + + group('Height conversion', () { + final height = _metric('height'); + + test('meters are converted to centimeters', () { + expect(height.toCategoryValue(1.75), closeTo(175, 0.001)); + }); + + test('a value already in centimeters is kept as-is', () { + expect(height.toCategoryValue(180), closeTo(180, 0.001)); + }); + }); + + test('enabledHealthMetrics matches the enabled flag', () { + expect( + enabledHealthMetrics, + healthMetrics.where((m) => m.enabled).toList(), + ); + // sanity: the disabled ones really are excluded + expect(enabledHealthMetrics.firstWhereOrNull((m) => m.metricType == 'steps'), isNull); + }); +} diff --git a/test/features/weight/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart similarity index 50% rename from test/features/weight/providers/health_sync_test.dart rename to test/features/health/providers/health_sync_test.dart index 407c6a316..6d16d92f3 100644 --- a/test/features/weight/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -17,49 +17,9 @@ */ import 'package:flutter_test/flutter_test.dart'; -import 'package:wger/features/weight/providers/health_sync.dart'; - -/// Mirrors the conversion logic in HealthSyncNotifier.syncOnAppOpen -double _convertWeight(double weightKg, {required bool isMetric}) { - return isMetric ? weightKg : weightKg * kgToLb; -} +import 'package:wger/features/health/providers/health_sync.dart'; void main() { - group('Health sync constants', () { - test('kgToLb conversion factor is correct', () { - // 1 kg = 2.20462 lb - expect(kgToLb, closeTo(2.20462, 0.00001)); - }); - }); - - 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; - const 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(); diff --git a/test/features/measurements/providers/measurement_notifier_test.mocks.dart b/test/features/measurements/providers/measurement_notifier_test.mocks.dart index 4f7399345..5a502e6c9 100644 --- a/test/features/measurements/providers/measurement_notifier_test.mocks.dart +++ b/test/features/measurements/providers/measurement_notifier_test.mocks.dart @@ -51,6 +51,16 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos ) as _i3.Stream<_i4.MeasurementCategory?>); + @override + _i3.Future> getAllOnce() => + (super.noSuchMethod( + Invocation.method(#getAllOnce, []), + returnValue: _i3.Future>.value( + <_i4.MeasurementCategory>[], + ), + ) + as _i3.Future>); + @override _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod( 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 8b8ed109a..91c79d7fe 100644 --- a/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart +++ b/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart @@ -51,6 +51,16 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos ) as _i3.Stream<_i4.MeasurementCategory?>); + @override + _i3.Future> getAllOnce() => + (super.noSuchMethod( + Invocation.method(#getAllOnce, []), + returnValue: _i3.Future>.value( + <_i4.MeasurementCategory>[], + ), + ) + as _i3.Future>); + @override _i3.Future deleteLocalDrift(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 8612dcbf4..15b6f34b1 100644 --- a/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart +++ b/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart @@ -60,6 +60,16 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos ) as _i3.Stream<_i4.MeasurementCategory?>); + @override + _i3.Future> getAllOnce() => + (super.noSuchMethod( + Invocation.method(#getAllOnce, []), + returnValue: _i3.Future>.value( + <_i4.MeasurementCategory>[], + ), + ) + as _i3.Future>); + @override _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod( diff --git a/test/powersync/connector_test.dart b/test/powersync/connector_test.dart index abdcf059b..556bbf9b1 100644 --- a/test/powersync/connector_test.dart +++ b/test/powersync/connector_test.dart @@ -73,6 +73,16 @@ void main() { expect(out.containsKey('routine_id'), isFalse); }); + test('keeps `external_id`, which is a value column and not a foreign key', () { + final out = connector.genericTransform( + 'measurements_measurement', + {'external_id': 'abc-123', 'category_id': 5}, + '1', + ); + expect(out['external_id'], 'abc-123'); + expect(out['category'], 5); + }); + test('handles null opData (delete events)', () { final out = connector.genericTransform('manager_routine', null, '99'); expect(out, {'id': '99'}); diff --git a/test/screenshots/screenshots_01_dashboard.mocks.dart b/test/screenshots/screenshots_01_dashboard.mocks.dart index 82a19b2ff..f5c2b54c0 100644 --- a/test/screenshots/screenshots_01_dashboard.mocks.dart +++ b/test/screenshots/screenshots_01_dashboard.mocks.dart @@ -472,6 +472,16 @@ class MockMeasurementRepository extends _i1.Mock implements _i23.MeasurementRepo ) as _i10.Stream<_i24.MeasurementCategory?>); + @override + _i10.Future> getAllOnce() => + (super.noSuchMethod( + Invocation.method(#getAllOnce, []), + returnValue: _i10.Future>.value( + <_i24.MeasurementCategory>[], + ), + ) + as _i10.Future>); + @override _i10.Future deleteLocalDrift(String? id) => (super.noSuchMethod( diff --git a/test/screenshots/screenshots_04_measurements.mocks.dart b/test/screenshots/screenshots_04_measurements.mocks.dart index ba5ffa86f..686d60878 100644 --- a/test/screenshots/screenshots_04_measurements.mocks.dart +++ b/test/screenshots/screenshots_04_measurements.mocks.dart @@ -51,6 +51,16 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos ) as _i3.Stream<_i4.MeasurementCategory?>); + @override + _i3.Future> getAllOnce() => + (super.noSuchMethod( + Invocation.method(#getAllOnce, []), + returnValue: _i3.Future>.value( + <_i4.MeasurementCategory>[], + ), + ) + as _i3.Future>); + @override _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod( From 01c13b1ad65a897d1fd0408c80c45f648495c16f Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 2 Jul 2026 22:07:03 +0200 Subject: [PATCH 018/484] Add health repository This follows the convention in the rest of the application and allows us to easily mock it for tests. --- .../health/models/health_reading.dart | 59 ++++++ .../health/providers/health_repository.dart | 84 +++++++++ .../health/providers/health_sync.dart | 101 ++++------ .../health/providers/health_sync.g.dart | 30 +-- .../health/providers/health_sync_test.dart | 148 +++++++++++++++ .../providers/health_sync_test.mocks.dart | 177 ++++++++++++++++++ 6 files changed, 518 insertions(+), 81 deletions(-) create mode 100644 lib/features/health/models/health_reading.dart create mode 100644 lib/features/health/providers/health_repository.dart create mode 100644 test/features/health/providers/health_sync_test.mocks.dart diff --git a/lib/features/health/models/health_reading.dart b/lib/features/health/models/health_reading.dart new file mode 100644 index 000000000..1a6e52200 --- /dev/null +++ b/lib/features/health/models/health_reading.dart @@ -0,0 +1,59 @@ +/* + * 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:health/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 +/// notifier so the sync logic can be tested with plain values. +class HealthReading { + const HealthReading({ + required this.type, + required this.value, + required this.date, + this.externalId, + }); + + /// The platform type this reading belongs to (matched against + /// `HealthMetric.dataType`). + final HealthDataType type; + + /// Numeric value in the platform's native unit. + final double value; + + /// Start of the reading. + final DateTime date; + + /// Platform record UUID for deduplication; `null` when the platform gives none. + final String? externalId; + + /// Builds a reading from a platform data point, or `null` for a non-numeric + /// point (which the importer cannot store). + static HealthReading? fromDataPoint(HealthDataPoint point) { + final value = point.value; + if (value is! NumericHealthValue) { + return null; + } + return HealthReading( + type: point.type, + value: value.numericValue.toDouble(), + date: point.dateFrom, + externalId: point.uuid.isEmpty ? null : point.uuid, + ); + } +} diff --git a/lib/features/health/providers/health_repository.dart b/lib/features/health/providers/health_repository.dart new file mode 100644 index 000000000..942d68d07 --- /dev/null +++ b/lib/features/health/providers/health_repository.dart @@ -0,0 +1,84 @@ +/* + * 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 'dart:io'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:health/health.dart'; +import 'package:logging/logging.dart'; +import 'package:wger/features/health/models/health_reading.dart'; + +final healthRepositoryProvider = Provider((ref) { + return HealthRepository(); +}); + +/// Wraps the `health` plugin so the rest of the app talks to a small, mockable +/// surface instead of Apple Health / Health Connect directly. +class HealthRepository { + HealthRepository([Health? health]) : _health = health ?? Health(); + + final Health _health; + final _logger = Logger('HealthRepository'); + + /// Identifies which platform a reading came from. + String get sourceName => Platform.isIOS ? 'apple_health' : 'health_connect'; + + /// Whether a health platform is usable on this device. + Future isAvailable() async { + if (Platform.isAndroid) { + await _health.configure(); + final status = await _health.getHealthConnectSdkStatus(); + return status == HealthConnectSdkStatus.sdkAvailable; + } + return Platform.isIOS; + } + + /// Ensures READ access to [types] (requesting it if needed) and, on Android, + /// access to historical data. Returns whether access is granted. + Future ensureAuthorized(List types) async { + await _health.configure(); + final access = List.filled(types.length, HealthDataAccess.READ); + + final hasPerms = await _health.hasPermissions(types, permissions: access); + if (hasPerms != true) { + final granted = await _health.requestAuthorization(types, permissions: access); + if (!granted) { + _logger.warning('Health permissions not granted'); + return false; + } + } + + if (Platform.isAndroid) { + await _health.requestHealthDataHistoryAuthorization(); + } + return true; + } + + /// Reads all [types] between [start] and [end], platform-deduplicated and + /// reduced to numeric [HealthReading]s. + Future> read({ + required List types, + required DateTime start, + required DateTime end, + }) async { + final points = _health.removeDuplicates( + await _health.getHealthDataFromTypes(types: types, startTime: start, endTime: end), + ); + return points.map(HealthReading.fromDataPoint).whereType().toList(); + } +} diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index e0e1a1971..6cf3c74a6 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -16,8 +16,6 @@ * along with this program. If not, see . */ -import 'dart:io'; - import 'package:collection/collection.dart'; import 'package:health/health.dart'; import 'package:logging/logging.dart'; @@ -25,6 +23,7 @@ import 'package:powersync/powersync.dart' as ps; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:wger/core/shared_preferences.dart'; import 'package:wger/features/health/models/health_metric.dart'; +import 'package:wger/features/health/providers/health_repository.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; import 'package:wger/features/measurements/models/measurement_entry.dart'; import 'package:wger/features/measurements/providers/measurement_repository.dart'; @@ -52,25 +51,22 @@ class HealthSyncState { } /// Imports body metrics from Apple Health / Health Connect into measurement -/// categories. Read-only: reads the platform, writes to the local Drift DB, and -/// lets PowerSync push the rows up. Re-imports are deduplicated via each -/// measurement's [MeasurementEntry.externalId] (the platform record UUID). +/// categories. Read-only: reads the platform (via [HealthRepository]), writes to +/// the local Drift DB, and lets PowerSync push the rows up. Re-imports are +/// deduplicated via each measurement's [MeasurementEntry.externalId] (the +/// platform record UUID). @Riverpod(keepAlive: true) class HealthSyncNotifier extends _$HealthSyncNotifier { final _logger = Logger('HealthSyncNotifier'); - late final Health _health; - late final MeasurementRepository _repo; + late final HealthRepository _health; + late final MeasurementRepository _measurements; List get _types => enabledHealthMetrics.map((m) => m.dataType).toList(); - List get _readAccess => List.filled(_types.length, HealthDataAccess.READ); - - String get _sourceName => Platform.isIOS ? 'apple_health' : 'health_connect'; - @override HealthSyncState build() { - _health = Health(); - _repo = ref.read(measurementRepositoryProvider); + _health = ref.read(healthRepositoryProvider); + _measurements = ref.read(measurementRepositoryProvider); _loadPersistedState(); return const HealthSyncState(); } @@ -82,33 +78,16 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { } /// Whether a health platform is available on this device. - Future isAvailable() async { - if (Platform.isAndroid) { - await _health.configure(); - final status = await _health.getHealthConnectSdkStatus(); - return status == HealthConnectSdkStatus.sdkAvailable; - } - return Platform.isIOS; - } + Future isAvailable() => _health.isAvailable(); /// Requests permissions, persists the preference, and runs an initial import. Future enableSync() async { _logger.info('Enabling health sync'); - await _health.configure(); - - final authorized = await _health.requestAuthorization(_types, permissions: _readAccess); - if (!authorized) { - _logger.warning('Health permissions not granted'); + if (!await _health.ensureAuthorized(_types)) { return 0; } - - if (Platform.isAndroid) { - await _health.requestHealthDataHistoryAuthorization(); - } - await PreferenceHelper.instance.setHealthSyncEnabled(true); state = state.copyWith(isEnabled: true); - return syncOnAppOpen(); } @@ -133,16 +112,10 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { state = state.copyWith(isEnabled: true, isSyncing: true); try { - await _health.configure(); - - final hasPerms = await _health.hasPermissions(_types, permissions: _readAccess); - if (hasPerms != true) { - final authorized = await _health.requestAuthorization(_types, permissions: _readAccess); - if (!authorized) { - _logger.warning('Health permissions not granted during sync'); - state = state.copyWith(isSyncing: false); - return 0; - } + if (!await _health.ensureAuthorized(_types)) { + _logger.warning('Health permissions not granted during sync'); + state = state.copyWith(isSyncing: false); + return 0; } final lastSyncStr = await prefs.getLastHealthSyncTimestamp(); @@ -150,25 +123,21 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { final endTime = DateTime.now(); _logger.info('Syncing health data from $startTime to $endTime'); - var points = await _health.getHealthDataFromTypes( - types: _types, - startTime: startTime, - endTime: endTime, - ); - points = _health.removeDuplicates(points); - if (points.isEmpty) { + final readings = await _health.read(types: _types, start: startTime, end: endTime); + if (readings.isEmpty) { _logger.info('No new health data'); state = state.copyWith(isSyncing: false, lastSyncCount: 0); return 0; } - final categories = await _repo.getAllOnce(); + final categories = await _measurements.getAllOnce(); + final source = _health.sourceName; var synced = 0; DateTime? latest; for (final metric in enabledHealthMetrics) { - final metricPoints = points.where((p) => p.type == metric.dataType); - if (metricPoints.isEmpty) { + final metricReadings = readings.where((r) => r.type == metric.dataType); + if (metricReadings.isEmpty) { continue; } @@ -178,33 +147,29 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { if (e.externalId != null) e.externalId!, }; - for (final point in metricPoints) { - final value = point.value; - if (value is! NumericHealthValue) { - continue; - } - final uuid = point.uuid; - if (uuid.isNotEmpty && seen.contains(uuid)) { + for (final reading in metricReadings) { + final uuid = reading.externalId; + if (uuid != null && seen.contains(uuid)) { continue; } - await _repo.addLocalDrift( + await _measurements.addLocalDrift( MeasurementEntry( categoryId: category.id!, - date: point.dateFrom, - value: metric.toCategoryValue(value.numericValue.toDouble()), + date: reading.date, + value: metric.toCategoryValue(reading.value), notes: '', - source: _sourceName, - externalId: uuid.isEmpty ? null : uuid, + source: source, + externalId: uuid, ), ); - if (uuid.isNotEmpty) { + if (uuid != null) { seen.add(uuid); } synced++; - if (latest == null || point.dateFrom.isAfter(latest)) { - latest = point.dateFrom; + if (latest == null || reading.date.isAfter(latest)) { + latest = reading.date; } } } @@ -243,7 +208,7 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { unit: metric.unit, metricType: metric.metricType, ); - await _repo.addLocalDriftCategory(category); + await _measurements.addLocalDriftCategory(category); categories.add(category); return category; } diff --git a/lib/features/health/providers/health_sync.g.dart b/lib/features/health/providers/health_sync.g.dart index 768adca84..686cde9b1 100644 --- a/lib/features/health/providers/health_sync.g.dart +++ b/lib/features/health/providers/health_sync.g.dart @@ -9,23 +9,26 @@ part of 'health_sync.dart'; // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint, type=warning /// Imports body metrics from Apple Health / Health Connect into measurement -/// categories. Read-only: reads the platform, writes to the local Drift DB, and -/// lets PowerSync push the rows up. Re-imports are deduplicated via each -/// measurement's [MeasurementEntry.externalId] (the platform record UUID). +/// categories. Read-only: reads the platform (via [HealthRepository]), writes to +/// the local Drift DB, and lets PowerSync push the rows up. Re-imports are +/// deduplicated via each measurement's [MeasurementEntry.externalId] (the +/// platform record UUID). @ProviderFor(HealthSyncNotifier) final healthSyncProvider = HealthSyncNotifierProvider._(); /// Imports body metrics from Apple Health / Health Connect into measurement -/// categories. Read-only: reads the platform, writes to the local Drift DB, and -/// lets PowerSync push the rows up. Re-imports are deduplicated via each -/// measurement's [MeasurementEntry.externalId] (the platform record UUID). +/// categories. Read-only: reads the platform (via [HealthRepository]), writes to +/// the local Drift DB, and lets PowerSync push the rows up. Re-imports are +/// deduplicated via each measurement's [MeasurementEntry.externalId] (the +/// platform record UUID). final class HealthSyncNotifierProvider extends $NotifierProvider { /// Imports body metrics from Apple Health / Health Connect into measurement - /// categories. Read-only: reads the platform, writes to the local Drift DB, and - /// lets PowerSync push the rows up. Re-imports are deduplicated via each - /// measurement's [MeasurementEntry.externalId] (the platform record UUID). + /// categories. Read-only: reads the platform (via [HealthRepository]), writes to + /// the local Drift DB, and lets PowerSync push the rows up. Re-imports are + /// deduplicated via each measurement's [MeasurementEntry.externalId] (the + /// platform record UUID). HealthSyncNotifierProvider._() : super( from: null, @@ -53,12 +56,13 @@ final class HealthSyncNotifierProvider } } -String _$healthSyncNotifierHash() => r'9efca0080b2dd104a3e409f1c81a9976ec0e635c'; +String _$healthSyncNotifierHash() => r'9c7a678e7740bfa32db7638bd227d64da3bfef09'; /// Imports body metrics from Apple Health / Health Connect into measurement -/// categories. Read-only: reads the platform, writes to the local Drift DB, and -/// lets PowerSync push the rows up. Re-imports are deduplicated via each -/// measurement's [MeasurementEntry.externalId] (the platform record UUID). +/// categories. Read-only: reads the platform (via [HealthRepository]), writes to +/// the local Drift DB, and lets PowerSync push the rows up. Re-imports are +/// deduplicated via each measurement's [MeasurementEntry.externalId] (the +/// platform record UUID). abstract class _$HealthSyncNotifier extends $Notifier { HealthSyncState build(); diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index 6d16d92f3..54ffdb88d 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -16,9 +16,24 @@ * along with this program. If not, see . */ +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:health/health.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; +import 'package:wger/core/shared_preferences.dart'; +import 'package:wger/features/health/models/health_reading.dart'; +import 'package:wger/features/health/providers/health_repository.dart'; import 'package:wger/features/health/providers/health_sync.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/models/measurement_entry.dart'; +import 'package:wger/features/measurements/providers/measurement_repository.dart'; +import 'health_sync_test.mocks.dart'; + +@GenerateMocks([HealthRepository, MeasurementRepository]) void main() { group('HealthSyncState', () { test('default state has sync disabled', () { @@ -36,4 +51,137 @@ void main() { expect(updated.lastSyncCount, 5); }); }); + + group('syncOnAppOpen', () { + late MockHealthRepository health; + late MockMeasurementRepository measurements; + + setUp(() async { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + await PreferenceHelper.instance.setHealthSyncEnabled(true); + + health = MockHealthRepository(); + measurements = MockMeasurementRepository(); + + when(health.ensureAuthorized(any)).thenAnswer((_) async => true); + when(health.sourceName).thenReturn('apple_health'); + when(measurements.addLocalDrift(any)).thenAnswer((_) async {}); + when(measurements.addLocalDriftCategory(any)).thenAnswer((_) async {}); + }); + + HealthSyncNotifier createNotifier() { + final container = ProviderContainer.test( + overrides: [ + healthRepositoryProvider.overrideWithValue(health), + measurementRepositoryProvider.overrideWithValue(measurements), + ], + ); + return container.read(healthSyncProvider.notifier); + } + + void stubReadings(List readings) { + when( + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + ), + ).thenAnswer((_) async => readings); + } + + test('imports enabled metrics into new categories with converted values', () async { + when(measurements.getAllOnce()).thenAnswer((_) async => []); + stubReadings([ + HealthReading( + type: HealthDataType.BODY_FAT_PERCENTAGE, + value: 0.2, + date: DateTime(2026, 1, 1), + externalId: 'bf-1', + ), + HealthReading( + type: HealthDataType.HEIGHT, + value: 1.8, + date: DateTime(2026, 1, 2), + externalId: 'h-1', + ), + ]); + + final count = await createNotifier().syncOnAppOpen(); + expect(count, 2); + + final createdCategories = verify( + measurements.addLocalDriftCategory(captureAny), + ).captured.cast(); + expect(createdCategories.map((c) => c.metricType), containsAll(['body_fat', 'height'])); + + final entries = verify( + measurements.addLocalDrift(captureAny), + ).captured.cast(); + + final bodyFat = entries.firstWhere((e) => e.externalId == 'bf-1'); + expect(bodyFat.value, closeTo(20, 0.001)); // fraction -> percent + expect(bodyFat.source, 'apple_health'); + + final height = entries.firstWhere((e) => e.externalId == 'h-1'); + expect(height.value, closeTo(180, 0.001)); // meters -> cm + }); + + test('skips readings already imported (dedup by externalId)', () async { + final existing = MeasurementCategory( + id: 'cat-bf', + name: 'Body fat', + unit: '%', + metricType: 'body_fat', + entries: [ + MeasurementEntry( + id: 'e1', + categoryId: 'cat-bf', + date: DateTime(2026, 1, 1), + value: 20, + notes: '', + source: 'apple_health', + externalId: 'bf-1', + ), + ], + ); + when(measurements.getAllOnce()).thenAnswer((_) async => [existing]); + stubReadings([ + HealthReading( + type: HealthDataType.BODY_FAT_PERCENTAGE, + value: 0.2, + date: DateTime(2026, 1, 1), + externalId: 'bf-1', // already imported + ), + HealthReading( + type: HealthDataType.BODY_FAT_PERCENTAGE, + value: 0.22, + date: DateTime(2026, 1, 3), + externalId: 'bf-2', // new + ), + ]); + + final count = await createNotifier().syncOnAppOpen(); + expect(count, 1); + verifyNever(measurements.addLocalDriftCategory(any)); + + final entries = verify( + measurements.addLocalDrift(captureAny), + ).captured.cast(); + expect(entries.single.externalId, 'bf-2'); + }); + + test('does nothing when sync is disabled', () async { + await PreferenceHelper.instance.setHealthSyncEnabled(false); + + final count = await createNotifier().syncOnAppOpen(); + expect(count, 0); + verifyNever( + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + ), + ); + }); + }); } diff --git a/test/features/health/providers/health_sync_test.mocks.dart b/test/features/health/providers/health_sync_test.mocks.dart new file mode 100644 index 000000000..938babcd9 --- /dev/null +++ b/test/features/health/providers/health_sync_test.mocks.dart @@ -0,0 +1,177 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/features/health/providers/health_sync_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i4; + +import 'package:health/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; +import 'package:wger/features/health/providers/health_repository.dart' as _i2; +import 'package:wger/features/measurements/models/measurement_category.dart' as _i8; +import 'package:wger/features/measurements/models/measurement_entry.dart' as _i9; +import 'package:wger/features/measurements/providers/measurement_repository.dart' as _i7; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [HealthRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { + MockHealthRepository() { + _i1.throwOnMissingStub(this); + } + + @override + String get sourceName => + (super.noSuchMethod( + Invocation.getter(#sourceName), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#sourceName), + ), + ) + as String); + + @override + _i4.Future isAvailable() => + (super.noSuchMethod( + Invocation.method(#isAvailable, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future ensureAuthorized(List<_i5.HealthDataType>? types) => + (super.noSuchMethod( + Invocation.method(#ensureAuthorized, [types]), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future> read({ + required List<_i5.HealthDataType>? types, + required DateTime? start, + required DateTime? end, + }) => + (super.noSuchMethod( + Invocation.method(#read, [], { + #types: types, + #start: start, + #end: end, + }), + returnValue: _i4.Future>.value( + <_i6.HealthReading>[], + ), + ) + as _i4.Future>); +} + +/// A class which mocks [MeasurementRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockMeasurementRepository extends _i1.Mock implements _i7.MeasurementRepository { + MockMeasurementRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i4.Stream> watchAll() => + (super.noSuchMethod( + Invocation.method(#watchAll, []), + returnValue: _i4.Stream>.empty(), + ) + as _i4.Stream>); + + @override + _i4.Stream<_i8.MeasurementCategory?> watchLocalDriftCategoryById( + String? id, + ) => + (super.noSuchMethod( + Invocation.method(#watchLocalDriftCategoryById, [id]), + returnValue: _i4.Stream<_i8.MeasurementCategory?>.empty(), + ) + as _i4.Stream<_i8.MeasurementCategory?>); + + @override + _i4.Future> getAllOnce() => + (super.noSuchMethod( + Invocation.method(#getAllOnce, []), + returnValue: _i4.Future>.value( + <_i8.MeasurementCategory>[], + ), + ) + as _i4.Future>); + + @override + _i4.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future updateLocalDrift(_i9.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [entry]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future addLocalDrift(_i9.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [entry]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future deleteLocalDriftCategory(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDriftCategory, [id]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future updateLocalDriftCategory( + _i8.MeasurementCategory? category, + ) => + (super.noSuchMethod( + Invocation.method(#updateLocalDriftCategory, [category]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future addLocalDriftCategory(_i8.MeasurementCategory? category) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftCategory, [category]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); +} From 84d0de78c61c825f4a4b8106f6ae5a22e8e8362d Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Thu, 2 Jul 2026 22:06:36 +0545 Subject: [PATCH 019/484] feat(measurements): introduce MetricType enum and category properties - Add MetricType enum supporting Django API field mapping - Provide localized en string descriptors for health categories - implement daily aggregation logic and bar chart widget - Implement MeasurementBarChartWidgetFl using fl_chart - Update getOverviewWidgets signatures to dynamically handle MetricType - Add buildChartForMetricType conditional rendering interceptor - Bind step, distance, sleep, and energy categories to the bar chart pipeline --- lib/l10n/app_en.arb | 40 ++++++ .../measurements/measurement_category.dart | 64 +++++++++ lib/widgets/measurements/charts.dart | 131 ++++++++++++++++++ lib/widgets/measurements/helpers.dart | 32 ++++- 4 files changed, 262 insertions(+), 5 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b185a7107..4aa2d492f 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -542,6 +542,46 @@ }, "measurementCategoriesHelpText": "Measurement category, such as 'biceps' or 'body fat'", "@measurementCategoriesHelpText": {}, + "metricCustom": "Custom", + "@metricCustom": { + "description": "Label for custom metric type" + }, + "metricBodyWeight": "Body weight", + "@metricBodyWeight": { + "description": "Label for body weight measurement" + }, + "metricBodyFat": "Body fat", + "@metricBodyFat": { + "description": "Label for body fat percentage measurement" + }, + "metricHeight": "Height", + "@metricHeight": { + "description": "Label for height measurement" + }, + "metricBloodPressure": "Blood pressure", + "@metricBloodPressure": { + "description": "Label for blood pressure measurement" + }, + "metricHeartRate": "Heart rate", + "@metricHeartRate": { + "description": "Label for heart rate measurement" + }, + "metricSteps": "Steps", + "@metricSteps": { + "description": "Label for step count measurement" + }, + "metricDistance": "Distance", + "@metricDistance": { + "description": "Label for distance measurement" + }, + "metricEnergy": "Energy", + "@metricEnergy": { + "description": "Label for energy/calories burned measurement" + }, + "metricSleep": "Sleep", + "@metricSleep": { + "description": "Label for sleep duration measurement" + }, "measurementEntriesHelpText": "The unit used to measure the category such as 'cm' or '%'", "@measurementEntriesHelpText": {}, "date": "Date", diff --git a/lib/models/measurements/measurement_category.dart b/lib/models/measurements/measurement_category.dart index 272e3724c..fa9d9f74e 100644 --- a/lib/models/measurements/measurement_category.dart +++ b/lib/models/measurements/measurement_category.dart @@ -17,13 +17,73 @@ */ import 'package:drift/drift.dart' hide JsonKey; +import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:wger/core/exceptions/no_such_entry_exception.dart'; import 'package:wger/database/powersync/database.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/measurements/measurement_entry.dart'; part 'measurement_category.freezed.dart'; +/// The wire values mirror the Django API field names (e.g., 'body_weight', 'heart_rate'), +enum MetricType { + custom('custom'), + bodyWeight('body_weight'), + bodyFat('body_fat'), + height('height'), + bloodPressure('blood_pressure'), + heartRate('heart_rate'), + steps('steps'), + distance('distance'), + energy('energy'), + sleep('sleep'); + + final String wireValue; + const MetricType(this.wireValue); + + /// Looks up an enum case by its Django wire value. + /// + /// Defaults to [MetricType.custom] if the value is not recognized. + static MetricType fromWire(String value) => MetricType.values.firstWhere( + (e) => e.wireValue == value, + orElse: () => MetricType.custom, + ); + + /// `true` for metric types that should be aggregated per-day and shown as + /// a bar/histogram instead of a raw-sample line chart. + bool get isSummedPerDay => switch (this) { + MetricType.steps || + MetricType.distance || + MetricType.energy || + MetricType.sleep => true, + _ => false, + }; +} + +extension MeasurementMetricTypeL10n on MetricType { + /// Localized human-readable label (e.g., "Body Weight", "Heart Rate"). + String localized(BuildContext context) { + final l10n = AppLocalizations.of(context); + return switch (this) { + MetricType.custom => l10n.metricCustom, + MetricType.bodyWeight => l10n.metricBodyWeight, + MetricType.bodyFat => l10n.metricBodyFat, + MetricType.height => l10n.metricHeight, + MetricType.bloodPressure => l10n.metricBloodPressure, + MetricType.heartRate => l10n.metricHeartRate, + MetricType.steps => l10n.metricSteps, + MetricType.distance => l10n.metricDistance, + MetricType.energy => l10n.metricEnergy, + MetricType.sleep => l10n.metricSleep, + }; + } +} + +// Missing concrete implementation of 'getter _$MeasurementCategory.metricType'. +// Try implementing the missing method, or make the class abstract.dartnon_abstract_class_inherits_abstract_member +// class MeasurementCategory with _$MeasurementCategory +// Declared in package:wger/models/measurements/measurement_category.dart. @freezed class MeasurementCategory with _$MeasurementCategory { /// Inclusive upper bound for [name] @@ -45,11 +105,15 @@ class MeasurementCategory with _$MeasurementCategory { @override final List entries; + @override + final MetricType metricType; + MeasurementCategory({ this.id, this.name = '', this.unit = '', this.entries = const [], + this.metricType = MetricType.custom, }); MeasurementEntry findEntryById(String id) { diff --git a/lib/widgets/measurements/charts.dart b/lib/widgets/measurements/charts.dart index fa3ddbc18..049b68e3e 100644 --- a/lib/widgets/measurements/charts.dart +++ b/lib/widgets/measurements/charts.dart @@ -22,6 +22,7 @@ import 'package:intl/intl.dart'; import 'package:wger/helpers/charts.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/measurements/measurement_entry.dart'; class MeasurementOverallChangeWidget extends StatelessWidget { final MeasurementChartEntry _first; @@ -251,6 +252,136 @@ List moving7dAverage(List vals) { return out; } +/// Sums entries per calendar day. Used for metric types where individual +/// samples aren't meaningful on their own (steps, distance, energy, sleep) — +/// see MeasurementMetricType.isSummedPerDay. +List aggregatePerDay(List vals) { + if (vals.isEmpty) { + return []; + } + + // Bucket by the day component only (strip time-of-day). + final Map sums = {}; + for (final e in vals) { + final day = DateTime(e.date.year, e.date.month, e.date.day); + sums.update(day, (existing) => existing + e.value, ifAbsent: () => e.value); + } + + final out = sums.entries.map((e) => MeasurementChartEntry(e.value, e.key)).toList() + ..sort((a, b) => a.date.compareTo(b.date)); + return out; +} + +class MeasurementBarChartWidgetFl extends StatefulWidget { + final List _entries; + final String _unit; + + const MeasurementBarChartWidgetFl(this._entries, this._unit); + + @override + State createState() => _MeasurementBarChartWidgetFlState(); +} + +class _MeasurementBarChartWidgetFlState extends State { + @override + Widget build(BuildContext context) { + return AspectRatio( + aspectRatio: 1.70, + child: Padding( + padding: const EdgeInsets.all(4), + child: BarChart(mainData()), + ), + ); + } + + BarTouchData tooltipData() { + return BarTouchData( + touchTooltipData: BarTouchTooltipData( + getTooltipColor: (group) => Theme.of(context).colorScheme.primaryContainer, + getTooltipItem: (group, groupIndex, rod, rodIndex) { + final numberFormat = NumberFormat.decimalPattern( + Localizations.localeOf(context).toString(), + ); + final DateTime date = DateTime.fromMillisecondsSinceEpoch(group.x); + final dateStr = DateFormat.Md(Localizations.localeOf(context).languageCode).format(date); + + return BarTooltipItem( + '$dateStr: ${numberFormat.format(rod.toY)} ${widget._unit}', + TextStyle(color: Theme.of(context).colorScheme.onPrimaryContainer), + ); + }, + ), + ); + } + + BarChartData mainData() { + final String locale = Localizations.localeOf(context).toString(); + final NumberFormat numberFormat = NumberFormat.decimalPattern(locale); + return BarChartData( + barTouchData: tooltipData(), + gridData: FlGridData( + show: true, + drawVerticalLine: false, + getDrawingHorizontalLine: (value) { + return FlLine(color: Theme.of(context).colorScheme.primaryContainer, strokeWidth: 1); + }, + ), + titlesData: FlTitlesData( + show: true, + rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)), + topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)), + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, meta) { + // avoid label overlap with the axis edges + if (value == meta.min || value == meta.max) { + return const Text(''); + } + final DateTime date = DateTime.fromMillisecondsSinceEpoch(value.toInt()); + return Text(DateFormat.Md(Localizations.localeOf(context).languageCode).format(date)); + }, + interval: widget._entries.isNotEmpty + ? chartGetInterval(widget._entries.last.date, widget._entries.first.date) + : CHART_MILLISECOND_FACTOR, + ), + ), + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + reservedSize: 65, + getTitlesWidget: (value, meta) { + if (value == meta.min || value == meta.max) { + return const Text(''); + } + return Text('${numberFormat.format(value)} ${widget._unit}'); + }, + ), + ), + ), + borderData: FlBorderData( + show: true, + border: Border.all(color: Theme.of(context).colorScheme.primaryContainer), + ), + barGroups: widget._entries + .map( + (e) => BarChartGroupData( + x: e.date.millisecondsSinceEpoch, + barRods: [ + BarChartRodData( + toY: e.value.toDouble(), + color: Theme.of(context).colorScheme.primary, + width: 12, + borderRadius: const BorderRadius.vertical(top: Radius.circular(2)), + ), + ], + ), + ) + .toList(), + ); + } +} + class Indicator extends StatelessWidget { const Indicator({ super.key, diff --git a/lib/widgets/measurements/helpers.dart b/lib/widgets/measurements/helpers.dart index 00369b06d..9086f568d 100644 --- a/lib/widgets/measurements/helpers.dart +++ b/lib/widgets/measurements/helpers.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:wger/helpers/measurements.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/measurements/measurement_category.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; import 'package:wger/widgets/measurements/charts.dart'; @@ -9,8 +10,9 @@ List getOverviewWidgets( List raw, List avg, String unit, - BuildContext context, -) { + BuildContext context, { + MetricType metricType = MetricType.custom, +}) { return [ Text( title, @@ -29,7 +31,7 @@ List getOverviewWidgets( ), ), ) - : MeasurementChartWidgetFl(raw, unit, avgs: avg), + : buildChartForMetricType(metricType, raw, avg, unit), ), if (avg.isNotEmpty) MeasurementOverallChangeWidget(avg.first, avg.last, unit), const SizedBox(height: 8), @@ -42,8 +44,9 @@ List getOverviewWidgetsSeries( List entries7dAvg, List plans, String unit, - BuildContext context, -) { + BuildContext context, { + MetricType metricType = MetricType.custom, +}) { final monthAgo = DateTime.now().subtract(const Duration(days: 30)); return [ ...getOverviewWidgets( @@ -52,6 +55,7 @@ List getOverviewWidgetsSeries( entries7dAvg, unit, context, + metricType: metricType, ), // Show overview widgets for each plan in plans for (final plan in plans) @@ -61,6 +65,7 @@ List getOverviewWidgetsSeries( entries7dAvg.whereDateWithInterpolation(plan.startDate, plan.endDate), unit, context, + metricType: metricType, ), // if all time is significantly longer than 30 days (let's say > 75 days) // then let's show a separate chart just focusing on the last 30 days, @@ -74,6 +79,7 @@ List getOverviewWidgetsSeries( entries7dAvg.whereDateWithInterpolation(monthAgo, null), unit, context, + metricType: metricType, ), // legend Row( @@ -120,3 +126,19 @@ List getOverviewWidgetsSeries( } return (entriesAll, entries7dAvg); } + +Widget buildChartForMetricType( + MetricType metricType, + List raw, + List avg, + String unit, +) { + if (metricType.isSummedPerDay) { + return MeasurementBarChartWidgetFl(aggregatePerDay(raw), unit); + } + return MeasurementChartWidgetFl( + raw, + unit, + avgs: avg, + ); +} From 5d1f0372195a23a225a87ad3d3c1fe54d96d9f0c Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Fri, 3 Jul 2026 10:51:55 +0545 Subject: [PATCH 020/484] feat(measurements): add metric type selection and detail view support - Replace hardcoded line charts with buildChartForMetricType - add metric type selection and detail view support - Add DropdownButtonFormField to MeasurementCategory form for user assignment - Pass metricType to detail view rendering pipeline in EntriesList - Update form state management to handle manual metric type assignment --- lib/models/measurements/measurement_category.dart | 11 ++--------- lib/widgets/measurements/categories_card.dart | 8 +++++--- lib/widgets/measurements/entries.dart | 1 + lib/widgets/measurements/forms.dart | 14 ++++++++++++++ 4 files changed, 22 insertions(+), 12 deletions(-) diff --git a/lib/models/measurements/measurement_category.dart b/lib/models/measurements/measurement_category.dart index fa9d9f74e..01a4c1cc1 100644 --- a/lib/models/measurements/measurement_category.dart +++ b/lib/models/measurements/measurement_category.dart @@ -43,7 +43,7 @@ enum MetricType { const MetricType(this.wireValue); /// Looks up an enum case by its Django wire value. - /// + /// /// Defaults to [MetricType.custom] if the value is not recognized. static MetricType fromWire(String value) => MetricType.values.firstWhere( (e) => e.wireValue == value, @@ -53,10 +53,7 @@ enum MetricType { /// `true` for metric types that should be aggregated per-day and shown as /// a bar/histogram instead of a raw-sample line chart. bool get isSummedPerDay => switch (this) { - MetricType.steps || - MetricType.distance || - MetricType.energy || - MetricType.sleep => true, + MetricType.steps || MetricType.distance || MetricType.energy || MetricType.sleep => true, _ => false, }; } @@ -80,10 +77,6 @@ extension MeasurementMetricTypeL10n on MetricType { } } -// Missing concrete implementation of 'getter _$MeasurementCategory.metricType'. -// Try implementing the missing method, or make the class abstract.dartnon_abstract_class_inherits_abstract_member -// class MeasurementCategory with _$MeasurementCategory -// Declared in package:wger/models/measurements/measurement_category.dart. @freezed class MeasurementCategory with _$MeasurementCategory { /// Inclusive upper bound for [name] diff --git a/lib/widgets/measurements/categories_card.dart b/lib/widgets/measurements/categories_card.dart index b778c9e28..4d6eb91d9 100644 --- a/lib/widgets/measurements/categories_card.dart +++ b/lib/widgets/measurements/categories_card.dart @@ -34,6 +34,7 @@ class CategoriesCard extends StatelessWidget { @override Widget build(BuildContext context) { + // sensibleRange() operates on raw (pre-aggregation) entries final (entriesAll, entries7dAvg) = sensibleRange( currentCategory.entries.map((e) => MeasurementChartEntry(e.value, e.date)).toList(), ); @@ -57,13 +58,14 @@ class CategoriesCard extends StatelessWidget { Container( padding: const EdgeInsets.all(10), height: 220, - child: MeasurementChartWidgetFl( + child: buildChartForMetricType( + currentCategory.metricType, entriesAll, + entries7dAvg, currentCategory.unit, - avgs: entries7dAvg, ), ), - if (entries7dAvg.isNotEmpty) + if (entries7dAvg.isNotEmpty && !currentCategory.metricType.isSummedPerDay) MeasurementOverallChangeWidget( entries7dAvg.first, entries7dAvg.last, diff --git a/lib/widgets/measurements/entries.dart b/lib/widgets/measurements/entries.dart index 5abc04080..8bb7cf298 100644 --- a/lib/widgets/measurements/entries.dart +++ b/lib/widgets/measurements/entries.dart @@ -56,6 +56,7 @@ class EntriesList extends ConsumerWidget { plans, _category.unit, context, + metricType: _category.metricType, ), SizedBox( height: 300, diff --git a/lib/widgets/measurements/forms.dart b/lib/widgets/measurements/forms.dart index 4a605ca92..5b9583084 100644 --- a/lib/widgets/measurements/forms.dart +++ b/lib/widgets/measurements/forms.dart @@ -95,6 +95,20 @@ class _MeasurementCategoryFormState extends ConsumerState DropdownMenuItem(value: t, child: Text(t.name))) + .toList(), + onChanged: (value) { + if (value != null) { + setState(() { + _draft = _draft.copyWith(metricType: value); + }); + } + }, + ), FormSubmitButton( label: AppLocalizations.of(context).save, onPressed: () async { From 6c3373fc73aed41a3bd695b17a3039c326c68b66 Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Sat, 4 Jul 2026 13:18:12 +0545 Subject: [PATCH 021/484] feat(measurements): add metricType to category schema - Add metricType property to MeasurementCategory model and DB table. - Include local-only persistence for metric categorization. - Update UI form and localization strings. --- lib/database/powersync/tables/measurements.dart | 2 ++ lib/l10n/app_en.arb | 4 ++++ lib/models/measurements/measurement_category.dart | 1 + lib/widgets/measurements/forms.dart | 2 ++ 4 files changed, 9 insertions(+) diff --git a/lib/database/powersync/tables/measurements.dart b/lib/database/powersync/tables/measurements.dart index d0e386f8f..fe39506b1 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -31,6 +31,7 @@ class MeasurementCategoryTable extends Table { TextColumn get name => text()(); TextColumn get unit => text()(); + TextColumn get metricType => text().named('metric_type').withDefault(const Constant('custom'))(); } const PowersyncMeasurementCategoryTable = ps.Table( @@ -38,6 +39,7 @@ const PowersyncMeasurementCategoryTable = ps.Table( [ ps.Column.text('name'), ps.Column.text('unit'), + // ps.Column.text('metric_type') ], ); diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 4aa2d492f..0dc21f14d 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -542,6 +542,10 @@ }, "measurementCategoriesHelpText": "Measurement category, such as 'biceps' or 'body fat'", "@measurementCategoriesHelpText": {}, + "metricType": "Metric Type", + "@metricType": { + "description": "Metric type for a measurement category" + }, "metricCustom": "Custom", "@metricCustom": { "description": "Label for custom metric type" diff --git a/lib/models/measurements/measurement_category.dart b/lib/models/measurements/measurement_category.dart index 01a4c1cc1..f2eeb8696 100644 --- a/lib/models/measurements/measurement_category.dart +++ b/lib/models/measurements/measurement_category.dart @@ -122,6 +122,7 @@ class MeasurementCategory with _$MeasurementCategory { id: id != null ? Value(id!) : const Value.absent(), name: Value(name), unit: Value(unit), + metricType: Value(metricType.wireValue) ); } } diff --git a/lib/widgets/measurements/forms.dart b/lib/widgets/measurements/forms.dart index 5b9583084..4f2cb6296 100644 --- a/lib/widgets/measurements/forms.dart +++ b/lib/widgets/measurements/forms.dart @@ -98,6 +98,8 @@ class _MeasurementCategoryFormState extends ConsumerState DropdownMenuItem(value: t, child: Text(t.name))) .toList(), From 5ff9d259d3f2de8eea7be4bf9be6ed3fefcac50d Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Sat, 4 Jul 2026 17:38:35 +0545 Subject: [PATCH 022/484] feat(charts): add smoothed trendline to measurement charts - Implement centered moving average trendline in charts.dart. - Update MeasurementChartWidgetFl to render trendline bar data. - Integrate smoothedTreadline logic into metric chart builder. refactor(db): implement MetricType Drift converter - Add MeasurementMetricTypeConverter to map enum to SQLite text. - Update MeasurementCategoryTable to use the new converter. --- .../measurement_metric_type_converter.dart | 31 +++++++++++++ lib/database/powersync/database.dart | 1 + .../powersync/tables/measurements.dart | 9 ++-- .../measurements/measurement_category.dart | 2 +- lib/widgets/measurements/charts.dart | 46 ++++++++++++++++++- lib/widgets/measurements/forms.dart | 2 +- lib/widgets/measurements/helpers.dart | 12 +++++ 7 files changed, 94 insertions(+), 9 deletions(-) create mode 100644 lib/database/converters/measurement_metric_type_converter.dart diff --git a/lib/database/converters/measurement_metric_type_converter.dart b/lib/database/converters/measurement_metric_type_converter.dart new file mode 100644 index 000000000..45105a269 --- /dev/null +++ b/lib/database/converters/measurement_metric_type_converter.dart @@ -0,0 +1,31 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2020 - 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:drift/drift.dart'; +import 'package:wger/models/measurements/measurement_category.dart'; + +/// Maps a [MetricType] to and from the SQLite string format. +class MeasurementMetricTypeConverter extends TypeConverter { + const MeasurementMetricTypeConverter(); + + @override + MetricType fromSql(String fromDb) => MetricType.fromWire(fromDb); + + @override + String toSql(MetricType value) => value.wireValue; +} diff --git a/lib/database/powersync/database.dart b/lib/database/powersync/database.dart index a4292a286..caa3ed586 100644 --- a/lib/database/powersync/database.dart +++ b/lib/database/powersync/database.dart @@ -23,6 +23,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:powersync/powersync.dart' as ps; import 'package:wger/database/converters/date_only_text_converter.dart'; import 'package:wger/database/converters/exercise_image_style_converter.dart'; +import 'package:wger/database/converters/measurement_metric_type_converter.dart'; import 'package:wger/database/converters/time_of_day_converter.dart'; import 'package:wger/database/converters/utc_datetime_converter.dart'; import 'package:wger/database/converters/workout_impression_converter.dart'; diff --git a/lib/database/powersync/tables/measurements.dart b/lib/database/powersync/tables/measurements.dart index fe39506b1..1f5c5063f 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -18,6 +18,7 @@ import 'package:drift/drift.dart'; import 'package:powersync/powersync.dart' as ps; +import 'package:wger/database/converters/measurement_metric_type_converter.dart'; import 'package:wger/database/converters/utc_datetime_converter.dart'; import 'package:wger/models/measurements/measurement_category.dart'; import 'package:wger/models/measurements/measurement_entry.dart'; @@ -31,16 +32,12 @@ class MeasurementCategoryTable extends Table { TextColumn get name => text()(); TextColumn get unit => text()(); - TextColumn get metricType => text().named('metric_type').withDefault(const Constant('custom'))(); + TextColumn get metricType => text().map(const MeasurementMetricTypeConverter())(); } const PowersyncMeasurementCategoryTable = ps.Table( 'measurements_category', - [ - ps.Column.text('name'), - ps.Column.text('unit'), - // ps.Column.text('metric_type') - ], + [ps.Column.text('name'), ps.Column.text('unit'), ps.Column.text('metric_type')], ); @UseRowClass(MeasurementEntry) diff --git a/lib/models/measurements/measurement_category.dart b/lib/models/measurements/measurement_category.dart index f2eeb8696..5c3fbeeaa 100644 --- a/lib/models/measurements/measurement_category.dart +++ b/lib/models/measurements/measurement_category.dart @@ -122,7 +122,7 @@ class MeasurementCategory with _$MeasurementCategory { id: id != null ? Value(id!) : const Value.absent(), name: Value(name), unit: Value(unit), - metricType: Value(metricType.wireValue) + metricType: Value(metricType), ); } } diff --git a/lib/widgets/measurements/charts.dart b/lib/widgets/measurements/charts.dart index 049b68e3e..94b76f3d2 100644 --- a/lib/widgets/measurements/charts.dart +++ b/lib/widgets/measurements/charts.dart @@ -55,9 +55,10 @@ String weightUnit(bool isMetric, BuildContext context) { class MeasurementChartWidgetFl extends StatefulWidget { final List _entries; final List? avgs; + final List? trend; final String _unit; - const MeasurementChartWidgetFl(this._entries, this._unit, {this.avgs}); + const MeasurementChartWidgetFl(this._entries, this._unit, {this.avgs, this.trend}); @override State createState() => _MeasurementChartWidgetFlState(); @@ -212,6 +213,17 @@ class _MeasurementChartWidgetFlState extends State { barWidth: 1, dotData: const FlDotData(show: false), ), + if (widget.trend != null && widget.trend!.isNotEmpty) + LineChartBarData( + spots: widget.trend! + .map((e) => FlSpot(e.date.millisecondsSinceEpoch.toDouble(), e.value.toDouble())) + .toList(), + isCurved: true, + curveSmoothness: 0.4, + color: Theme.of(context).colorScheme.secondary, + barWidth: 3, + dotData: const FlDotData(show: false), + ), ], ); } @@ -382,6 +394,38 @@ class _MeasurementBarChartWidgetFlState extends State smoothedTrendline( + List vals, { + // int windowDays = 14, + int period = 10, +}) { + if (vals.isEmpty) { + return []; + } + + final sorted = [...vals]..sort((a, b) => a.date.compareTo(b.date)); + final List out = []; + + // Seed the initialization layer with the first data point value + double currentEma = sorted[0].value.toDouble(); + final double smoothing = 2 / (period + 1); + + for (int i = 0; i < sorted.length; i++) { + final point = sorted[i]; + + if (i > 0) { + // EMA equation: point.weight * smoothing + ema * (1 - smoothing) + currentEma = (point.value * smoothing) + (currentEma * (1 - smoothing)); + } + + out.add(MeasurementChartEntry(currentEma, point.date)); + } + + return out; +} + class Indicator extends StatelessWidget { const Indicator({ super.key, diff --git a/lib/widgets/measurements/forms.dart b/lib/widgets/measurements/forms.dart index 4f2cb6296..0e928b019 100644 --- a/lib/widgets/measurements/forms.dart +++ b/lib/widgets/measurements/forms.dart @@ -101,7 +101,7 @@ class _MeasurementCategoryFormState extends ConsumerState DropdownMenuItem(value: t, child: Text(t.name))) + .map((t) => DropdownMenuItem(value: t, child: Text(t.localized(context)))) .toList(), onChanged: (value) { if (value != null) { diff --git a/lib/widgets/measurements/helpers.dart b/lib/widgets/measurements/helpers.dart index 9086f568d..a62c4dd1b 100644 --- a/lib/widgets/measurements/helpers.dart +++ b/lib/widgets/measurements/helpers.dart @@ -95,6 +95,14 @@ List getOverviewWidgetsSeries( text: AppLocalizations.of(context).indicatorAvg, isSquare: true, ), + // if (!metricType.isSummedPerDay && !metricType.isRangeType) + if (!metricType.isSummedPerDay) + Indicator( + color: Theme.of(context).colorScheme.secondary, + text: 'trend', + // text: AppLocalizations.of(context).indicatorTrend, + isSquare: true, + ), ], ), ]; @@ -136,9 +144,13 @@ Widget buildChartForMetricType( if (metricType.isSummedPerDay) { return MeasurementBarChartWidgetFl(aggregatePerDay(raw), unit); } + // if (metricType.isRangeType) { + // return buildRangeChartForMetricType(metricType, raw, unit); + // } return MeasurementChartWidgetFl( raw, unit, avgs: avg, + trend: smoothedTrendline(raw), ); } From 42507844d251e05a088e4fa1302d198690c326a3 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 9 Jul 2026 17:12:51 +0200 Subject: [PATCH 023/484] Cleanup, translations and small tests --- .../measurement_metric_type_converter.dart | 11 +- lib/database/powersync/database.g.dart | 17 +-- .../powersync/tables/measurements.dart | 2 +- lib/features/health/models/health_metric.dart | 4 +- .../health/providers/health_repository.dart | 5 +- .../health/providers/health_sync.dart | 6 +- .../models/measurement_entry.dart | 6 +- .../models/measurement_entry.freezed.dart | 4 +- lib/features/measurements/widgets/charts.dart | 6 +- .../measurements/widgets/helpers.dart | 4 +- lib/l10n/app_de.arb | 1 + lib/l10n/app_en.arb | 4 + lib/l10n/app_es.arb | 1 + lib/l10n/app_fr.arb | 1 + test/core/validators_test.mocks.dart | 11 ++ .../health/providers/health_sync_test.dart | 5 +- .../models/measurement_category_test.dart | 30 +++++ .../measurements/widgets/charts_test.dart | 105 ++++++++++++++++++ 18 files changed, 185 insertions(+), 38 deletions(-) create mode 100644 test/features/measurements/widgets/charts_test.dart diff --git a/lib/database/converters/measurement_metric_type_converter.dart b/lib/database/converters/measurement_metric_type_converter.dart index 0a22916bd..da716261c 100644 --- a/lib/database/converters/measurement_metric_type_converter.dart +++ b/lib/database/converters/measurement_metric_type_converter.dart @@ -20,17 +20,12 @@ import 'package:drift/drift.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; /// Maps a [MetricType] to and from the SQLite string format. -/// -/// The SQL side is nullable: the server does not persist `metric_type` yet, so a -/// category synced back down arrives without it. A missing value reads as -/// [MetricType.custom] rather than crashing the non-nullable model field. -class MeasurementMetricTypeConverter extends TypeConverter { +class MeasurementMetricTypeConverter extends TypeConverter { const MeasurementMetricTypeConverter(); @override - MetricType fromSql(String? fromDb) => - fromDb == null ? MetricType.custom : MetricType.fromWire(fromDb); + MetricType fromSql(String fromDb) => MetricType.fromWire(fromDb); @override - String? toSql(MetricType value) => value.wireValue; + String toSql(MetricType value) => value.wireValue; } diff --git a/lib/database/powersync/database.g.dart b/lib/database/powersync/database.g.dart index 4de3c2b82..473084017 100644 --- a/lib/database/powersync/database.g.dart +++ b/lib/database/powersync/database.g.dart @@ -4885,9 +4885,9 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable GeneratedColumn( 'metric_type', aliasedName, - true, + false, type: DriftSqlType.string, - requiredDuringInsert: false, + requiredDuringInsert: true, ).withConverter( $MeasurementCategoryTableTable.$convertermetricType, ); @@ -4949,7 +4949,7 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable attachedDatabase.typeMapping.read( DriftSqlType.string, data['${effectivePrefix}metric_type'], - ), + )!, ), ); } @@ -4959,7 +4959,7 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable return $MeasurementCategoryTableTable(attachedDatabase, alias); } - static TypeConverter $convertermetricType = + static TypeConverter $convertermetricType = const MeasurementMetricTypeConverter(); } @@ -4980,10 +4980,11 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion custom({ Expression? id, Expression? name, @@ -16474,7 +16475,7 @@ typedef $$MeasurementCategoryTableTableCreateCompanionBuilder = Value id, required String name, required String unit, - Value metricType, + required MetricType metricType, Value rowid, }); typedef $$MeasurementCategoryTableTableUpdateCompanionBuilder = @@ -16706,7 +16707,7 @@ class $$MeasurementCategoryTableTableTableManager Value id = const Value.absent(), required String name, required String unit, - Value metricType = const Value.absent(), + required MetricType metricType, Value rowid = const Value.absent(), }) => MeasurementCategoryTableCompanion.insert( id: id, diff --git a/lib/database/powersync/tables/measurements.dart b/lib/database/powersync/tables/measurements.dart index e28069e22..b59893272 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -33,7 +33,7 @@ class MeasurementCategoryTable extends Table { TextColumn get name => text()(); TextColumn get unit => text()(); TextColumn get metricType => - text().named('metric_type').nullable().map(const MeasurementMetricTypeConverter())(); + text().named('metric_type').map(const MeasurementMetricTypeConverter())(); } const PowersyncMeasurementCategoryTable = ps.Table( diff --git a/lib/features/health/models/health_metric.dart b/lib/features/health/models/health_metric.dart index b4615430f..a4afdc9a4 100644 --- a/lib/features/health/models/health_metric.dart +++ b/lib/features/health/models/health_metric.dart @@ -42,8 +42,8 @@ class HealthMetric { final HealthDataType dataType; /// Stable, non-localized category name. Used to find-or-create the category, - /// and as the fallback match after a sync round-trip resets [metricType] to - /// [MetricType.custom] (the server does not persist it yet). + /// and as the fallback match for a category the user already created by hand + /// (which carries [MetricType.custom], not this metric's type). final String canonicalName; /// Unit the value is stored in on the category. diff --git a/lib/features/health/providers/health_repository.dart b/lib/features/health/providers/health_repository.dart index 942d68d07..95c6e8a6c 100644 --- a/lib/features/health/providers/health_repository.dart +++ b/lib/features/health/providers/health_repository.dart @@ -35,8 +35,9 @@ class HealthRepository { final Health _health; final _logger = Logger('HealthRepository'); - /// Identifies which platform a reading came from. - String get sourceName => Platform.isIOS ? 'apple_health' : 'health_connect'; + /// The measurement `source` value for readings from this platform: `apple` + /// for Apple Health, `google` for Health Connect. + String get sourceName => Platform.isIOS ? 'apple' : 'google'; /// Whether a health platform is usable on this device. Future isAvailable() async { diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index 6cf3c74a6..f0a5d1b74 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.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 @@ -188,8 +188,8 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { } /// Finds the category for [metric] (by `metric_type`, falling back to the - /// canonical name once the server has nulled `metric_type` on a round-trip) - /// or creates it. The created category is appended to [categories] so a later + /// canonical name to reuse a matching category the user created by hand) or + /// creates it. The created category is appended to [categories] so a later /// metric in the same run reuses it. Future _findOrCreateCategory( HealthMetric metric, diff --git a/lib/features/measurements/models/measurement_entry.dart b/lib/features/measurements/models/measurement_entry.dart index 717408547..0f0b154cf 100644 --- a/lib/features/measurements/models/measurement_entry.dart +++ b/lib/features/measurements/models/measurement_entry.dart @@ -43,8 +43,8 @@ class MeasurementEntry with _$MeasurementEntry { @override final String notes; - /// Where the reading came from: `manual` or a health platform - /// (`apple_health`, `health_connect`). + /// Origin of the reading; one of the server's `source` values + /// (`user`, `google`, `apple`). @override final String source; @@ -59,7 +59,7 @@ class MeasurementEntry with _$MeasurementEntry { required this.date, required this.value, required this.notes, - this.source = 'manual', + this.source = 'user', this.externalId, }); diff --git a/lib/features/measurements/models/measurement_entry.freezed.dart b/lib/features/measurements/models/measurement_entry.freezed.dart index 4f0b855f7..84bb4fea5 100644 --- a/lib/features/measurements/models/measurement_entry.freezed.dart +++ b/lib/features/measurements/models/measurement_entry.freezed.dart @@ -15,8 +15,8 @@ T _$identity(T value) => value; mixin _$MeasurementEntry { /// Client-generated UUID, is `null` only before the first persist - String? get id; String get categoryId; DateTime get date; num get value; String get notes;/// Where the reading came from: `manual` or a health platform -/// (`apple_health`, `health_connect`). + String? get id; String get categoryId; DateTime get date; num get value; String get notes;/// Origin of the reading; one of the server's `source` values +/// (`user`, `google`, `apple`). String get source;/// Platform record UUID, used to deduplicate re-imports. `null` for manual /// entries. String? get externalId; diff --git a/lib/features/measurements/widgets/charts.dart b/lib/features/measurements/widgets/charts.dart index e9738c97e..8d43749f5 100644 --- a/lib/features/measurements/widgets/charts.dart +++ b/lib/features/measurements/widgets/charts.dart @@ -392,11 +392,11 @@ class _MeasurementBarChartWidgetFlState extends State smoothedTrendline( List vals, { - // int windowDays = 14, int period = 10, }) { if (vals.isEmpty) { diff --git a/lib/features/measurements/widgets/helpers.dart b/lib/features/measurements/widgets/helpers.dart index d4e9d7f34..456282c93 100644 --- a/lib/features/measurements/widgets/helpers.dart +++ b/lib/features/measurements/widgets/helpers.dart @@ -95,12 +95,10 @@ List getOverviewWidgetsSeries( text: AppLocalizations.of(context).indicatorAvg, isSquare: true, ), - // if (!metricType.isSummedPerDay && !metricType.isRangeType) if (!metricType.isSummedPerDay) Indicator( color: Theme.of(context).colorScheme.secondary, - text: 'trend', - // text: AppLocalizations.of(context).indicatorTrend, + text: AppLocalizations.of(context).indicatorTrend, isSquare: true, ), ], diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 84bb6786b..1204cf164 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -837,6 +837,7 @@ "@indicatorAvg": { "description": "added for localization of Class Indicator's field text" }, + "indicatorTrend": "Trend", "themeMode": "Theme Modus", "lightMode": "Immer Hellmodus", "systemMode": "Systemeinstellungen", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 8a7b10988..4e45bb7d6 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1318,6 +1318,10 @@ "@indicatorAvg": { "description": "added for localization of Class Indicator's field text" }, + "indicatorTrend": "trend", + "@indicatorTrend": { + "description": "Legend label for the smoothed trendline on measurement charts" + }, "endWorkout": "End workout", "@endWorkout": { "description": "Use the imperative, label on button to finish the current workout in gym mode" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index f7063822d..7ec8167a6 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -838,6 +838,7 @@ "@indicatorAvg": { "description": "added for localization of Class Indicator's field text" }, + "indicatorTrend": "tendencia", "themeMode": "Modo del tema", "darkMode": "Siempre en modo oscuro", "lightMode": "Siempre en modo claro", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 13406e317..0f1c4343e 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -761,6 +761,7 @@ "@indicatorAvg": { "description": "added for localization of Class Indicator's field text" }, + "indicatorTrend": "tendance", "resistance_band": "Bande de résistance", "@resistance_band": { "description": "Generated entry for translation for server strings" diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index c751b9960..067e74602 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -4261,6 +4261,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get indicatorTrend => + (super.noSuchMethod( + Invocation.getter(#indicatorTrend), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#indicatorTrend), + ), + ) + as String); + @override String get endWorkout => (super.noSuchMethod( diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index c304730e0..2f3b66864 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -64,7 +64,7 @@ void main() { measurements = MockMeasurementRepository(); when(health.ensureAuthorized(any)).thenAnswer((_) async => true); - when(health.sourceName).thenReturn('apple_health'); + when(health.sourceName).thenReturn('apple'); when(measurements.addLocalDrift(any)).thenAnswer((_) async {}); when(measurements.addLocalDriftCategory(any)).thenAnswer((_) async {}); }); @@ -123,7 +123,7 @@ void main() { final bodyFat = entries.firstWhere((e) => e.externalId == 'bf-1'); expect(bodyFat.value, closeTo(20, 0.001)); // fraction -> percent - expect(bodyFat.source, 'apple_health'); + expect(bodyFat.source, 'apple'); final height = entries.firstWhere((e) => e.externalId == 'h-1'); expect(height.value, closeTo(180, 0.001)); // meters -> cm @@ -142,7 +142,6 @@ void main() { date: DateTime(2026, 1, 1), value: 20, notes: '', - source: 'apple_health', externalId: 'bf-1', ), ], diff --git a/test/features/measurements/models/measurement_category_test.dart b/test/features/measurements/models/measurement_category_test.dart index e76820418..1f0619fe8 100644 --- a/test/features/measurements/models/measurement_category_test.dart +++ b/test/features/measurements/models/measurement_category_test.dart @@ -43,4 +43,34 @@ void main() { expect(() => category.findEntryById('abc'), throwsA(isA())); }); }); + + group('MetricType', () { + test('fromWire maps a known wire value to its enum case', () { + expect(MetricType.fromWire('body_fat'), MetricType.bodyFat); + expect(MetricType.fromWire('blood_pressure'), MetricType.bloodPressure); + expect(MetricType.fromWire('custom'), MetricType.custom); + }); + + test('fromWire defaults to custom for an unknown value', () { + expect(MetricType.fromWire('something_new'), MetricType.custom); + expect(MetricType.fromWire(''), MetricType.custom); + }); + + test('wireValue round-trips through fromWire for every case', () { + for (final type in MetricType.values) { + expect(MetricType.fromWire(type.wireValue), type); + } + }); + + test('isSummedPerDay is true only for cumulative daily metrics', () { + expect(MetricType.steps.isSummedPerDay, isTrue); + expect(MetricType.distance.isSummedPerDay, isTrue); + expect(MetricType.energy.isSummedPerDay, isTrue); + expect(MetricType.sleep.isSummedPerDay, isTrue); + + expect(MetricType.custom.isSummedPerDay, isFalse); + expect(MetricType.bodyWeight.isSummedPerDay, isFalse); + expect(MetricType.heartRate.isSummedPerDay, isFalse); + }); + }); } diff --git a/test/features/measurements/widgets/charts_test.dart b/test/features/measurements/widgets/charts_test.dart new file mode 100644 index 000000000..0043acfc3 --- /dev/null +++ b/test/features/measurements/widgets/charts_test.dart @@ -0,0 +1,105 @@ +/* + * 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/features/measurements/widgets/charts.dart'; + +void main() { + MeasurementChartEntry entry(num value, DateTime date) => MeasurementChartEntry(value, date); + + group('aggregatePerDay', () { + test('returns an empty list for no entries', () { + expect(aggregatePerDay([]), isEmpty); + }); + + test('sums entries sharing a calendar day into one point', () { + final result = aggregatePerDay([ + entry(1000, DateTime(2026, 1, 1, 8)), + entry(2500, DateTime(2026, 1, 1, 20)), + ]); + + expect(result.length, 1); + expect(result.single.value, 3500); + // time-of-day is stripped to the day boundary + expect(result.single.date, DateTime(2026, 1, 1)); + }); + + test('keeps separate days apart and sorts them ascending', () { + final result = aggregatePerDay([ + entry(30, DateTime(2026, 1, 3)), + entry(10, DateTime(2026, 1, 1, 6)), + entry(5, DateTime(2026, 1, 1, 23)), + entry(20, DateTime(2026, 1, 2)), + ]); + + expect(result.map((e) => e.date), [ + DateTime(2026, 1, 1), + DateTime(2026, 1, 2), + DateTime(2026, 1, 3), + ]); + expect(result.map((e) => e.value), [15, 20, 30]); + }); + }); + + group('smoothedTrendline', () { + test('returns an empty list for no entries', () { + expect(smoothedTrendline([]), isEmpty); + }); + + test('seeds the first point with the raw value and keeps the dates', () { + final input = [ + entry(10, DateTime(2026, 1, 1)), + entry(20, DateTime(2026, 1, 2)), + entry(30, DateTime(2026, 1, 3)), + ]; + final result = smoothedTrendline(input, period: 10); + + expect(result.length, 3); + expect(result.first.value, 10); // seed == first raw value + expect(result.map((e) => e.date), input.map((e) => e.date)); + }); + + test('EMA follows a rising series but lags behind the raw values', () { + final result = smoothedTrendline([ + entry(10, DateTime(2026, 1, 1)), + entry(20, DateTime(2026, 1, 2)), + entry(30, DateTime(2026, 1, 3)), + ], period: 10); + + // smoothing k = 2 / (10 + 1) ~= 0.1818 + // point 2: 20*k + 10*(1-k) = 11.818... + expect(result[1].value, closeTo(11.818, 0.001)); + // point 3: 30*k + 11.818*(1-k) = 15.123... + expect(result[2].value, closeTo(15.123, 0.001)); + // trend trails the raw climb + expect(result[2].value, lessThan(30)); + }); + + test('sorts unordered input by date before smoothing', () { + final result = smoothedTrendline([ + entry(30, DateTime(2026, 1, 3)), + entry(10, DateTime(2026, 1, 1)), + entry(20, DateTime(2026, 1, 2)), + ], period: 10); + + expect(result.first.date, DateTime(2026, 1, 1)); + expect(result.first.value, 10); + expect(result.last.date, DateTime(2026, 1, 3)); + }); + }); +} From 8aac3da7a8bc3a5d486c86259a938e7f35f6e4c0 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 10 Jul 2026 15:46:42 +0200 Subject: [PATCH 024/484] Add workaround for swift package manager for the health package --- ios/Flutter/Debug.xcconfig | 1 - ios/Flutter/Release.xcconfig | 1 - ios/Runner.xcodeproj/project.pbxproj | 14 +++---------- lib/features/health/models/health_metric.dart | 2 +- .../health/models/health_reading.dart | 2 +- .../health/providers/health_repository.dart | 2 +- .../health/providers/health_sync.dart | 2 +- pubspec.lock | 21 +++++++------------ pubspec.yaml | 10 ++++++++- .../health/providers/health_sync_test.dart | 2 +- .../providers/health_sync_test.mocks.dart | 2 +- 11 files changed, 25 insertions(+), 34 deletions(-) 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/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/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/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..0fde5d99f 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; From 066d6430d870123a7d5662eb441d22e0ee13d65c Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 10 Jul 2026 16:18:48 +0200 Subject: [PATCH 025/484] Refactor the data model for multi-value categories Measurement categories can optionally point to another category, In practice, this will just be something like blood pressure since these values only make sense in a pair. Others can be interesting while combined (heart rate and steps), but are valid on their own. --- .../dashboard/widgets/measurements.dart | 5 +- lib/database/powersync/database.g.dart | 232 +++++++++++++++++- .../powersync/tables/measurements.dart | 19 +- .../models/measurement_category.dart | 24 ++ .../models/measurement_category.freezed.dart | 23 +- .../providers/measurement_notifier.dart | 6 + .../providers/measurement_notifier.g.dart | 2 +- .../providers/measurement_repository.dart | 34 ++- .../measurements/widgets/categories.dart | 16 +- .../measurements/widgets/categories_card.dart | 63 +++++ lib/features/measurements/widgets/forms.dart | 141 +++++++++++ lib/l10n/app_en.arb | 8 + test/core/validators_test.mocks.dart | 22 ++ .../providers/health_sync_test.mocks.dart | 11 + .../measurement_notifier_test.mocks.dart | 11 + .../measurement_repository_test.dart | 65 +++++ ...surement_categories_screen_test.mocks.dart | 11 + ...measurement_entries_screen_test.mocks.dart | 11 + .../screenshots_01_dashboard.mocks.dart | 11 + .../screenshots_04_measurements.mocks.dart | 11 + 20 files changed, 702 insertions(+), 24 deletions(-) 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 b59893272..cd16325a6 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -34,11 +34,28 @@ class MeasurementCategoryTable extends Table { TextColumn get unit => text()(); TextColumn get metricType => text().named('metric_type').map(const MeasurementMetricTypeConverter())(); + + /// 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( 'measurements_category', - [ps.Column.text('name'), ps.Column.text('unit'), ps.Column.text('metric_type')], + [ + 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/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index 47f72165f..24eca5553 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -103,14 +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, @@ -125,6 +147,8 @@ 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 8c8f6471f..eea5be3b3 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 06ce035fd..05b293ea7 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'); @@ -50,6 +54,7 @@ class MeasurementRepository { _db.measurementEntryTable.categoryId.equalsExp(_db.measurementCategoryTable.id), ), ])..orderBy([ + OrderingTerm(expression: _db.measurementCategoryTable.order), OrderingTerm(expression: _db.measurementCategoryTable.name), OrderingTerm(expression: _db.measurementEntryTable.date, mode: OrderingMode.desc), ]); @@ -71,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(); }); } @@ -102,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 4e45bb7d6..c0b232432 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -588,6 +588,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/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.mocks.dart b/test/features/health/providers/health_sync_test.mocks.dart index 0fde5d99f..db9fef171 100644 --- a/test/features/health/providers/health_sync_test.mocks.dart +++ b/test/features/health/providers/health_sync_test.mocks.dart @@ -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( From 29032dec408027524f11c13e03e3df7e48768f02 Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Fri, 10 Jul 2026 21:06:16 +0545 Subject: [PATCH 026/484] feat(measurements): add order field to MeasurementCategory model and drag-and-drop category sort screen - sort categories by order and implement reorder logic --- .../powersync/tables/measurements.dart | 8 ++- .../models/measurement_category.dart | 5 ++ .../providers/measurement_notifier.dart | 14 +++++ .../providers/measurement_repository.dart | 11 +++- .../measurement_categories_screen.dart | 16 ++++- .../measurement_category_sort_screen.dart | 59 +++++++++++++++++++ lib/l10n/app_en.arb | 4 ++ lib/main.dart | 2 + 8 files changed, 115 insertions(+), 4 deletions(-) create mode 100644 lib/features/measurements/screens/measurement_category_sort_screen.dart diff --git a/lib/database/powersync/tables/measurements.dart b/lib/database/powersync/tables/measurements.dart index b59893272..7e6e0aee2 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -34,11 +34,17 @@ class MeasurementCategoryTable extends Table { TextColumn get unit => text()(); TextColumn get metricType => text().named('metric_type').map(const MeasurementMetricTypeConverter())(); + IntColumn get order => integer().nullable()(); } const PowersyncMeasurementCategoryTable = ps.Table( 'measurements_category', - [ps.Column.text('name'), ps.Column.text('unit'), ps.Column.text('metric_type')], + [ + ps.Column.text('name'), + ps.Column.text('unit'), + ps.Column.text('metric_type'), + ps.Column.integer('order'), + ], ); @UseRowClass(MeasurementEntry) diff --git a/lib/features/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index 47f72165f..3bf552ffd 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -103,12 +103,16 @@ class MeasurementCategory with _$MeasurementCategory { @override final MetricType metricType; + @override + final int order; + MeasurementCategory({ this.id, this.name = '', this.unit = '', this.entries = const [], this.metricType = MetricType.custom, + this.order = 0, }); MeasurementEntry findEntryById(String id) { @@ -125,6 +129,7 @@ class MeasurementCategory with _$MeasurementCategory { name: Value(name), unit: Value(unit), metricType: Value(metricType), + order: Value(order), ); } } diff --git a/lib/features/measurements/providers/measurement_notifier.dart b/lib/features/measurements/providers/measurement_notifier.dart index 8c8f6471f..59d8f4e6c 100644 --- a/lib/features/measurements/providers/measurement_notifier.dart +++ b/lib/features/measurements/providers/measurement_notifier.dart @@ -84,4 +84,18 @@ final class MeasurementNotifier extends _$MeasurementNotifier { Future addCategory(MeasurementCategory category) async { await _repo.addLocalDriftCategory(category); } + + Future setCategoryOrder(int oldIndex, int newIndex) async { + final categories = state.asData?.value; + if (categories == null) return; + if (oldIndex < newIndex) newIndex -= 1; + + final reordered = List.from(categories); + final moved = reordered.removeAt(oldIndex); + reordered.insert(newIndex, moved); + + for (int i = 0; i < reordered.length; i++) { + await _repo.reorderCategory(reordered[i].id!, i); + } + } } diff --git a/lib/features/measurements/providers/measurement_repository.dart b/lib/features/measurements/providers/measurement_repository.dart index 06ce035fd..55216cb19 100644 --- a/lib/features/measurements/providers/measurement_repository.dart +++ b/lib/features/measurements/providers/measurement_repository.dart @@ -50,8 +50,9 @@ class MeasurementRepository { _db.measurementEntryTable.categoryId.equalsExp(_db.measurementCategoryTable.id), ), ])..orderBy([ + OrderingTerm(expression: _db.measurementCategoryTable.order), OrderingTerm(expression: _db.measurementCategoryTable.name), - OrderingTerm(expression: _db.measurementEntryTable.date, mode: OrderingMode.desc), + // OrderingTerm(expression: _db.measurementEntryTable.date, mode: OrderingMode.desc), ]); return joined.watch().map((rows) { @@ -118,4 +119,12 @@ class MeasurementRepository { _logger.finer('Adding local measurement category ${category.name}'); await _db.into(_db.measurementCategoryTable).insert(category.toCompanion()); } + + Future reorderCategory(String id, int newOrder) async { + _logger.finer('Reording category id $id to order $newOrder'); + final stmt = _db.update(_db.measurementCategoryTable)..where((t) => t.id.equals(id)); + await stmt.write( + MeasurementCategoryTableCompanion(order: Value(newOrder)), + ); + } } diff --git a/lib/features/measurements/screens/measurement_categories_screen.dart b/lib/features/measurements/screens/measurement_categories_screen.dart index 985f020fd..abe8aa646 100644 --- a/lib/features/measurements/screens/measurement_categories_screen.dart +++ b/lib/features/measurements/screens/measurement_categories_screen.dart @@ -19,6 +19,7 @@ import 'package:flutter/material.dart'; import 'package:wger/core/form_screen.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/features/measurements/screens/measurement_category_sort_screen.dart'; import 'package:wger/features/measurements/widgets/categories.dart'; import 'package:wger/features/measurements/widgets/forms.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -30,8 +31,19 @@ class MeasurementCategoriesScreen extends StatelessWidget { @override Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); return Scaffold( - appBar: AppBar(title: Text(AppLocalizations.of(context).measurements)), + appBar: AppBar( + title: Text(AppLocalizations.of(context).measurements), + actions: [ + IconButton( + icon: Icon(Icons.sort), + tooltip: i18n.reorderCategories, + onPressed: () => + Navigator.of(context).pushNamed(MeasurementCategorySortScreen.routeName), + ), + ], + ), floatingActionButton: FloatingActionButton( child: const Icon(Icons.add, color: Colors.white), onPressed: () { @@ -39,7 +51,7 @@ class MeasurementCategoriesScreen extends StatelessWidget { context, FormScreen.routeName, arguments: FormScreenArguments( - AppLocalizations.of(context).newEntry, + i18n.newEntry, const MeasurementCategoryForm(), ), ); diff --git a/lib/features/measurements/screens/measurement_category_sort_screen.dart b/lib/features/measurements/screens/measurement_category_sort_screen.dart new file mode 100644 index 000000000..cbf4ef071 --- /dev/null +++ b/lib/features/measurements/screens/measurement_category_sort_screen.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/core/widgets/async_value_widget.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/providers/measurement_notifier.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +class MeasurementCategorySortScreen extends ConsumerWidget { + static const routeName = '/measurement-categories-sort'; + + const MeasurementCategorySortScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final i18n = AppLocalizations.of(context); + return Scaffold( + appBar: AppBar( + title: Text(i18n.reorderCategories), + ), + body: WidescreenWrapper( + child: AsyncValueWidget>( + value: ref.watch(measurementProvider), + loggerName: 'MeasurementCategorySortScreen', + data: (categories) => _SortableList(categories), + ), + ), + ); + } +} + +class _SortableList extends ConsumerWidget { + final List _categories; + const _SortableList(this._categories); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final notifier = ref.read(measurementProvider.notifier); + return ReorderableListView.builder( + // physics: const NeverScrollableScrollPhysics(), + // shrinkWrap: true, + // buildDefaultDragHandles: false, + itemCount: _categories.length, + itemBuilder: (context, index) { + final category = _categories[index]; + return ListTile( + key: ValueKey(category.id), + title: Text(category.name), + subtitle: Text(category.unit), + trailing: ReorderableDelayedDragStartListener( + index: index, + child: const Icon(Icons.drag_handle), + ), + ); + }, + onReorderItem: (oldIndex, newIndex) => notifier.setCategoryOrder(oldIndex, newIndex), + ); + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 4e45bb7d6..90930f8f0 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -546,6 +546,10 @@ "@metricType": { "description": "Metric type for a measurement category" }, + "reorderCategories": "Reorder categories", + "@reorderCategories": { + "description": "measurement categories reordering" + }, "metricCustom": "Custom", "@metricCustom": { "description": "Label for custom metric type" diff --git a/lib/main.dart b/lib/main.dart index 74d053ce9..2a5cb29ff 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -51,6 +51,7 @@ import 'package:wger/features/exercises/screens/exercise_screen.dart'; import 'package:wger/features/exercises/screens/exercises_screen.dart'; import 'package:wger/features/gallery/screens/gallery_screen.dart'; import 'package:wger/features/measurements/screens/measurement_categories_screen.dart'; +import 'package:wger/features/measurements/screens/measurement_category_sort_screen.dart'; import 'package:wger/features/measurements/screens/measurement_entries_screen.dart'; import 'package:wger/features/nutrition/screens/ingredient_detail_screen.dart'; import 'package:wger/features/nutrition/screens/ingredients_screen.dart'; @@ -206,6 +207,7 @@ class MainApp extends ConsumerWidget { GymModeScreen.routeName: (ctx) => const GymModeScreen(), HomeTabsScreen.routeName: (ctx) => const HomeTabsScreen(), MeasurementCategoriesScreen.routeName: (ctx) => const MeasurementCategoriesScreen(), + MeasurementCategorySortScreen.routeName: (ctx) => const MeasurementCategorySortScreen(), MeasurementEntriesScreen.routeName: (ctx) => const MeasurementEntriesScreen(), NutritionalPlansScreen.routeName: (ctx) => const NutritionalPlansScreen(), NutritionalDiaryScreen.routeName: (ctx) => const NutritionalDiaryScreen(), From cbb960bdef3054b1cea707fdfebf1b4260be1f5b Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 00:31:35 +0200 Subject: [PATCH 027/484] Filter out sub-categories, fix off-by-one index --- .../providers/measurement_notifier.dart | 16 +- .../providers/measurement_notifier.g.dart | 2 +- .../providers/measurement_repository.dart | 20 ++- .../measurement_categories_screen.dart | 2 +- .../measurement_category_sort_screen.dart | 138 +++++++++-------- .../providers/health_sync_test.mocks.dart | 9 ++ .../providers/measurement_notifier_test.dart | 59 ++++++++ .../measurement_notifier_test.mocks.dart | 9 ++ .../measurement_repository_test.dart | 36 +++++ ...surement_categories_screen_test.mocks.dart | 9 ++ ...measurement_category_sort_screen_test.dart | 89 +++++++++++ ...ement_category_sort_screen_test.mocks.dart | 139 ++++++++++++++++++ ...measurement_entries_screen_test.mocks.dart | 9 ++ .../screenshots_01_dashboard.mocks.dart | 9 ++ .../screenshots_04_measurements.mocks.dart | 9 ++ 15 files changed, 481 insertions(+), 74 deletions(-) create mode 100644 test/features/measurements/screens/measurement_category_sort_screen_test.dart create mode 100644 test/features/measurements/screens/measurement_category_sort_screen_test.mocks.dart diff --git a/lib/features/measurements/providers/measurement_notifier.dart b/lib/features/measurements/providers/measurement_notifier.dart index 593020fd0..2f86c12ca 100644 --- a/lib/features/measurements/providers/measurement_notifier.dart +++ b/lib/features/measurements/providers/measurement_notifier.dart @@ -91,17 +91,21 @@ final class MeasurementNotifier extends _$MeasurementNotifier { await _repo.addLocalDriftCategory(category); } + /// Moves the top-level category at [oldIndex] to [newIndex] and renumbers + /// all top-level categories accordingly. + /// + /// Indices refer to the top-level list only (children of multi-value groups + /// keep their in-group order). Future setCategoryOrder(int oldIndex, int newIndex) async { final categories = state.asData?.value; - if (categories == null) return; - if (oldIndex < newIndex) newIndex -= 1; + if (categories == null) { + return; + } - final reordered = List.from(categories); + final reordered = categories.where((c) => c.parentId == null).toList(); final moved = reordered.removeAt(oldIndex); reordered.insert(newIndex, moved); - for (int i = 0; i < reordered.length; i++) { - await _repo.reorderCategory(reordered[i].id!, i); - } + await _repo.reorderCategories([for (final c in reordered) c.id!]); } } diff --git a/lib/features/measurements/providers/measurement_notifier.g.dart b/lib/features/measurements/providers/measurement_notifier.g.dart index 270cb246e..561817c74 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'397b6739b5d49e226b1ca3bb1837b2f16c55e0f7'; +String _$measurementNotifierHash() => r'2072d9a5dd3b0c64830913541d236f5dfe28fbbc'; 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 ae2ed4559..fa24db21c 100644 --- a/lib/features/measurements/providers/measurement_repository.dart +++ b/lib/features/measurements/providers/measurement_repository.dart @@ -56,7 +56,7 @@ class MeasurementRepository { ])..orderBy([ OrderingTerm(expression: _db.measurementCategoryTable.order), OrderingTerm(expression: _db.measurementCategoryTable.name), - // OrderingTerm(expression: _db.measurementEntryTable.date, mode: OrderingMode.desc), + OrderingTerm(expression: _db.measurementEntryTable.date, mode: OrderingMode.desc), ]); return joined.watch().map((rows) { @@ -147,11 +147,17 @@ class MeasurementRepository { await _db.into(_db.measurementCategoryTable).insert(category.toCompanion()); } - Future reorderCategory(String id, int newOrder) async { - _logger.finer('Reording category id $id to order $newOrder'); - final stmt = _db.update(_db.measurementCategoryTable)..where((t) => t.id.equals(id)); - await stmt.write( - MeasurementCategoryTableCompanion(order: Value(newOrder)), - ); + /// Persists the given display order: each category gets its list index as + /// [MeasurementCategory.order]. Categories whose order is unchanged are not + /// written, so no sync upload is queued for them. + Future reorderCategories(List orderedIds) async { + _logger.finer('Reordering ${orderedIds.length} categories'); + await _db.transaction(() async { + for (var i = 0; i < orderedIds.length; i++) { + final stmt = _db.update(_db.measurementCategoryTable) + ..where((t) => t.id.equals(orderedIds[i]) & t.order.equals(i).not()); + await stmt.write(MeasurementCategoryTableCompanion(order: Value(i))); + } + }); } } diff --git a/lib/features/measurements/screens/measurement_categories_screen.dart b/lib/features/measurements/screens/measurement_categories_screen.dart index abe8aa646..51393e67b 100644 --- a/lib/features/measurements/screens/measurement_categories_screen.dart +++ b/lib/features/measurements/screens/measurement_categories_screen.dart @@ -37,7 +37,7 @@ class MeasurementCategoriesScreen extends StatelessWidget { title: Text(AppLocalizations.of(context).measurements), actions: [ IconButton( - icon: Icon(Icons.sort), + icon: const Icon(Icons.sort), tooltip: i18n.reorderCategories, onPressed: () => Navigator.of(context).pushNamed(MeasurementCategorySortScreen.routeName), diff --git a/lib/features/measurements/screens/measurement_category_sort_screen.dart b/lib/features/measurements/screens/measurement_category_sort_screen.dart index cbf4ef071..96675dce8 100644 --- a/lib/features/measurements/screens/measurement_category_sort_screen.dart +++ b/lib/features/measurements/screens/measurement_category_sort_screen.dart @@ -1,59 +1,79 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:wger/core/wide_screen_wrapper.dart'; -import 'package:wger/core/widgets/async_value_widget.dart'; -import 'package:wger/features/measurements/models/measurement_category.dart'; -import 'package:wger/features/measurements/providers/measurement_notifier.dart'; -import 'package:wger/l10n/generated/app_localizations.dart'; - -class MeasurementCategorySortScreen extends ConsumerWidget { - static const routeName = '/measurement-categories-sort'; - - const MeasurementCategorySortScreen({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final i18n = AppLocalizations.of(context); - return Scaffold( - appBar: AppBar( - title: Text(i18n.reorderCategories), - ), - body: WidescreenWrapper( - child: AsyncValueWidget>( - value: ref.watch(measurementProvider), - loggerName: 'MeasurementCategorySortScreen', - data: (categories) => _SortableList(categories), - ), - ), - ); - } -} - -class _SortableList extends ConsumerWidget { - final List _categories; - const _SortableList(this._categories); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final notifier = ref.read(measurementProvider.notifier); - return ReorderableListView.builder( - // physics: const NeverScrollableScrollPhysics(), - // shrinkWrap: true, - // buildDefaultDragHandles: false, - itemCount: _categories.length, - itemBuilder: (context, index) { - final category = _categories[index]; - return ListTile( - key: ValueKey(category.id), - title: Text(category.name), - subtitle: Text(category.unit), - trailing: ReorderableDelayedDragStartListener( - index: index, - child: const Icon(Icons.drag_handle), - ), - ); - }, - onReorderItem: (oldIndex, newIndex) => notifier.setCategoryOrder(oldIndex, newIndex), - ); - } -} +/* + * 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/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/core/widgets/async_value_widget.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/providers/measurement_notifier.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Drag-and-drop reordering of the top-level measurement categories. +/// +/// Children of multi-value groups are not listed; they keep their in-group +/// order and follow their parent. +class MeasurementCategorySortScreen extends ConsumerWidget { + static const routeName = '/measurement-categories-sort'; + + const MeasurementCategorySortScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final i18n = AppLocalizations.of(context); + return Scaffold( + appBar: AppBar( + title: Text(i18n.reorderCategories), + ), + body: WidescreenWrapper( + child: AsyncValueWidget>( + value: ref.watch(measurementProvider), + loggerName: 'MeasurementCategorySortScreen', + data: (categories) => _SortableList(categories.where((c) => c.parentId == null).toList()), + ), + ), + ); + } +} + +class _SortableList extends ConsumerWidget { + final List _categories; + const _SortableList(this._categories); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final notifier = ref.read(measurementProvider.notifier); + return ReorderableListView.builder( + buildDefaultDragHandles: false, + itemCount: _categories.length, + itemBuilder: (context, index) { + final category = _categories[index]; + return ListTile( + key: ValueKey(category.id), + title: Text(category.name), + subtitle: Text(category.unit), + trailing: ReorderableDragStartListener( + index: index, + child: const Icon(Icons.drag_handle), + ), + ); + }, + onReorderItem: notifier.setCategoryOrder, + ); + } +} diff --git a/test/features/health/providers/health_sync_test.mocks.dart b/test/features/health/providers/health_sync_test.mocks.dart index db9fef171..952330127 100644 --- a/test/features/health/providers/health_sync_test.mocks.dart +++ b/test/features/health/providers/health_sync_test.mocks.dart @@ -185,4 +185,13 @@ class MockMeasurementRepository extends _i1.Mock implements _i7.MeasurementRepos returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); + + @override + _i4.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } diff --git a/test/features/measurements/providers/measurement_notifier_test.dart b/test/features/measurements/providers/measurement_notifier_test.dart index f1987e09f..0075fb560 100644 --- a/test/features/measurements/providers/measurement_notifier_test.dart +++ b/test/features/measurements/providers/measurement_notifier_test.dart @@ -20,6 +20,7 @@ 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/features/measurements/models/measurement_category.dart'; import 'package:wger/features/measurements/providers/measurement_notifier.dart'; import 'package:wger/features/measurements/providers/measurement_repository.dart'; @@ -102,4 +103,62 @@ void main() { verify(mockRepo.watchAll()).called(1); }); }); + + group('setCategoryOrder', () { + // Body fat ('1') and Biceps ('2') from the shared test data plus a third + // top-level category. + final categories = [ + ...getMeasurementCategories(), + MeasurementCategory(id: '3', name: 'Waist', unit: 'cm'), + ]; + + setUp(() { + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(categories)); + when(mockRepo.reorderCategories(any)).thenAnswer((_) async {}); + }); + + // Loads the notifier with its state resolved from the watchAll stream. + Future loadedNotifier() async { + container.listen(measurementProvider, (_, _) {}); + await pumpEventQueue(); + return container.read(measurementProvider.notifier); + } + + test('moves an item down (newIndex already adjusted, onReorderItem semantics)', () async { + final notifier = await loadedNotifier(); + + await notifier.setCategoryOrder(0, 2); + verify(mockRepo.reorderCategories(['2', '3', '1'])).called(1); + }); + + test('moves an item up', () async { + final notifier = await loadedNotifier(); + + await notifier.setCategoryOrder(2, 0); + verify(mockRepo.reorderCategories(['3', '1', '2'])).called(1); + }); + + test('excludes children of multi-value groups', () async { + when(mockRepo.watchAll()).thenAnswer( + (_) => Stream.value([ + categories[0], + MeasurementCategory(id: '2a', name: 'Left', unit: 'cm', parentId: '2'), + categories[1], + categories[2], + ]), + ); + final notifier = await loadedNotifier(); + + await notifier.setCategoryOrder(0, 1); + verify(mockRepo.reorderCategories(['2', '1', '3'])).called(1); + }); + + test('does nothing while the list is still loading', () async { + when(mockRepo.watchAll()).thenAnswer((_) => const Stream.empty()); + final notifier = await loadedNotifier(); + + await notifier.setCategoryOrder(0, 1); + verifyNever(mockRepo.reorderCategories(any)); + }); + }); } diff --git a/test/features/measurements/providers/measurement_notifier_test.mocks.dart b/test/features/measurements/providers/measurement_notifier_test.mocks.dart index baf6519c2..28cd63948 100644 --- a/test/features/measurements/providers/measurement_notifier_test.mocks.dart +++ b/test/features/measurements/providers/measurement_notifier_test.mocks.dart @@ -127,4 +127,13 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); + + @override + _i3.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } diff --git a/test/features/measurements/providers/measurement_repository_test.dart b/test/features/measurements/providers/measurement_repository_test.dart index 36ec5ab7e..f35f0c798 100644 --- a/test/features/measurements/providers/measurement_repository_test.dart +++ b/test/features/measurements/providers/measurement_repository_test.dart @@ -287,4 +287,40 @@ void main() { expect(emitted, isEmpty); }); }); + + group('reorderCategories', () { + test('persists the list positions as order', () async { + await repo.addLocalDriftCategory(MeasurementCategory(id: 'c1', name: 'Aaa', unit: 'cm')); + await repo.addLocalDriftCategory(MeasurementCategory(id: 'c2', name: 'Bbb', unit: 'cm')); + await repo.addLocalDriftCategory(MeasurementCategory(id: 'c3', name: 'Ccc', unit: 'cm')); + + await repo.reorderCategories(['c3', 'c1', 'c2']); + + final emitted = await repo.watchAll().first; + expect(emitted.map((c) => c.id), ['c3', 'c1', 'c2']); + expect(emitted.map((c) => c.order), [0, 1, 2]); + }); + + test('keeps the in-group order of children', () 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), + ); + await repo.addLocalDriftCategory( + MeasurementCategory(id: 'c1', name: 'Waist', unit: 'cm', order: 1), + ); + + await repo.reorderCategories(['c1', 'bp']); + + final emitted = await repo.watchAll().first; + final parent = emitted.firstWhere((c) => c.id == 'bp'); + expect(parent.order, 1); + expect(parent.children.map((c) => c.id), ['sys', 'dia']); + }); + }); } 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 8fa32a7e8..743054ede 100644 --- a/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart +++ b/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart @@ -127,4 +127,13 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); + + @override + _i3.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } diff --git a/test/features/measurements/screens/measurement_category_sort_screen_test.dart b/test/features/measurements/screens/measurement_category_sort_screen_test.dart new file mode 100644 index 000000000..884de8d15 --- /dev/null +++ b/test/features/measurements/screens/measurement_category_sort_screen_test.dart @@ -0,0 +1,89 @@ +/* + * 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/material.dart'; +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/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/providers/measurement_repository.dart'; +import 'package:wger/features/measurements/screens/measurement_category_sort_screen.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../../../test_data/measurements.dart'; +import 'measurement_category_sort_screen_test.mocks.dart'; + +@GenerateMocks([MeasurementRepository]) +void main() { + late MockMeasurementRepository mockRepo; + + // Body fat ('1') and Biceps ('2') from the shared test data plus a third + // top-level category and a group child. + final categories = [ + ...getMeasurementCategories(), + MeasurementCategory(id: '2a', name: 'Left', unit: 'cm', parentId: '2'), + MeasurementCategory(id: '3', name: 'Waist', unit: 'cm'), + ]; + + setUp(() { + mockRepo = MockMeasurementRepository(); + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(categories)); + when(mockRepo.reorderCategories(any)).thenAnswer((_) async {}); + }); + + Widget createSortScreen() { + return ProviderScope( + overrides: [ + measurementRepositoryProvider.overrideWithValue(mockRepo), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: MeasurementCategorySortScreen(), + ), + ); + } + + testWidgets('lists only top-level categories', (tester) async { + await tester.pumpWidget(createSortScreen()); + await tester.pumpAndSettle(); + + expect(find.text('Body fat'), findsOneWidget); + expect(find.text('Biceps'), findsOneWidget); + expect(find.text('Waist'), findsOneWidget); + expect(find.text('Left'), findsNothing); + expect(find.byIcon(Icons.drag_handle), findsNWidgets(3)); + }); + + testWidgets('dragging an item to the bottom persists the new order', (tester) async { + await tester.pumpWidget(createSortScreen()); + await tester.pumpAndSettle(); + + final firstHandle = find.byIcon(Icons.drag_handle).first; + final itemHeight = tester.getSize(find.byType(ListTile).first).height; + await tester.timedDrag( + firstHandle, + Offset(0, itemHeight * 3), + const Duration(milliseconds: 300), + ); + await tester.pumpAndSettle(); + + verify(mockRepo.reorderCategories(['2', '3', '1'])).called(1); + }); +} diff --git a/test/features/measurements/screens/measurement_category_sort_screen_test.mocks.dart b/test/features/measurements/screens/measurement_category_sort_screen_test.mocks.dart new file mode 100644 index 000000000..fa002a9c4 --- /dev/null +++ b/test/features/measurements/screens/measurement_category_sort_screen_test.mocks.dart @@ -0,0 +1,139 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/features/measurements/screens/measurement_category_sort_screen_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/measurements/models/measurement_category.dart' as _i4; +import 'package:wger/features/measurements/models/measurement_entry.dart' as _i5; +import 'package:wger/features/measurements/providers/measurement_repository.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [MeasurementRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepository { + MockMeasurementRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Stream> watchAll() => + (super.noSuchMethod( + Invocation.method(#watchAll, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream<_i4.MeasurementCategory?> watchLocalDriftCategoryById( + String? id, + ) => + (super.noSuchMethod( + Invocation.method(#watchLocalDriftCategoryById, [id]), + returnValue: _i3.Stream<_i4.MeasurementCategory?>.empty(), + ) + as _i3.Stream<_i4.MeasurementCategory?>); + + @override + _i3.Future> getAllOnce() => + (super.noSuchMethod( + Invocation.method(#getAllOnce, []), + returnValue: _i3.Future>.value( + <_i4.MeasurementCategory>[], + ), + ) + as _i3.Future>); + + @override + _i3.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + 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( + Invocation.method(#deleteLocalDriftCategory, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDriftCategory( + _i4.MeasurementCategory? category, + ) => + (super.noSuchMethod( + Invocation.method(#updateLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDriftCategory(_i4.MeasurementCategory? category) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} 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 c31c80f05..5ca65e223 100644 --- a/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart +++ b/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart @@ -136,6 +136,15 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); + + @override + _i3.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } /// A class which mocks [NutritionRepository]. diff --git a/test/screenshots/screenshots_01_dashboard.mocks.dart b/test/screenshots/screenshots_01_dashboard.mocks.dart index f0af1a51a..ebe4614fd 100644 --- a/test/screenshots/screenshots_01_dashboard.mocks.dart +++ b/test/screenshots/screenshots_01_dashboard.mocks.dart @@ -548,6 +548,15 @@ class MockMeasurementRepository extends _i1.Mock implements _i23.MeasurementRepo returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); + + @override + _i10.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); } /// A class which mocks [UserProfileRepository]. diff --git a/test/screenshots/screenshots_04_measurements.mocks.dart b/test/screenshots/screenshots_04_measurements.mocks.dart index ab8aa659f..7272e698c 100644 --- a/test/screenshots/screenshots_04_measurements.mocks.dart +++ b/test/screenshots/screenshots_04_measurements.mocks.dart @@ -127,4 +127,13 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); + + @override + _i3.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } From 3fc33e1acc2d5140e7a6e1bead1b1b8bc3b693cf Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 00:37:10 +0200 Subject: [PATCH 028/484] Add multi-value measurements to the test data --- .../providers/measurement_notifier_test.dart | 22 ++++++------ .../measurement_repository_test.dart | 24 ++++--------- ...measurement_category_sort_screen_test.dart | 15 ++++---- test_data/measurements.dart | 34 +++++++++++++++++++ 4 files changed, 58 insertions(+), 37 deletions(-) diff --git a/test/features/measurements/providers/measurement_notifier_test.dart b/test/features/measurements/providers/measurement_notifier_test.dart index 0075fb560..6e78a5c65 100644 --- a/test/features/measurements/providers/measurement_notifier_test.dart +++ b/test/features/measurements/providers/measurement_notifier_test.dart @@ -20,7 +20,6 @@ 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/features/measurements/models/measurement_category.dart'; import 'package:wger/features/measurements/providers/measurement_notifier.dart'; import 'package:wger/features/measurements/providers/measurement_repository.dart'; @@ -105,11 +104,11 @@ void main() { }); group('setCategoryOrder', () { - // Body fat ('1') and Biceps ('2') from the shared test data plus a third - // top-level category. + // Three top-level categories: Body fat ('1'), Biceps ('2') and the blood + // pressure group parent ('bp'), whose children must stay untouched. final categories = [ ...getMeasurementCategories(), - MeasurementCategory(id: '3', name: 'Waist', unit: 'cm'), + ...getBloodPressureGroup(), ]; setUp(() { @@ -128,29 +127,30 @@ void main() { final notifier = await loadedNotifier(); await notifier.setCategoryOrder(0, 2); - verify(mockRepo.reorderCategories(['2', '3', '1'])).called(1); + verify(mockRepo.reorderCategories(['2', 'bp', '1'])).called(1); }); test('moves an item up', () async { final notifier = await loadedNotifier(); await notifier.setCategoryOrder(2, 0); - verify(mockRepo.reorderCategories(['3', '1', '2'])).called(1); + verify(mockRepo.reorderCategories(['bp', '1', '2'])).called(1); }); test('excludes children of multi-value groups', () async { + // Children interleaved between the top-level categories. when(mockRepo.watchAll()).thenAnswer( (_) => Stream.value([ - categories[0], - MeasurementCategory(id: '2a', name: 'Left', unit: 'cm', parentId: '2'), - categories[1], - categories[2], + testMeasurementCategorySystolic, + ...getMeasurementCategories(), + testMeasurementCategoryDiastolic, + testMeasurementCategoryBloodPressure, ]), ); final notifier = await loadedNotifier(); await notifier.setCategoryOrder(0, 1); - verify(mockRepo.reorderCategories(['2', '1', '3'])).called(1); + verify(mockRepo.reorderCategories(['2', '1', 'bp'])).called(1); }); test('does nothing while the list is still loading', () async { diff --git a/test/features/measurements/providers/measurement_repository_test.dart b/test/features/measurements/providers/measurement_repository_test.dart index f35f0c798..9868aab38 100644 --- a/test/features/measurements/providers/measurement_repository_test.dart +++ b/test/features/measurements/providers/measurement_repository_test.dart @@ -225,15 +225,9 @@ void main() { 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), - ); + for (final category in getBloodPressureGroup()) { + await repo.addLocalDriftCategory(category); + } } test('watchAll attaches children to their parent in group order', () async { @@ -302,15 +296,9 @@ void main() { }); test('keeps the in-group order of children', () 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), - ); + for (final category in getBloodPressureGroup()) { + await repo.addLocalDriftCategory(category); + } await repo.addLocalDriftCategory( MeasurementCategory(id: 'c1', name: 'Waist', unit: 'cm', order: 1), ); diff --git a/test/features/measurements/screens/measurement_category_sort_screen_test.dart b/test/features/measurements/screens/measurement_category_sort_screen_test.dart index 884de8d15..6b46b9e68 100644 --- a/test/features/measurements/screens/measurement_category_sort_screen_test.dart +++ b/test/features/measurements/screens/measurement_category_sort_screen_test.dart @@ -21,7 +21,6 @@ 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/features/measurements/models/measurement_category.dart'; import 'package:wger/features/measurements/providers/measurement_repository.dart'; import 'package:wger/features/measurements/screens/measurement_category_sort_screen.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -33,12 +32,11 @@ import 'measurement_category_sort_screen_test.mocks.dart'; void main() { late MockMeasurementRepository mockRepo; - // Body fat ('1') and Biceps ('2') from the shared test data plus a third - // top-level category and a group child. + // Three top-level categories: Body fat ('1'), Biceps ('2') and the blood + // pressure group parent ('bp'); its children must not be listed. final categories = [ ...getMeasurementCategories(), - MeasurementCategory(id: '2a', name: 'Left', unit: 'cm', parentId: '2'), - MeasurementCategory(id: '3', name: 'Waist', unit: 'cm'), + ...getBloodPressureGroup(), ]; setUp(() { @@ -66,8 +64,9 @@ void main() { expect(find.text('Body fat'), findsOneWidget); expect(find.text('Biceps'), findsOneWidget); - expect(find.text('Waist'), findsOneWidget); - expect(find.text('Left'), findsNothing); + expect(find.text('Blood pressure'), findsOneWidget); + expect(find.text('Systolic'), findsNothing); + expect(find.text('Diastolic'), findsNothing); expect(find.byIcon(Icons.drag_handle), findsNWidgets(3)); }); @@ -84,6 +83,6 @@ void main() { ); await tester.pumpAndSettle(); - verify(mockRepo.reorderCategories(['2', '3', '1'])).called(1); + verify(mockRepo.reorderCategories(['2', 'bp', '1'])).called(1); }); } diff --git a/test_data/measurements.dart b/test_data/measurements.dart index 3ada4ceea..73c237751 100644 --- a/test_data/measurements.dart +++ b/test_data/measurements.dart @@ -78,6 +78,40 @@ final testMeasurementEntry8 = MeasurementEntry( notes: '', ); +/// Multi-value group: blood pressure with systolic/diastolic components. +final testMeasurementCategoryBloodPressure = MeasurementCategory( + id: 'bp', + name: 'Blood pressure', + unit: 'mmHg', + metricType: MetricType.bloodPressure, +); + +final testMeasurementCategorySystolic = MeasurementCategory( + id: 'sys', + name: 'Systolic', + unit: 'mmHg', + parentId: 'bp', + order: 0, +); + +final testMeasurementCategoryDiastolic = MeasurementCategory( + id: 'dia', + name: 'Diastolic', + unit: 'mmHg', + parentId: 'bp', + order: 1, +); + +/// The blood pressure group as a flat list (parent first), as stored in the +/// database. Not included in [getMeasurementCategories]. +List getBloodPressureGroup() { + return [ + testMeasurementCategoryBloodPressure, + testMeasurementCategorySystolic, + testMeasurementCategoryDiastolic, + ]; +} + List getMeasurementCategories() { return [ MeasurementCategory( From 55cdd64fb31f4ba95822399da0983ade5bec716e Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 00:46:20 +0200 Subject: [PATCH 029/484] Fix trigger for CI --- .github/workflows/analyze.yml | 5 ++++- .github/workflows/ci.yml | 7 +++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/analyze.yml b/.github/workflows/analyze.yml index 4e7a67558..4d8b8b0f1 100644 --- a/.github/workflows/analyze.yml +++ b/.github/workflows/analyze.yml @@ -1,6 +1,10 @@ name: Analyze on: + # Direct pushes are only validated on master (post-merge); everything else + # is covered by the pull_request trigger, avoiding duplicate runs for + # same-repo PR branches. push: + branches: [ master, ] paths: - '**.dart' - 'pubspec.yaml' @@ -9,7 +13,6 @@ on: - 'ios/Runner/Info.plist' - 'android/app/src/main/res/xml/locales_config.xml' pull_request: - branches: [ master, ] paths: - '**/*.dart' - 'pubspec.yaml' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 89f67420b..5cb55563c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,11 +1,14 @@ -name: Continous Integration +name: Continuous Integration on: + # Direct pushes are only validated on master (post-merge); everything else + # is covered by the pull_request trigger, avoiding duplicate runs for + # same-repo PR branches. push: + branches: [ master, ] paths: - '**.dart' - 'pubspec.yaml' pull_request: - branches: [ master, ] paths: - '**/*.dart' - 'pubspec.yaml' From e81bb990ea3a4a47fd957930fec47542352b7581 Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Sun, 12 Jul 2026 13:47:45 +0545 Subject: [PATCH 030/484] test(measurements): add unit tests for chart rendering, aggregation, metric routing, and composite group cards (#1251) Validates MeasurementBarChartWidgetFl rendering, aggregatePerDay logic, buildChartForMetricType routing, and CategoriesCard group composition for multi-value metrics like blood pressure. --- .../build_chart_for_metric_type_test.dart | 67 +++++++++ .../widgets/categories_card_group_test.dart | 111 ++++++++++++++ .../measurements/widgets/charts_test.dart | 39 ++++- .../widgets/get_overview_widgets_test.dart | 135 ++++++++++++++++++ 4 files changed, 349 insertions(+), 3 deletions(-) create mode 100644 test/features/measurements/widgets/build_chart_for_metric_type_test.dart create mode 100644 test/features/measurements/widgets/categories_card_group_test.dart create mode 100644 test/features/measurements/widgets/get_overview_widgets_test.dart diff --git a/test/features/measurements/widgets/build_chart_for_metric_type_test.dart b/test/features/measurements/widgets/build_chart_for_metric_type_test.dart new file mode 100644 index 000000000..170df0afa --- /dev/null +++ b/test/features/measurements/widgets/build_chart_for_metric_type_test.dart @@ -0,0 +1,67 @@ +/* + * 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/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/widgets/charts.dart'; +import 'package:wger/features/measurements/widgets/helpers.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +Widget _wrapChart(Widget chart) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox(width: 400, height: 300, child: chart), + ), +); + +void main() { + final entries = [ + MeasurementChartEntry(1000, DateTime(2026, 1, 1)), + MeasurementChartEntry(2000, DateTime(2026, 1, 2)), + ]; + + group('buildChartForMetricType routing', () { + testWidgets('steps -> MeasurementBarChartWidgetFl', (tester) async { + final widget = buildChartForMetricType(MetricType.steps, entries, [], 'steps'); + await tester.pumpWidget(_wrapChart(widget)); + await tester.pumpAndSettle(); + + expect(find.byType(MeasurementBarChartWidgetFl), findsOneWidget); + expect(find.byType(MeasurementChartWidgetFl), findsNothing); + }); + + testWidgets('custom -> MeasurementChartWidgetFl', (tester) async { + final widget = buildChartForMetricType(MetricType.custom, entries, [], 'cm'); + await tester.pumpWidget(_wrapChart(widget)); + await tester.pumpAndSettle(); + + expect(find.byType(MeasurementChartWidgetFl), findsOneWidget); + expect(find.byType(MeasurementBarChartWidgetFl), findsNothing); + }); + + testWidgets('energy -> MeasurementBarChartWidgetFl', (tester) async { + final widget = buildChartForMetricType(MetricType.energy, entries, [], 'kcal'); + await tester.pumpWidget(_wrapChart(widget)); + await tester.pumpAndSettle(); + + expect(find.byType(MeasurementBarChartWidgetFl), findsOneWidget); + }); + }); +} diff --git a/test/features/measurements/widgets/categories_card_group_test.dart b/test/features/measurements/widgets/categories_card_group_test.dart new file mode 100644 index 000000000..6e6fc30dd --- /dev/null +++ b/test/features/measurements/widgets/categories_card_group_test.dart @@ -0,0 +1,111 @@ +/* + * 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/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/models/measurement_entry.dart'; +import 'package:wger/features/measurements/widgets/categories_card.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +Widget _wrap(Widget child) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + routes: { + '/form': (ctx) => const Scaffold(body: Text('form screen')), + }, + home: Scaffold(body: child), +); + +MeasurementCategory _bpGroup({bool withEntries = false}) { + final sysEntries = withEntries + ? [ + MeasurementEntry( + id: 'e1', + categoryId: 'sys', + date: DateTime(2026, 1, 1), + value: 120, + notes: '', + ), + ] + : []; + final diaEntries = withEntries + ? [ + MeasurementEntry( + id: 'e2', + categoryId: 'dia', + date: DateTime(2026, 1, 1), + value: 80, + notes: '', + ), + ] + : []; + + final sys = MeasurementCategory( + id: 'sys', + name: 'Systolic', + unit: 'mmHg', + parentId: 'bp', + order: 0, + entries: sysEntries, + ); + final dia = MeasurementCategory( + id: 'dia', + name: 'Diastolic', + unit: 'mmHg', + parentId: 'bp', + order: 1, + entries: diaEntries, + ); + + return MeasurementCategory( + id: 'bp', + name: 'Blood pressure', + unit: 'mmHg', + metricType: MetricType.bloodPressure, + children: [sys, dia], + ); +} + +void main() { + group('CategoriesCard — group card', () { + testWidgets('shows one ListTile per child with latest reading', (tester) async { + await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: true)))); + await tester.pumpAndSettle(); + + expect(find.byType(ListTile), findsNWidgets(2)); + expect(find.textContaining('120'), findsOneWidget); + expect(find.textContaining('80'), findsOneWidget); + }); + + testWidgets('shows dash when child has no entries', (tester) async { + await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: false)))); + await tester.pumpAndSettle(); + + // Text('—') should appear for both children + expect(find.text('—'), findsNWidgets(2)); + }); + + testWidgets('add icon button is present on group card', (tester) async { + await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup()))); + await tester.pumpAndSettle(); + + expect(find.byIcon(Icons.add), findsOneWidget); + }); + }); +} diff --git a/test/features/measurements/widgets/charts_test.dart b/test/features/measurements/widgets/charts_test.dart index 0043acfc3..73c85a75c 100644 --- a/test/features/measurements/widgets/charts_test.dart +++ b/test/features/measurements/widgets/charts_test.dart @@ -16,18 +16,51 @@ * along with this program. If not, see . */ +import 'package:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:wger/features/measurements/widgets/charts.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +Widget _wrap(Widget child) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox(width: 400, height: 300, child: child), + ), +); void main() { MeasurementChartEntry entry(num value, DateTime date) => MeasurementChartEntry(value, date); - group('aggregatePerDay', () { - test('returns an empty list for no entries', () { + group('MeasurementBarChartWidgetFl', () { + testWidgets('renders without error for empty entries', (tester) async { + await tester.pumpWidget( + _wrap(const MeasurementBarChartWidgetFl([], 'steps')), + ); + await tester.pumpAndSettle(); + expect(find.byType(MeasurementBarChartWidgetFl), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + // T-24 + testWidgets('BarChart is present for non-empty entries', (tester) async { + final entries = [ + entry(1000, DateTime(2026, 1, 1)), + entry(2000, DateTime(2026, 1, 2)), + entry(1500, DateTime(2026, 1, 3)), + ]; + await tester.pumpWidget(_wrap(MeasurementBarChartWidgetFl(entries, 'steps'))); + await tester.pumpAndSettle(); + + expect(find.byType(BarChart), findsOneWidget); + }); + + test('aggregatePerDay returns an empty list for no entries', () { expect(aggregatePerDay([]), isEmpty); }); - test('sums entries sharing a calendar day into one point', () { + test('aggregatePerDay sums entries sharing a calendar day into one point', () { final result = aggregatePerDay([ entry(1000, DateTime(2026, 1, 1, 8)), entry(2500, DateTime(2026, 1, 1, 20)), diff --git a/test/features/measurements/widgets/get_overview_widgets_test.dart b/test/features/measurements/widgets/get_overview_widgets_test.dart new file mode 100644 index 000000000..8a838b199 --- /dev/null +++ b/test/features/measurements/widgets/get_overview_widgets_test.dart @@ -0,0 +1,135 @@ +/* + * This file is part of wger Workout Manager . + * 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 + * 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/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/widgets/charts.dart'; +import 'package:wger/features/measurements/widgets/helpers.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +void main() { + final rawEntries = [ + MeasurementChartEntry(10, DateTime(2026, 1, 1)), + MeasurementChartEntry(20, DateTime(2026, 1, 10)), + ]; + final avgEntries = moving7dAverage(rawEntries); + + group('getOverviewWidgets', () { + testWidgets('empty raw shows no-data placeholder', (tester) async { + late List widgets; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (ctx) { + widgets = getOverviewWidgets('Test', [], [], 'cm', ctx); + return Scaffold( + body: SingleChildScrollView(child: Column(children: widgets)), + ); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('No data available'), findsOneWidget); + }); + + testWidgets('non-empty avg includes MeasurementOverallChangeWidget', (tester) async { + late List widgets; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (ctx) { + widgets = getOverviewWidgets('Test', rawEntries, avgEntries, 'cm', ctx); + return Scaffold( + body: SingleChildScrollView(child: Column(children: widgets)), + ); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(MeasurementOverallChangeWidget), findsOneWidget); + }); + }); + + group('getOverviewWidgetsSeries — Indicator legend', () { + testWidgets('three Indicator widgets for non-summed metric (custom)', (tester) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (ctx) { + final widgets = getOverviewWidgetsSeries( + 'Weight', + rawEntries, + avgEntries, + [], + 'kg', + ctx, + metricType: MetricType.custom, + ); + return Scaffold( + body: SingleChildScrollView(child: Column(children: widgets)), + ); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(Indicator), findsNWidgets(3)); + }); + + testWidgets('two Indicator widgets for summed metric (steps — no trend)', (tester) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (ctx) { + final widgets = getOverviewWidgetsSeries( + 'Steps', + rawEntries, + avgEntries, + [], + 'steps', + ctx, + metricType: MetricType.steps, + ); + return Scaffold( + body: SingleChildScrollView(child: Column(children: widgets)), + ); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + // isSummedPerDay -> trend indicator is hidden + expect(find.byType(Indicator), findsNWidgets(2)); + }); + }); +} From 5c129bbb7d029520513bf9ded6b737e8be62ff8f Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Mon, 13 Jul 2026 15:08:44 +0545 Subject: [PATCH 031/484] test(measurements): add GroupMeasurementEntryForm widget tests and addGroupEntries notifier unit tests --- .../providers/measurement_notifier_test.dart | 19 ++++ .../widgets/categories_card_group_test.dart | 53 ++-------- .../group_measurement_entry_form_test.dart | 96 +++++++++++++++++++ test_data/measurements.dart | 17 ++++ 4 files changed, 139 insertions(+), 46 deletions(-) create mode 100644 test/features/measurements/widgets/group_measurement_entry_form_test.dart diff --git a/test/features/measurements/providers/measurement_notifier_test.dart b/test/features/measurements/providers/measurement_notifier_test.dart index 6e78a5c65..aef364810 100644 --- a/test/features/measurements/providers/measurement_notifier_test.dart +++ b/test/features/measurements/providers/measurement_notifier_test.dart @@ -40,6 +40,8 @@ void main() { when(mockRepo.updateLocalDrift(any)).thenAnswer((_) async {}); when(mockRepo.addLocalDrift(any)).thenAnswer((_) async {}); + when(mockRepo.addLocalDriftGroupEntries(any)).thenAnswer((_) async {}); + when(mockRepo.deleteLocalDriftCategory(any)).thenAnswer((_) async {}); when(mockRepo.updateLocalDriftCategory(any)).thenAnswer((_) async {}); when(mockRepo.addLocalDriftCategory(any)).thenAnswer((_) async {}); @@ -103,6 +105,23 @@ void main() { }); }); + group('addGroupEntries', () { + test('addGroupEntries calls repository', () async { + final notifier = container.read(measurementProvider.notifier); + final entries = [testNeasurementEntry9, testNeasurementEntry10]; + + await notifier.addGroupEntries(entries); + verify(mockRepo.addLocalDriftGroupEntries(entries)).called(1); + }); + + test('addGroupEntries forwards empty list to repository', () async { + final notifier = container.read(measurementProvider.notifier); + + await notifier.addGroupEntries([]); + verify(mockRepo.addLocalDriftGroupEntries([])).called(1); + }); + }); + group('setCategoryOrder', () { // Three top-level categories: Body fat ('1'), Biceps ('2') and the blood // pressure group parent ('bp'), whose children must stay untouched. diff --git a/test/features/measurements/widgets/categories_card_group_test.dart b/test/features/measurements/widgets/categories_card_group_test.dart index 6e6fc30dd..b46d7fd51 100644 --- a/test/features/measurements/widgets/categories_card_group_test.dart +++ b/test/features/measurements/widgets/categories_card_group_test.dart @@ -23,6 +23,8 @@ import 'package:wger/features/measurements/models/measurement_entry.dart'; import 'package:wger/features/measurements/widgets/categories_card.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import '../../../../test_data/measurements.dart'; + Widget _wrap(Widget child) => MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, @@ -33,53 +35,12 @@ Widget _wrap(Widget child) => MaterialApp( ); MeasurementCategory _bpGroup({bool withEntries = false}) { - final sysEntries = withEntries - ? [ - MeasurementEntry( - id: 'e1', - categoryId: 'sys', - date: DateTime(2026, 1, 1), - value: 120, - notes: '', - ), - ] - : []; - final diaEntries = withEntries - ? [ - MeasurementEntry( - id: 'e2', - categoryId: 'dia', - date: DateTime(2026, 1, 1), - value: 80, - notes: '', - ), - ] - : []; + final sysEntries = withEntries ? [testNeasurementEntry9] : []; + final diaEntries = withEntries ? [testNeasurementEntry10] : []; + final sys = testMeasurementCategorySystolic.copyWith(entries: sysEntries); + final dia = testMeasurementCategoryDiastolic.copyWith(entries: diaEntries); - final sys = MeasurementCategory( - id: 'sys', - name: 'Systolic', - unit: 'mmHg', - parentId: 'bp', - order: 0, - entries: sysEntries, - ); - final dia = MeasurementCategory( - id: 'dia', - name: 'Diastolic', - unit: 'mmHg', - parentId: 'bp', - order: 1, - entries: diaEntries, - ); - - return MeasurementCategory( - id: 'bp', - name: 'Blood pressure', - unit: 'mmHg', - metricType: MetricType.bloodPressure, - children: [sys, dia], - ); + return testMeasurementCategoryBloodPressure.copyWith(children: [sys, dia]); } void main() { diff --git a/test/features/measurements/widgets/group_measurement_entry_form_test.dart b/test/features/measurements/widgets/group_measurement_entry_form_test.dart new file mode 100644 index 000000000..971b60e22 --- /dev/null +++ b/test/features/measurements/widgets/group_measurement_entry_form_test.dart @@ -0,0 +1,96 @@ +/* + * 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/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:wger/core/widgets/decimal_input.dart'; +import 'package:wger/features/measurements/providers/measurement_repository.dart'; +import 'package:wger/features/measurements/widgets/forms.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../../../test_data/measurements.dart'; +import '../providers/measurement_notifier_test.mocks.dart'; + +Widget _wrap(MockMeasurementRepository mockRepo) { + return ProviderScope( + overrides: [ + measurementRepositoryProvider.overrideWithValue(mockRepo), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SingleChildScrollView( + child: GroupMeasurementEntryForm(testMeasurementCategoryBloodPressure), + ), + ), + ), + ); +} + +void main() { + late MockMeasurementRepository mockRepo; + + setUp(() { + mockRepo = MockMeasurementRepository(); + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([])); + when(mockRepo.addLocalDriftGroupEntries(any)).thenAnswer((_) async {}); + }); + + group('GroupMeasurementEntryForm', () { + testWidgets('renders one DecimalInputWidget per child component', (tester) async { + await tester.pumpWidget(_wrap(mockRepo)); + await tester.pumpAndSettle(); + + expect(find.byType(DecimalInputWidget), findsNWidgets(2)); + }); + + testWidgets('empty value fields fail validation', (tester) async { + await tester.pumpWidget(_wrap(mockRepo)); + await tester.pumpAndSettle(); + + // Tap save without entering values + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + // Form doesnot pop + expect(find.byType(GroupMeasurementEntryForm), findsOneWidget); + }); + + testWidgets('valid submission calls addGroupEntries with correct count', (tester) async { + await tester.pumpWidget(_wrap(mockRepo)); + await tester.pumpAndSettle(); + + final fields = find.byType(TextFormField); + // Fields : Date, Time, Systolic value, Diastolic value + await tester.enterText(fields.at(2), '120'); + await tester.enterText(fields.at(3), '80'); + + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + verify( + mockRepo.addLocalDriftGroupEntries( + argThat(hasLength(2)), + ), + ).called(1); + }); + }); +} diff --git a/test_data/measurements.dart b/test_data/measurements.dart index 73c237751..f26e18492 100644 --- a/test_data/measurements.dart +++ b/test_data/measurements.dart @@ -78,12 +78,29 @@ final testMeasurementEntry8 = MeasurementEntry( notes: '', ); +final testNeasurementEntry9 = MeasurementEntry( + id: 'e1', + categoryId: 'sys', + date: DateTime(2026, 1, 1), + value: 120, + notes: '', +); + +final testNeasurementEntry10 = MeasurementEntry( + id: 'e2', + categoryId: 'dia', + date: DateTime(2026, 1, 1), + value: 80, + notes: '', +); + /// Multi-value group: blood pressure with systolic/diastolic components. final testMeasurementCategoryBloodPressure = MeasurementCategory( id: 'bp', name: 'Blood pressure', unit: 'mmHg', metricType: MetricType.bloodPressure, + children: [testMeasurementCategorySystolic, testMeasurementCategoryDiastolic], ); final testMeasurementCategorySystolic = MeasurementCategory( From 432d9f1dde8abc40ab325f8decf3fa7dea41a76e Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Mon, 13 Jul 2026 21:27:41 +0545 Subject: [PATCH 032/484] feat(measurements): add category form test , update categories screen test --- .../measurement_categories_screen_test.dart | 17 ++- .../widgets/categories_list_test.dart | 65 ++++++++++ .../measurement_category_form_test.dart | 114 ++++++++++++++++++ 3 files changed, 193 insertions(+), 3 deletions(-) create mode 100644 test/features/measurements/widgets/categories_list_test.dart create mode 100644 test/features/measurements/widgets/measurement_category_form_test.dart diff --git a/test/features/measurements/screens/measurement_categories_screen_test.dart b/test/features/measurements/screens/measurement_categories_screen_test.dart index 03bc12dc7..5ffa0f185 100644 --- a/test/features/measurements/screens/measurement_categories_screen_test.dart +++ b/test/features/measurements/screens/measurement_categories_screen_test.dart @@ -36,7 +36,12 @@ void main() { final mockRepo = MockMeasurementRepository(); when( mockRepo.watchAll(), - ).thenAnswer((_) => Stream>.value(getMeasurementCategories())); + ).thenAnswer( + (_) => Stream>.value([ + ...getMeasurementCategories(), + ...getBloodPressureGroup(), + ]), + ); return ProviderScope( overrides: [ @@ -52,13 +57,19 @@ void main() { } testWidgets('Test the widgets on the measurement category screen', (WidgetTester tester) async { + tester.view.physicalSize = const Size(800, 2200); + tester.view.devicePixelRatio = 1.0; + await tester.pumpWidget(createMeasurementScreen()); await tester.pumpAndSettle(); expect(find.text('Measurements'), findsOneWidget); expect(find.text('Body fat'), findsOneWidget); expect(find.text('Biceps'), findsOneWidget); - expect(find.byType(Card), findsNWidgets(2)); - expect(find.byType(MeasurementChartWidgetFl), findsNWidgets(2)); + expect(find.text('Blood pressure'), findsOneWidget); + expect(find.text('Systolic'), findsOneWidget); + expect(find.text('Diastolic'), findsOneWidget); + expect(find.byType(ListTile), findsNWidgets(2)); // Systolic , Diastolic + expect(find.byType(MeasurementChartWidgetFl), findsNWidgets(2)); // Body fat, Biceps }); } diff --git a/test/features/measurements/widgets/categories_list_test.dart b/test/features/measurements/widgets/categories_list_test.dart new file mode 100644 index 000000000..e6b2c1694 --- /dev/null +++ b/test/features/measurements/widgets/categories_list_test.dart @@ -0,0 +1,65 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:wger/features/measurements/providers/measurement_repository.dart'; +import 'package:wger/features/measurements/widgets/categories.dart'; +import 'package:wger/features/measurements/widgets/categories_card.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import '../../../../test_data/measurements.dart'; +import '../providers/measurement_notifier_test.mocks.dart'; + +Widget _wrap(MockMeasurementRepository mockRepo) { + return ProviderScope( + overrides: [ + measurementRepositoryProvider.overrideWithValue(mockRepo), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: CategoriesList()), + ), + ); +} + +void main() { + late MockMeasurementRepository mockRepo; + + setUp(() { + mockRepo = MockMeasurementRepository(); + }); + + group('CategoriesList', () { + testWidgets('two top-level categories render two CategoriesCard widgets', (tester) async { + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(getMeasurementCategories())); + + await tester.pumpWidget(_wrap(mockRepo)); + await tester.pumpAndSettle(); + + expect(find.byType(CategoriesCard), findsNWidgets(2)); + }); + + testWidgets(' children of multi-value groups are not rendered as own list items', ( + tester, + ) async { + // Only 'bp' should produce a CategoriesCard; children stay inside it. + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(getBloodPressureGroup())); + + await tester.pumpWidget(_wrap(mockRepo)); + await tester.pumpAndSettle(); + + expect(find.byType(CategoriesCard), findsOneWidget); + expect(find.text('Systolic'), findsOneWidget); + expect(find.text('Diastolic'), findsOneWidget); + }); + + testWidgets('empty list renders no CategoriesCard', (tester) async { + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([])); + + await tester.pumpWidget(_wrap(mockRepo)); + await tester.pumpAndSettle(); + + expect(find.byType(CategoriesCard), findsNothing); + }); + }); +} diff --git a/test/features/measurements/widgets/measurement_category_form_test.dart b/test/features/measurements/widgets/measurement_category_form_test.dart new file mode 100644 index 000000000..45098b9f9 --- /dev/null +++ b/test/features/measurements/widgets/measurement_category_form_test.dart @@ -0,0 +1,114 @@ +/* + * 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/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/providers/measurement_repository.dart'; +import 'package:wger/features/measurements/widgets/forms.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../../../test_data/measurements.dart'; +import '../providers/measurement_notifier_test.mocks.dart'; + +Widget _wrap(Widget child, MockMeasurementRepository mockRepo) { + return ProviderScope( + overrides: [ + measurementRepositoryProvider.overrideWithValue(mockRepo), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SingleChildScrollView(child: child), + ), + ), + ); +} + +void main() { + late MockMeasurementRepository mockRepo; + + setUp(() { + mockRepo = MockMeasurementRepository(); + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([])); + }); + + group('MeasurementCategoryForm validation', () { + testWidgets('empty name fails validation', (tester) async { + await tester.pumpWidget(_wrap(const MeasurementCategoryForm(), mockRepo)); + await tester.pumpAndSettle(); + + // Tap save without entering any text + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + // Check for validation errors. + final error = find.byWidgetPredicate((widget) { + if (widget is TextField) { + return widget.decoration?.errorText != null; + } + return false; + }); + expect(error, findsAtLeastNWidgets(1)); + }); + + testWidgets('empty unit field fails validation', (tester) async { + await tester.pumpWidget(_wrap(const MeasurementCategoryForm(), mockRepo)); + await tester.pumpAndSettle(); + + // Fill name but leave unit empty + await tester.enterText(find.byType(TextFormField).first, 'Body fat'); + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + // still on same screen + expect(find.byType(MeasurementCategoryForm), findsOneWidget); + }); + + testWidgets('metricType dropdown renders all MetricType values', (tester) async { + await tester.pumpWidget(_wrap(const MeasurementCategoryForm(), mockRepo)); + await tester.pumpAndSettle(); + + // Open the dropdown + await tester.tap(find.byType(DropdownButtonFormField)); + await tester.pumpAndSettle(); + + // We expect N + 1 items here because when the dropdown is opened: + // 1. The initialValue is still displayed on the form background as a DropdownMenuItem. + // 2. The opened menu overlay displays all 6 total MetricType options. + // Total = 1 (background label) + 6 (popup menu options) = 7 widgets. + expect( + find.byType(DropdownMenuItem), + findsNWidgets(MetricType.values.length + 1), + ); + }); + + testWidgets('editing existing category pre-fills name and unit', (tester) async { + final existing = getMeasurementCategories()[1]; + + await tester.pumpWidget(_wrap(MeasurementCategoryForm(existing), mockRepo)); + await tester.pumpAndSettle(); + + expect(find.widgetWithText(TextFormField, 'Biceps'), findsOneWidget); + expect(find.widgetWithText(TextFormField, 'cm'), findsOneWidget); + }); + }); +} From b6c83ff37fa23f8cf0ad205a13c9728ab4bd922e Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 17 Jul 2026 17:38:50 +0200 Subject: [PATCH 033/484] Rename files so they match the ones they test --- ...up_test.dart => categories_card_test.dart} | 141 ++++++------ ...es_list_test.dart => categories_test.dart} | 151 +++++++------ .../widgets/categories_test.mocks.dart | 139 ++++++++++++ .../measurements/widgets/charts_test.dart | 7 +- ...ategory_form_test.dart => forms_test.dart} | 98 ++++++-- .../widgets/forms_test.mocks.dart | 139 ++++++++++++ .../widgets/get_overview_widgets_test.dart | 135 ----------- .../group_measurement_entry_form_test.dart | 96 -------- ...etric_type_test.dart => helpers_test.dart} | 213 ++++++++++++------ test_data/measurements.dart | 5 +- 10 files changed, 660 insertions(+), 464 deletions(-) rename test/features/measurements/widgets/{categories_card_group_test.dart => categories_card_test.dart} (93%) rename test/features/measurements/widgets/{categories_list_test.dart => categories_test.dart} (68%) create mode 100644 test/features/measurements/widgets/categories_test.mocks.dart rename test/features/measurements/widgets/{measurement_category_form_test.dart => forms_test.dart} (52%) create mode 100644 test/features/measurements/widgets/forms_test.mocks.dart delete mode 100644 test/features/measurements/widgets/get_overview_widgets_test.dart delete mode 100644 test/features/measurements/widgets/group_measurement_entry_form_test.dart rename test/features/measurements/widgets/{build_chart_for_metric_type_test.dart => helpers_test.dart} (51%) diff --git a/test/features/measurements/widgets/categories_card_group_test.dart b/test/features/measurements/widgets/categories_card_test.dart similarity index 93% rename from test/features/measurements/widgets/categories_card_group_test.dart rename to test/features/measurements/widgets/categories_card_test.dart index b46d7fd51..4330cdfae 100644 --- a/test/features/measurements/widgets/categories_card_group_test.dart +++ b/test/features/measurements/widgets/categories_card_test.dart @@ -1,72 +1,69 @@ -/* - * 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/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:wger/features/measurements/models/measurement_category.dart'; -import 'package:wger/features/measurements/models/measurement_entry.dart'; -import 'package:wger/features/measurements/widgets/categories_card.dart'; -import 'package:wger/l10n/generated/app_localizations.dart'; - -import '../../../../test_data/measurements.dart'; - -Widget _wrap(Widget child) => MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - routes: { - '/form': (ctx) => const Scaffold(body: Text('form screen')), - }, - home: Scaffold(body: child), -); - -MeasurementCategory _bpGroup({bool withEntries = false}) { - final sysEntries = withEntries ? [testNeasurementEntry9] : []; - final diaEntries = withEntries ? [testNeasurementEntry10] : []; - final sys = testMeasurementCategorySystolic.copyWith(entries: sysEntries); - final dia = testMeasurementCategoryDiastolic.copyWith(entries: diaEntries); - - return testMeasurementCategoryBloodPressure.copyWith(children: [sys, dia]); -} - -void main() { - group('CategoriesCard — group card', () { - testWidgets('shows one ListTile per child with latest reading', (tester) async { - await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: true)))); - await tester.pumpAndSettle(); - - expect(find.byType(ListTile), findsNWidgets(2)); - expect(find.textContaining('120'), findsOneWidget); - expect(find.textContaining('80'), findsOneWidget); - }); - - testWidgets('shows dash when child has no entries', (tester) async { - await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: false)))); - await tester.pumpAndSettle(); - - // Text('—') should appear for both children - expect(find.text('—'), findsNWidgets(2)); - }); - - testWidgets('add icon button is present on group card', (tester) async { - await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup()))); - await tester.pumpAndSettle(); - - expect(find.byIcon(Icons.add), findsOneWidget); - }); - }); -} +/* + * 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/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/models/measurement_entry.dart'; +import 'package:wger/features/measurements/widgets/categories_card.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../../../test_data/measurements.dart'; + +Widget _wrap(Widget child) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: child), +); + +MeasurementCategory _bpGroup({bool withEntries = false}) { + final sysEntries = withEntries ? [testNeasurementEntry9] : []; + final diaEntries = withEntries ? [testNeasurementEntry10] : []; + final sys = testMeasurementCategorySystolic.copyWith(entries: sysEntries); + final dia = testMeasurementCategoryDiastolic.copyWith(entries: diaEntries); + + return testMeasurementCategoryBloodPressure.copyWith(children: [sys, dia]); +} + +void main() { + group('CategoriesCard group card', () { + testWidgets('shows one ListTile per child with latest reading', (tester) async { + await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: true)))); + await tester.pumpAndSettle(); + + expect(find.byType(ListTile), findsNWidgets(2)); + expect(find.textContaining('120'), findsOneWidget); + expect(find.textContaining('80'), findsOneWidget); + }); + + testWidgets('shows dash when child has no entries', (tester) async { + await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: false)))); + await tester.pumpAndSettle(); + + // Text('—') should appear for both children + expect(find.text('—'), findsNWidgets(2)); + }); + + testWidgets('add icon button is present on group card', (tester) async { + await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup()))); + await tester.pumpAndSettle(); + + expect(find.byIcon(Icons.add), findsOneWidget); + }); + }); +} diff --git a/test/features/measurements/widgets/categories_list_test.dart b/test/features/measurements/widgets/categories_test.dart similarity index 68% rename from test/features/measurements/widgets/categories_list_test.dart rename to test/features/measurements/widgets/categories_test.dart index e6b2c1694..39150c51d 100644 --- a/test/features/measurements/widgets/categories_list_test.dart +++ b/test/features/measurements/widgets/categories_test.dart @@ -1,65 +1,86 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/mockito.dart'; -import 'package:wger/features/measurements/providers/measurement_repository.dart'; -import 'package:wger/features/measurements/widgets/categories.dart'; -import 'package:wger/features/measurements/widgets/categories_card.dart'; -import 'package:wger/l10n/generated/app_localizations.dart'; -import '../../../../test_data/measurements.dart'; -import '../providers/measurement_notifier_test.mocks.dart'; - -Widget _wrap(MockMeasurementRepository mockRepo) { - return ProviderScope( - overrides: [ - measurementRepositoryProvider.overrideWithValue(mockRepo), - ], - child: const MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold(body: CategoriesList()), - ), - ); -} - -void main() { - late MockMeasurementRepository mockRepo; - - setUp(() { - mockRepo = MockMeasurementRepository(); - }); - - group('CategoriesList', () { - testWidgets('two top-level categories render two CategoriesCard widgets', (tester) async { - when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(getMeasurementCategories())); - - await tester.pumpWidget(_wrap(mockRepo)); - await tester.pumpAndSettle(); - - expect(find.byType(CategoriesCard), findsNWidgets(2)); - }); - - testWidgets(' children of multi-value groups are not rendered as own list items', ( - tester, - ) async { - // Only 'bp' should produce a CategoriesCard; children stay inside it. - when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(getBloodPressureGroup())); - - await tester.pumpWidget(_wrap(mockRepo)); - await tester.pumpAndSettle(); - - expect(find.byType(CategoriesCard), findsOneWidget); - expect(find.text('Systolic'), findsOneWidget); - expect(find.text('Diastolic'), findsOneWidget); - }); - - testWidgets('empty list renders no CategoriesCard', (tester) async { - when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([])); - - await tester.pumpWidget(_wrap(mockRepo)); - await tester.pumpAndSettle(); - - expect(find.byType(CategoriesCard), findsNothing); - }); - }); -} +/* + * 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/material.dart'; +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/features/measurements/providers/measurement_repository.dart'; +import 'package:wger/features/measurements/widgets/categories.dart'; +import 'package:wger/features/measurements/widgets/categories_card.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../../../test_data/measurements.dart'; +import 'categories_test.mocks.dart'; + +Widget _wrap(MockMeasurementRepository mockRepo) { + return ProviderScope( + overrides: [ + measurementRepositoryProvider.overrideWithValue(mockRepo), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: CategoriesList()), + ), + ); +} + +@GenerateMocks([MeasurementRepository]) +void main() { + late MockMeasurementRepository mockRepo; + + setUp(() { + mockRepo = MockMeasurementRepository(); + }); + + group('CategoriesList', () { + testWidgets('two top-level categories render two CategoriesCard widgets', (tester) async { + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(getMeasurementCategories())); + + await tester.pumpWidget(_wrap(mockRepo)); + await tester.pumpAndSettle(); + + expect(find.byType(CategoriesCard), findsNWidgets(2)); + }); + + testWidgets('children of multi-value groups are not rendered as own list items', ( + tester, + ) async { + // Only 'bp' should produce a CategoriesCard; children stay inside it. + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(getBloodPressureGroup())); + + await tester.pumpWidget(_wrap(mockRepo)); + await tester.pumpAndSettle(); + + expect(find.byType(CategoriesCard), findsOneWidget); + expect(find.text('Systolic'), findsOneWidget); + expect(find.text('Diastolic'), findsOneWidget); + }); + + testWidgets('empty list renders no CategoriesCard', (tester) async { + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([])); + + await tester.pumpWidget(_wrap(mockRepo)); + await tester.pumpAndSettle(); + + expect(find.byType(CategoriesCard), findsNothing); + }); + }); +} diff --git a/test/features/measurements/widgets/categories_test.mocks.dart b/test/features/measurements/widgets/categories_test.mocks.dart new file mode 100644 index 000000000..ff91c58aa --- /dev/null +++ b/test/features/measurements/widgets/categories_test.mocks.dart @@ -0,0 +1,139 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/features/measurements/widgets/categories_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/measurements/models/measurement_category.dart' as _i4; +import 'package:wger/features/measurements/models/measurement_entry.dart' as _i5; +import 'package:wger/features/measurements/providers/measurement_repository.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [MeasurementRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepository { + MockMeasurementRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Stream> watchAll() => + (super.noSuchMethod( + Invocation.method(#watchAll, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream<_i4.MeasurementCategory?> watchLocalDriftCategoryById( + String? id, + ) => + (super.noSuchMethod( + Invocation.method(#watchLocalDriftCategoryById, [id]), + returnValue: _i3.Stream<_i4.MeasurementCategory?>.empty(), + ) + as _i3.Stream<_i4.MeasurementCategory?>); + + @override + _i3.Future> getAllOnce() => + (super.noSuchMethod( + Invocation.method(#getAllOnce, []), + returnValue: _i3.Future>.value( + <_i4.MeasurementCategory>[], + ), + ) + as _i3.Future>); + + @override + _i3.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + 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( + Invocation.method(#deleteLocalDriftCategory, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDriftCategory( + _i4.MeasurementCategory? category, + ) => + (super.noSuchMethod( + Invocation.method(#updateLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDriftCategory(_i4.MeasurementCategory? category) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} diff --git a/test/features/measurements/widgets/charts_test.dart b/test/features/measurements/widgets/charts_test.dart index 73c85a75c..4d7cab2a4 100644 --- a/test/features/measurements/widgets/charts_test.dart +++ b/test/features/measurements/widgets/charts_test.dart @@ -43,7 +43,6 @@ void main() { expect(tester.takeException(), isNull); }); - // T-24 testWidgets('BarChart is present for non-empty entries', (tester) async { final entries = [ entry(1000, DateTime(2026, 1, 1)), @@ -55,12 +54,14 @@ void main() { expect(find.byType(BarChart), findsOneWidget); }); + }); - test('aggregatePerDay returns an empty list for no entries', () { + group('aggregatePerDay', () { + test('returns an empty list for no entries', () { expect(aggregatePerDay([]), isEmpty); }); - test('aggregatePerDay sums entries sharing a calendar day into one point', () { + test('sums entries sharing a calendar day into one point', () { final result = aggregatePerDay([ entry(1000, DateTime(2026, 1, 1, 8)), entry(2500, DateTime(2026, 1, 1, 20)), diff --git a/test/features/measurements/widgets/measurement_category_form_test.dart b/test/features/measurements/widgets/forms_test.dart similarity index 52% rename from test/features/measurements/widgets/measurement_category_form_test.dart rename to test/features/measurements/widgets/forms_test.dart index 45098b9f9..ff78cf4d3 100644 --- a/test/features/measurements/widgets/measurement_category_form_test.dart +++ b/test/features/measurements/widgets/forms_test.dart @@ -19,41 +19,46 @@ import 'package:flutter/material.dart'; 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/core/widgets/decimal_input.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/models/measurement_entry.dart'; import 'package:wger/features/measurements/providers/measurement_repository.dart'; import 'package:wger/features/measurements/widgets/forms.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import '../../../../test_data/measurements.dart'; -import '../providers/measurement_notifier_test.mocks.dart'; - -Widget _wrap(Widget child, MockMeasurementRepository mockRepo) { - return ProviderScope( - overrides: [ - measurementRepositoryProvider.overrideWithValue(mockRepo), - ], - child: MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold( - body: SingleChildScrollView(child: child), - ), - ), - ); -} +import 'forms_test.mocks.dart'; +@GenerateMocks([MeasurementRepository]) void main() { late MockMeasurementRepository mockRepo; setUp(() { mockRepo = MockMeasurementRepository(); when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([])); + when(mockRepo.addLocalDriftGroupEntries(any)).thenAnswer((_) async {}); }); + Widget wrap(Widget child) { + return ProviderScope( + overrides: [ + measurementRepositoryProvider.overrideWithValue(mockRepo), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SingleChildScrollView(child: child), + ), + ), + ); + } + group('MeasurementCategoryForm validation', () { testWidgets('empty name fails validation', (tester) async { - await tester.pumpWidget(_wrap(const MeasurementCategoryForm(), mockRepo)); + await tester.pumpWidget(wrap(const MeasurementCategoryForm())); await tester.pumpAndSettle(); // Tap save without entering any text @@ -71,7 +76,7 @@ void main() { }); testWidgets('empty unit field fails validation', (tester) async { - await tester.pumpWidget(_wrap(const MeasurementCategoryForm(), mockRepo)); + await tester.pumpWidget(wrap(const MeasurementCategoryForm())); await tester.pumpAndSettle(); // Fill name but leave unit empty @@ -84,17 +89,15 @@ void main() { }); testWidgets('metricType dropdown renders all MetricType values', (tester) async { - await tester.pumpWidget(_wrap(const MeasurementCategoryForm(), mockRepo)); + await tester.pumpWidget(wrap(const MeasurementCategoryForm())); await tester.pumpAndSettle(); // Open the dropdown await tester.tap(find.byType(DropdownButtonFormField)); await tester.pumpAndSettle(); - // We expect N + 1 items here because when the dropdown is opened: - // 1. The initialValue is still displayed on the form background as a DropdownMenuItem. - // 2. The opened menu overlay displays all 6 total MetricType options. - // Total = 1 (background label) + 6 (popup menu options) = 7 widgets. + // The initialValue stays visible on the form behind the opened menu + // overlay, which shows every MetricType option once. expect( find.byType(DropdownMenuItem), findsNWidgets(MetricType.values.length + 1), @@ -104,11 +107,58 @@ void main() { testWidgets('editing existing category pre-fills name and unit', (tester) async { final existing = getMeasurementCategories()[1]; - await tester.pumpWidget(_wrap(MeasurementCategoryForm(existing), mockRepo)); + await tester.pumpWidget(wrap(MeasurementCategoryForm(existing))); await tester.pumpAndSettle(); expect(find.widgetWithText(TextFormField, 'Biceps'), findsOneWidget); expect(find.widgetWithText(TextFormField, 'cm'), findsOneWidget); }); }); + + group('GroupMeasurementEntryForm', () { + testWidgets('renders one DecimalInputWidget per child component', (tester) async { + await tester.pumpWidget( + wrap(GroupMeasurementEntryForm(testMeasurementCategoryBloodPressure)), + ); + await tester.pumpAndSettle(); + + expect(find.byType(DecimalInputWidget), findsNWidgets(2)); + }); + + testWidgets('empty value fields fail validation', (tester) async { + await tester.pumpWidget( + wrap(GroupMeasurementEntryForm(testMeasurementCategoryBloodPressure)), + ); + await tester.pumpAndSettle(); + + // Tap save without entering values + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + // Form does not pop + expect(find.byType(GroupMeasurementEntryForm), findsOneWidget); + verifyNever(mockRepo.addLocalDriftGroupEntries(any)); + }); + + testWidgets('valid submission adds one entry per component, sharing the date', (tester) async { + await tester.pumpWidget( + wrap(GroupMeasurementEntryForm(testMeasurementCategoryBloodPressure)), + ); + await tester.pumpAndSettle(); + + final fields = find.byType(TextFormField); + // Fields: date, time, systolic value, diastolic value + await tester.enterText(fields.at(2), '120'); + await tester.enterText(fields.at(3), '80'); + + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + final entries = + verify(mockRepo.addLocalDriftGroupEntries(captureAny)).captured.single + as List; + expect(entries.map((e) => (e.categoryId, e.value)), [('sys', 120), ('dia', 80)]); + expect(entries.first.date, entries.last.date); + }); + }); } diff --git a/test/features/measurements/widgets/forms_test.mocks.dart b/test/features/measurements/widgets/forms_test.mocks.dart new file mode 100644 index 000000000..4ee31c79d --- /dev/null +++ b/test/features/measurements/widgets/forms_test.mocks.dart @@ -0,0 +1,139 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/features/measurements/widgets/forms_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/measurements/models/measurement_category.dart' as _i4; +import 'package:wger/features/measurements/models/measurement_entry.dart' as _i5; +import 'package:wger/features/measurements/providers/measurement_repository.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [MeasurementRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepository { + MockMeasurementRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Stream> watchAll() => + (super.noSuchMethod( + Invocation.method(#watchAll, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream<_i4.MeasurementCategory?> watchLocalDriftCategoryById( + String? id, + ) => + (super.noSuchMethod( + Invocation.method(#watchLocalDriftCategoryById, [id]), + returnValue: _i3.Stream<_i4.MeasurementCategory?>.empty(), + ) + as _i3.Stream<_i4.MeasurementCategory?>); + + @override + _i3.Future> getAllOnce() => + (super.noSuchMethod( + Invocation.method(#getAllOnce, []), + returnValue: _i3.Future>.value( + <_i4.MeasurementCategory>[], + ), + ) + as _i3.Future>); + + @override + _i3.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + 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( + Invocation.method(#deleteLocalDriftCategory, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDriftCategory( + _i4.MeasurementCategory? category, + ) => + (super.noSuchMethod( + Invocation.method(#updateLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDriftCategory(_i4.MeasurementCategory? category) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} diff --git a/test/features/measurements/widgets/get_overview_widgets_test.dart b/test/features/measurements/widgets/get_overview_widgets_test.dart deleted file mode 100644 index 8a838b199..000000000 --- a/test/features/measurements/widgets/get_overview_widgets_test.dart +++ /dev/null @@ -1,135 +0,0 @@ -/* - * This file is part of wger Workout Manager . - * 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 - * 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/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:wger/features/measurements/models/measurement_category.dart'; -import 'package:wger/features/measurements/widgets/charts.dart'; -import 'package:wger/features/measurements/widgets/helpers.dart'; -import 'package:wger/l10n/generated/app_localizations.dart'; - -void main() { - final rawEntries = [ - MeasurementChartEntry(10, DateTime(2026, 1, 1)), - MeasurementChartEntry(20, DateTime(2026, 1, 10)), - ]; - final avgEntries = moving7dAverage(rawEntries); - - group('getOverviewWidgets', () { - testWidgets('empty raw shows no-data placeholder', (tester) async { - late List widgets; - await tester.pumpWidget( - MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Builder( - builder: (ctx) { - widgets = getOverviewWidgets('Test', [], [], 'cm', ctx); - return Scaffold( - body: SingleChildScrollView(child: Column(children: widgets)), - ); - }, - ), - ), - ); - await tester.pumpAndSettle(); - - expect(find.text('No data available'), findsOneWidget); - }); - - testWidgets('non-empty avg includes MeasurementOverallChangeWidget', (tester) async { - late List widgets; - await tester.pumpWidget( - MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Builder( - builder: (ctx) { - widgets = getOverviewWidgets('Test', rawEntries, avgEntries, 'cm', ctx); - return Scaffold( - body: SingleChildScrollView(child: Column(children: widgets)), - ); - }, - ), - ), - ); - await tester.pumpAndSettle(); - - expect(find.byType(MeasurementOverallChangeWidget), findsOneWidget); - }); - }); - - group('getOverviewWidgetsSeries — Indicator legend', () { - testWidgets('three Indicator widgets for non-summed metric (custom)', (tester) async { - await tester.pumpWidget( - MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Builder( - builder: (ctx) { - final widgets = getOverviewWidgetsSeries( - 'Weight', - rawEntries, - avgEntries, - [], - 'kg', - ctx, - metricType: MetricType.custom, - ); - return Scaffold( - body: SingleChildScrollView(child: Column(children: widgets)), - ); - }, - ), - ), - ); - await tester.pumpAndSettle(); - - expect(find.byType(Indicator), findsNWidgets(3)); - }); - - testWidgets('two Indicator widgets for summed metric (steps — no trend)', (tester) async { - await tester.pumpWidget( - MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Builder( - builder: (ctx) { - final widgets = getOverviewWidgetsSeries( - 'Steps', - rawEntries, - avgEntries, - [], - 'steps', - ctx, - metricType: MetricType.steps, - ); - return Scaffold( - body: SingleChildScrollView(child: Column(children: widgets)), - ); - }, - ), - ), - ); - await tester.pumpAndSettle(); - - // isSummedPerDay -> trend indicator is hidden - expect(find.byType(Indicator), findsNWidgets(2)); - }); - }); -} diff --git a/test/features/measurements/widgets/group_measurement_entry_form_test.dart b/test/features/measurements/widgets/group_measurement_entry_form_test.dart deleted file mode 100644 index 971b60e22..000000000 --- a/test/features/measurements/widgets/group_measurement_entry_form_test.dart +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/mockito.dart'; -import 'package:wger/core/widgets/decimal_input.dart'; -import 'package:wger/features/measurements/providers/measurement_repository.dart'; -import 'package:wger/features/measurements/widgets/forms.dart'; -import 'package:wger/l10n/generated/app_localizations.dart'; - -import '../../../../test_data/measurements.dart'; -import '../providers/measurement_notifier_test.mocks.dart'; - -Widget _wrap(MockMeasurementRepository mockRepo) { - return ProviderScope( - overrides: [ - measurementRepositoryProvider.overrideWithValue(mockRepo), - ], - child: MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold( - body: SingleChildScrollView( - child: GroupMeasurementEntryForm(testMeasurementCategoryBloodPressure), - ), - ), - ), - ); -} - -void main() { - late MockMeasurementRepository mockRepo; - - setUp(() { - mockRepo = MockMeasurementRepository(); - when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([])); - when(mockRepo.addLocalDriftGroupEntries(any)).thenAnswer((_) async {}); - }); - - group('GroupMeasurementEntryForm', () { - testWidgets('renders one DecimalInputWidget per child component', (tester) async { - await tester.pumpWidget(_wrap(mockRepo)); - await tester.pumpAndSettle(); - - expect(find.byType(DecimalInputWidget), findsNWidgets(2)); - }); - - testWidgets('empty value fields fail validation', (tester) async { - await tester.pumpWidget(_wrap(mockRepo)); - await tester.pumpAndSettle(); - - // Tap save without entering values - await tester.tap(find.byType(ElevatedButton)); - await tester.pumpAndSettle(); - - // Form doesnot pop - expect(find.byType(GroupMeasurementEntryForm), findsOneWidget); - }); - - testWidgets('valid submission calls addGroupEntries with correct count', (tester) async { - await tester.pumpWidget(_wrap(mockRepo)); - await tester.pumpAndSettle(); - - final fields = find.byType(TextFormField); - // Fields : Date, Time, Systolic value, Diastolic value - await tester.enterText(fields.at(2), '120'); - await tester.enterText(fields.at(3), '80'); - - await tester.tap(find.byType(ElevatedButton)); - await tester.pumpAndSettle(); - - verify( - mockRepo.addLocalDriftGroupEntries( - argThat(hasLength(2)), - ), - ).called(1); - }); - }); -} diff --git a/test/features/measurements/widgets/build_chart_for_metric_type_test.dart b/test/features/measurements/widgets/helpers_test.dart similarity index 51% rename from test/features/measurements/widgets/build_chart_for_metric_type_test.dart rename to test/features/measurements/widgets/helpers_test.dart index 170df0afa..cac308246 100644 --- a/test/features/measurements/widgets/build_chart_for_metric_type_test.dart +++ b/test/features/measurements/widgets/helpers_test.dart @@ -1,67 +1,146 @@ -/* - * 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/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:wger/features/measurements/models/measurement_category.dart'; -import 'package:wger/features/measurements/widgets/charts.dart'; -import 'package:wger/features/measurements/widgets/helpers.dart'; -import 'package:wger/l10n/generated/app_localizations.dart'; - -Widget _wrapChart(Widget chart) => MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold( - body: SizedBox(width: 400, height: 300, child: chart), - ), -); - -void main() { - final entries = [ - MeasurementChartEntry(1000, DateTime(2026, 1, 1)), - MeasurementChartEntry(2000, DateTime(2026, 1, 2)), - ]; - - group('buildChartForMetricType routing', () { - testWidgets('steps -> MeasurementBarChartWidgetFl', (tester) async { - final widget = buildChartForMetricType(MetricType.steps, entries, [], 'steps'); - await tester.pumpWidget(_wrapChart(widget)); - await tester.pumpAndSettle(); - - expect(find.byType(MeasurementBarChartWidgetFl), findsOneWidget); - expect(find.byType(MeasurementChartWidgetFl), findsNothing); - }); - - testWidgets('custom -> MeasurementChartWidgetFl', (tester) async { - final widget = buildChartForMetricType(MetricType.custom, entries, [], 'cm'); - await tester.pumpWidget(_wrapChart(widget)); - await tester.pumpAndSettle(); - - expect(find.byType(MeasurementChartWidgetFl), findsOneWidget); - expect(find.byType(MeasurementBarChartWidgetFl), findsNothing); - }); - - testWidgets('energy -> MeasurementBarChartWidgetFl', (tester) async { - final widget = buildChartForMetricType(MetricType.energy, entries, [], 'kcal'); - await tester.pumpWidget(_wrapChart(widget)); - await tester.pumpAndSettle(); - - expect(find.byType(MeasurementBarChartWidgetFl), findsOneWidget); - }); - }); -} +/* + * 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/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/widgets/charts.dart'; +import 'package:wger/features/measurements/widgets/helpers.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +Widget _wrapChart(Widget chart) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox(width: 400, height: 300, child: chart), + ), +); + +/// Pumps a MaterialApp whose body is the widget list built by [builder]. +Future _pumpWidgetList( + WidgetTester tester, + List Function(BuildContext context) builder, +) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (ctx) => Scaffold( + body: SingleChildScrollView(child: Column(children: builder(ctx))), + ), + ), + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + final rawEntries = [ + MeasurementChartEntry(10, DateTime(2026, 1, 1)), + MeasurementChartEntry(20, DateTime(2026, 1, 10)), + ]; + final avgEntries = moving7dAverage(rawEntries); + + group('buildChartForMetricType routing', () { + final entries = [ + MeasurementChartEntry(1000, DateTime(2026, 1, 1)), + MeasurementChartEntry(2000, DateTime(2026, 1, 2)), + ]; + + testWidgets('steps -> MeasurementBarChartWidgetFl', (tester) async { + final widget = buildChartForMetricType(MetricType.steps, entries, [], 'steps'); + await tester.pumpWidget(_wrapChart(widget)); + await tester.pumpAndSettle(); + + expect(find.byType(MeasurementBarChartWidgetFl), findsOneWidget); + expect(find.byType(MeasurementChartWidgetFl), findsNothing); + }); + + testWidgets('custom -> MeasurementChartWidgetFl', (tester) async { + final widget = buildChartForMetricType(MetricType.custom, entries, [], 'cm'); + await tester.pumpWidget(_wrapChart(widget)); + await tester.pumpAndSettle(); + + expect(find.byType(MeasurementChartWidgetFl), findsOneWidget); + expect(find.byType(MeasurementBarChartWidgetFl), findsNothing); + }); + + testWidgets('energy -> MeasurementBarChartWidgetFl', (tester) async { + final widget = buildChartForMetricType(MetricType.energy, entries, [], 'kcal'); + await tester.pumpWidget(_wrapChart(widget)); + await tester.pumpAndSettle(); + + expect(find.byType(MeasurementBarChartWidgetFl), findsOneWidget); + }); + }); + + group('getOverviewWidgets', () { + testWidgets('empty raw shows no-data placeholder', (tester) async { + await _pumpWidgetList(tester, (ctx) => getOverviewWidgets('Test', [], [], 'cm', ctx)); + + expect(find.text('No data available'), findsOneWidget); + }); + + testWidgets('non-empty avg includes MeasurementOverallChangeWidget', (tester) async { + await _pumpWidgetList( + tester, + (ctx) => getOverviewWidgets('Test', rawEntries, avgEntries, 'cm', ctx), + ); + + expect(find.byType(MeasurementOverallChangeWidget), findsOneWidget); + }); + }); + + group('getOverviewWidgetsSeries legend', () { + testWidgets('three Indicator widgets for non-summed metric (custom)', (tester) async { + await _pumpWidgetList( + tester, + (ctx) => getOverviewWidgetsSeries( + 'Weight', + rawEntries, + avgEntries, + [], + 'kg', + ctx, + metricType: MetricType.custom, + ), + ); + + expect(find.byType(Indicator), findsNWidgets(3)); + }); + + testWidgets('two Indicator widgets for summed metric (steps, no trend)', (tester) async { + await _pumpWidgetList( + tester, + (ctx) => getOverviewWidgetsSeries( + 'Steps', + rawEntries, + avgEntries, + [], + 'steps', + ctx, + metricType: MetricType.steps, + ), + ); + + // isSummedPerDay -> trend indicator is hidden + expect(find.byType(Indicator), findsNWidgets(2)); + }); + }); +} diff --git a/test_data/measurements.dart b/test_data/measurements.dart index f26e18492..7f2f84c33 100644 --- a/test_data/measurements.dart +++ b/test_data/measurements.dart @@ -119,8 +119,9 @@ final testMeasurementCategoryDiastolic = MeasurementCategory( order: 1, ); -/// The blood pressure group as a flat list (parent first), as stored in the -/// database. Not included in [getMeasurementCategories]. +/// The blood pressure group as a flat list (parent first) with the children +/// attached to the parent, matching the shape the repository's watchAll() +/// returns. Not included in [getMeasurementCategories]. List getBloodPressureGroup() { return [ testMeasurementCategoryBloodPressure, From f0a088eb0e9832fdd169d9c38daf0c384e520d9b Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 01:31:22 +0200 Subject: [PATCH 034/484] Round imported health values to match backend and lowercase external ids --- .../health/models/health_reading.dart | 5 +- .../health/providers/health_sync.dart | 7 +- .../health/models/health_reading_test.dart | 70 +++++++++++++++++++ .../health/providers/health_sync_test.dart | 7 +- 4 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 test/features/health/models/health_reading_test.dart diff --git a/lib/features/health/models/health_reading.dart b/lib/features/health/models/health_reading.dart index 64101adf7..1d78bea84 100644 --- a/lib/features/health/models/health_reading.dart +++ b/lib/features/health/models/health_reading.dart @@ -53,7 +53,10 @@ class HealthReading { type: point.type, value: value.numericValue.toDouble(), date: point.dateFrom, - externalId: point.uuid.isEmpty ? null : point.uuid, + // HealthKit reports UUIDs in uppercase, but the server's UUIDField + // normalizes to lowercase. Lowercase here so the dedup key stays stable + // once the entry round-trips through the server. + externalId: point.uuid.isEmpty ? null : point.uuid.toLowerCase(), ); } } diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index b45c8edd0..a4e8b86e3 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -153,11 +153,16 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { continue; } + // The server stores values as Decimal with 2 places and rejects + // anything more precise, so round away unit-conversion float noise + // (1.803 m * 100 = 180.29999999999998). + final value = (metric.toCategoryValue(reading.value) * 100).roundToDouble() / 100; + await _measurements.addLocalDrift( MeasurementEntry( categoryId: category.id!, date: reading.date, - value: metric.toCategoryValue(reading.value), + value: value, notes: '', source: source, externalId: uuid, diff --git a/test/features/health/models/health_reading_test.dart b/test/features/health/models/health_reading_test.dart new file mode 100644 index 000000000..552bb9cba --- /dev/null +++ b/test/features/health/models/health_reading_test.dart @@ -0,0 +1,70 @@ +/* + * 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:health_bridge/health.dart'; +import 'package:wger/features/health/models/health_reading.dart'; + +HealthDataPoint dataPoint({String uuid = 'abc-123', HealthValue? value}) { + return HealthDataPoint( + uuid: uuid, + value: value ?? NumericHealthValue(numericValue: 1.8), + type: HealthDataType.HEIGHT, + unit: HealthDataUnit.METER, + dateFrom: DateTime(2026, 1, 1, 8, 30), + dateTo: DateTime(2026, 1, 1, 8, 30), + sourcePlatform: HealthPlatformType.appleHealth, + sourceDeviceId: 'device', + sourceId: 'source', + sourceName: 'test', + ); +} + +void main() { + group('fromDataPoint', () { + test('extracts the numeric value, type and start date', () { + final reading = HealthReading.fromDataPoint(dataPoint())!; + + expect(reading.type, HealthDataType.HEIGHT); + expect(reading.value, 1.8); + expect(reading.date, DateTime(2026, 1, 1, 8, 30)); + expect(reading.externalId, 'abc-123'); + }); + + test('returns null for a non-numeric value', () { + final point = dataPoint(value: NutritionHealthValue()); + + expect(HealthReading.fromDataPoint(point), isNull); + }); + + test('lowercases the platform UUID to match the server normalization', () { + final point = dataPoint(uuid: '1A2B3C4D-C36C-495A-93FC-0C247A3E6E5F'); + + expect( + HealthReading.fromDataPoint(point)!.externalId, + '1a2b3c4d-c36c-495a-93fc-0c247a3e6e5f', + ); + }); + + test('maps an empty UUID to null', () { + final point = dataPoint(uuid: ''); + + expect(HealthReading.fromDataPoint(point)!.externalId, isNull); + }); + }); +} diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index 5f94eaf73..29ea8723a 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -100,7 +100,10 @@ void main() { ), HealthReading( type: HealthDataType.HEIGHT, - value: 1.8, + // 1.803 * 100 is 180.29999999999998 in double arithmetic; the + // server's Decimal(2) validation requires the stored value to be + // rounded to exactly 180.3 + value: 1.803, date: DateTime(2026, 1, 2), externalId: 'h-1', ), @@ -126,7 +129,7 @@ void main() { expect(bodyFat.source, 'apple'); final height = entries.firstWhere((e) => e.externalId == 'h-1'); - expect(height.value, closeTo(180, 0.001)); // meters -> cm + expect(height.value, 180.3); // meters -> cm, rounded to two decimals }); test('skips readings already imported (dedup by externalId)', () async { From 7ebb97c4625cdfafd6476d32afec1a551392beaf Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 01:37:19 +0200 Subject: [PATCH 035/484] Fix source default, hide health settings section when unavailable --- lib/database/powersync/database.g.dart | 2 +- .../powersync/tables/measurements.dart | 6 +-- lib/features/account/widgets/settings.dart | 3 -- .../account/widgets/settings/health_sync.dart | 52 +++++++++++-------- .../health/providers/health_sync.g.dart | 2 +- .../providers/measurement_notifier.g.dart | 2 +- test/core/validators_test.mocks.dart | 11 ++++ 7 files changed, 47 insertions(+), 31 deletions(-) diff --git a/lib/database/powersync/database.g.dart b/lib/database/powersync/database.g.dart index c01662f61..f2e624c68 100644 --- a/lib/database/powersync/database.g.dart +++ b/lib/database/powersync/database.g.dart @@ -5192,7 +5192,7 @@ class $MeasurementEntryTableTable extends MeasurementEntryTable false, type: DriftSqlType.string, requiredDuringInsert: false, - defaultValue: const Constant('manual'), + defaultValue: const Constant('user'), ); static const VerificationMeta _externalIdMeta = const VerificationMeta( 'externalId', diff --git a/lib/database/powersync/tables/measurements.dart b/lib/database/powersync/tables/measurements.dart index cd16325a6..6b3b922fa 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -71,9 +71,9 @@ class MeasurementEntryTable extends Table { RealColumn get value => real()(); TextColumn get notes => text()(); - /// Where the reading came from: `manual` or a health platform - /// (`apple_health`, `health_connect`). - TextColumn get source => text().withDefault(const Constant('manual'))(); + /// Where the reading came from; one of the server's `source` values: + /// `user` for manual entries or a health platform (`apple`, `google`). + TextColumn get source => text().withDefault(const Constant('user'))(); /// Platform record UUID, used to deduplicate re-imports. `null` for manual /// entries. diff --git a/lib/features/account/widgets/settings.dart b/lib/features/account/widgets/settings.dart index d430f6cc0..39957dfed 100644 --- a/lib/features/account/widgets/settings.dart +++ b/lib/features/account/widgets/settings.dart @@ -54,9 +54,6 @@ class SettingsPage extends StatelessWidget { ), ), const SettingsDataPrivacy(), - ListTile( - title: Text(i18n.health, style: Theme.of(context).textTheme.headlineSmall), - ), const HealthSyncSettingsTile(), ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)), const SettingsTheme(), diff --git a/lib/features/account/widgets/settings/health_sync.dart b/lib/features/account/widgets/settings/health_sync.dart index 91d3528d2..de20858b1 100644 --- a/lib/features/account/widgets/settings/health_sync.dart +++ b/lib/features/account/widgets/settings/health_sync.dart @@ -47,7 +47,8 @@ class _HealthSyncSettingsTileState extends ConsumerState @override Widget build(BuildContext context) { - // Hide entirely if platform check hasn't completed or is unavailable + // Hide entirely (including the section header) if the platform check + // hasn't completed or no health platform is available if (_isAvailable != true) { return const SizedBox.shrink(); } @@ -56,27 +57,34 @@ class _HealthSyncSettingsTileState extends ConsumerState final i18n = AppLocalizations.of(context); - return SwitchListTile( - title: Text(i18n.healthSync), - subtitle: Text(i18n.healthSyncDescription), - value: syncState.isEnabled, - onChanged: syncState.isSyncing - ? null - : (enabled) async { - final notifier = ref.read(healthSyncProvider.notifier); - if (enabled) { - final count = await notifier.enableSync(); - // Imported entries land in the local Drift DB and surface through - // the measurement stream automatically, so no manual refresh is needed. - if (context.mounted && count > 0) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(i18n.healthSyncSuccess(count))), - ); - } - } else { - await notifier.disableSync(); - } - }, + return Column( + children: [ + ListTile( + title: Text(i18n.health, style: Theme.of(context).textTheme.headlineSmall), + ), + SwitchListTile( + title: Text(i18n.healthSync), + subtitle: Text(i18n.healthSyncDescription), + value: syncState.isEnabled, + onChanged: syncState.isSyncing + ? null + : (enabled) async { + final notifier = ref.read(healthSyncProvider.notifier); + if (enabled) { + final count = await notifier.enableSync(); + // Imported entries land in the local Drift DB and surface through + // the measurement stream automatically, so no manual refresh is needed. + if (context.mounted && count > 0) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(i18n.healthSyncSuccess(count))), + ); + } + } else { + await notifier.disableSync(); + } + }, + ), + ], ); } } diff --git a/lib/features/health/providers/health_sync.g.dart b/lib/features/health/providers/health_sync.g.dart index 686cde9b1..8410b9c61 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'9c7a678e7740bfa32db7638bd227d64da3bfef09'; +String _$healthSyncNotifierHash() => r'bc23c2f6013f731414a7aa1ac98c618d1937c711'; /// 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/providers/measurement_notifier.g.dart b/lib/features/measurements/providers/measurement_notifier.g.dart index 561817c74..5897b64f6 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'2072d9a5dd3b0c64830913541d236f5dfe28fbbc'; +String _$measurementNotifierHash() => r'd21ed9e3cba86b2395e6df78d51fceb523e7c4fb'; abstract class _$MeasurementNotifier extends $StreamNotifier> { Stream> build(); diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index ac8462028..92ef67ae0 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -2030,6 +2030,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get reorderCategories => + (super.noSuchMethod( + Invocation.getter(#reorderCategories), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#reorderCategories), + ), + ) + as String); + @override String get metricCustom => (super.noSuchMethod( From 3bea05e7c2a7b7407aa0bedc46127ce0a3c1a6fd Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 01:40:18 +0200 Subject: [PATCH 036/484] Read health data with an overlap window to catch backdated records --- .../health/providers/health_sync.dart | 11 +++++++++- .../health/providers/health_sync_test.dart | 21 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index a4e8b86e3..52f364120 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -57,6 +57,10 @@ class HealthSyncState { /// platform record UUID). @Riverpod(keepAlive: true) class HealthSyncNotifier extends _$HealthSyncNotifier { + /// How far the read window reaches back before the last-sync watermark, to + /// pick up records that arrived late with a past date. + static const _syncOverlap = Duration(days: 30); + final _logger = Logger('HealthSyncNotifier'); late final HealthRepository _health; late final MeasurementRepository _measurements; @@ -118,8 +122,13 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { return 0; } + // Health records can arrive late with past dates (e.g. a scale that + // only syncs days after the measurement), so the read window reaches + // back beyond the watermark; re-reads are deduplicated via externalId. final lastSyncStr = await prefs.getLastHealthSyncTimestamp(); - final startTime = lastSyncStr != null ? DateTime.parse(lastSyncStr) : DateTime(2000); + final startTime = lastSyncStr != null + ? DateTime.parse(lastSyncStr).subtract(_syncOverlap) + : DateTime(2000); final endTime = DateTime.now(); _logger.info('Syncing health data from $startTime to $endTime'); diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index 29ea8723a..f4adbab97 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -175,6 +175,27 @@ void main() { expect(entries.single.externalId, 'bf-2'); }); + test('reads with an overlap window before the stored watermark', () async { + await PreferenceHelper.instance.setLastHealthSyncTimestamp('2026-06-01T12:00:00.000'); + when(measurements.getAllOnce()).thenAnswer((_) async => []); + stubReadings([]); + + await createNotifier().syncOnAppOpen(); + + final start = + verify( + health.read( + types: anyNamed('types'), + start: captureAnyNamed('start'), + end: anyNamed('end'), + ), + ).captured.single + as DateTime; + // 30 days before the watermark, so late-arriving backdated records + // (e.g. a scale syncing days after the measurement) are still picked up + expect(start, DateTime(2026, 5, 2, 12)); + }); + test('does nothing when sync is disabled', () async { await PreferenceHelper.instance.setHealthSyncEnabled(false); From 6d08c0afa63cc4c0f8e4e14282afd7cf7cb45adc Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 01:52:14 +0200 Subject: [PATCH 037/484] Notify the user with a snackbar when health permissions are denied --- .../account/widgets/settings/health_sync.dart | 14 ++- .../health/providers/health_sync.dart | 7 +- lib/l10n/app_en.arb | 4 + .../widgets/settings/health_sync_test.dart | 86 +++++++++++++++++ .../health/providers/health_sync_test.dart | 95 +++++++++++++------ 5 files changed, 170 insertions(+), 36 deletions(-) create mode 100644 test/features/account/widgets/settings/health_sync_test.dart diff --git a/lib/features/account/widgets/settings/health_sync.dart b/lib/features/account/widgets/settings/health_sync.dart index de20858b1..62fcc0ab2 100644 --- a/lib/features/account/widgets/settings/health_sync.dart +++ b/lib/features/account/widgets/settings/health_sync.dart @@ -71,10 +71,18 @@ class _HealthSyncSettingsTileState extends ConsumerState : (enabled) async { final notifier = ref.read(healthSyncProvider.notifier); if (enabled) { + // null means the platform permissions were not granted final count = await notifier.enableSync(); - // Imported entries land in the local Drift DB and surface through - // the measurement stream automatically, so no manual refresh is needed. - if (context.mounted && count > 0) { + if (!context.mounted) { + return; + } + if (count == null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(i18n.healthSyncPermissionDenied)), + ); + } else if (count > 0) { + // Imported entries land in the local Drift DB and surface through + // the measurement stream automatically, so no manual refresh is needed. ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(i18n.healthSyncSuccess(count))), ); diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index 52f364120..3b3542414 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -85,10 +85,13 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { Future isAvailable() => _health.isAvailable(); /// Requests permissions, persists the preference, and runs an initial import. - Future enableSync() async { + /// + /// Returns the number of imported entries, or `null` when the platform + /// permissions were not granted (sync stays disabled). + Future enableSync() async { _logger.info('Enabling health sync'); if (!await _health.ensureAuthorized(_types)) { - return 0; + return null; } await PreferenceHelper.instance.setHealthSyncEnabled(true); state = state.copyWith(isEnabled: true); diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b45efdef0..480a476bb 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1512,6 +1512,10 @@ } } }, + "healthSyncPermissionDenied": "Access to health data was not granted", + "@healthSyncPermissionDenied": { + "description": "Snackbar shown when enabling health sync fails because the platform permissions were denied" + }, "health": "Health", "@health": { "description": "Section header for health-related settings" diff --git a/test/features/account/widgets/settings/health_sync_test.dart b/test/features/account/widgets/settings/health_sync_test.dart new file mode 100644 index 000000000..81e84aff6 --- /dev/null +++ b/test/features/account/widgets/settings/health_sync_test.dart @@ -0,0 +1,86 @@ +/* + * 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/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/account/widgets/settings/health_sync.dart'; +import 'package:wger/features/health/providers/health_sync.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Reports the platform as available and returns a canned result from +/// [enableSync] without touching the real health/preferences stack. +class _FakeHealthSyncNotifier extends HealthSyncNotifier { + final int? enableSyncResult; + + _FakeHealthSyncNotifier(this.enableSyncResult); + + @override + HealthSyncState build() => const HealthSyncState(); + + @override + Future isAvailable() async => true; + + @override + Future enableSync() async => enableSyncResult; +} + +void main() { + Widget createTile(int? enableSyncResult) { + return ProviderScope( + overrides: [ + healthSyncProvider.overrideWith(() => _FakeHealthSyncNotifier(enableSyncResult)), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: HealthSyncSettingsTile()), + ), + ); + } + + testWidgets('shows a snackbar when the permissions are denied', (tester) async { + await tester.pumpWidget(createTile(null)); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(SwitchListTile)); + await tester.pumpAndSettle(); + + expect(find.text('Access to health data was not granted'), findsOneWidget); + }); + + testWidgets('shows the import count after a successful sync', (tester) async { + await tester.pumpWidget(createTile(5)); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(SwitchListTile)); + await tester.pumpAndSettle(); + + expect(find.text('Imported 5 measurements from Health'), findsOneWidget); + }); + + testWidgets('shows no snackbar when nothing was imported', (tester) async { + await tester.pumpWidget(createTile(0)); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(SwitchListTile)); + await tester.pumpAndSettle(); + + expect(find.byType(SnackBar), findsNothing); + }); +} diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index f4adbab97..edc7fc6c3 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -35,6 +35,42 @@ import 'health_sync_test.mocks.dart'; @GenerateMocks([HealthRepository, MeasurementRepository]) void main() { + late MockHealthRepository health; + late MockMeasurementRepository measurements; + + setUp(() async { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + await PreferenceHelper.instance.setHealthSyncEnabled(true); + + health = MockHealthRepository(); + measurements = MockMeasurementRepository(); + + when(health.ensureAuthorized(any)).thenAnswer((_) async => true); + when(health.sourceName).thenReturn('apple'); + when(measurements.addLocalDrift(any)).thenAnswer((_) async {}); + when(measurements.addLocalDriftCategory(any)).thenAnswer((_) async {}); + }); + + HealthSyncNotifier createNotifier() { + final container = ProviderContainer.test( + overrides: [ + healthRepositoryProvider.overrideWithValue(health), + measurementRepositoryProvider.overrideWithValue(measurements), + ], + ); + return container.read(healthSyncProvider.notifier); + } + + void stubReadings(List readings) { + when( + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + ), + ).thenAnswer((_) async => readings); + } + group('HealthSyncState', () { test('default state has sync disabled', () { const state = HealthSyncState(); @@ -52,43 +88,40 @@ void main() { }); }); - group('syncOnAppOpen', () { - late MockHealthRepository health; - late MockMeasurementRepository measurements; + group('enableSync', () { + test('returns null and stays disabled when permissions are denied', () async { + await PreferenceHelper.instance.setHealthSyncEnabled(false); + when(health.ensureAuthorized(any)).thenAnswer((_) async => false); - setUp(() async { - SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); - await PreferenceHelper.instance.setHealthSyncEnabled(true); + final count = await createNotifier().enableSync(); - health = MockHealthRepository(); - measurements = MockMeasurementRepository(); - - when(health.ensureAuthorized(any)).thenAnswer((_) async => true); - when(health.sourceName).thenReturn('apple'); - when(measurements.addLocalDrift(any)).thenAnswer((_) async {}); - when(measurements.addLocalDriftCategory(any)).thenAnswer((_) async {}); + expect(count, isNull); + expect(await PreferenceHelper.instance.getHealthSyncEnabled(), isFalse); + verifyNever( + health.read(types: anyNamed('types'), start: anyNamed('start'), end: anyNamed('end')), + ); }); - HealthSyncNotifier createNotifier() { - final container = ProviderContainer.test( - overrides: [ - healthRepositoryProvider.overrideWithValue(health), - measurementRepositoryProvider.overrideWithValue(measurements), - ], - ); - return container.read(healthSyncProvider.notifier); - } - - void stubReadings(List readings) { - when( - health.read( - types: anyNamed('types'), - start: anyNamed('start'), - end: anyNamed('end'), + test('persists the preference and runs an initial import', () async { + await PreferenceHelper.instance.setHealthSyncEnabled(false); + when(measurements.getAllOnce()).thenAnswer((_) async => []); + stubReadings([ + HealthReading( + type: HealthDataType.HEIGHT, + value: 1.8, + date: DateTime(2026, 1, 2), + externalId: 'h-1', ), - ).thenAnswer((_) async => readings); - } + ]); + final count = await createNotifier().enableSync(); + + expect(count, 1); + expect(await PreferenceHelper.instance.getHealthSyncEnabled(), isTrue); + }); + }); + + group('syncOnAppOpen', () { test('imports enabled metrics into new categories with converted values', () async { when(measurements.getAllOnce()).thenAnswer((_) async => []); stubReadings([ From 31153a22ec4168cda5e7c4c0ddfd59c8ab099b9c Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 01:54:15 +0200 Subject: [PATCH 038/484] Update translations --- lib/l10n/app_de.arb | 21 ++++++++++++++++++++- lib/l10n/app_es.arb | 21 ++++++++++++++++++++- lib/l10n/app_fr.arb | 21 ++++++++++++++++++++- 3 files changed, 60 insertions(+), 3 deletions(-) diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 1204cf164..3be91c1be 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1152,5 +1152,24 @@ "sessionExpired": "Deine Sitzung ist abgelaufen, bitte melde dich erneut an", "endBeforeStart": "Der Endwert darf nicht vor dem Startwert liegen", "minLengthRoutine": "Die Routine muss mindestens {number} Wochen lang sein", - "maxLengthRoutine": "Die Routine darf maximal {number} Wochen lang sein" + "maxLengthRoutine": "Die Routine darf maximal {number} Wochen lang sein", + "metricType": "Metrik-Typ", + "reorderCategories": "Kategorien neu anordnen", + "metricCustom": "Benutzerdefiniert", + "metricBodyWeight": "Körpergewicht", + "metricBodyFat": "Körperfett", + "metricHeight": "Körpergröße", + "metricBloodPressure": "Blutdruck", + "metricHeartRate": "Herzfrequenz", + "metricSteps": "Schritte", + "metricDistance": "Distanz", + "metricEnergy": "Energie", + "metricSleep": "Schlaf", + "partOfGroup": "Teil der Gruppe", + "noGroup": "Keine Gruppe", + "healthSync": "Health-Synchronisation", + "healthSyncDescription": "Importiert Körpermesswerte aus Apple Health oder Health Connect", + "healthSyncSuccess": "{count} Messwerte aus Health importiert", + "health": "Gesundheit", + "healthSyncPermissionDenied": "Zugriff auf die Gesundheitsdaten wurde nicht gewährt" } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 7ec8167a6..c6daef575 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1191,5 +1191,24 @@ "timeStartEndBothOrNeither": "Indica la hora de inicio y de fin, o deja ambas vacías", "endBeforeStart": "El final no puede ser anterior al inicio", "minLengthRoutine": "La rutina debe ser de al menos {number} semanas", - "maxLengthRoutine": "La rutina debe tener como mucho {number} semanas" + "maxLengthRoutine": "La rutina debe tener como mucho {number} semanas", + "metricType": "Tipo de métrica", + "reorderCategories": "Reordenar categorías", + "metricCustom": "Personalizado", + "metricBodyWeight": "Peso corporal", + "metricBodyFat": "Grasa corporal", + "metricHeight": "Altura", + "metricBloodPressure": "Presión arterial", + "metricHeartRate": "Frecuencia cardíaca", + "metricSteps": "Pasos", + "metricDistance": "Distancia", + "metricEnergy": "Energía", + "metricSleep": "Sueño", + "partOfGroup": "Parte del grupo", + "noGroup": "Sin grupo", + "healthSync": "Sincronización de salud", + "healthSyncDescription": "Importa medidas corporales desde Apple Health o Health Connect", + "healthSyncSuccess": "Se importaron {count} medidas de salud", + "health": "Salud", + "healthSyncPermissionDenied": "No se concedió el acceso a los datos de salud" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 0f1c4343e..0a94d5875 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1162,5 +1162,24 @@ "timeStartEndBothOrNeither": "Indiquez l'heure de début et de fin, ou laissez les deux vides", "endBeforeStart": "La valeur de fin ne peut être avant le début", "minLengthRoutine": "La routine doit durer au moins {number} semaines", - "maxLengthRoutine": "La routine peut durer au maximum {number} semaines" + "maxLengthRoutine": "La routine peut durer au maximum {number} semaines", + "metricType": "Type de métrique", + "reorderCategories": "Réorganiser les catégories", + "metricCustom": "Personnalisé", + "metricBodyWeight": "Poids corporel", + "metricBodyFat": "Graisse corporelle", + "metricHeight": "Taille", + "metricBloodPressure": "Pression artérielle", + "metricHeartRate": "Fréquence cardiaque", + "metricSteps": "Pas", + "metricDistance": "Distance", + "metricEnergy": "Énergie", + "metricSleep": "Sommeil", + "partOfGroup": "Fait partie du groupe", + "noGroup": "Aucun groupe", + "healthSync": "Synchronisation santé", + "healthSyncDescription": "Importe les mesures corporelles depuis Apple Santé ou Health Connect", + "healthSyncSuccess": "{count} mesures de santé importées", + "health": "Santé", + "healthSyncPermissionDenied": "L'accès aux données de santé n'a pas été autorisé" } From d8408aa75d1f17a5532df6d3ac6574ede96ab10b Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 01:58:36 +0200 Subject: [PATCH 039/484] Convert HealthSyncState to freezed --- .../health/providers/health_sync.dart | 27 +- .../health/providers/health_sync.freezed.dart | 271 ++++++++++++++++++ .../health/providers/health_sync.g.dart | 2 +- test/core/validators_test.mocks.dart | 11 + 4 files changed, 292 insertions(+), 19 deletions(-) create mode 100644 lib/features/health/providers/health_sync.freezed.dart diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index 3b3542414..dd1ceefd2 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -17,6 +17,7 @@ */ import 'package:collection/collection.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:health_bridge/health.dart'; import 'package:logging/logging.dart'; import 'package:powersync/powersync.dart' as ps; @@ -28,26 +29,16 @@ import 'package:wger/features/measurements/models/measurement_category.dart'; import 'package:wger/features/measurements/models/measurement_entry.dart'; import 'package:wger/features/measurements/providers/measurement_repository.dart'; +part 'health_sync.freezed.dart'; part 'health_sync.g.dart'; -class HealthSyncState { - final bool isEnabled; - final bool isSyncing; - final int lastSyncCount; - - const HealthSyncState({ - this.isEnabled = false, - this.isSyncing = false, - this.lastSyncCount = 0, - }); - - HealthSyncState copyWith({bool? isEnabled, bool? isSyncing, int? lastSyncCount}) { - return HealthSyncState( - isEnabled: isEnabled ?? this.isEnabled, - isSyncing: isSyncing ?? this.isSyncing, - lastSyncCount: lastSyncCount ?? this.lastSyncCount, - ); - } +@freezed +sealed class HealthSyncState with _$HealthSyncState { + const factory HealthSyncState({ + @Default(false) bool isEnabled, + @Default(false) bool isSyncing, + @Default(0) int lastSyncCount, + }) = _HealthSyncState; } /// Imports body metrics from Apple Health / Health Connect into measurement diff --git a/lib/features/health/providers/health_sync.freezed.dart b/lib/features/health/providers/health_sync.freezed.dart new file mode 100644 index 000000000..144b7758b --- /dev/null +++ b/lib/features/health/providers/health_sync.freezed.dart @@ -0,0 +1,271 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'health_sync.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$HealthSyncState { + + bool get isEnabled; bool get isSyncing; int get lastSyncCount; +/// Create a copy of HealthSyncState +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$HealthSyncStateCopyWith get copyWith => _$HealthSyncStateCopyWithImpl(this as HealthSyncState, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is HealthSyncState&&(identical(other.isEnabled, isEnabled) || other.isEnabled == isEnabled)&&(identical(other.isSyncing, isSyncing) || other.isSyncing == isSyncing)&&(identical(other.lastSyncCount, lastSyncCount) || other.lastSyncCount == lastSyncCount)); +} + + +@override +int get hashCode => Object.hash(runtimeType,isEnabled,isSyncing,lastSyncCount); + +@override +String toString() { + return 'HealthSyncState(isEnabled: $isEnabled, isSyncing: $isSyncing, lastSyncCount: $lastSyncCount)'; +} + + +} + +/// @nodoc +abstract mixin class $HealthSyncStateCopyWith<$Res> { + factory $HealthSyncStateCopyWith(HealthSyncState value, $Res Function(HealthSyncState) _then) = _$HealthSyncStateCopyWithImpl; +@useResult +$Res call({ + bool isEnabled, bool isSyncing, int lastSyncCount +}); + + + + +} +/// @nodoc +class _$HealthSyncStateCopyWithImpl<$Res> + implements $HealthSyncStateCopyWith<$Res> { + _$HealthSyncStateCopyWithImpl(this._self, this._then); + + final HealthSyncState _self; + final $Res Function(HealthSyncState) _then; + +/// Create a copy of HealthSyncState +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? isEnabled = null,Object? isSyncing = null,Object? lastSyncCount = null,}) { + return _then(_self.copyWith( +isEnabled: null == isEnabled ? _self.isEnabled : isEnabled // ignore: cast_nullable_to_non_nullable +as bool,isSyncing: null == isSyncing ? _self.isSyncing : isSyncing // ignore: cast_nullable_to_non_nullable +as bool,lastSyncCount: null == lastSyncCount ? _self.lastSyncCount : lastSyncCount // ignore: cast_nullable_to_non_nullable +as int, + )); +} + +} + + +/// Adds pattern-matching-related methods to [HealthSyncState]. +extension HealthSyncStatePatterns on HealthSyncState { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _HealthSyncState value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _HealthSyncState() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _HealthSyncState value) $default,){ +final _that = this; +switch (_that) { +case _HealthSyncState(): +return $default(_that);} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _HealthSyncState value)? $default,){ +final _that = this; +switch (_that) { +case _HealthSyncState() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( bool isEnabled, bool isSyncing, int lastSyncCount)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _HealthSyncState() when $default != null: +return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( bool isEnabled, bool isSyncing, int lastSyncCount) $default,) {final _that = this; +switch (_that) { +case _HealthSyncState(): +return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount);} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( bool isEnabled, bool isSyncing, int lastSyncCount)? $default,) {final _that = this; +switch (_that) { +case _HealthSyncState() when $default != null: +return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _HealthSyncState implements HealthSyncState { + const _HealthSyncState({this.isEnabled = false, this.isSyncing = false, this.lastSyncCount = 0}); + + +@override@JsonKey() final bool isEnabled; +@override@JsonKey() final bool isSyncing; +@override@JsonKey() final int lastSyncCount; + +/// Create a copy of HealthSyncState +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$HealthSyncStateCopyWith<_HealthSyncState> get copyWith => __$HealthSyncStateCopyWithImpl<_HealthSyncState>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _HealthSyncState&&(identical(other.isEnabled, isEnabled) || other.isEnabled == isEnabled)&&(identical(other.isSyncing, isSyncing) || other.isSyncing == isSyncing)&&(identical(other.lastSyncCount, lastSyncCount) || other.lastSyncCount == lastSyncCount)); +} + + +@override +int get hashCode => Object.hash(runtimeType,isEnabled,isSyncing,lastSyncCount); + +@override +String toString() { + return 'HealthSyncState(isEnabled: $isEnabled, isSyncing: $isSyncing, lastSyncCount: $lastSyncCount)'; +} + + +} + +/// @nodoc +abstract mixin class _$HealthSyncStateCopyWith<$Res> implements $HealthSyncStateCopyWith<$Res> { + factory _$HealthSyncStateCopyWith(_HealthSyncState value, $Res Function(_HealthSyncState) _then) = __$HealthSyncStateCopyWithImpl; +@override @useResult +$Res call({ + bool isEnabled, bool isSyncing, int lastSyncCount +}); + + + + +} +/// @nodoc +class __$HealthSyncStateCopyWithImpl<$Res> + implements _$HealthSyncStateCopyWith<$Res> { + __$HealthSyncStateCopyWithImpl(this._self, this._then); + + final _HealthSyncState _self; + final $Res Function(_HealthSyncState) _then; + +/// Create a copy of HealthSyncState +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? isEnabled = null,Object? isSyncing = null,Object? lastSyncCount = null,}) { + return _then(_HealthSyncState( +isEnabled: null == isEnabled ? _self.isEnabled : isEnabled // ignore: cast_nullable_to_non_nullable +as bool,isSyncing: null == isSyncing ? _self.isSyncing : isSyncing // ignore: cast_nullable_to_non_nullable +as bool,lastSyncCount: null == lastSyncCount ? _self.lastSyncCount : lastSyncCount // ignore: cast_nullable_to_non_nullable +as int, + )); +} + + +} + +// dart format on diff --git a/lib/features/health/providers/health_sync.g.dart b/lib/features/health/providers/health_sync.g.dart index 8410b9c61..5fd454271 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'bc23c2f6013f731414a7aa1ac98c618d1937c711'; +String _$healthSyncNotifierHash() => r'9465f7d3438b1bbab7c57f337b3f1673a28b3226'; /// Imports body metrics from Apple Health / Health Connect into measurement /// categories. Read-only: reads the platform (via [HealthRepository]), writes to diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 92ef67ae0..7814b5ef1 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -4734,6 +4734,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get healthSyncPermissionDenied => + (super.noSuchMethod( + Invocation.getter(#healthSyncPermissionDenied), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#healthSyncPermissionDenied), + ), + ) + as String); + @override String get health => (super.noSuchMethod( From 6cb489a8e4ef03441260ee347f4c4e3a5564c780 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 02:01:38 +0200 Subject: [PATCH 040/484] Fix iOS health usage description --- ios/Runner/Info.plist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 60b66f05c..b074f5c63 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -87,7 +87,7 @@ NSCameraUsageDescription Workout photos NSHealthShareUsageDescription - wger uses your health data to automatically sync weight measurements from your smart scale + wger reads your health data to automatically import body measurements such as body fat and height UIApplicationSceneManifest UIApplicationSupportsMultipleScenes From a9e2950bf5cb41afa86e057d29e23b8f7c3a76c0 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 11 Jul 2026 02:01:53 +0200 Subject: [PATCH 041/484] Add some more tests --- .../health/providers/health_sync_test.dart | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index edc7fc6c3..a2b50821b 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -51,8 +51,10 @@ void main() { when(measurements.addLocalDriftCategory(any)).thenAnswer((_) async {}); }); + late ProviderContainer container; + HealthSyncNotifier createNotifier() { - final container = ProviderContainer.test( + container = ProviderContainer.test( overrides: [ healthRepositoryProvider.overrideWithValue(health), measurementRepositoryProvider.overrideWithValue(measurements), @@ -121,6 +123,22 @@ void main() { }); }); + group('disableSync', () { + test('clears the preferences and resets the state', () async { + await PreferenceHelper.instance.setLastHealthSyncTimestamp('2026-06-01T12:00:00.000'); + final notifier = createNotifier(); + // let _loadPersistedState finish so it cannot re-enable the state later + await pumpEventQueue(); + expect(container.read(healthSyncProvider).isEnabled, isTrue); + + await notifier.disableSync(); + + expect(await PreferenceHelper.instance.getHealthSyncEnabled(), isFalse); + expect(await PreferenceHelper.instance.getLastHealthSyncTimestamp(), isNull); + expect(container.read(healthSyncProvider).isEnabled, isFalse); + }); + }); + group('syncOnAppOpen', () { test('imports enabled metrics into new categories with converted values', () async { when(measurements.getAllOnce()).thenAnswer((_) async => []); @@ -163,6 +181,12 @@ void main() { final height = entries.firstWhere((e) => e.externalId == 'h-1'); expect(height.value, 180.3); // meters -> cm, rounded to two decimals + + // The newest imported reading date becomes the next sync watermark + expect( + await PreferenceHelper.instance.getLastHealthSyncTimestamp(), + DateTime(2026, 1, 2).toIso8601String(), + ); }); test('skips readings already imported (dedup by externalId)', () async { From d855135aba005e943da4f33b8a22e1772478195d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 27 Jul 2026 00:54:19 +0000 Subject: [PATCH 042/484] Bump video_player from 2.12.0 to 2.13.0 Bumps [video_player](https://github.com/flutter/packages/tree/main/packages/video_player) from 2.12.0 to 2.13.0. - [Commits](https://github.com/flutter/packages/commits/video_player-v2.13.0/packages/video_player) --- updated-dependencies: - dependency-name: video_player dependency-version: 2.13.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pubspec.lock | 8 ++++---- pubspec.yaml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index c7ad7f33a..1799679f9 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1701,10 +1701,10 @@ packages: dependency: "direct main" description: name: video_player - sha256: "0431179e1a7a2234a1148f64dde63c73167ca23829815169b24cc0bc6b9444a3" + sha256: "20ef311160e2ced020a62f38e4cc399a1bf289e722fc5fe37c9d7b18e44c9e8d" url: "https://pub.dev" source: hosted - version: "2.12.0" + version: "2.13.0" video_player_android: dependency: transitive description: @@ -1717,10 +1717,10 @@ packages: dependency: transitive description: name: video_player_avfoundation - sha256: "9338f3ec22774f88146b22f13273a446719b1da010fd200c4d1d97802156ac58" + sha256: c238f5f0a26845cd0bcc2956049b63065a4d3c40ddfc22c3414cd170bef7fff9 url: "https://pub.dev" source: hosted - version: "2.9.7" + version: "2.11.0" video_player_platform_interface: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 14e42c02e..fd34d78ee 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -64,7 +64,7 @@ dependencies: table_calendar: ^3.2.0 url_launcher: ^6.3.2 version: ^3.0.2 - video_player: ^2.12.0 + video_player: ^2.13.0 logging: ^1.3.0 flutter_riverpod: ^3.3.2 riverpod_annotation: ^4.0.3 From bababb813fb7221a63fffa90a43e3cd6156c3032 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 27 Jul 2026 00:54:27 +0000 Subject: [PATCH 043/484] Bump connectivity_plus from 7.2.0 to 7.3.1 Bumps [connectivity_plus](https://github.com/fluttercommunity/plus_plugins/tree/main/packages/connectivity_plus) from 7.2.0 to 7.3.1. - [Release notes](https://github.com/fluttercommunity/plus_plugins/releases) - [Commits](https://github.com/fluttercommunity/plus_plugins/commits/connectivity_plus-v7.3.1/packages/connectivity_plus) --- updated-dependencies: - dependency-name: connectivity_plus dependency-version: 7.3.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pubspec.lock | 4 ++-- pubspec.yaml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index c7ad7f33a..47a960c25 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -285,10 +285,10 @@ packages: dependency: "direct main" description: name: connectivity_plus - sha256: cad0e811a289ea2a941119dc483c204ec1684cbb9a8fc7351fe4a230b8313160 + sha256: "762c99f890ca8bf87f7337236f99edd42793843bc6c3631da294a76653a54bd0" url: "https://pub.dev" source: hosted - version: "7.2.0" + version: "7.3.1" connectivity_plus_platform_interface: dependency: "direct dev" description: diff --git a/pubspec.yaml b/pubspec.yaml index 14e42c02e..f3fb76847 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -71,7 +71,7 @@ dependencies: drift_sqlite_async: ^0.3.1 stream_transform: ^2.1.1 state_notifier: ^1.0.0 - connectivity_plus: ^7.2.0 + connectivity_plus: ^7.3.1 powersync: ^2.3.1 dev_dependencies: From 89a1bfef591a3816da51fa1cf75447213caf6ed8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 27 Jul 2026 00:54:31 +0000 Subject: [PATCH 044/484] Bump drift from 2.34.0 to 2.34.2 Bumps [drift](https://github.com/simolus3/drift) from 2.34.0 to 2.34.2. - [Release notes](https://github.com/simolus3/drift/releases) - [Commits](https://github.com/simolus3/drift/compare/drift-2.34.0...drift-2.34.2) --- updated-dependencies: - dependency-name: drift dependency-version: 2.34.2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pubspec.lock | 8 ++++---- pubspec.yaml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index c7ad7f33a..b645116f3 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -365,10 +365,10 @@ packages: dependency: "direct main" description: name: drift - sha256: "6cc0b623c0e83f7080524d8396e9301b1d78b9c66a4fdceeb0f798211303254c" + sha256: "84688491040b0ceb26575709a84d701c84ad4df4d8aff020adf6d85f155fb0dd" url: "https://pub.dev" source: hosted - version: "2.34.0" + version: "2.34.2" drift_dev: dependency: "direct dev" description: @@ -1429,10 +1429,10 @@ packages: dependency: transitive description: name: sqlite3 - sha256: "37356bcb56ce0d9404d602c41e4bdb7765e7e9732a3e47adb3d98c556a6abdad" + sha256: c73fd75df1332d76a6257f4823ae4df9c791f522b97e4a60cbcad214de1becf4 url: "https://pub.dev" source: hosted - version: "3.3.3" + version: "3.5.0" sqlite3_connection_pool: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 14e42c02e..50e2b176b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -37,7 +37,7 @@ dependencies: clock: ^1.1.2 collection: ^1.19.1 cupertino_icons: ^1.0.9 - drift: ^2.34.0 + drift: ^2.34.2 equatable: ^2.1.0 extended_image: ^10.0.1 fl_chart: ^1.2.0 From d71a416d1e3a8f255286348e9dcaad3f67a1afce Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 27 Jul 2026 00:54:38 +0000 Subject: [PATCH 045/484] Bump build_runner from 2.15.0 to 2.15.1 Bumps [build_runner](https://github.com/dart-lang/build) from 2.15.0 to 2.15.1. - [Release notes](https://github.com/dart-lang/build/releases) - [Commits](https://github.com/dart-lang/build/compare/build_runner-v2.15.0...build_runner-v2.15.1) --- updated-dependencies: - dependency-name: build_runner dependency-version: 2.15.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pubspec.lock | 8 ++++---- pubspec.yaml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index c7ad7f33a..814ca20c4 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -101,10 +101,10 @@ packages: dependency: transitive description: name: build - sha256: a156715e7cd728130c592f30552575908aae5b100005fbc1f0fb16b3c03a3d10 + sha256: "45d14a0fb23e018d8287c32fc98d726ce466b231928ed9b9200f29bd3ccd39ae" url: "https://pub.dev" source: hosted - version: "4.0.6" + version: "4.0.7" build_config: dependency: transitive description: @@ -125,10 +125,10 @@ packages: dependency: "direct dev" description: name: build_runner - sha256: "1523ce62448ebac2c15a8ba5fbad8acac169788658a7dd2a1c2d9c2a9318b9a6" + sha256: "5367e521935b102bdf1e735d2aab461e36b2edca6517662d088dd04cc39f8d16" url: "https://pub.dev" source: hosted - version: "2.15.0" + version: "2.15.1" built_collection: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 14e42c02e..1d91cd7ca 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -79,7 +79,7 @@ dev_dependencies: sdk: flutter integration_test: sdk: flutter - build_runner: ^2.15.0 + build_runner: ^2.15.1 cider: ^0.2.10 fake_async: ^1.3.1 # Used to stub the connectivity_plus platform interface From 1b199bd06eb875a838f5101cc5217968f811c8e2 Mon Sep 17 00:00:00 2001 From: Matz Hilven Date: Tue, 28 Jul 2026 00:07:43 +0200 Subject: [PATCH 046/484] Fix crash when copying a log with no hydrated exercise Log.exerciseObj was declared late and is only ever assigned when hydrating the logs of a routine's sessions. Logs read from the database are built through drift's row class and only carry exerciseId, so copyWith threw a LateInitializationError when it unconditionally read the field. Copying a past log in gym mode does exactly that. Make the field nullable behind a getter that throws a descriptive error, add exerciseObjOrNull for callers that legitimately handle logs straight from the database, and only carry the exercise over when there is one. Hydrating the exercise in watchLogsByExerciseDrift instead would mean joining its translations, images, muscles and equipment for every log, which most callers don't need. The log page tests mocked the query with the test routine's logs, which are hydrated, which is why this was never caught. They now return logs without an exercise, like the real query does. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XzxNFoPMxsFPxHD3P2Ma3w --- lib/features/routines/models/log.dart | 26 ++++++++++++-- test/features/routines/models/log_test.dart | 36 +++++++++++++++++++ .../widgets/gym_mode/log_page_test.dart | 21 ++++++++++- 3 files changed, 80 insertions(+), 3 deletions(-) diff --git a/lib/features/routines/models/log.dart b/lib/features/routines/models/log.dart index d73675307..c800b70c0 100644 --- a/lib/features/routines/models/log.dart +++ b/lib/features/routines/models/log.dart @@ -43,7 +43,25 @@ class Log { String? id; late int exerciseId; - late Exercise exerciseObj; + + Exercise? _exerciseObj; + + /// The exercise this log belongs to, throws if it was never hydrated + /// + /// Logs read from the database only carry [exerciseId], joining the whole + /// exercise with its translations, images and muscles would be wasteful for + /// a value most callers don't need. Use [exerciseObjOrNull] for those. + Exercise get exerciseObj { + if (_exerciseObj == null) { + throw StateError('Log $id has no hydrated exercise (exercise ID $exerciseId)'); + } + return _exerciseObj!; + } + + set exerciseObj(Exercise value) => _exerciseObj = value; + + /// Like [exerciseObj] but returns null instead of throwing + Exercise? get exerciseObjOrNull => _exerciseObj; int? routineId; String? sessionId; @@ -153,7 +171,11 @@ class Log { out.weightUnitObj = weightUnitObj; out.weightUnitId = weightUnitObj.id; } - out.exerciseObj = exerciseObj; + + // Logs read from the database have no exercise, so only copy an existing one + if (_exerciseObj != null) { + out.exerciseObj = _exerciseObj!; + } return out; } diff --git a/test/features/routines/models/log_test.dart b/test/features/routines/models/log_test.dart index 9756702c2..28180846f 100644 --- a/test/features/routines/models/log_test.dart +++ b/test/features/routines/models/log_test.dart @@ -23,6 +23,8 @@ import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; +import '../../../../test_data/exercises.dart'; + void main() { group('Log.volume', () { test('returns weight * repetitions for metric (kg) and repetition unit', () { @@ -199,6 +201,40 @@ void main() { }); }); + group('Log exercise hydration', () { + /// A log as it comes out of the database, with only the exercise ID set + Log makeDriftLog() => Log( + id: 'log-1', + exerciseId: 1, + routineId: 100, + weight: 20, + repetitions: 10, + date: DateTime(2026, 1, 1), + ); + + test('copies a log whose exercise was never hydrated', () { + final copy = makeDriftLog().copyWith(date: DateTime(2026, 2, 2)); + + expect(copy.exerciseObjOrNull, isNull); + }); + + test('reading an unhydrated exercise throws a descriptive error', () { + expect( + () => makeDriftLog().exerciseObj, + throwsA(isA().having((e) => e.message, 'message', contains('log-1'))), + ); + }); + + test('propagates the exercise when it is hydrated', () { + final log = makeDriftLog()..exercise = testBenchPress; + + final copy = log.copyWith(weight: 30); + + expect(copy.exerciseObj.id, testBenchPress.id); + expect(copy.exerciseId, testBenchPress.id); + }); + }); + group('Test the workout log model', () { late Log log1; late Log log2; diff --git a/test/features/routines/widgets/gym_mode/log_page_test.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index c50344cfc..289591470 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.dart @@ -42,6 +42,23 @@ import '../../../../../test_data/exercises.dart'; import '../../../../../test_data/routines.dart' as testdata; import 'log_page_test.mocks.dart'; +/// Strips the exercise off a fixture log, watchLogsByExerciseDrift only joins the units +Log asDriftLog(Log log) => + Log( + id: log.id, + exerciseId: log.exerciseId, + iteration: log.iteration, + slotEntryId: log.slotEntryId, + routineId: log.routineId, + sessionId: log.sessionId, + repetitions: log.repetitions, + rir: log.rir, + weight: log.weight, + date: log.date, + ) + ..repetitionUnit = log.repetitionsUnitObj + ..weightUnit = log.weightUnitObj; + @GenerateMocks([WorkoutLogRepository]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -65,7 +82,9 @@ void main() { ), ).thenAnswer((invocation) { final exerciseId = invocation.namedArguments[#exerciseId] as int; - return Stream.value(testdata.getTestRoutine().filterLogsByExercise(exerciseId)); + return Stream.value( + testdata.getTestRoutine().filterLogsByExercise(exerciseId).map(asDriftLog).toList(), + ); }); container = ProviderContainer.test( overrides: [workoutLogRepositoryProvider.overrideWithValue(mockWorkoutLogRepo)], From b7a0d4893cc077dda08d42e2a62a69ce964633b8 Mon Sep 17 00:00:00 2001 From: Matz Hilven Date: Tue, 28 Jul 2026 00:11:08 +0200 Subject: [PATCH 047/484] Hydrate the exercise when copying a past log in gym mode Not copying an exercise that isn't there keeps the crash away, but gym mode then holds a log with no exercise, which would bite the next reader. The past logs widget already knows the exercise from the set config, so pass it down to setLog, which assigns it through the exercise setter so that exerciseId stays consistent. The notifier test worked around the old behaviour by setting exerciseObj on every fixture, with a comment explaining that copyWith needs it. That was the bug, written down, so it's gone. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01XzxNFoPMxsFPxHD3P2Ma3w --- .../routines/providers/gym_log_notifier.dart | 12 +++++++++-- .../routines/widgets/gym_mode/log_page.dart | 15 ++++++++++---- .../providers/gym_log_notifier_test.dart | 20 ++++++++++++++++--- 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/lib/features/routines/providers/gym_log_notifier.dart b/lib/features/routines/providers/gym_log_notifier.dart index 8f3d829c0..5bbf5bd5f 100644 --- a/lib/features/routines/providers/gym_log_notifier.dart +++ b/lib/features/routines/providers/gym_log_notifier.dart @@ -19,6 +19,7 @@ import 'package:clock/clock.dart'; import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/repetition_unit.dart'; import 'package:wger/features/routines/models/weight_unit.dart'; @@ -35,12 +36,19 @@ class GymLogNotifier extends _$GymLogNotifier { return null; } - void setLog(Log log) { + /// Pass [exercise] to hydrate the copy, logs read from the database only + /// carry their exercise ID + void setLog(Log log, {Exercise? exercise}) { // Clear the id so Drift mints a fresh UUID on insert, and the sessionId so // the copy lands in today's session instead of the template's historical one. - state = log.copyWith(date: clock.now()) + final out = log.copyWith(date: clock.now()) ..id = null ..sessionId = null; + + if (exercise != null) { + out.exercise = exercise; + } + state = out; } void setWeight(num weight) { diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index 2b69c93e6..6226bee1f 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -24,6 +24,7 @@ import 'package:wger/core/formatting/formatting.dart'; import 'package:wger/core/snackbar.dart'; import 'package:wger/core/widgets/core.dart'; import 'package:wger/core/widgets/error.dart'; +import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/models/slot_entry.dart'; @@ -142,7 +143,7 @@ class LogPage extends ConsumerWidget { // Overriding the log scope from here is handled in a follow-up, the // settings currently only live in the gym mode options. // _LogScopeControls(gymState: gymState), - Expanded(child: _buildPastLogs(pastLogs)), + Expanded(child: _buildPastLogs(pastLogs, setConfigData.exercise)), Padding( padding: const EdgeInsets.all(10), @@ -165,7 +166,7 @@ class LogPage extends ConsumerWidget { } /// Renders the previous logs for this exercise - Widget _buildPastLogs(AsyncValue> pastLogs) { + Widget _buildPastLogs(AsyncValue> pastLogs, Exercise exercise) { if (pastLogs.hasError) { _logger.warning('Could not load past logs', pastLogs.error, pastLogs.stackTrace); // Scroll-wrap so the indicator fits this slim slot instead of overflowing. @@ -174,7 +175,9 @@ class LogPage extends ConsumerWidget { ); } final logs = pastLogs.value ?? const []; - return logs.isEmpty ? const SizedBox.shrink() : LogsPastLogsWidget(pastLogs: logs); + return logs.isEmpty + ? const SizedBox.shrink() + : LogsPastLogsWidget(pastLogs: logs, exercise: exercise); } } @@ -235,9 +238,13 @@ class LogsPlatesWidget extends ConsumerWidget { class LogsPastLogsWidget extends ConsumerWidget { final List pastLogs; + /// The exercise the logs belong to, they only carry its ID + final Exercise exercise; + const LogsPastLogsWidget({ super.key, required this.pastLogs, + required this.exercise, }); @override @@ -261,7 +268,7 @@ class LogsPastLogsWidget extends ConsumerWidget { subtitle: Text(dateFormat.format(pastLog.date)), trailing: const Icon(Icons.copy), onTap: () { - logProvider.setLog(pastLog); + logProvider.setLog(pastLog, exercise: exercise); ScaffoldMessenger.of(context).hideCurrentSnackBar(); showSnackbar(context, AppLocalizations.of(context).dataCopied); }, diff --git a/test/features/routines/providers/gym_log_notifier_test.dart b/test/features/routines/providers/gym_log_notifier_test.dart index 28aed7820..7d98e5861 100644 --- a/test/features/routines/providers/gym_log_notifier_test.dart +++ b/test/features/routines/providers/gym_log_notifier_test.dart @@ -41,8 +41,6 @@ void main() { num repetitions = 10, DateTime? date, }) { - // Log.copyWith reads exerciseObj internally, so it must be set before - // setLog (which calls copyWith) is invoked. return Log( id: id ?? 'log-1', exerciseId: exerciseId, @@ -50,13 +48,29 @@ void main() { weight: weight, repetitions: repetitions, date: date ?? DateTime.utc(2020, 1, 1), - )..exerciseObj = testBenchPress; + ); } test('initial state is null', () { expect(container.read(gymLogProvider), isNull); }); + test('setLog accepts a log with no exercise, as read from the database', () { + container.read(gymLogProvider.notifier).setLog(makeLog()); + + final state = container.read(gymLogProvider)!; + expect(state.exerciseId, 1); + expect(state.exerciseObjOrNull, isNull); + }); + + test('setLog hydrates the exercise when the caller passes one', () { + container.read(gymLogProvider.notifier).setLog(makeLog(), exercise: testBenchPress); + + final state = container.read(gymLogProvider)!; + expect(state.exerciseObj.id, testBenchPress.id); + expect(state.exerciseId, testBenchPress.id); + }); + test('setLog stores a copy with cleared id/sessionId and the current clock as date', () { final fixed = DateTime.utc(2026, 5, 1, 12); withClock(Clock.fixed(fixed), () { From 46396f12553dc7dc72aafda0b45ba544e1c6146d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 28 Jul 2026 11:06:51 +0000 Subject: [PATCH 048/484] Bump powersync from 2.3.1 to 2.3.2 Bumps [powersync](https://github.com/powersync-ja/powersync.dart) from 2.3.1 to 2.3.2. - [Release notes](https://github.com/powersync-ja/powersync.dart/releases) - [Commits](https://github.com/powersync-ja/powersync.dart/compare/powersync-v2.3.1...powersync-v2.3.2) --- updated-dependencies: - dependency-name: powersync dependency-version: 2.3.2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pubspec.lock | 16 ++++++++-------- pubspec.yaml | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 1be5c8d14..2d3d2727e 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1184,10 +1184,10 @@ packages: dependency: "direct main" description: name: powersync - sha256: fd497501e9adbfcafb65870311c6c2b48f6146cbf67bb4e2d92f3f8da23bd9ab + sha256: "11a43bd499ad9fe8b573e93a0f2702fe695f4f3c3d20c40306468c7d985a90ae" url: "https://pub.dev" source: hosted - version: "2.3.1" + version: "2.3.2" powersync_flutter_libs: dependency: transitive description: @@ -1437,10 +1437,10 @@ packages: dependency: transitive description: name: sqlite3_connection_pool - sha256: "9d2b3b398b03c96743fd071521fc665be73c33c9cd5c56d87196baff8d8b4398" + sha256: ad51972d37bdf82929888e4c85e722bd9a0b5ff8ad389f89b1b00d19603c0d2d url: "https://pub.dev" source: hosted - version: "0.2.6" + version: "0.2.7" sqlite3_flutter_libs: dependency: transitive description: @@ -1453,18 +1453,18 @@ packages: dependency: transitive description: name: sqlite3_web - sha256: "183cd6e1523dd4c9097c0f8e8e3e92da2d852f9c680df441c53626444d6d8dce" + sha256: aa6af15ef8bf8551d3a84203e3cbc022990567372e46ef98f91bdb2018fcfb0e url: "https://pub.dev" source: hosted - version: "0.9.0" + version: "0.9.4" sqlite_async: dependency: transitive description: name: sqlite_async - sha256: "17176f00a10e5b8ba6e0205e42de1c15a94ff8762745fed19750b44b6bbd5649" + sha256: "83aff15d2bb3b296d35e15419a85c3207df3baca62b64b778958a59eb291502d" url: "https://pub.dev" source: hosted - version: "0.14.3" + version: "0.14.4" sqlparser: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 166533c5e..ffee458db 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -72,7 +72,7 @@ dependencies: stream_transform: ^2.1.1 state_notifier: ^1.0.0 connectivity_plus: ^7.3.1 - powersync: ^2.3.1 + powersync: ^2.3.2 dev_dependencies: flutter_test: From 3ee512fd6cb129bc9570e097be4d6f294224adb7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 28 Jul 2026 14:49:04 +0200 Subject: [PATCH 049/484] More intelligent powersync service URL handling When the server-provided powersync URL is not reachable, try using $server-url/ps/. This should help with self-hosted instances where SITE_URL points to localhost or other similar misconfigurations See https://github.com/wger-project/wger/issues/2432 --- lib/core/helpers.dart | 60 +++++++ lib/core/network/server_gating.dart | 31 ++-- lib/database/powersync/powersync.dart | 1 + lib/powersync/connector.dart | 65 +++++++- test/core/helpers_test.dart | 153 ++++++++++++++++++ .../network/auth_notifier_powersync_test.dart | 20 ++- test/core/network/server_gating_test.dart | 92 +++++++++++ test/powersync/connector_test.dart | 149 ++++++++++++++++- 8 files changed, 550 insertions(+), 21 deletions(-) diff --git a/lib/core/helpers.dart b/lib/core/helpers.dart index e151b1cde..9a8122165 100644 --- a/lib/core/helpers.dart +++ b/lib/core/helpers.dart @@ -20,6 +20,8 @@ import 'dart:async'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/misc.dart' show ProviderListenable; +import 'package:http/http.dart' as http; +import 'package:logging/logging.dart'; /// Awaits the first value of `provider` by explicitly subscribing via /// [Ref.listen]. Use this in notifier methods (outside of `build()`) @@ -102,6 +104,64 @@ Uri makeHeadlessUri(String serverUrl, String path) { ); } +final _probeLogger = Logger('powersync-probe'); + +/// Builds `/ps/`, the default path under which wger's reverse +/// proxy exposes the PowerSync service. +String _defaultPowerSyncUrl(String serverUrl) { + final server = Uri.parse(serverUrl); + final basePath = server.path.endsWith('/') + ? server.path.substring(0, server.path.length - 1) + : server.path; + return Uri( + scheme: server.scheme, + host: server.host, + port: server.port, + path: '$basePath/ps/', + ).toString(); +} + +/// Returns the first PowerSync endpoint that answers its liveness probe with +/// a 200, or null when none does. +/// +/// The `powersync_url` [provided] by the server's token endpoint is tried +/// first, then `/ps/` as a fallback. Probing instead of trusting +/// [provided] rescues servers whose `SITE_URL` doesn't match the URL the app +/// reaches them under (e.g. left at its `http://localhost` default): that +/// value is unreachable from the device, while the reverse proxy usually +/// still exposes the service under the default path. +Future findLivePowerSyncUrl({ + required http.Client client, + required String serverUrl, + required String? provided, + Duration probeTimeout = const Duration(seconds: 5), +}) async { + final parsed = provided == null ? null : Uri.tryParse(provided); + final candidates = { + if (parsed != null && parsed.hasScheme && parsed.host.isNotEmpty) provided!, + _defaultPowerSyncUrl(serverUrl), + }; + + for (final candidate in candidates) { + final probeUri = Uri.parse( + '$candidate${candidate.endsWith('/') ? '' : '/'}probes/liveness', + ); + + // Log failed probes + try { + final response = await client.get(probeUri).timeout(probeTimeout); + if (response.statusCode == 200) { + return candidate; + } + _probeLogger.info('PowerSync probe: $probeUri returned ${response.statusCode}'); + } on Exception catch (e) { + // Unreachable or timed out: try the next candidate. + _probeLogger.info('PowerSync probe: $probeUri failed: $e'); + } + } + return null; +} + /// Builds the absolute URL for a server-side media file given its /// [relativePath] (the raw value of a Django `ImageField` / `FileField` /// as stored in the DB, e.g. `ingredients/42/foo.jpg`). diff --git a/lib/core/network/server_gating.dart b/lib/core/network/server_gating.dart index fc099bd71..188d6be83 100644 --- a/lib/core/network/server_gating.dart +++ b/lib/core/network/server_gating.dart @@ -164,22 +164,27 @@ class ServerGating { return false; } final body = json.decode(tokenResponse.body) as Map; - final powerSyncUrl = body['powersync_url'] as String?; - if (powerSyncUrl == null || powerSyncUrl.isEmpty) { - _logger.warning('PowerSync probe: empty powersync_url in token response'); + final providedUrl = body['powersync_url'] as String?; + final powerSyncUrl = await findLivePowerSyncUrl( + client: _client, + serverUrl: serverUrl, + provided: providedUrl, + ); + if (powerSyncUrl == null) { + _logger.warning( + 'PowerSync probe: no endpoint answered the liveness probe ' + '(server-provided powersync_url: "$providedUrl")', + ); return false; } - - final probeUri = Uri.parse( - '$powerSyncUrl${powerSyncUrl.endsWith('/') ? '' : '/'}probes/liveness', - ); - final probeResponse = await _client.get(probeUri); - if (probeResponse.statusCode == 200) { - await _storage.markEverSynced(); - return true; + if (powerSyncUrl != providedUrl) { + _logger.warning( + 'PowerSync probe: server-provided powersync_url "$providedUrl" is ' + 'unreachable, using $powerSyncUrl instead', + ); } - _logger.warning('PowerSync probe: liveness returned ${probeResponse.statusCode}'); - return false; + await _storage.markEverSynced(); + return true; } on Exception catch (e, s) { _logger.warning('PowerSync probe failed: $e', e, s); return false; diff --git a/lib/database/powersync/powersync.dart b/lib/database/powersync/powersync.dart index e0d9eb167..7ccf2711c 100644 --- a/lib/database/powersync/powersync.dart +++ b/lib/database/powersync/powersync.dart @@ -187,6 +187,7 @@ void connectPowerSync(PowerSyncDatabase db, String baseUrl, http.Client client) connector: DjangoConnector( baseUrl: baseUrl, apiClient: ApiClient(baseUrl, client: client), + client: client, ), ); } diff --git a/lib/powersync/connector.dart b/lib/powersync/connector.dart index 09bdb55f6..1058f458e 100644 --- a/lib/powersync/connector.dart +++ b/lib/powersync/connector.dart @@ -26,6 +26,7 @@ import 'package:logging/logging.dart'; import 'package:powersync/powersync.dart'; import 'package:wger/core/error_dialogs.dart'; import 'package:wger/core/exceptions/http_exception.dart'; +import 'package:wger/core/helpers.dart'; import 'package:wger/core/network/jwt.dart'; import 'package:wger/powersync/api_client.dart'; @@ -67,6 +68,9 @@ class DjangoConnector extends PowerSyncBackendConnector { final String baseUrl; final ApiClient apiClient; + /// Client for the endpoint liveness probes in [fetchCredentials]. + final http.Client _probeClient; + /// IDs of CRUD operations that already triggered a user-facing /// rejection dialog this session. Without this gate the same /// permanent-failure op would re-pop the dialog on every sync tick @@ -85,7 +89,26 @@ class DjangoConnector extends PowerSyncBackendConnector { /// reachable. DateTime? _lastUnreachableLogAt; - DjangoConnector({required this.baseUrl, required this.apiClient}); + /// Endpoint last announced in the logs. [fetchCredentials] runs on every + /// token refresh, so the endpoint is only logged when it changes. + String? _lastLoggedEndpoint; + + /// When "no live PowerSync endpoint" was last logged; null while an + /// endpoint resolves. Throttled like [_logUnreachable], since PowerSync + /// re-drives [fetchCredentials] on its retry schedule. + DateTime? _lastNoEndpointLogAt; + + /// The `powersync_url` from the last token response and the endpoint it + /// resolved to. While the server keeps advertising the same URL, the cached + /// resolution is reused instead of re-probing on every token refresh (a dead + /// advertised URL would otherwise cost a probe timeout each time). A failed + /// resolution is never cached, so retries keep probing. Cleared on app + /// restart with the connector. + String? _lastProvidedUrl; + String? _lastResolvedEndpoint; + + DjangoConnector({required this.baseUrl, required this.apiClient, http.Client? client}) + : _probeClient = client ?? http.Client(); /// Get a token to authenticate against the PowerSync instance. @override @@ -109,8 +132,35 @@ class DjangoConnector extends PowerSyncBackendConnector { final token = session['token'] as String; final payload = decodeJwtPayload(token); + final provided = session['powersync_url'] as String?; + String? endpoint; + if (provided == _lastProvidedUrl && _lastResolvedEndpoint != null) { + endpoint = _lastResolvedEndpoint; + } else { + endpoint = await findLivePowerSyncUrl( + client: _probeClient, + serverUrl: baseUrl, + provided: provided, + ); + if (endpoint != null) { + _lastProvidedUrl = provided; + _lastResolvedEndpoint = endpoint; + } + } + if (endpoint == null) { + // The wger backend answered (the token fetch above succeeded), so this + // is a bad or down sync service, not the device being offline. + // Returning null skips the attempt; PowerSync retries on its own. + _logNoEndpoint(); + return null; + } + _lastNoEndpointLogAt = null; + if (endpoint != _lastLoggedEndpoint) { + logger.info('Connecting to PowerSync endpoint $endpoint'); + _lastLoggedEndpoint = endpoint; + } return PowerSyncCredentials( - endpoint: session['powersync_url'], + endpoint: endpoint, token: token, userId: payload?['sub']?.toString(), expiresAt: jwtExpOnLocalClock(payload), @@ -128,6 +178,17 @@ class DjangoConnector extends PowerSyncBackendConnector { } } + /// Logs an unresolved PowerSync endpoint at WARNING, throttled to once per + /// [unreachableLogInterval] per outage. + void _logNoEndpoint() { + final now = DateTime.now(); + final last = _lastNoEndpointLogAt; + if (last == null || now.difference(last) >= unreachableLogInterval) { + logger.warning('No PowerSync endpoint answered its liveness probe, skipping credentials'); + _lastNoEndpointLogAt = now; + } + } + /// Closes an outage announced by [_logUnreachable], if any. void _logReachableAgain() { if (_lastUnreachableLogAt != null) { diff --git a/test/core/helpers_test.dart b/test/core/helpers_test.dart index 66b73d0fb..9f62d7641 100644 --- a/test/core/helpers_test.dart +++ b/test/core/helpers_test.dart @@ -17,6 +17,9 @@ */ import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:logging/logging.dart'; import 'package:wger/core/helpers.dart'; void main() { @@ -177,4 +180,154 @@ void main() { }); }); }); + + group('findLivePowerSyncUrl', () { + const serverUrl = 'https://wger.example.com'; + + /// Client answering 200 only for the liveness probe of [liveEndpoint] + /// (with or without its trailing slash); records every requested URL. + MockClient liveOnlyAt(String liveEndpoint, [List? requested]) { + final probe = '$liveEndpoint${liveEndpoint.endsWith('/') ? '' : '/'}probes/liveness'; + return MockClient((request) async { + requested?.add(request.url.toString()); + return request.url.toString() == probe + ? http.Response('{"ready":true}', 200) + : http.Response('not found', 404); + }); + } + + test('uses the server-provided URL when it answers the probe', () async { + final requested = []; + final client = liveOnlyAt('https://ps.example.com', requested); + + expect( + await findLivePowerSyncUrl( + client: client, + serverUrl: serverUrl, + provided: 'https://ps.example.com', + ), + 'https://ps.example.com', + ); + expect(requested, ['https://ps.example.com/probes/liveness']); + }); + + test('falls back to /ps/ when the provided URL does not answer', () async { + // The #2432 shape: SITE_URL left at its localhost default, so the + // advertised URL points at the device itself. + expect( + await findLivePowerSyncUrl( + client: liveOnlyAt('$serverUrl/ps/'), + serverUrl: serverUrl, + provided: 'http://localhost/ps/', + ), + '$serverUrl/ps/', + ); + }); + + test('falls back when probing the provided URL throws', () async { + final client = MockClient((request) async { + if (request.url.host == 'ps.example.com') { + throw http.ClientException('Connection refused'); + } + return http.Response('{"ready":true}', 200); + }); + + expect( + await findLivePowerSyncUrl( + client: client, + serverUrl: serverUrl, + provided: 'https://ps.example.com', + ), + '$serverUrl/ps/', + ); + }); + + test('probes only the fallback for a missing URL', () async { + final requested = []; + final client = liveOnlyAt('$serverUrl/ps/', requested); + + expect( + await findLivePowerSyncUrl(client: client, serverUrl: serverUrl, provided: null), + '$serverUrl/ps/', + ); + expect(requested, ['$serverUrl/ps/probes/liveness']); + }); + + test('skips a URL without a scheme', () async { + final requested = []; + final client = liveOnlyAt('$serverUrl/ps/', requested); + + expect( + await findLivePowerSyncUrl( + client: client, + serverUrl: serverUrl, + provided: 'wger.example.com/ps/', + ), + '$serverUrl/ps/', + ); + expect(requested, ['$serverUrl/ps/probes/liveness']); + }); + + test('returns null when no candidate answers', () async { + expect( + await findLivePowerSyncUrl( + client: MockClient((_) async => http.Response('not found', 404)), + serverUrl: serverUrl, + provided: 'https://ps.example.com', + ), + isNull, + ); + }); + + test('logs failed probes at INFO with status code or exception', () async { + final records = []; + final sub = Logger.root.onRecord.listen(records.add); + addTearDown(sub.cancel); + + final client = MockClient((request) async { + if (request.url.host == 'ps.example.com') { + throw http.ClientException('Connection refused'); + } + return http.Response('bad gateway', 502); + }); + await findLivePowerSyncUrl( + client: client, + serverUrl: serverUrl, + provided: 'https://ps.example.com', + ); + + final messages = records.where((r) => r.level == Level.INFO).map((r) => r.message); + expect( + messages, + contains('PowerSync probe: https://ps.example.com/probes/liveness failed: ' + 'ClientException: Connection refused'), + ); + expect( + messages, + contains('PowerSync probe: $serverUrl/ps/probes/liveness returned 502'), + ); + }); + + test('keeps a sub-directory installation path in the fallback', () async { + expect( + await findLivePowerSyncUrl( + client: liveOnlyAt('https://example.com/wger/ps/'), + serverUrl: 'https://example.com/wger', + provided: null, + ), + 'https://example.com/wger/ps/', + ); + }); + + test('handles a trailing slash on the server URL', () async { + expect( + await findLivePowerSyncUrl( + client: liveOnlyAt('$serverUrl/ps/'), + serverUrl: '$serverUrl/', + provided: null, + ), + '$serverUrl/ps/', + ); + }); + }); } diff --git a/test/core/network/auth_notifier_powersync_test.dart b/test/core/network/auth_notifier_powersync_test.dart index c188bfe54..aa88b0412 100644 --- a/test/core/network/auth_notifier_powersync_test.dart +++ b/test/core/network/auth_notifier_powersync_test.dart @@ -78,6 +78,7 @@ void main() { final tMinAppVersion = Uri.parse('$serverUrl/api/v2/min-app-version/'); final tPowerSyncToken = Uri.parse('$serverUrl/api/v2/powersync-token'); final tLiveness = Uri.parse('${powerSyncUrl}probes/liveness'); + final tFallbackLiveness = Uri.parse('$serverUrl/ps/probes/liveness'); final tIssueRefresh = Uri.parse('$serverUrl/api/v2/issue-refresh-token'); final tHeadlessRefresh = Uri.parse('$serverUrl/allauth/app/v1/tokens/refresh'); @@ -157,6 +158,10 @@ void main() { ); when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('OK', 200)); + // When the advertised URL fails its probe, the resolution falls back to + // /ps/. A 404 keeps the "unreachable" scenarios unreachable; + // fallback-specific tests override this. + when(mockClient.get(tFallbackLiveness)).thenAnswer((_) async => Response('not found', 404)); // Default: the legacy-DRF → JWT migration POST silently fails as // "offline" so existing tests that seed PREFS_USER fall through to the @@ -447,11 +452,24 @@ void main() { final state = await container.read(authProvider.future); expect(state.status, AuthStatus.powerSyncUnreachable); - // Probe should never run if we can't resolve the URL. + // The unusable advertised URL is never probed; only the + // /ps/ fallback is (dead here via the setUp default). verifyNever(mockClient.get(tLiveness)); + verify(mockClient.get(tFallbackLiveness)).called(1); }, ); + test('dead advertised URL but live /ps/ fallback → loggedIn', () async { + when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('Bad Gateway', 502)); + when(mockClient.get(tFallbackLiveness)).thenAnswer((_) async => Response('OK', 200)); + + final container = makeContainer(); + final state = await container.read(authProvider.future); + + expect(state.status, AuthStatus.loggedIn); + expect(await PreferenceHelper.asyncPref.getBool(PREFS_HAS_EVER_SYNCED), true); + }); + test('token endpoint returns 500 → powerSyncUnreachable', () async { when( mockClient.get(tPowerSyncToken, headers: anyNamed('headers')), diff --git a/test/core/network/server_gating_test.dart b/test/core/network/server_gating_test.dart index bd3b391da..7c2e8688a 100644 --- a/test/core/network/server_gating_test.dart +++ b/test/core/network/server_gating_test.dart @@ -16,15 +16,20 @@ * along with this program. If not, see . */ +import 'dart:convert'; + import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:version/version.dart'; import 'package:wger/core/consts.dart'; +import 'package:wger/core/network/auth_credential.dart'; import 'package:wger/core/network/auth_credentials_storage.dart'; import 'package:wger/core/network/secure_token_storage.dart'; import 'package:wger/core/network/server_gating.dart'; +import '../../fake_auth_environment.dart'; + /// The version gates don't touch storage; this stand-in satisfies the /// constructor without pulling in secure-storage plumbing. class _FakeSecureTokenStorage extends Fake implements SecureTokenStorage {} @@ -35,6 +40,9 @@ ServerGating _gatingReturning(http.Response response) => ServerGating( ); void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + installFakeAuthEnvironment(); + group('min server version check', () { final minVersion = Version.parse(MIN_SERVER_VERSION); final aboveMin = Version(minVersion.major, minVersion.minor + 1, 0).toString(); @@ -129,4 +137,88 @@ void main() { expect(await gating.applicationUpdateRequired(serverUrl, '1.0.0'), true); }); }); + + group('isPowerSyncReachable', () { + const serverUrl = 'https://wger.example.com'; + const credential = AuthCredential.legacy('abc123'); + + /// Gating whose token endpoint answers [tokenBody] and whose liveness + /// probes answer 200 only for [liveUrl]. Every requested URL is + /// recorded in [requested]. + ServerGating gatingWithTokenResponse( + Map tokenBody, + String liveUrl, + List requested, + ) => ServerGating( + MockClient((request) async { + requested.add(request.url.toString()); + if (request.url.path.endsWith('/powersync-token')) { + return http.Response(json.encode(tokenBody), 200); + } + if (request.url.toString() == liveUrl) { + return http.Response('{"ready":true}', 200); + } + return http.Response('not found', 404); + }), + AuthCredentialsStorage(_FakeSecureTokenStorage()), + ); + + test('probes the server-provided powersync_url', () async { + final requested = []; + final gating = gatingWithTokenResponse( + {'token': 't', 'powersync_url': 'https://ps.example.com'}, + 'https://ps.example.com/probes/liveness', + requested, + ); + + expect( + await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential), + true, + ); + expect(requested, contains('https://ps.example.com/probes/liveness')); + }); + + test('falls back to /ps/ when powersync_url points at loopback', () async { + final requested = []; + final gating = gatingWithTokenResponse( + {'token': 't', 'powersync_url': 'http://localhost/ps/'}, + '$serverUrl/ps/probes/liveness', + requested, + ); + + expect( + await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential), + true, + ); + expect(requested, contains('$serverUrl/ps/probes/liveness')); + }); + + test('falls back to /ps/ when powersync_url is missing', () async { + final requested = []; + final gating = gatingWithTokenResponse( + {'token': 't'}, + '$serverUrl/ps/probes/liveness', + requested, + ); + + expect( + await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential), + true, + ); + expect(requested, contains('$serverUrl/ps/probes/liveness')); + }); + + test('returns false when the resolved URL does not answer the probe', () async { + final gating = gatingWithTokenResponse( + {'token': 't', 'powersync_url': 'https://ps.example.com'}, + 'https://somewhere-else.example.com/probes/liveness', + [], + ); + + expect( + await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential), + false, + ); + }); + }); } diff --git a/test/powersync/connector_test.dart b/test/powersync/connector_test.dart index 20edfa9df..ede037a1b 100644 --- a/test/powersync/connector_test.dart +++ b/test/powersync/connector_test.dart @@ -21,6 +21,7 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; import 'package:logging/logging.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -167,9 +168,28 @@ void main() { }); group('fetchCredentials', () { + /// Probe client answering 200 for any liveness probe, so the endpoint + /// resolution keeps whatever URL the token response advertised. + MockClient anyLivenessOk() => MockClient( + (request) async => request.url.path.endsWith('/probes/liveness') + ? http.Response('{"ready":true}', 200) + : http.Response('not found', 404), + ); + + /// Probe client answering 200 only for [probeUrl]. + MockClient liveOnlyAt(String probeUrl) => MockClient( + (request) async => request.url.toString() == probeUrl + ? http.Response('{"ready":true}', 200) + : http.Response('not found', 404), + ); + test('builds PowerSyncCredentials with userId from sub and expiresAt from exp', () async { final mockApi = MockApiClient(); - final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi); + final connector = DjangoConnector( + baseUrl: 'http://example.invalid', + apiClient: mockApi, + client: anyLivenessOk(), + ); final jwt = makeJwt({'sub': 'user-42', 'exp': 1700000000}); when(mockApi.getPowersyncToken()).thenAnswer( (_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'}, @@ -186,7 +206,11 @@ void main() { test('coerces a numeric sub into a String (Django sends ints)', () async { final mockApi = MockApiClient(); - final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi); + final connector = DjangoConnector( + baseUrl: 'http://example.invalid', + apiClient: mockApi, + client: anyLivenessOk(), + ); final jwt = makeJwt({'sub': 42, 'exp': 1700000000}); when(mockApi.getPowersyncToken()).thenAnswer( (_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'}, @@ -199,7 +223,11 @@ void main() { test('still produces credentials when JWT is opaque (userId/expiresAt null)', () async { final mockApi = MockApiClient(); - final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi); + final connector = DjangoConnector( + baseUrl: 'http://example.invalid', + apiClient: mockApi, + client: anyLivenessOk(), + ); when(mockApi.getPowersyncToken()).thenAnswer( (_) async => {'token': 'not.a.jwt', 'powersync_url': 'https://ps.example.com'}, ); @@ -212,6 +240,92 @@ void main() { expect(creds.expiresAt, isNull); }); + test('falls back to /ps/ when powersync_url does not answer the probe', () async { + final mockApi = MockApiClient(); + final connector = DjangoConnector( + baseUrl: 'http://example.invalid', + apiClient: mockApi, + client: liveOnlyAt('http://example.invalid/ps/probes/liveness'), + ); + final jwt = makeJwt({'sub': 'user-42', 'exp': 1700000000}); + when(mockApi.getPowersyncToken()).thenAnswer( + (_) async => {'token': jwt, 'powersync_url': 'http://localhost/ps/'}, + ); + + final creds = await connector.fetchCredentials(); + + expect(creds!.endpoint, 'http://example.invalid/ps/'); + }); + + test('falls back to /ps/ when powersync_url is missing', () async { + final mockApi = MockApiClient(); + final connector = DjangoConnector( + baseUrl: 'http://example.invalid', + apiClient: mockApi, + client: liveOnlyAt('http://example.invalid/ps/probes/liveness'), + ); + final jwt = makeJwt({'sub': 'user-42', 'exp': 1700000000}); + when(mockApi.getPowersyncToken()).thenAnswer( + (_) async => {'token': jwt}, + ); + + final creds = await connector.fetchCredentials(); + + expect(creds!.endpoint, 'http://example.invalid/ps/'); + }); + + test('probes once per powersync_url value, again when it changes', () async { + final probes = []; + final mockApi = MockApiClient(); + final connector = DjangoConnector( + baseUrl: 'http://example.invalid', + apiClient: mockApi, + client: MockClient((request) async { + probes.add(request.url.toString()); + return http.Response('{"ready":true}', 200); + }), + ); + final jwt = makeJwt({'sub': 'u', 'exp': 1700000000}); + when(mockApi.getPowersyncToken()).thenAnswer( + (_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'}, + ); + + await connector.fetchCredentials(); + await connector.fetchCredentials(); + expect(probes, ['https://ps.example.com/probes/liveness']); + + when(mockApi.getPowersyncToken()).thenAnswer( + (_) async => {'token': jwt, 'powersync_url': 'https://other.example.com'}, + ); + final creds = await connector.fetchCredentials(); + + expect(probes, hasLength(2)); + expect(creds!.endpoint, 'https://other.example.com'); + }); + + test('does not cache a failed resolution', () async { + final probes = []; + final mockApi = MockApiClient(); + final connector = DjangoConnector( + baseUrl: 'http://example.invalid', + apiClient: mockApi, + client: MockClient((request) async { + probes.add(request.url.toString()); + return http.Response('not found', 404); + }), + ); + final jwt = makeJwt({'sub': 'u', 'exp': 1700000000}); + when(mockApi.getPowersyncToken()).thenAnswer( + (_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'}, + ); + + expect(await connector.fetchCredentials(), isNull); + expect(await connector.fetchCredentials(), isNull); + + // Both candidates probed on both attempts: no negative caching. + expect(probes, hasLength(4)); + }); + test('returns null when the backend is unreachable', () async { final mockApi = MockApiClient(); final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi); @@ -224,7 +338,11 @@ void main() { test('anchors expiresAt to the local clock via the token lifetime', () async { final mockApi = MockApiClient(); - final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi); + final connector = DjangoConnector( + baseUrl: 'http://example.invalid', + apiClient: mockApi, + client: anyLivenessOk(), + ); // iat/exp lie far in the past; only their 600 s difference may matter. final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600}); when(mockApi.getPowersyncToken()).thenAnswer( @@ -244,7 +362,11 @@ void main() { setUp(() { mockApi = MockApiClient(); - connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi); + connector = DjangoConnector( + baseUrl: 'http://example.invalid', + apiClient: mockApi, + client: anyLivenessOk(), + ); records = []; final sub = Logger.root.onRecord.listen(records.add); addTearDown(sub.cancel); @@ -300,6 +422,23 @@ void main() { expect(infoLines('backend unreachable'), hasLength(2)); }); + test('logs the endpoint once, again only when it changes', () async { + final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600}); + when(mockApi.getPowersyncToken()).thenAnswer( + (_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'}, + ); + await connector.fetchCredentials(); + await connector.fetchCredentials(); + + when(mockApi.getPowersyncToken()).thenAnswer( + (_) async => {'token': jwt, 'powersync_url': 'https://other.example.com'}, + ); + await connector.fetchCredentials(); + + expect(infoLines('endpoint https://ps.example.com'), hasLength(1)); + expect(infoLines('endpoint https://other.example.com'), hasLength(1)); + }); + test('does not log recovery when there was no outage', () async { final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600}); when(mockApi.getPowersyncToken()).thenAnswer( From b5847b4f847ecf5f45048d52aea9ef75b724bfc9 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 28 Jul 2026 15:18:55 +0200 Subject: [PATCH 050/484] Adapt the code to changes in powersync 2.3.2 --- lib/database/powersync/powersync.dart | 2 +- .../core/widgets/sync_status_dialog_test.dart | 37 ++++++++------- test/helpers/sync_status.dart | 46 +++++++++++++++++++ test/powersync/sync_watchdog_test.dart | 30 ++++++------ 4 files changed, 79 insertions(+), 36 deletions(-) create mode 100644 test/helpers/sync_status.dart diff --git a/lib/database/powersync/powersync.dart b/lib/database/powersync/powersync.dart index e0d9eb167..8306f96b5 100644 --- a/lib/database/powersync/powersync.dart +++ b/lib/database/powersync/powersync.dart @@ -199,7 +199,7 @@ final _syncStatusInternal = StreamProvider((ref) { final syncStatus = Provider((ref) { // ignore: invalid_use_of_internal_member - return ref.watch(_syncStatusInternal).value ?? const SyncStatus(); + return ref.watch(_syncStatusInternal).value ?? const SyncStatus.uninitialized(); }); Future _getDatabasePath() async { diff --git a/test/core/widgets/sync_status_dialog_test.dart b/test/core/widgets/sync_status_dialog_test.dart index 591636fea..76c4985f1 100644 --- a/test/core/widgets/sync_status_dialog_test.dart +++ b/test/core/widgets/sync_status_dialog_test.dart @@ -16,9 +16,6 @@ * along with this program. If not, see . */ -// SyncStatus constructor is marked as @internal -// ignore_for_file: invalid_use_of_internal_member - import 'dart:io' show SocketException; import 'package:flutter/material.dart'; @@ -35,6 +32,8 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/l10n/generated/app_localizations_en.dart'; import 'package:wger/powersync/connector.dart' show RetryableUploadException; +import '../../helpers/sync_status.dart'; + Widget _wrap(Widget child) { return MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -55,26 +54,26 @@ void main() { group('syncStatusIconAndLabel', () { test('idle, online → Connected + cloud_done', () { - final r = syncStatusIconAndLabel(const SyncStatus(connected: true), i18n); + final r = syncStatusIconAndLabel(buildSyncStatus(connected: true), i18n); expect(r.icon, Icons.cloud_done_outlined); expect(r.label, i18n.syncStatusConnected); }); test('connecting → Connecting + cloud_queue', () { - final r = syncStatusIconAndLabel(const SyncStatus(connecting: true), i18n); + final r = syncStatusIconAndLabel(buildSyncStatus(connecting: true), i18n); expect(r.icon, Icons.cloud_queue); expect(r.label, i18n.syncStatusConnecting); }); test('disconnected → Disconnected + cloud_off', () { - final r = syncStatusIconAndLabel(const SyncStatus(), i18n); + final r = syncStatusIconAndLabel(buildSyncStatus(), i18n); expect(r.icon, Icons.cloud_off); expect(r.label, i18n.syncStatusDisconnected); }); test('uploading only → Uploading + cloud_upload', () { final r = syncStatusIconAndLabel( - const SyncStatus(connected: true, uploading: true), + buildSyncStatus(connected: true, uploading: true), i18n, ); expect(r.icon, Icons.cloud_upload_outlined); @@ -83,7 +82,7 @@ void main() { test('downloading only → Downloading + cloud_download', () { final r = syncStatusIconAndLabel( - const SyncStatus(connected: true, downloading: true), + buildSyncStatus(connected: true, downloading: true), i18n, ); expect(r.icon, Icons.cloud_download_outlined); @@ -92,7 +91,7 @@ void main() { test('uploading + downloading → Synchronizing + cloud_sync', () { final r = syncStatusIconAndLabel( - const SyncStatus(connected: true, uploading: true, downloading: true), + buildSyncStatus(connected: true, uploading: true, downloading: true), i18n, ); expect(r.icon, Icons.cloud_sync_outlined); @@ -101,7 +100,7 @@ void main() { test('error while connected → Sync error + sync_problem', () { final r = syncStatusIconAndLabel( - SyncStatus(connected: true, downloadError: Exception('boom')), + buildSyncStatus(connected: true, downloadError: Exception('boom')), i18n, ); expect(r.icon, Icons.sync_problem); @@ -110,7 +109,7 @@ void main() { test('error while disconnected → Sync error + cloud_off', () { final r = syncStatusIconAndLabel( - SyncStatus(downloadError: Exception('boom')), + buildSyncStatus(downloadError: Exception('boom')), i18n, ); expect(r.icon, Icons.cloud_off); @@ -120,7 +119,7 @@ void main() { group('SyncStatusDialog rendering', () { testWidgets('renders title, status label, and "never synced" placeholder', (tester) async { - await _pumpDialog(tester, const SyncStatus(connected: true)); + await _pumpDialog(tester, buildSyncStatus(connected: true)); expect(find.text(i18n.syncStatusDialogTitle), findsOneWidget); expect(find.text(i18n.syncStatusConnected), findsOneWidget); @@ -130,14 +129,14 @@ void main() { testWidgets('formats the last-sync timestamp when set', (tester) async { final lastSync = DateTime.utc(2025, 1, 15, 9, 30, 45); - await _pumpDialog(tester, SyncStatus(connected: true, lastSyncedAt: lastSync)); + await _pumpDialog(tester, buildSyncStatus(connected: true, lastSyncedAt: lastSync)); expect(find.text('-/-'), findsNothing); expect(find.textContaining('2025'), findsOneWidget); }); testWidgets('omits the error expander when there is no error', (tester) async { - await _pumpDialog(tester, const SyncStatus(connected: true)); + await _pumpDialog(tester, buildSyncStatus(connected: true)); expect(find.byType(ExpansionTile), findsNothing); expect(find.text(i18n.syncStatusErrorDetails), findsNothing); @@ -145,7 +144,7 @@ void main() { testWidgets('shows the blocked-connection hint when stalled without an error', (tester) async { await tester.pumpWidget( - _wrap(const SyncStatusDialog(SyncStatus(connecting: true), stalled: true)), + _wrap(SyncStatusDialog(buildSyncStatus(connecting: true), stalled: true)), ); await tester.pumpAndSettle(); @@ -154,7 +153,7 @@ void main() { }); testWidgets('omits the stalled hint when not stalled', (tester) async { - await _pumpDialog(tester, const SyncStatus(connecting: true)); + await _pumpDialog(tester, buildSyncStatus(connecting: true)); expect(find.text(i18n.syncStatusStalledHint), findsNothing); expect(find.text(i18n.applicationLogs), findsNothing); @@ -164,7 +163,7 @@ void main() { await tester.pumpWidget( _wrap( SyncStatusDialog( - SyncStatus(connecting: true, downloadError: Exception('boom')), + buildSyncStatus(connecting: true, downloadError: Exception('boom')), stalled: true, ), ), @@ -178,7 +177,7 @@ void main() { testWidgets('renders the expander with the raw error message when present', (tester) async { await _pumpDialog( tester, - SyncStatus(connected: true, downloadError: Exception('disk-on-fire')), + buildSyncStatus(connected: true, downloadError: Exception('disk-on-fire')), ); expect(find.byType(ExpansionTile), findsOneWidget); @@ -193,7 +192,7 @@ void main() { group('SyncStatusDialog error categorisation', () { Future expectCategory(WidgetTester tester, Object error, String? category) async { - await _pumpDialog(tester, SyncStatus(connected: true, downloadError: error)); + await _pumpDialog(tester, buildSyncStatus(connected: true, downloadError: error)); if (category == null) { for (final candidate in const [ 'Authentication error', diff --git a/test/helpers/sync_status.dart b/test/helpers/sync_status.dart new file mode 100644 index 000000000..b8220687a --- /dev/null +++ b/test/helpers/sync_status.dart @@ -0,0 +1,46 @@ +/* + * 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:powersync/powersync.dart' show SyncStatus; + +/// Builds a [SyncStatus] for tests. Since powersync 2.3.2 the constructor is +/// @internal and requires every parameter, so fabricate statuses through this +/// helper instead. +SyncStatus buildSyncStatus({ + bool connected = false, + bool connecting = false, + bool downloading = false, + bool uploading = false, + DateTime? lastSyncedAt, + Object? downloadError, + Object? uploadError, +}) { + // ignore: invalid_use_of_internal_member + return SyncStatus( + connected: connected, + connecting: connecting, + downloading: downloading, + uploading: uploading, + lastSyncedAt: lastSyncedAt, + downloadProgress: null, + downloadError: downloadError, + uploadError: uploadError, + priorityStatusEntries: const [], + streamSubscriptions: null, + ); +} diff --git a/test/powersync/sync_watchdog_test.dart b/test/powersync/sync_watchdog_test.dart index cd4fde5c8..67cab6bcc 100644 --- a/test/powersync/sync_watchdog_test.dart +++ b/test/powersync/sync_watchdog_test.dart @@ -16,15 +16,13 @@ * along with this program. If not, see . */ -// SyncStatus constructor is marked as @internal -// ignore_for_file: invalid_use_of_internal_member - import 'package:fake_async/fake_async.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:logging/logging.dart'; -import 'package:powersync/powersync.dart' show SyncStatus; import 'package:wger/powersync/sync_watchdog.dart'; +import '../helpers/sync_status.dart'; + void main() { late SyncStreamWatchdog watchdog; late List records; @@ -42,7 +40,7 @@ void main() { test('flags a connection that never delivers a checkpoint', () { fakeAsync((async) { - watchdog.onStatus(const SyncStatus(connecting: true)); + watchdog.onStatus(buildSyncStatus(connecting: true)); async.elapse(watchdog.timeout - const Duration(seconds: 1)); expect(watchdog.stalled.value, isFalse); @@ -58,9 +56,9 @@ void main() { // Mimic the status flapping of an iteration that starts, ends cleanly // and retries: connecting toggles, lastSyncedAt never moves. for (var i = 0; i < 20; i++) { - watchdog.onStatus(const SyncStatus(connecting: true)); + watchdog.onStatus(buildSyncStatus(connecting: true)); async.elapse(const Duration(seconds: 5)); - watchdog.onStatus(const SyncStatus()); + watchdog.onStatus(buildSyncStatus()); async.elapse(const Duration(seconds: 5)); } @@ -71,9 +69,9 @@ void main() { test('a checkpoint disarms the watchdog, idle time does not re-trigger it', () { fakeAsync((async) { - watchdog.onStatus(const SyncStatus(connecting: true)); + watchdog.onStatus(buildSyncStatus(connecting: true)); async.elapse(const Duration(seconds: 10)); - watchdog.onStatus(SyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23))); + watchdog.onStatus(buildSyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23))); // A healthy connection can sit idle without new status events for far // longer than the timeout. @@ -86,7 +84,7 @@ void main() { test('an active download holds the watchdog off', () { fakeAsync((async) { - watchdog.onStatus(const SyncStatus(connected: true, downloading: true)); + watchdog.onStatus(buildSyncStatus(connected: true, downloading: true)); async.elapse(watchdog.timeout * 2); expect(watchdog.stalled.value, isFalse); @@ -95,7 +93,7 @@ void main() { test('a surfaced sync error holds the watchdog off', () { fakeAsync((async) { - watchdog.onStatus(SyncStatus(connecting: true, downloadError: Exception('boom'))); + watchdog.onStatus(buildSyncStatus(connecting: true, downloadError: Exception('boom'))); async.elapse(watchdog.timeout * 2); expect(watchdog.stalled.value, isFalse); @@ -104,11 +102,11 @@ void main() { test('recovers and logs once when a checkpoint finally arrives', () { fakeAsync((async) { - watchdog.onStatus(const SyncStatus(connecting: true)); + watchdog.onStatus(buildSyncStatus(connecting: true)); async.elapse(watchdog.timeout); expect(watchdog.stalled.value, isTrue); - watchdog.onStatus(SyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23))); + watchdog.onStatus(buildSyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23))); expect(watchdog.stalled.value, isFalse); expect(logLines(Level.INFO, 'recovered'), hasLength(1)); @@ -117,7 +115,7 @@ void main() { test('reset() clears the pending timer and the stalled flag', () { fakeAsync((async) { - watchdog.onStatus(const SyncStatus(connecting: true)); + watchdog.onStatus(buildSyncStatus(connecting: true)); async.elapse(watchdog.timeout); expect(watchdog.stalled.value, isTrue); @@ -132,10 +130,10 @@ void main() { test('re-arms after reset() for the next connection epoch', () { fakeAsync((async) { - watchdog.onStatus(SyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23))); + watchdog.onStatus(buildSyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23))); watchdog.reset(); - watchdog.onStatus(const SyncStatus(connecting: true)); + watchdog.onStatus(buildSyncStatus(connecting: true)); async.elapse(watchdog.timeout); expect(watchdog.stalled.value, isTrue); From 4a632189d34d250b466145c1771a3ec96a4d47c6 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 28 Jul 2026 15:29:50 +0200 Subject: [PATCH 051/484] Fix flaky test --- .../routines/widgets/gym_mode/session_page_test.dart | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/test/features/routines/widgets/gym_mode/session_page_test.dart b/test/features/routines/widgets/gym_mode/session_page_test.dart index 19b97b86a..199d9a7d5 100644 --- a/test/features/routines/widgets/gym_mode/session_page_test.dart +++ b/test/features/routines/widgets/gym_mode/session_page_test.dart @@ -119,12 +119,13 @@ void main() { ); notifier.calculatePages(); - await tester.pumpWidget(renderSessionPage()); - await tester.pumpAndSettle(); + await withClock(Clock.fixed(DateTime(2021, 5, 1, 15, 23)), () async { + await tester.pumpWidget(renderSessionPage()); + await tester.pumpAndSettle(); - final timeNow = TimeOfDay.now().format(tester.element(find.byType(TextFormField).first)); - expect(find.text('1:35 PM'), findsOneWidget); - expect(find.text(timeNow), findsOneWidget); + expect(find.text('1:35 PM'), findsOneWidget); + expect(find.text('3:23 PM'), findsOneWidget); + }); }); testWidgets('Test correct default data (no existing session)', (WidgetTester tester) async { From 0cf4111c8d40a8767d7fb65c9d547cc5a0474719 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 28 Jul 2026 17:04:44 +0200 Subject: [PATCH 052/484] Set fixed size for logo This was causing tests to fail due to the screen size and the sharding behaviour in CI --- lib/features/auth/screens/auth_screen.dart | 1 + test/features/auth/screens/auth_screen_test.dart | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/lib/features/auth/screens/auth_screen.dart b/lib/features/auth/screens/auth_screen.dart index cd6d96df8..b1f20ba36 100644 --- a/lib/features/auth/screens/auth_screen.dart +++ b/lib/features/auth/screens/auth_screen.dart @@ -53,6 +53,7 @@ class AuthScreen extends StatelessWidget { const Image( image: AssetImage('assets/images/logo-white.png'), width: 85, + height: 85, ), Container( margin: const EdgeInsets.only(bottom: 20.0), diff --git a/test/features/auth/screens/auth_screen_test.dart b/test/features/auth/screens/auth_screen_test.dart index 35af5e06c..9c4da0552 100644 --- a/test/features/auth/screens/auth_screen_test.dart +++ b/test/features/auth/screens/auth_screen_test.dart @@ -334,6 +334,10 @@ void main() { await tester.pumpAndSettle(); // Act + // The card overflows the default 800x600 test surface and clips the + // ADVANCED footer at the bottom, so scroll it into view before tapping. + await tester.ensureVisible(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); await tester.tap(find.byKey(const Key('advancedButton'))); await tester.pumpAndSettle(); await tester.tap(find.text('Refresh token')); @@ -382,6 +386,10 @@ void main() { await tester.pumpAndSettle(); // Act + // The card overflows the default 800x600 test surface and clips the + // ADVANCED footer at the bottom, so scroll it into view before tapping. + await tester.ensureVisible(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); await tester.tap(find.byKey(const Key('advancedButton'))); await tester.pumpAndSettle(); await tester.tap(find.text('Refresh token')); From 7122d3032a70425dd6f88e5295429ba0db3d33f0 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 14:36:09 +0200 Subject: [PATCH 053/484] Bump flutter version --- .github/actions/flutter-common/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/flutter-common/action.yml b/.github/actions/flutter-common/action.yml index 051656e5e..eaf2fd817 100644 --- a/.github/actions/flutter-common/action.yml +++ b/.github/actions/flutter-common/action.yml @@ -9,7 +9,7 @@ runs: uses: subosito/flutter-action@v2 with: channel: stable - flutter-version: 3.44.4 + flutter-version: 3.44.8 cache: true - name: Install Flutter dependencies From 4f4b32e61d0a78aa9f2784de300b3584cdbd1838 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 14:46:54 +0200 Subject: [PATCH 054/484] Make exerciseObj in SlotEntry hydration-safe --- lib/features/routines/models/slot_entry.dart | 20 ++++++++++++- .../models/slot_entry_model_test.dart | 29 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/lib/features/routines/models/slot_entry.dart b/lib/features/routines/models/slot_entry.dart index 9dcc47c2f..67abb8952 100644 --- a/lib/features/routines/models/slot_entry.dart +++ b/lib/features/routines/models/slot_entry.dart @@ -91,8 +91,26 @@ class SlotEntry { @JsonKey(required: true) late SlotEntryType type; + Exercise? _exerciseObj; + + /// The exercise of this entry, throws if it was never hydrated + /// + /// Entries parsed from the API only carry [exerciseId], the exercise is + /// attached later from the local exercise list, which may not have synced + /// yet. Use [exerciseObjOrNull] for callers that handle that case. @JsonKey(includeFromJson: false, includeToJson: false) - late Exercise exerciseObj; + Exercise get exerciseObj { + if (_exerciseObj == null) { + throw StateError('Slot entry $id has no hydrated exercise (exercise ID $exerciseId)'); + } + return _exerciseObj!; + } + + set exerciseObj(Exercise value) => _exerciseObj = value; + + /// Like [exerciseObj] but returns null instead of throwing + @JsonKey(includeFromJson: false, includeToJson: false) + Exercise? get exerciseObjOrNull => _exerciseObj; @JsonKey(required: true, name: 'exercise') late int exerciseId; diff --git a/test/features/routines/models/slot_entry_model_test.dart b/test/features/routines/models/slot_entry_model_test.dart index 00160c116..dc27681ed 100644 --- a/test/features/routines/models/slot_entry_model_test.dart +++ b/test/features/routines/models/slot_entry_model_test.dart @@ -22,6 +22,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:wger/features/routines/models/base_config.dart'; import 'package:wger/features/routines/models/slot_entry.dart'; +import '../../../../test_data/exercises.dart'; import '../../../fixtures/fixture_reader.dart'; void main() { @@ -30,6 +31,7 @@ void main() { final slotEntry = SlotEntry.fromJson(json.decode(apiResponse)); expect(slotEntry.id, 143); + expect(slotEntry.exerciseObjOrNull, isNull); expect(slotEntry.slotId, 140); expect(slotEntry.order, 2); expect(slotEntry.config, null); @@ -61,4 +63,31 @@ void main() { slotEntry.weightConfigs.add(BaseConfig.firstIteration(4, 1)); expect(slotEntry.hasProgressionRules, true); }); + + group('exercise hydration', () { + SlotEntry makeEntry() => SlotEntry( + id: 42, + slotId: 1, + exerciseId: 1, + repetitionUnitId: 1, + repetitionRounding: 1, + weightUnitId: 1, + weightRounding: 1.25, + ); + + test('reading an unhydrated exercise throws a descriptive error', () { + expect( + () => makeEntry().exerciseObj, + throwsA(isA().having((e) => e.message, 'message', contains('42'))), + ); + }); + + test('setting the exercise hydrates the entry', () { + final entry = makeEntry()..exercise = testBenchPress; + + expect(entry.exerciseObj.id, testBenchPress.id); + expect(entry.exerciseObjOrNull, isNotNull); + expect(entry.exerciseId, testBenchPress.id); + }); + }); } From cea7d8d9784497562a75f34e99011b39d56f14f7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 14:53:07 +0200 Subject: [PATCH 055/484] Fix run step name --- .github/actions/flutter-common/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/flutter-common/action.yml b/.github/actions/flutter-common/action.yml index eaf2fd817..2e0dd31ac 100644 --- a/.github/actions/flutter-common/action.yml +++ b/.github/actions/flutter-common/action.yml @@ -16,7 +16,7 @@ runs: run: flutter pub get shell: bash - - name: Install Flutter dependencies + - name: Show versions run: | dart --version flutter --version From 4261debc0b362c17ff2925f7dd96ba696f7ff219 Mon Sep 17 00:00:00 2001 From: Github-Actions Date: Wed, 29 Jul 2026 13:08:56 +0000 Subject: [PATCH 056/484] Bump version to 2.0.3 --- flatpak/de.wger.flutter.metainfo.xml | 6 ++++++ pubspec.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/flatpak/de.wger.flutter.metainfo.xml b/flatpak/de.wger.flutter.metainfo.xml index 54bf31437..63ad61563 100755 --- a/flatpak/de.wger.flutter.metainfo.xml +++ b/flatpak/de.wger.flutter.metainfo.xml @@ -87,6 +87,12 @@ + + +

Bug fixes and improvements.

+
+ https://github.com/wger-project/flutter/releases/tag/2.0.3 +

Bug fixes and improvements.

diff --git a/pubspec.yaml b/pubspec.yaml index ffee458db..9dae68fac 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -21,7 +21,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # - the version number is taken from the git tag vX.Y.Z # - the build number is computed by reading the last one from the play store # and increasing by one -version: 2.0.2+230 +version: 2.0.3+240 environment: sdk: '>=3.10.0 <4.0.0' From d72a0ccf93c4974985607fe4f9525093d5ff773d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 16:22:30 +0200 Subject: [PATCH 057/484] Allow users to force-reconnect to the powersync service --- lib/core/widgets/app_bar.dart | 20 ++++++++++-- lib/core/widgets/sync_status_dialog.dart | 18 ++++++++++- lib/l10n/app_de.arb | 1 + lib/l10n/app_en.arb | 4 +++ lib/l10n/app_es.arb | 1 + lib/l10n/app_fr.arb | 1 + .../core/widgets/sync_status_dialog_test.dart | 32 +++++++++++++++++++ 7 files changed, 74 insertions(+), 3 deletions(-) diff --git a/lib/core/widgets/app_bar.dart b/lib/core/widgets/app_bar.dart index 9713f86e5..350260967 100644 --- a/lib/core/widgets/app_bar.dart +++ b/lib/core/widgets/app_bar.dart @@ -19,12 +19,15 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/core/form_screen.dart'; +import 'package:wger/core/network/auth_http_client.dart'; import 'package:wger/core/network/auth_notifier.dart'; import 'package:wger/core/network/network_provider.dart'; +import 'package:wger/core/network/wger_base.dart'; import 'package:wger/core/settings_dashboard_widgets_screen.dart'; import 'package:wger/core/widgets/about.dart'; import 'package:wger/core/widgets/sync_status_dialog.dart'; -import 'package:wger/database/powersync/powersync.dart' show syncStatus, syncWatchdogProvider; +import 'package:wger/database/powersync/powersync.dart' + show builtPowerSyncInstance, connectPowerSync, syncStatus, syncWatchdogProvider; import 'package:wger/features/account/providers/account_notifier.dart'; import 'package:wger/features/account/widgets/forms.dart'; import 'package:wger/features/account/widgets/settings.dart'; @@ -53,10 +56,23 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { icon: Icon(status.icon), onPressed: () => showDialog( context: context, - // Like syncState, the stalled flag is a snapshot taken when the dialog opens + // Like syncState, the stalled and offline flags are snapshots + // taken when the dialog opens. No reconnect action while offline: + // the app deliberately disconnects there (see powerSyncInstance) builder: (_) => SyncStatusDialog( syncState, stalled: ref.read(syncWatchdogProvider).stalled.value, + onReconnect: !ref.read(networkStatusProvider) + ? null + : () { + final db = builtPowerSyncInstance; + final serverUrl = ref.read(wgerBaseProvider).serverUrl; + if (db == null || serverUrl == null) { + return; + } + ref.read(syncWatchdogProvider).reset(); + connectPowerSync(db, serverUrl, ref.read(authenticatedHttpClientProvider)); + }, ), ), ), diff --git a/lib/core/widgets/sync_status_dialog.dart b/lib/core/widgets/sync_status_dialog.dart index 3f362bab9..3fa41ab10 100644 --- a/lib/core/widgets/sync_status_dialog.dart +++ b/lib/core/widgets/sync_status_dialog.dart @@ -100,7 +100,11 @@ class SyncStatusDialog extends StatelessWidget { /// case, so the dialog adds a hint about likely network-side blockers. final bool stalled; - const SyncStatusDialog(this._status, {this.stalled = false, super.key}); + /// Drops the current sync connection and opens a fresh one. When null, + /// the reconnect action is not shown. + final VoidCallback? onReconnect; + + const SyncStatusDialog(this._status, {this.stalled = false, this.onReconnect, super.key}); @override Widget build(BuildContext context) { @@ -198,6 +202,18 @@ class SyncStatusDialog extends StatelessWidget { }, child: Text(i18n.applicationLogs), ), + // A stuck stream (firewall, VPN, flaky DNS) often recovers on a + // fresh connection and can look healthy here while hanging, so the + // action is not gated on an error. Absent only while offline, where + // reconnecting would just spin against an unreachable backend. + if (onReconnect != null) + TextButton( + onPressed: () { + Navigator.of(context).pop(); + onReconnect!(); + }, + child: Text(i18n.syncStatusReconnect), + ), TextButton( onPressed: () => Navigator.of(context).pop(), child: Text(MaterialLocalizations.of(context).closeButtonLabel), diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index cde9d0198..33b8c4f7e 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1149,6 +1149,7 @@ "syncStatusLastSynced": "Letzte Synchronisierung", "syncStatusErrorDetails": "Fehlerdetails", "syncStatusStalledHint": "Die Verbindung zum Synchronisierungsdienst scheint blockiert zu werden. Möglicherweise stört ein VPN, Werbeblocker, Virenscanner oder eine Firewall in diesem Netzwerk.", + "syncStatusReconnect": "Neu verbinden", "sessionExpired": "Deine Sitzung ist abgelaufen, bitte melde dich erneut an", "endBeforeStart": "Der Endwert darf nicht vor dem Startwert liegen", "minLengthRoutine": "Die Routine muss mindestens {number} Wochen lang sein", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index c8026edc9..6c6564e35 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1401,6 +1401,10 @@ "@syncStatusStalledHint": { "description": "Hint shown in the sync status dialog when the app keeps connecting but never receives any sync data, which usually means something on the network is blocking the connection" }, + "syncStatusReconnect": "Reconnect", + "@syncStatusReconnect": { + "description": "Button in the sync status dialog that drops the stuck connection to the sync service and opens a fresh one" + }, "filterNutriscore": "Nutri-Score filter", "@filterNutriscore": { "description": "Heading for the Nutri-Score slider in the ingredient search filter dialog" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 16cc2d7e5..e02a5d948 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1186,6 +1186,7 @@ "syncStatusLastSynced": "Última sincronización", "syncStatusErrorDetails": "Detalles del error", "syncStatusStalledHint": "La conexión con el servicio de sincronización parece estar bloqueada. Es posible que una VPN, un bloqueador de anuncios, un antivirus o un cortafuegos de esta red estén interfiriendo.", + "syncStatusReconnect": "Reconectar", "sessionExpired": "Tu sesión ha expirado, inicia sesión de nuevo", "weightOrRepsRequired": "Introduce un peso, repeticiones o ambos", "timeStartEndBothOrNeither": "Indica la hora de inicio y de fin, o deja ambas vacías", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 51a7e989a..f6f259e2b 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1157,6 +1157,7 @@ "syncStatusLastSynced": "Dernière synchronisation", "syncStatusErrorDetails": "Détails de l'erreur", "syncStatusStalledHint": "La connexion au service de synchronisation semble être bloquée. Un VPN, un bloqueur de publicités, un antivirus ou un pare-feu sur ce réseau interfère peut-être.", + "syncStatusReconnect": "Reconnecter", "sessionExpired": "Votre session a expiré, veuillez vous reconnecter", "weightOrRepsRequired": "Veuillez saisir un poids, des répétitions, ou les deux", "timeStartEndBothOrNeither": "Indiquez l'heure de début et de fin, ou laissez les deux vides", diff --git a/test/core/widgets/sync_status_dialog_test.dart b/test/core/widgets/sync_status_dialog_test.dart index 76c4985f1..e0b499cd2 100644 --- a/test/core/widgets/sync_status_dialog_test.dart +++ b/test/core/widgets/sync_status_dialog_test.dart @@ -174,6 +174,38 @@ void main() { expect(find.text(i18n.syncStatusError), findsOneWidget); }); + testWidgets('shows the reconnect action on error and fires the callback', (tester) async { + var reconnected = false; + await tester.pumpWidget( + _wrap( + SyncStatusDialog( + buildSyncStatus(connected: true, downloadError: Exception('boom')), + onReconnect: () => reconnected = true, + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text(i18n.syncStatusReconnect)); + await tester.pumpAndSettle(); + expect(reconnected, isTrue); + }); + + testWidgets('shows the reconnect action even while the sync looks healthy', (tester) async { + await tester.pumpWidget( + _wrap(SyncStatusDialog(buildSyncStatus(connected: true), onReconnect: () {})), + ); + await tester.pumpAndSettle(); + + expect(find.text(i18n.syncStatusReconnect), findsOneWidget); + }); + + testWidgets('omits the reconnect action without a callback', (tester) async { + await _pumpDialog(tester, buildSyncStatus(connected: true, downloadError: Exception('boom'))); + + expect(find.text(i18n.syncStatusReconnect), findsNothing); + }); + testWidgets('renders the expander with the raw error message when present', (tester) async { await _pumpDialog( tester, From 30f44ad4713f229a35ec8d70f81285b25f9a12a3 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 16:50:14 +0200 Subject: [PATCH 058/484] Show more sync information on the sync status dialog Also, make it stateful so it shows live data for sync queue size, etc. --- lib/core/widgets/app_bar.dart | 10 +- lib/core/widgets/sync_status_dialog.dart | 259 ++++++++++-------- lib/database/powersync/powersync.dart | 9 + lib/l10n/app_de.arb | 2 + lib/l10n/app_en.arb | 13 + lib/l10n/app_es.arb | 2 + lib/l10n/app_fr.arb | 2 + .../core/widgets/sync_status_dialog_test.dart | 126 +++++++-- test/helpers/sync_status.dart | 7 + 9 files changed, 297 insertions(+), 133 deletions(-) diff --git a/lib/core/widgets/app_bar.dart b/lib/core/widgets/app_bar.dart index 350260967..d32b7e396 100644 --- a/lib/core/widgets/app_bar.dart +++ b/lib/core/widgets/app_bar.dart @@ -56,12 +56,12 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { icon: Icon(status.icon), onPressed: () => showDialog( context: context, - // Like syncState, the stalled and offline flags are snapshots - // taken when the dialog opens. No reconnect action while offline: - // the app deliberately disconnects there (see powerSyncInstance) + // The dialog watches the sync state itself; only the server URL + // and the offline gate are snapshots taken when it opens. + // No reconnect action while offline: the app deliberately + // disconnects there (see powerSyncInstance) builder: (_) => SyncStatusDialog( - syncState, - stalled: ref.read(syncWatchdogProvider).stalled.value, + serverUrl: ref.read(wgerBaseProvider).serverUrl, onReconnect: !ref.read(networkStatusProvider) ? null : () { diff --git a/lib/core/widgets/sync_status_dialog.dart b/lib/core/widgets/sync_status_dialog.dart index 3fa41ab10..f41796a31 100644 --- a/lib/core/widgets/sync_status_dialog.dart +++ b/lib/core/widgets/sync_status_dialog.dart @@ -17,10 +17,13 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:powersync/powersync.dart' show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus; import 'package:wger/core/formatting/formatting.dart'; import 'package:wger/core/widgets/log_overview.dart' show LogOverviewPage; +import 'package:wger/database/powersync/powersync.dart' + show pendingUploadCountProvider, syncStatus, syncWatchdogProvider; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/powersync/connector.dart' show RetryableUploadException; @@ -91,134 +94,172 @@ String? _categoriseSyncError(Object error) { } } -/// Shows the current powersync status -class SyncStatusDialog extends StatelessWidget { - final SyncStatus _status; - - /// True when the sync stream keeps reconnecting without ever receiving - /// data (see SyncStreamWatchdog). There is no error to show in that - /// case, so the dialog adds a hint about likely network-side blockers. - final bool stalled; - +/// Shows the current powersync status. Watches the status, the upload queue +/// and the watchdog, so the content keeps updating while the dialog is open. +class SyncStatusDialog extends ConsumerWidget { /// Drops the current sync connection and opens a fresh one. When null, /// the reconnect action is not shown. final VoidCallback? onReconnect; - const SyncStatusDialog(this._status, {this.stalled = false, this.onReconnect, super.key}); + /// Server this app is syncing against. Hidden when null. + final String? serverUrl; + + const SyncStatusDialog({this.onReconnect, this.serverUrl, super.key}); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { final i18n = AppLocalizations.of(context); final theme = Theme.of(context); - final status = syncStatusIconAndLabel(_status, i18n); - final lastSynced = _status.lastSyncedAt; - final errorCategory = _status.anyError == null ? null : _categoriseSyncError(_status.anyError!); + final syncState = ref.watch(syncStatus); + // The queue count loads async for a moment; treat that as an empty queue + final pendingUploads = ref.watch(pendingUploadCountProvider).value ?? 0; + final status = syncStatusIconAndLabel(syncState, i18n); + final lastSynced = syncState.lastSyncedAt; + final errorCategory = syncState.anyError == null + ? null + : _categoriseSyncError(syncState.anyError!); - return AlertDialog( - title: Text(i18n.syncStatusDialogTitle), - content: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Icon(status.icon, size: 28), - const SizedBox(width: 12), - Expanded( - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(status.label, style: theme.textTheme.titleMedium), - if (errorCategory != null) - Text( - errorCategory, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, + // stalled: the sync stream keeps reconnecting without ever receiving + // data (see SyncStreamWatchdog). There is no error to show in that + // case, so the dialog adds a hint about likely network-side blockers. + return ValueListenableBuilder( + valueListenable: ref.watch(syncWatchdogProvider).stalled, + builder: (context, stalled, _) => AlertDialog( + title: Text(i18n.syncStatusDialogTitle), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Icon(status.icon, size: 28), + const SizedBox(width: 12), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(status.label, style: theme.textTheme.titleMedium), + if (errorCategory != null) + Text( + errorCategory, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), ), + ], + ), + ), + ], + ), + // Progress through the running download, so a long initial sync + // is visibly moving instead of sitting on a static label. + if (syncState.downloadProgress case final progress?) ...[ + const SizedBox(height: 12), + LinearProgressIndicator(value: progress.downloadedFraction), + const SizedBox(height: 4), + Text( + '${progress.downloadedOperations} / ${progress.totalOperations}', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + if (stalled && syncState.anyError == null) ...[ + const SizedBox(height: 8), + Text( + i18n.syncStatusStalledHint, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + if (pendingUploads > 0) ...[ + const SizedBox(height: 8), + Text( + i18n.syncStatusPendingUploads(pendingUploads), + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + const SizedBox(height: 16), + + // Last sync timestamp if available + Text(i18n.syncStatusLastSynced, style: theme.textTheme.labelMedium), + const SizedBox(height: 4), + Text( + lastSynced != null + ? localizedDate(context).add_Hms().format(lastSynced.toLocal()) + : syncState.hasSynced == false + ? i18n.syncStatusNeverSynced + : '-/-', + ), + if (serverUrl != null) ...[ + const SizedBox(height: 16), + Text(i18n.serverSectionLabel, style: theme.textTheme.labelMedium), + const SizedBox(height: 4), + Text(serverUrl!), + ], + + // Raw error in an expandable section. Only shown when an error + // actually exists; otherwise we don't render the tile at all, + // so the dialog stays compact in the happy case. + if (syncState.anyError != null) ...[ + const SizedBox(height: 8), + Theme( + // ExpansionTile draws its own dividers; suppress the default + // divider colour so the tile blends with the dialog content. + data: theme.copyWith(dividerColor: Colors.transparent), + child: ExpansionTile( + tilePadding: EdgeInsets.zero, + childrenPadding: const EdgeInsets.only(bottom: 8), + title: Text(i18n.syncStatusErrorDetails), + children: [ + SelectableText( + syncState.anyError!.toString(), + style: theme.textTheme.bodySmall?.copyWith( + fontFamily: 'monospace', + color: theme.colorScheme.error, ), + ), ], ), ), ], - ), - if (stalled && _status.anyError == null) ...[ - const SizedBox(height: 8), - Text( - i18n.syncStatusStalledHint, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), ], - const SizedBox(height: 16), - - // Last sync timestamp if available - Text(i18n.syncStatusLastSynced, style: theme.textTheme.labelMedium), - const SizedBox(height: 4), - Text( - lastSynced == null - ? '-/-' - : localizedDate(context).add_Hms().format(lastSynced.toLocal()), - ), - - // Raw error in an expandable section. Only shown when an error - // actually exists; otherwise we don't render the tile at all, - // so the dialog stays compact in the happy case. - if (_status.anyError != null) ...[ - const SizedBox(height: 8), - Theme( - // ExpansionTile draws its own dividers; suppress the default - // divider colour so the tile blends with the dialog content. - data: theme.copyWith(dividerColor: Colors.transparent), - child: ExpansionTile( - tilePadding: EdgeInsets.zero, - childrenPadding: const EdgeInsets.only(bottom: 8), - title: Text(i18n.syncStatusErrorDetails), - children: [ - SelectableText( - _status.anyError!.toString(), - style: theme.textTheme.bodySmall?.copyWith( - fontFamily: 'monospace', - color: theme.colorScheme.error, - ), - ), - ], - ), + ), + actions: [ + // The stalled hint and the WARNING land in the application logs; + // give the user a direct path to them. + if (stalled && syncState.anyError == null) + TextButton( + onPressed: () { + final navigator = Navigator.of(context); + navigator.pop(); + navigator.pushNamed(LogOverviewPage.routeName); + }, + child: Text(i18n.applicationLogs), ), - ], + // A stuck stream (firewall, VPN, flaky DNS) often recovers on a + // fresh connection and can look healthy here while hanging, so the + // action is not gated on an error. Absent only while offline, where + // reconnecting would just spin against an unreachable backend. + if (onReconnect != null) + TextButton( + onPressed: () { + Navigator.of(context).pop(); + onReconnect!(); + }, + child: Text(i18n.syncStatusReconnect), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(MaterialLocalizations.of(context).closeButtonLabel), + ), ], ), - actions: [ - // The stalled hint and the WARNING land in the application logs; - // give the user a direct path to them. - if (stalled && _status.anyError == null) - TextButton( - onPressed: () { - final navigator = Navigator.of(context); - navigator.pop(); - navigator.pushNamed(LogOverviewPage.routeName); - }, - child: Text(i18n.applicationLogs), - ), - // A stuck stream (firewall, VPN, flaky DNS) often recovers on a - // fresh connection and can look healthy here while hanging, so the - // action is not gated on an error. Absent only while offline, where - // reconnecting would just spin against an unreachable backend. - if (onReconnect != null) - TextButton( - onPressed: () { - Navigator.of(context).pop(); - onReconnect!(); - }, - child: Text(i18n.syncStatusReconnect), - ), - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: Text(MaterialLocalizations.of(context).closeButtonLabel), - ), - ], ); } } diff --git a/lib/database/powersync/powersync.dart b/lib/database/powersync/powersync.dart index 1349c9c99..09d508a85 100644 --- a/lib/database/powersync/powersync.dart +++ b/lib/database/powersync/powersync.dart @@ -192,6 +192,15 @@ void connectPowerSync(PowerSyncDatabase db, String baseUrl, http.Client client) ); } +/// Number of local changes still waiting in the upload queue. Emits again +/// whenever the queue changes, so consumers can show a live count. +final pendingUploadCountProvider = StreamProvider.autoDispose((ref) async* { + final db = await ref.watch(powerSyncInstanceProvider.future); + yield* db + .watch('SELECT count(*) AS count FROM ps_crud', triggerOnTables: ['ps_crud']) + .map((rows) => rows.first['count'] as int); +}); + final _syncStatusInternal = StreamProvider((ref) { return Stream.fromFuture( ref.watch(powerSyncInstanceProvider.future), diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 33b8c4f7e..37f3cc372 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1150,6 +1150,8 @@ "syncStatusErrorDetails": "Fehlerdetails", "syncStatusStalledHint": "Die Verbindung zum Synchronisierungsdienst scheint blockiert zu werden. Möglicherweise stört ein VPN, Werbeblocker, Virenscanner oder eine Firewall in diesem Netzwerk.", "syncStatusReconnect": "Neu verbinden", + "syncStatusPendingUploads": "{count, plural, =1{Eine lokale Änderung wartet auf den Upload} other{{count} lokale Änderungen warten auf den Upload}}", + "syncStatusNeverSynced": "Noch nie synchronisiert", "sessionExpired": "Deine Sitzung ist abgelaufen, bitte melde dich erneut an", "endBeforeStart": "Der Endwert darf nicht vor dem Startwert liegen", "minLengthRoutine": "Die Routine muss mindestens {number} Wochen lang sein", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 6c6564e35..1b3ebcd57 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1405,6 +1405,19 @@ "@syncStatusReconnect": { "description": "Button in the sync status dialog that drops the stuck connection to the sync service and opens a fresh one" }, + "syncStatusPendingUploads": "{count, plural, =1{One local change waiting for upload} other{{count} local changes waiting for upload}}", + "@syncStatusPendingUploads": { + "description": "Line in the sync status dialog showing how many local changes have not reached the server yet", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "syncStatusNeverSynced": "Not yet synchronised", + "@syncStatusNeverSynced": { + "description": "Shown in the sync status dialog instead of the last-sync timestamp when this device has never completed a synchronisation" + }, "filterNutriscore": "Nutri-Score filter", "@filterNutriscore": { "description": "Heading for the Nutri-Score slider in the ingredient search filter dialog" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index e02a5d948..82fe3fc47 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1187,6 +1187,8 @@ "syncStatusErrorDetails": "Detalles del error", "syncStatusStalledHint": "La conexión con el servicio de sincronización parece estar bloqueada. Es posible que una VPN, un bloqueador de anuncios, un antivirus o un cortafuegos de esta red estén interfiriendo.", "syncStatusReconnect": "Reconectar", + "syncStatusPendingUploads": "{count, plural, =1{Un cambio local pendiente de subir} other{{count} cambios locales pendientes de subir}}", + "syncStatusNeverSynced": "Aún no sincronizado", "sessionExpired": "Tu sesión ha expirado, inicia sesión de nuevo", "weightOrRepsRequired": "Introduce un peso, repeticiones o ambos", "timeStartEndBothOrNeither": "Indica la hora de inicio y de fin, o deja ambas vacías", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index f6f259e2b..469adaca9 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1158,6 +1158,8 @@ "syncStatusErrorDetails": "Détails de l'erreur", "syncStatusStalledHint": "La connexion au service de synchronisation semble être bloquée. Un VPN, un bloqueur de publicités, un antivirus ou un pare-feu sur ce réseau interfère peut-être.", "syncStatusReconnect": "Reconnecter", + "syncStatusPendingUploads": "{count, plural, =1{Une modification locale en attente d'envoi} other{{count} modifications locales en attente d'envoi}}", + "syncStatusNeverSynced": "Pas encore synchronisé", "sessionExpired": "Votre session a expiré, veuillez vous reconnecter", "weightOrRepsRequired": "Veuillez saisir un poids, des répétitions, ou les deux", "timeStartEndBothOrNeither": "Indiquez l'heure de début et de fin, ou laissez les deux vides", diff --git a/test/core/widgets/sync_status_dialog_test.dart b/test/core/widgets/sync_status_dialog_test.dart index e0b499cd2..f123fb4d4 100644 --- a/test/core/widgets/sync_status_dialog_test.dart +++ b/test/core/widgets/sync_status_dialog_test.dart @@ -16,9 +16,11 @@ * along with this program. If not, see . */ +import 'dart:async'; import 'dart:io' show SocketException; import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:powersync/powersync.dart' show @@ -28,24 +30,43 @@ import 'package:powersync/powersync.dart' SyncStatus, UpdateType; import 'package:wger/core/widgets/sync_status_dialog.dart'; +import 'package:wger/database/powersync/powersync.dart' + show pendingUploadCountProvider, syncStatus, syncWatchdogProvider; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/l10n/generated/app_localizations_en.dart'; import 'package:wger/powersync/connector.dart' show RetryableUploadException; +import 'package:wger/powersync/sync_watchdog.dart'; import '../../helpers/sync_status.dart'; -Widget _wrap(Widget child) { - return MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - locale: const Locale('en'), - home: Scaffold(body: child), +/// Wraps [child] in a MaterialApp with the providers the dialog watches +/// overridden to fixed test values. +Widget _wrap( + Widget child, { + required SyncStatus status, + bool stalled = false, + Stream? pendingUploads, +}) { + final watchdog = SyncStreamWatchdog(); + watchdog.stalled.value = stalled; + return ProviderScope( + overrides: [ + syncStatus.overrideWithValue(status), + syncWatchdogProvider.overrideWithValue(watchdog), + pendingUploadCountProvider.overrideWith((ref) => pendingUploads ?? const Stream.empty()), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('en'), + home: Scaffold(body: child), + ), ); } -/// Renders [SyncStatusDialog] inside a minimal MaterialApp + Scaffold. +/// Renders a plain [SyncStatusDialog] for the given status. Future _pumpDialog(WidgetTester tester, SyncStatus status) async { - await tester.pumpWidget(_wrap(SyncStatusDialog(status))); + await tester.pumpWidget(_wrap(const SyncStatusDialog(), status: status)); await tester.pumpAndSettle(); } @@ -118,13 +139,83 @@ void main() { }); group('SyncStatusDialog rendering', () { - testWidgets('renders title, status label, and "never synced" placeholder', (tester) async { + testWidgets('renders title, status label, and the never-synced text', (tester) async { + // Without a lastSyncedAt the status derives hasSynced == false await _pumpDialog(tester, buildSyncStatus(connected: true)); expect(find.text(i18n.syncStatusDialogTitle), findsOneWidget); expect(find.text(i18n.syncStatusConnected), findsOneWidget); expect(find.text(i18n.syncStatusLastSynced), findsOneWidget); + expect(find.text(i18n.syncStatusNeverSynced), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsNothing); + }); + + testWidgets('renders the placeholder while the sync state is still unknown', (tester) async { + await _pumpDialog(tester, buildUninitializedSyncStatus()); + expect(find.text('-/-'), findsOneWidget); + expect(find.text(i18n.syncStatusNeverSynced), findsNothing); + }); + + testWidgets('shows the pending-upload count when changes are waiting', (tester) async { + await tester.pumpWidget( + _wrap( + const SyncStatusDialog(), + status: buildSyncStatus(connected: true), + pendingUploads: Stream.value(3), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text(i18n.syncStatusPendingUploads(3)), findsOneWidget); + }); + + testWidgets('omits the pending-upload line when the queue is empty', (tester) async { + await tester.pumpWidget( + _wrap( + const SyncStatusDialog(), + status: buildSyncStatus(connected: true), + pendingUploads: Stream.value(0), + ), + ); + await tester.pumpAndSettle(); + + expect(find.textContaining('upload'), findsNothing); + }); + + testWidgets('updates the pending-upload count while the dialog is open', (tester) async { + final queue = StreamController(); + addTearDown(queue.close); + await tester.pumpWidget( + _wrap( + const SyncStatusDialog(), + status: buildSyncStatus(connected: true), + pendingUploads: queue.stream, + ), + ); + await tester.pumpAndSettle(); + + queue.add(2); + await tester.pumpAndSettle(); + expect(find.text(i18n.syncStatusPendingUploads(2)), findsOneWidget); + + // The queue drained: the line disappears without reopening the dialog + queue.add(0); + await tester.pumpAndSettle(); + expect(find.textContaining('upload'), findsNothing); + }); + + testWidgets('shows the server URL when provided', (tester) async { + await tester.pumpWidget( + _wrap( + const SyncStatusDialog(serverUrl: 'https://wger.example'), + status: buildSyncStatus(connected: true), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text(i18n.serverSectionLabel), findsOneWidget); + expect(find.text('https://wger.example'), findsOneWidget); }); testWidgets('formats the last-sync timestamp when set', (tester) async { @@ -144,7 +235,7 @@ void main() { testWidgets('shows the blocked-connection hint when stalled without an error', (tester) async { await tester.pumpWidget( - _wrap(SyncStatusDialog(buildSyncStatus(connecting: true), stalled: true)), + _wrap(const SyncStatusDialog(), status: buildSyncStatus(connecting: true), stalled: true), ); await tester.pumpAndSettle(); @@ -162,10 +253,9 @@ void main() { testWidgets('prefers the real error over the stalled hint', (tester) async { await tester.pumpWidget( _wrap( - SyncStatusDialog( - buildSyncStatus(connecting: true, downloadError: Exception('boom')), - stalled: true, - ), + const SyncStatusDialog(), + status: buildSyncStatus(connecting: true, downloadError: Exception('boom')), + stalled: true, ), ); await tester.pumpAndSettle(); @@ -178,10 +268,8 @@ void main() { var reconnected = false; await tester.pumpWidget( _wrap( - SyncStatusDialog( - buildSyncStatus(connected: true, downloadError: Exception('boom')), - onReconnect: () => reconnected = true, - ), + SyncStatusDialog(onReconnect: () => reconnected = true), + status: buildSyncStatus(connected: true, downloadError: Exception('boom')), ), ); await tester.pumpAndSettle(); @@ -193,7 +281,7 @@ void main() { testWidgets('shows the reconnect action even while the sync looks healthy', (tester) async { await tester.pumpWidget( - _wrap(SyncStatusDialog(buildSyncStatus(connected: true), onReconnect: () {})), + _wrap(SyncStatusDialog(onReconnect: () {}), status: buildSyncStatus(connected: true)), ); await tester.pumpAndSettle(); diff --git a/test/helpers/sync_status.dart b/test/helpers/sync_status.dart index b8220687a..b64546907 100644 --- a/test/helpers/sync_status.dart +++ b/test/helpers/sync_status.dart @@ -44,3 +44,10 @@ SyncStatus buildSyncStatus({ streamSubscriptions: null, ); } + +/// Builds the status used before the sync state has been loaded from the +/// database (`hasSynced` still null). +SyncStatus buildUninitializedSyncStatus() { + // ignore: invalid_use_of_internal_member + return const SyncStatus.uninitialized(); +} From 718fa05d1b6f7174b02bd6057ff892586a478168 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 17:06:05 +0200 Subject: [PATCH 059/484] Add sync diagnostics to the "submit to github" error dialog --- lib/core/error_dialogs.dart | 2 + lib/core/errors.dart | 6 +- lib/core/widgets/sync_status_dialog.dart | 98 +++++++------- lib/powersync/sync_diagnostics.dart | 120 ++++++++++++++++++ test/core/errors_test.dart | 42 ++++++ .../core/widgets/sync_status_dialog_test.dart | 16 +++ test/powersync/sync_diagnostics_test.dart | 86 +++++++++++++ 7 files changed, 316 insertions(+), 54 deletions(-) create mode 100644 lib/powersync/sync_diagnostics.dart create mode 100644 test/powersync/sync_diagnostics_test.dart diff --git a/lib/core/error_dialogs.dart b/lib/core/error_dialogs.dart index 4105e2209..2a6869e6a 100644 --- a/lib/core/error_dialogs.dart +++ b/lib/core/error_dialogs.dart @@ -28,6 +28,7 @@ import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/core/keys.dart'; import 'package:wger/core/logs.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/powersync/sync_diagnostics.dart' show collectSyncDiagnostics; /// Whether an error dialog is currently on screen. /// @@ -222,6 +223,7 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext issueErrorMessage: issueErrorMessage, stackTrace: fullStackTrace, applicationLogs: applicationLogs, + syncDiagnostics: await collectSyncDiagnostics(), ); final Uri reportUri = Uri.parse(githubIssueUrl); diff --git a/lib/core/errors.dart b/lib/core/errors.dart index 07a2ac8bb..14457f7a6 100644 --- a/lib/core/errors.dart +++ b/lib/core/errors.dart @@ -74,8 +74,9 @@ bool isNetworkError(Object e) { String buildGithubIssueUrl({ required String issueTitle, required String issueErrorMessage, - required String stackTrace, required List applicationLogs, + String? stackTrace, + String? syncDiagnostics, }) { String composeUrl(List logs) { final logText = logs.isEmpty ? '-- No logs available --' : logs.join('\n'); @@ -85,7 +86,8 @@ String buildGithubIssueUrl({ '## Error details\n\n' 'Error title: $issueTitle\n' 'Error message: $issueErrorMessage\n' - 'Stack trace:\n```\n$stackTrace\n```\n\n' + '${stackTrace != null ? 'Stack trace:\n```\n$stackTrace\n```\n\n' : ''}' + '${syncDiagnostics != null ? 'Sync status:\n```\n$syncDiagnostics\n```\n\n' : ''}' 'App logs (last ${logs.length} entries):\n```\n$logText\n```'; return '$GITHUB_ISSUES_BUG_URL' '&title=${Uri.encodeComponent(issueTitle)}' diff --git a/lib/core/widgets/sync_status_dialog.dart b/lib/core/widgets/sync_status_dialog.dart index f41796a31..28efa616c 100644 --- a/lib/core/widgets/sync_status_dialog.dart +++ b/lib/core/widgets/sync_status_dialog.dart @@ -18,53 +18,19 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:powersync/powersync.dart' - show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus; +import 'package:logging/logging.dart'; +import 'package:powersync/powersync.dart' show SyncStatus; +import 'package:url_launcher/url_launcher.dart'; +import 'package:wger/core/errors.dart' show buildGithubIssueUrl; import 'package:wger/core/formatting/formatting.dart'; +import 'package:wger/core/logs.dart'; import 'package:wger/core/widgets/log_overview.dart' show LogOverviewPage; import 'package:wger/database/powersync/powersync.dart' show pendingUploadCountProvider, syncStatus, syncWatchdogProvider; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/powersync/connector.dart' show RetryableUploadException; +import 'package:wger/powersync/sync_diagnostics.dart'; -/// Maps an HTTP status code to a short English category label. -String _categoriseHttpStatus(int statusCode) { - if (statusCode == 401 || statusCode == 403) { - return 'Authentication error'; - } - if (statusCode >= 500) { - return 'Server error'; - } - return 'HTTP $statusCode'; -} - -/// Classifies a sync error into a short English category label -String? _categoriseSyncError(Object error) { - if (error is CredentialsException) { - return 'Authentication error'; - } - - if (error is PowerSyncProtocolException) { - return 'Protocol error'; - } - - if (error is SyncResponseException) { - return _categoriseHttpStatus(error.statusCode); - } - if (error is RetryableUploadException) { - return _categoriseHttpStatus(error.statusCode); - } - - final typeName = error.runtimeType.toString(); - if (typeName.endsWith('SocketException') || - typeName == 'WebSocketChannelException' || - typeName == 'ClientException' || - typeName == 'HttpException') { - return 'Connection error'; - } - - return null; -} +final _logger = Logger('SyncStatusDialog'); ({IconData icon, String label}) syncStatusIconAndLabel( SyncStatus status, @@ -117,7 +83,7 @@ class SyncStatusDialog extends ConsumerWidget { final lastSynced = syncState.lastSyncedAt; final errorCategory = syncState.anyError == null ? null - : _categoriseSyncError(syncState.anyError!); + : categoriseSyncError(syncState.anyError!); // stalled: the sync stream keeps reconnecting without ever receiving // data (see SyncStreamWatchdog). There is no error to show in that @@ -153,6 +119,18 @@ class SyncStatusDialog extends ConsumerWidget { ), ], ), + + // Stalled or errored sync + if (stalled && syncState.anyError == null) ...[ + const SizedBox(height: 8), + Text( + i18n.syncStatusStalledHint, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + // Progress through the running download, so a long initial sync // is visibly moving instead of sitting on a static label. if (syncState.downloadProgress case final progress?) ...[ @@ -166,15 +144,6 @@ class SyncStatusDialog extends ConsumerWidget { ), ), ], - if (stalled && syncState.anyError == null) ...[ - const SizedBox(height: 8), - Text( - i18n.syncStatusStalledHint, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], if (pendingUploads > 0) ...[ const SizedBox(height: 8), Text( @@ -205,7 +174,6 @@ class SyncStatusDialog extends ConsumerWidget { // Raw error in an expandable section. Only shown when an error // actually exists; otherwise we don't render the tile at all, - // so the dialog stays compact in the happy case. if (syncState.anyError != null) ...[ const SizedBox(height: 8), Theme( @@ -242,6 +210,32 @@ class SyncStatusDialog extends ConsumerWidget { }, child: Text(i18n.applicationLogs), ), + // Pre-filled bug report including the sync snapshot. Sync problems + // usually never raise the fatal error dialog, so this is their + // report path. + if (stalled || syncState.anyError != null) + TextButton( + onPressed: () async { + final url = buildGithubIssueUrl( + issueTitle: 'Sync error', + issueErrorMessage: + syncState.anyError?.toString() ?? + 'Sync stream stalled (connects but receives no data)', + applicationLogs: InMemoryLogStore().getFormattedLogs(), + syncDiagnostics: formatSyncDiagnostics( + syncState, + pendingUploads: pendingUploads, + server: serverCategory(serverUrl), + ), + ); + try { + await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication); + } catch (e) { + _logger.warning('Error opening issue tracker: $e'); + } + }, + child: const Text('Report issue'), + ), // A stuck stream (firewall, VPN, flaky DNS) often recovers on a // fresh connection and can look healthy here while hanging, so the // action is not gated on an error. Absent only while offline, where diff --git a/lib/powersync/sync_diagnostics.dart b/lib/powersync/sync_diagnostics.dart new file mode 100644 index 000000000..8c02fdcd1 --- /dev/null +++ b/lib/powersync/sync_diagnostics.dart @@ -0,0 +1,120 @@ +/* + * 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:powersync/powersync.dart' + show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus; +import 'package:wger/core/consts.dart'; +import 'package:wger/database/powersync/powersync.dart' show builtPowerSyncInstance; +import 'package:wger/powersync/connector.dart' show RetryableUploadException; + +/// Maps an HTTP status code to a short English category label. +String _categoriseHttpStatus(int statusCode) { + if (statusCode == 401 || statusCode == 403) { + return 'Authentication error'; + } + if (statusCode >= 500) { + return 'Server error'; + } + return 'HTTP $statusCode'; +} + +/// Classifies a sync error into a short English category label +String? categoriseSyncError(Object error) { + if (error is CredentialsException) { + return 'Authentication error'; + } + + if (error is PowerSyncProtocolException) { + return 'Protocol error'; + } + + if (error is SyncResponseException) { + return _categoriseHttpStatus(error.statusCode); + } + if (error is RetryableUploadException) { + return _categoriseHttpStatus(error.statusCode); + } + + final typeName = error.runtimeType.toString(); + if (typeName.endsWith('SocketException') || + typeName == 'WebSocketChannelException' || + typeName == 'ClientException' || + typeName == 'HttpException') { + return 'Connection error'; + } + + return null; +} + +/// Reduces [serverUrl] to a category for bug reports, so self-hosted URLs +/// stay private. Null when the URL is unknown. +String? serverCategory(String? serverUrl) { + return switch (serverUrl) { + null => null, + DEFAULT_SERVER_PROD => 'wger.de', + DEFAULT_SERVER_TEST => 'dev.wger.de', + _ => 'self-hosted', + }; +} + +/// Renders a compact sync-state summary for bug reports. +String formatSyncDiagnostics( + SyncStatus status, { + required int pendingUploads, + String? server, +}) { + final buffer = StringBuffer(); + if (server != null) { + buffer.writeln('server: $server'); + } + buffer + ..writeln( + 'connected: ${status.connected}, connecting: ${status.connecting}, ' + 'downloading: ${status.downloading}, uploading: ${status.uploading}', + ) + ..writeln('last successful sync: ${status.lastSyncedAt?.toUtc().toIso8601String() ?? 'never'}') + ..writeln('pending uploads: $pendingUploads'); + if (status.downloadProgress case final progress?) { + buffer.writeln( + 'download progress: ${progress.downloadedOperations} / ${progress.totalOperations}', + ); + } + if (status.anyError case final error?) { + // Clamped: some exception toStrings embed whole response bodies, and + // the report has to fit into a GitHub issue URL. + final text = error.toString(); + final clamped = text.length <= 300 ? text : '${text.substring(0, 300)}…'; + buffer.writeln('error (${categoriseSyncError(error) ?? 'Uncategorised'}): $clamped'); + } + return buffer.toString().trimRight(); +} + +/// Snapshot of the current sync state for bug reports, or null when the +/// PowerSync database has not been initialised. +Future collectSyncDiagnostics({String? serverUrl}) async { + final db = builtPowerSyncInstance; + if (db == null) { + return null; + } + final queue = await db.getUploadQueueStats(); + return formatSyncDiagnostics( + db.currentStatus, + pendingUploads: queue.count, + server: serverCategory(serverUrl), + ); +} diff --git a/test/core/errors_test.dart b/test/core/errors_test.dart index 780efbff7..78318e58d 100644 --- a/test/core/errors_test.dart +++ b/test/core/errors_test.dart @@ -147,6 +147,48 @@ void main() { expect(description, contains('log line 1')); }); + test('Includes the sync status section when diagnostics are passed', () { + final url = buildGithubIssueUrl( + issueTitle: 'Sync error', + issueErrorMessage: 'boom', + applicationLogs: ['log line'], + syncDiagnostics: 'connected: false\npending uploads: 3', + ); + + final description = Uri.parse(url).queryParameters['description']!; + expect(description, contains('Sync status:')); + expect(description, contains('pending uploads: 3')); + // No stack trace was passed, so the section is omitted entirely + expect(description, isNot(contains('Stack trace:'))); + }); + + test('Keeps the sync status section and drops logs instead', () { + final url = buildGithubIssueUrl( + issueTitle: 'Sync error', + issueErrorMessage: 'boom', + applicationLogs: List.generate(3000, (i) => 'log entry number $i'), + syncDiagnostics: 'connected: false\npending uploads: 3', + ); + + expect(url.length, lessThanOrEqualTo(GITHUB_ISSUES_MAX_URL_LENGTH)); + final description = Uri.parse(url).queryParameters['description']!; + expect(description, contains('pending uploads: 3')); + expect(description, isNot(contains('log entry number 2999'))); + }); + + test('Omits the sync status section without diagnostics', () { + final url = buildGithubIssueUrl( + issueTitle: 'An error occurred', + issueErrorMessage: 'boom', + stackTrace: 'trace', + applicationLogs: ['log line'], + ); + + final description = Uri.parse(url).queryParameters['description']!; + expect(description, isNot(contains('Sync status:'))); + expect(description, contains('Stack trace:')); + }); + test('Drops the oldest log entries, keeps the newest', () { // Logs come newest-first, so index 0 is the most recent entry. final logs = List.generate(3000, (i) => 'log entry $i'); diff --git a/test/core/widgets/sync_status_dialog_test.dart b/test/core/widgets/sync_status_dialog_test.dart index f123fb4d4..1b22fc200 100644 --- a/test/core/widgets/sync_status_dialog_test.dart +++ b/test/core/widgets/sync_status_dialog_test.dart @@ -288,6 +288,22 @@ void main() { expect(find.text(i18n.syncStatusReconnect), findsOneWidget); }); + testWidgets('offers the report action on error and when stalled, not while healthy', ( + tester, + ) async { + await _pumpDialog(tester, buildSyncStatus(connected: true)); + expect(find.text('Report issue'), findsNothing); + + await _pumpDialog(tester, buildSyncStatus(connected: true, downloadError: Exception('boom'))); + expect(find.text('Report issue'), findsOneWidget); + + await tester.pumpWidget( + _wrap(const SyncStatusDialog(), status: buildSyncStatus(connecting: true), stalled: true), + ); + await tester.pumpAndSettle(); + expect(find.text('Report issue'), findsOneWidget); + }); + testWidgets('omits the reconnect action without a callback', (tester) async { await _pumpDialog(tester, buildSyncStatus(connected: true, downloadError: Exception('boom'))); diff --git a/test/powersync/sync_diagnostics_test.dart b/test/powersync/sync_diagnostics_test.dart new file mode 100644 index 000000000..4ef0de2c6 --- /dev/null +++ b/test/powersync/sync_diagnostics_test.dart @@ -0,0 +1,86 @@ +/* + * 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 'dart:io' show SocketException; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/core/consts.dart'; +import 'package:wger/powersync/sync_diagnostics.dart'; + +import '../helpers/sync_status.dart'; + +void main() { + group('serverCategory', () { + test('maps the known servers and hides self-hosted URLs', () { + expect(serverCategory(null), isNull); + expect(serverCategory(DEFAULT_SERVER_PROD), 'wger.de'); + expect(serverCategory(DEFAULT_SERVER_TEST), 'dev.wger.de'); + expect(serverCategory('https://wger.my-private-nas.example'), 'self-hosted'); + }); + }); + + group('formatSyncDiagnostics', () { + test('renders the healthy state', () { + final text = formatSyncDiagnostics( + buildSyncStatus(connected: true, lastSyncedAt: DateTime.utc(2026, 7, 29, 10, 30)), + pendingUploads: 0, + server: 'wger.de', + ); + + expect(text, contains('server: wger.de')); + expect(text, contains('connected: true, connecting: false')); + expect(text, contains('last successful sync: 2026-07-29T10:30:00.000Z')); + expect(text, contains('pending uploads: 0')); + expect(text, isNot(contains('error'))); + }); + + test('reports a never-completed sync and the pending queue', () { + final text = formatSyncDiagnostics(buildSyncStatus(connecting: true), pendingUploads: 3); + + expect(text, contains('last successful sync: never')); + expect(text, contains('pending uploads: 3')); + expect(text, isNot(contains('server:'))); + }); + + test('includes the categorised error', () { + final text = formatSyncDiagnostics( + buildSyncStatus(downloadError: const SocketException('no route to host')), + pendingUploads: 0, + ); + + expect(text, contains('error (Connection error): SocketException')); + }); + + test('clamps oversized error messages', () { + final text = formatSyncDiagnostics( + buildSyncStatus(downloadError: Exception('x' * 5000)), + pendingUploads: 0, + ); + + final errorLine = text.split('\n').firstWhere((line) => line.startsWith('error')); + expect(errorLine.length, lessThan(350)); + expect(errorLine, endsWith('…')); + }); + }); + + group('collectSyncDiagnostics', () { + test('returns null while the PowerSync database is not initialised', () async { + expect(await collectSyncDiagnostics(), isNull); + }); + }); +} From 9e446e0b94d82ca29d0d477af90322bd8a9c4b20 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 17:23:09 +0200 Subject: [PATCH 060/484] Allow users to submit issues to github with full stackstrace and sync debug info --- lib/core/consts.dart | 6 ++- lib/core/errors.dart | 63 +++++++++++++++++++----------- lib/core/widgets/about.dart | 19 ++++++++- lib/core/widgets/log_overview.dart | 24 +++++++++++- test/core/errors_test.dart | 23 +++++++++-- 5 files changed, 106 insertions(+), 29 deletions(-) diff --git a/lib/core/consts.dart b/lib/core/consts.dart index 30136fdd7..449f43d6c 100644 --- a/lib/core/consts.dart +++ b/lib/core/consts.dart @@ -161,8 +161,10 @@ const GITHUB_ISSUES_URL = '$GITHUB_REPO_URL/issues/new/choose'; const GITHUB_ISSUES_BUG_URL = '$GITHUB_REPO_URL/issues/new?template=1_bug.yml'; const GITHUB_SPONSORS_URL = 'https://github.com/sponsors/wger-project'; -/// Maximum length for a pre-filled GitHub issue URL -const GITHUB_ISSUES_MAX_URL_LENGTH = 8000; +/// Maximum length for a pre-filled GitHub issue URL. GitHub starts answering +/// issues/new with an error page at roughly 7050 characters (measured 2026-07), +/// so stay well below that. +const GITHUB_ISSUES_MAX_URL_LENGTH = 6500; const DISCORD_URL = 'https://discord.gg/rPWFv6W'; const MASTODON_URL = 'https://fosstodon.org/@wger'; const READTHEDOCS_URL = 'https://wger.readthedocs.io'; diff --git a/lib/core/errors.dart b/lib/core/errors.dart index 14457f7a6..df7b06467 100644 --- a/lib/core/errors.dart +++ b/lib/core/errors.dart @@ -67,42 +67,61 @@ bool isNetworkError(Object e) { /// Builds the URL that opens a pre-filled GitHub bug report. /// -/// The error details are passed to GitHub as query parameters and since -/// GitHub rejects URLs longer than [GITHUB_ISSUES_MAX_URL_LENGTH], when -/// the report would exceed that limit, the oldest log entries are pruned -/// until the URL fits. +/// All error-related parameters are optional so user-initiated reports (no +/// crash, just logs and diagnostics) render without empty error sections. +/// The details are passed to GitHub as query parameters and since GitHub +/// rejects URLs longer than [GITHUB_ISSUES_MAX_URL_LENGTH], an oversized +/// report first drops the oldest log entries and then, if still too long, +/// trims the stack trace from the bottom until the URL fits. String buildGithubIssueUrl({ - required String issueTitle, - required String issueErrorMessage, required List applicationLogs, + String? issueTitle, + String? issueErrorMessage, String? stackTrace, String? syncDiagnostics, }) { - String composeUrl(List logs) { + final descriptionPrompt = issueErrorMessage != null + ? '[Please describe what you were doing when the error occurred.]' + : '[Please describe the problem you are seeing.]'; + + String composeUrl(List logs, String? trace) { final logText = logs.isEmpty ? '-- No logs available --' : logs.join('\n'); - final description = - '## Description\n\n' - '[Please describe what you were doing when the error occurred.]\n\n' - '## Error details\n\n' - 'Error title: $issueTitle\n' - 'Error message: $issueErrorMessage\n' - '${stackTrace != null ? 'Stack trace:\n```\n$stackTrace\n```\n\n' : ''}' - '${syncDiagnostics != null ? 'Sync status:\n```\n$syncDiagnostics\n```\n\n' : ''}' - 'App logs (last ${logs.length} entries):\n```\n$logText\n```'; + final errorDetails = issueErrorMessage == null + ? null + : '## Error details\n\n' + '${issueTitle != null ? 'Error title: $issueTitle\n' : ''}' + 'Error message: $issueErrorMessage' + '${trace != null ? '\nStack trace:\n```\n$trace\n```' : ''}'; + final sections = [ + '## Description\n\n$descriptionPrompt', + ?errorDetails, + if (syncDiagnostics != null) 'Sync status:\n```\n$syncDiagnostics\n```', + 'App logs (last ${logs.length} entries):\n```\n$logText\n```', + ]; + final description = sections.join('\n\n'); return '$GITHUB_ISSUES_BUG_URL' - '&title=${Uri.encodeComponent(issueTitle)}' + '${issueTitle != null ? '&title=${Uri.encodeComponent(issueTitle)}' : ''}' '&description=${Uri.encodeComponent(description)}'; } - // The logs come newest-first, so the oldest entry is the last one. Drop it - // and retry until the URL fits within the limit. + // The logs come newest-first, so the oldest entry is the last one. Once + // all logs are gone, drop stack frames starting from the outermost one; + // the top of the trace is where the error actually happened. var logs = applicationLogs; + var trace = stackTrace; while (true) { - final url = composeUrl(logs); - if (url.length <= GITHUB_ISSUES_MAX_URL_LENGTH || logs.isEmpty) { + final url = composeUrl(logs, trace); + if (url.length <= GITHUB_ISSUES_MAX_URL_LENGTH) { + return url; + } + if (logs.isNotEmpty) { + logs = logs.sublist(0, logs.length - 1); + } else if (trace != null && trace.contains('\n')) { + trace = trace.substring(0, trace.lastIndexOf('\n')); + } else { + // Nothing left to trim return url; } - logs = logs.sublist(0, logs.length - 1); } } diff --git a/lib/core/widgets/about.dart b/lib/core/widgets/about.dart index 87a7de5a0..144308fa0 100644 --- a/lib/core/widgets/about.dart +++ b/lib/core/widgets/about.dart @@ -22,12 +22,16 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:wger/core/consts.dart'; +import 'package:wger/core/errors.dart' show buildGithubIssueUrl; +import 'package:wger/core/logs.dart'; import 'package:wger/core/misc.dart'; import 'package:wger/core/network/auth_notifier.dart'; import 'package:wger/core/network/network_provider.dart'; +import 'package:wger/core/network/wger_base.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/features/exercises/screens/add_exercise_screen.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/powersync/sync_diagnostics.dart' show collectSyncDiagnostics; import 'log_overview.dart'; @@ -113,7 +117,20 @@ class AboutPage extends ConsumerWidget { trailing: const Icon(Icons.arrow_outward), title: Text(i18n.aboutBugsListTitle), contentPadding: EdgeInsets.zero, - onTap: () => launchURL(GITHUB_ISSUES_URL, context), + // Pre-fill the report with the app logs and the sync + // snapshot, so user-initiated issues carry the same context + // as crash reports + onTap: () async { + final url = buildGithubIssueUrl( + applicationLogs: InMemoryLogStore().getFormattedLogs(), + syncDiagnostics: await collectSyncDiagnostics( + serverUrl: ref.read(wgerBaseProvider).serverUrl, + ), + ); + if (context.mounted) { + launchURL(url, context); + } + }, ), ListTile( leading: const Icon(Icons.translate), diff --git a/lib/core/widgets/log_overview.dart b/lib/core/widgets/log_overview.dart index 61c128b82..9894c76e0 100644 --- a/lib/core/widgets/log_overview.dart +++ b/lib/core/widgets/log_overview.dart @@ -18,8 +18,11 @@ import 'package:flutter/material.dart'; import 'package:logging/logging.dart'; +import 'package:wger/core/errors.dart' show buildGithubIssueUrl; import 'package:wger/core/logs.dart'; +import 'package:wger/core/misc.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/powersync/sync_diagnostics.dart' show collectSyncDiagnostics; class LogOverviewPage extends StatelessWidget { static String routeName = '/LogOverviewPage'; @@ -32,7 +35,26 @@ class LogOverviewPage extends StatelessWidget { final logs = InMemoryLogStore().logs.reversed.toList(); return Scaffold( - appBar: AppBar(title: Text(i18n.applicationLogs)), + appBar: AppBar( + title: Text(i18n.applicationLogs), + actions: [ + // Opens a pre-filled GitHub issue with these logs and the current + // sync snapshot + IconButton( + icon: const Icon(Icons.bug_report), + tooltip: 'Report issue', + onPressed: () async { + final url = buildGithubIssueUrl( + applicationLogs: InMemoryLogStore().getFormattedLogs(), + syncDiagnostics: await collectSyncDiagnostics(), + ); + if (context.mounted) { + launchURL(url, context); + } + }, + ), + ], + ), body: logs.isEmpty ? const Center(child: Text('No logs available.')) : ListView.builder( diff --git a/test/core/errors_test.dart b/test/core/errors_test.dart index 78318e58d..b1b3cf3db 100644 --- a/test/core/errors_test.dart +++ b/test/core/errors_test.dart @@ -147,6 +147,21 @@ void main() { expect(description, contains('log line 1')); }); + test('Builds a user-initiated report without error sections', () { + final url = buildGithubIssueUrl( + applicationLogs: ['log line'], + syncDiagnostics: 'connected: true', + ); + + expect(url, startsWith(GITHUB_ISSUES_BUG_URL)); + expect(url, isNot(contains('&title='))); + final description = Uri.parse(url).queryParameters['description']!; + expect(description, contains('[Please describe the problem you are seeing.]')); + expect(description, isNot(contains('Error details'))); + expect(description, contains('Sync status:')); + expect(description, contains('log line')); + }); + test('Includes the sync status section when diagnostics are passed', () { final url = buildGithubIssueUrl( issueTitle: 'Sync error', @@ -206,7 +221,7 @@ void main() { expect(description, isNot(contains('log entry 2999'))); // oldest dropped }); - test('Keeps the full stack trace and drops logs instead', () { + test('Drops logs first, then trims the stack trace from the bottom', () { final longTrace = List.generate( 80, (i) => '#$i SomeClass.someMethod (package:wger/some/file.dart:$i:11)', @@ -221,9 +236,11 @@ void main() { expect(url.length, lessThanOrEqualTo(GITHUB_ISSUES_MAX_URL_LENGTH)); final description = Uri.parse(url).queryParameters['description']!; - // The stack trace is never trimmed: first and last frame survive. + // The trace alone exceeds the limit here, so the logs are gone and + // the outermost frames were dropped; the top of the trace survives. expect(description, contains('#0 SomeClass.someMethod')); - expect(description, contains('#79 SomeClass.someMethod')); + expect(description, isNot(contains('#79 SomeClass.someMethod'))); + expect(description, isNot(contains('log entry number'))); }); }); From 630d4864d8a1e65c89a6cd7a08a6566b3f3f407d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 17:28:47 +0200 Subject: [PATCH 061/484] Cleanup --- lib/core/widgets/app_bar.dart | 7 ++++--- lib/powersync/sync_diagnostics.dart | 24 ++++++++++++++++++------ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/lib/core/widgets/app_bar.dart b/lib/core/widgets/app_bar.dart index d32b7e396..98d51154d 100644 --- a/lib/core/widgets/app_bar.dart +++ b/lib/core/widgets/app_bar.dart @@ -58,8 +58,9 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { context: context, // The dialog watches the sync state itself; only the server URL // and the offline gate are snapshots taken when it opens. - // No reconnect action while offline: the app deliberately - // disconnects there (see powerSyncInstance) + // No reconnect while offline: the app deliberately disconnects + // there (see powerSyncInstance). The tap-time check covers the + // network dropping while the dialog is open builder: (_) => SyncStatusDialog( serverUrl: ref.read(wgerBaseProvider).serverUrl, onReconnect: !ref.read(networkStatusProvider) @@ -67,7 +68,7 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { : () { final db = builtPowerSyncInstance; final serverUrl = ref.read(wgerBaseProvider).serverUrl; - if (db == null || serverUrl == null) { + if (db == null || serverUrl == null || !ref.read(networkStatusProvider)) { return; } ref.read(syncWatchdogProvider).reset(); diff --git a/lib/powersync/sync_diagnostics.dart b/lib/powersync/sync_diagnostics.dart index 8c02fdcd1..cff4da5bd 100644 --- a/lib/powersync/sync_diagnostics.dart +++ b/lib/powersync/sync_diagnostics.dart @@ -16,12 +16,15 @@ * along with this program. If not, see . */ +import 'package:logging/logging.dart'; import 'package:powersync/powersync.dart' show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus; import 'package:wger/core/consts.dart'; import 'package:wger/database/powersync/powersync.dart' show builtPowerSyncInstance; import 'package:wger/powersync/connector.dart' show RetryableUploadException; +final _logger = Logger('sync_diagnostics'); + /// Maps an HTTP status code to a short English category label. String _categoriseHttpStatus(int statusCode) { if (statusCode == 401 || statusCode == 403) { @@ -106,15 +109,24 @@ String formatSyncDiagnostics( /// Snapshot of the current sync state for bug reports, or null when the /// PowerSync database has not been initialised. +/// +/// Never throws: this runs on report paths where the app may already be in +/// a broken state (e.g. the DB is closing down), and a missing sync section +/// must not prevent the report itself. Future collectSyncDiagnostics({String? serverUrl}) async { final db = builtPowerSyncInstance; if (db == null) { return null; } - final queue = await db.getUploadQueueStats(); - return formatSyncDiagnostics( - db.currentStatus, - pendingUploads: queue.count, - server: serverCategory(serverUrl), - ); + try { + final queue = await db.getUploadQueueStats(); + return formatSyncDiagnostics( + db.currentStatus, + pendingUploads: queue.count, + server: serverCategory(serverUrl), + ); + } catch (e) { + _logger.warning('Could not collect sync diagnostics: $e'); + return null; + } } From 30cc2fc9595c1ac34039caa90d8d9e93016babfd Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 17:42:31 +0200 Subject: [PATCH 062/484] Improve logging --- lib/core/widgets/sync_status_dialog.dart | 4 ++-- lib/powersync/sync_diagnostics.dart | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/core/widgets/sync_status_dialog.dart b/lib/core/widgets/sync_status_dialog.dart index 28efa616c..baa878410 100644 --- a/lib/core/widgets/sync_status_dialog.dart +++ b/lib/core/widgets/sync_status_dialog.dart @@ -230,8 +230,8 @@ class SyncStatusDialog extends ConsumerWidget { ); try { await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication); - } catch (e) { - _logger.warning('Error opening issue tracker: $e'); + } catch (e, s) { + _logger.warning('Error opening issue tracker', e, s); } }, child: const Text('Report issue'), diff --git a/lib/powersync/sync_diagnostics.dart b/lib/powersync/sync_diagnostics.dart index cff4da5bd..27a389e2f 100644 --- a/lib/powersync/sync_diagnostics.dart +++ b/lib/powersync/sync_diagnostics.dart @@ -125,8 +125,8 @@ Future collectSyncDiagnostics({String? serverUrl}) async { pendingUploads: queue.count, server: serverCategory(serverUrl), ); - } catch (e) { - _logger.warning('Could not collect sync diagnostics: $e'); + } catch (e, s) { + _logger.warning('Could not collect sync diagnostics', e, s); return null; } } From bcf2a2ce42f92ef3acaef022e2b386d8ef11b043 Mon Sep 17 00:00:00 2001 From: Jure Repinc Date: Wed, 29 Jul 2026 02:45:52 +0200 Subject: [PATCH 063/484] Translated using Weblate (Slovenian) Currently translated at 66.6% (2 of 3 strings) Translation: wger Workout Manager/Play Store Translate-URL: https://hosted.weblate.org/projects/wger/play-store/sl/ --- fastlane/metadata/android/sl/short_description.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 fastlane/metadata/android/sl/short_description.txt diff --git a/fastlane/metadata/android/sl/short_description.txt b/fastlane/metadata/android/sl/short_description.txt new file mode 100644 index 000000000..4884707ec --- /dev/null +++ b/fastlane/metadata/android/sl/short_description.txt @@ -0,0 +1 @@ +Spremljanje fitnesa/treningov, prehrane in teže From 9f70ce28436509b2820fd2c1b474159863f92194 Mon Sep 17 00:00:00 2001 From: Jure Repinc Date: Wed, 29 Jul 2026 03:44:15 +0200 Subject: [PATCH 064/484] Added translation using Weblate (Slovenian) --- lib/l10n/app_sl.arb | 1 + 1 file changed, 1 insertion(+) create mode 100644 lib/l10n/app_sl.arb diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/lib/l10n/app_sl.arb @@ -0,0 +1 @@ +{} From 9a2283c4d30d728b673e0ffe2603e00b6caf4941 Mon Sep 17 00:00:00 2001 From: Jure Repinc Date: Wed, 29 Jul 2026 05:50:12 +0200 Subject: [PATCH 065/484] Translated using Weblate (Slovenian) Currently translated at 46.0% (210 of 456 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/sl/ --- lib/l10n/app_sl.arb | 579 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 578 insertions(+), 1 deletion(-) diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 0967ef424..99b6474f2 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -1 +1,578 @@ -{} +{ + "userProfile": "Vaš profil", + "login": "Prijava", + "@login": { + "description": "Text for login button" + }, + "logout": "Odjava", + "@logout": { + "description": "Text for logout button" + }, + "register": "Vpis", + "@register": { + "description": "Text for registration button" + }, + "invalidUrl": "Vnesite veljavno lokacijo", + "@invalidUrl": { + "description": "Error message when the user enters an invalid URL, e.g. in the login form" + }, + "usernameValidChars": "Uporabniško ime lahko vsebuje le črke, števke, in znake @, +, ., -, _", + "@usernameValidChars": { + "description": "Error message when the user tries to register a username with forbidden characters" + }, + "passwordsDontMatch": "Gesli nista enaki", + "@passwordsDontMatch": { + "description": "Error message when the user enters two different passwords during registration" + }, + "passwordTooShort": "Geslo je prekratko", + "@passwordTooShort": { + "description": "Error message when the user a password that is too short" + }, + "selectAvailablePlates": "Izberite razpoložljive plošče", + "barWeight": "Teža palice", + "useColors": "Uporabi barve", + "password": "Geslo", + "confirmPassword": "Potrdite geslo", + "invalidEmail": "Vnesite veljaven naslov elektronske pošte", + "@invalidEmail": { + "description": "Error message when the user enters an invalid email" + }, + "email": "E-poštni naslov", + "username": "Uporabniško ime", + "invalidUsername": "Vnesite veljavno uporabniško ime", + "@invalidUsername": { + "description": "Error message when the user enters an invalid username" + }, + "refreshToken": "Žeton za osveževanje", + "invalidRefreshToken": "Vnesite veljaven žeton za osveževanje", + "@invalidRefreshToken": { + "description": "Error message when the user enters an invalid refresh token" + }, + "refreshTokenValidChars": "Žeton za osveževanje ima tri dele, ločene s piko (glava.vsebina.podpis). Vsak del je iz črk, števk »-« in »_«.", + "@refreshTokenValidChars": { + "description": "Error message when the user pastes a string that does not match the JWT shape" + }, + "refreshTokenHelperText": "Na spletni strani wger ustvarite žeton za osveževanje JWT in ga prilepite sem. Uporabno, ko je strežnik za overitvenim posrednikom ali ko želite preskočiti običajen postopek prijave.", + "@refreshTokenHelperText": { + "description": "Helper text on the refresh-token paste field" + }, + "mfaChallengeTitle": "Dvo-delno overjanje", + "@mfaChallengeTitle": { + "description": "App bar title on the 2FA challenge screen" + }, + "mfaChallengeTotpPrompt": "Vnesite 6-mestno številsko kodo iz aplikacije za overjanje", + "@mfaChallengeTotpPrompt": { + "description": "Helper text above the TOTP input field" + }, + "mfaChallengeRecoveryPrompt": "Vnesite eno izmed vaših kod za obnavljanje", + "@mfaChallengeRecoveryPrompt": { + "description": "Helper text above the recovery-code input field" + }, + "mfaCodeLabel": "Koda", + "@mfaCodeLabel": { + "description": "Label on the 2FA code input field" + }, + "mfaInvalidCode": "Vnesite kodo", + "@mfaInvalidCode": { + "description": "Validation error when the 2FA code field is empty" + }, + "mfaUseRecoveryCode": "Namesto tega uporabi kodo za obnavljanje", + "@mfaUseRecoveryCode": { + "description": "Button that switches the 2FA challenge to recovery-code mode" + }, + "mfaUseTotpCode": "Uporabi kodo iz aplikacije za overjanje", + "@mfaUseTotpCode": { + "description": "Button that switches the 2FA challenge back to TOTP mode" + }, + "mfaSubmit": "Potrdi", + "@mfaSubmit": { + "description": "Submit button on the 2FA challenge screen" + }, + "mfaUnsupportedFactor": "Vaš račun je nastavljen z dvo-delnim overjanjem, ki ga ta aplikacija še ne podpira. Prijavite se na spletni strani.", + "@mfaUnsupportedFactor": { + "description": "Shown when the server reports only factor types the app cannot handle (e.g. webauthn)" + }, + "manageAccountOnWeb": "Upravljaj račun na spletni strani", + "@manageAccountOnWeb": { + "description": "Label on a button that opens the user's preferences page on the wger website" + }, + "manageAccountOnWebSubtitle": "Spremenite svoje geslo, nastavite dvo-delno overjanje, upravljajte žetone za programski vmesnik ali izbrišite svoj rčaun.", + "@manageAccountOnWebSubtitle": { + "description": "Helper text below the 'Manage account on the web' button listing what is configurable there" + }, + "customServerUrl": "Lokacija strežnika wger", + "@customServerUrl": { + "description": "Label in the form where the users can enter their own wger instance" + }, + "customServerHint": "Vnesite naslov strežnika. Če pustite prazno bo uporabljen privzeti strežnik.", + "@customServerHint": { + "description": "Hint text for the form where the users can enter their own wger instance" + }, + "reset": "Ponastavi", + "@reset": { + "description": "Button text allowing the user to reset the entered values to the default" + }, + "advanced": "Napredno", + "advancedSubtitle": "Možnosti strežnika in overjanja", + "serverSectionLabel": "Strežnik", + "signInMethodSectionLabel": "Način prijave", + "serverOptionDefaultDetail": "Uradni strežnik", + "serverOptionSelfHostedTitle": "Lastni strežnik", + "serverOptionSelfHostedDetail": "Povežite se na svoj lastni strežnik", + "authOptionPasswordTitle": "Uporabniško ime in geslo", + "signInWithToken": "Prijavi se z žetonom", + "tokenSubtitle": "Ustvarite ga na spletni strani wger", + "newToWger": "Ali prvič uporabljate wger?", + "alreadyHaveAccount": "Ali že imate račun?", + "tokenLabel": "Žeton", + "webHandoffLinkLabel": "Druge možnosti prijave", + "webHandoffLinkSubtitle": "Prijava prek družbenih omrežij, PassKey, enojna prijava (SSO)", + "labelBottomNavWorkout": "Trening", + "@labelBottomNavWorkout": { + "description": "Label used in bottom navigation, use a short word" + }, + "labelBottomNavNutrition": "Prehrana", + "@labelBottomNavNutrition": { + "description": "Label used in bottom navigation, use a short word" + }, + "labelWorkoutLogs": "Dnevniki treningov", + "@labelWorkoutLogs": { + "description": "(Workout) logs" + }, + "labelWorkoutPlan": "Načrt treninga", + "@labelWorkoutPlan": { + "description": "Title for screen workout plan" + }, + "dashboardWidgets": "Gradniki preglednega pulta", + "labelDashboard": "Pregledni pult", + "@labelDashboard": { + "description": "Title for screen dashboard" + }, + "success": "Uspeh", + "@success": { + "description": "Message when an action completed successfully, usually used as a heading" + }, + "successfullyDeleted": "Izbrisano", + "@successfullyDeleted": { + "description": "Message when an item was successfully deleted" + }, + "successfullySaved": "Shranjeno", + "@successfullySaved": { + "description": "Message when an item was successfully saved" + }, + "exerciseList": "Seznam vaj", + "exercise": "Vaja", + "@exercise": { + "description": "An exercise for a workout" + }, + "exercises": "Vaje", + "@exercises": { + "description": "Multiple exercises for a workout" + }, + "exerciseName": "Ime vaje", + "@exerciseName": { + "description": "Label for the name of a workout exercise" + }, + "searchExercise": "Poiščite vaje za dodajanje", + "@searchExercise": { + "description": "Label on set form. Selected exercises are added to the set" + }, + "noIngredientsDefined": "Določene še ni nobene sestavine", + "noMatchingExerciseFound": "Najdena ni bila nobena ustrezna vaja", + "@noMatchingExerciseFound": { + "description": "Message returned if no exercises match the searched string" + }, + "equipment": "Oprema", + "@equipment": { + "description": "Equipment needed to perform an exercise" + }, + "muscles": "Mišice", + "@muscles": { + "description": "(main) muscles trained by an exercise" + }, + "musclesSecondary": "Sekundarne mišice", + "@musclesSecondary": { + "description": "secondary muscles trained by an exercise" + }, + "category": "Kategorija", + "@category": { + "description": "Category for an exercise, ingredient, etc." + }, + "startDate": "Začetek", + "@startDate": { + "description": "The start date of a nutritional plan or routine" + }, + "dayTypeCustom": "Po meri", + "dayTypeEnom": "Vsako minuto na minuto", + "dayTypeAmrap": "Kolikor krogov/ponovitev je mogoče", + "dayTypeHiit": "Trening z intervali visoke intenzivnosti", + "dayTypeTabata": "Tabata", + "dayTypeEdt": "Trening s povečevanjem gostote", + "dayTypeRft": "Krogi za čas", + "dayTypeAfap": "Kakor hitro je mogoče", + "slotEntryTypeNormal": "Normalni", + "slotEntryTypeDropset": "Lažji niz", + "slotEntryTypeMyo": "Myo", + "slotEntryTypeWarmup": "Ogrevanje", + "slotEntryTypePartial": "Delni", + "slotEntryTypeForced": "Prisiljeni", + "slotEntryTypeTut": "Čas pod napetostjo", + "slotEntryTypeIso": "Izometrično držanje", + "slotEntryTypeJump": "Skok", + "trophies": "Trofeje", + "routines": "Rutine", + "newRoutine": "Nova rutina", + "noRoutines": "Nimate še nobene rutine", + "reps": "Ponov.", + "@reps": { + "description": "Shorthand for repetitions, used when space constraints are tighter" + }, + "restTime": "Čas počitka", + "sets": "Nizi", + "@sets": { + "description": "The number of sets to be done for one exercise" + }, + "rir": "PvR", + "@rir": { + "description": "Shorthand for Repetitions In Reserve" + }, + "rirNotUsed": "PvR se ne uporabljajo", + "@rirNotUsed": { + "description": "Label used in RiR slider when the RiR value is not used/saved for the current setting or log" + }, + "useMetric": "Za telesno težo uporabi metrične enote", + "weightUnit": "Enota teže", + "repetitionUnit": "Enota ponovitve", + "set": "Niz", + "@set": { + "description": "A set in a workout plan" + }, + "dayDescriptionHelp": "Opis, kaj delate ta dan (npr. »Dan za vleko«) ali katere dele telesa trenirate (npr. »Prsni koš in ramena«)", + "exerciseNr": "{nr}. vaja", + "@exerciseNr": { + "description": "Header in form indicating the number of the current exercise. Can also be translated as something like 'Set Nr. xy'.", + "type": "text", + "placeholders": { + "nr": { + "type": "String" + } + } + }, + "supersetNr": "{nr}. superniz", + "@supersetNr": { + "description": "Header in form indicating the number of the current exercise. Can also be translated as something like 'Superset Nr. xy'.", + "type": "text", + "placeholders": { + "nr": { + "type": "String" + } + } + }, + "setNr": "{nr}. niz", + "@setNr": { + "description": "Header in form indicating the number of the current set within a group of same exercises.", + "type": "text", + "placeholders": { + "nr": { + "type": "String" + } + } + }, + "comment": "Komentar", + "@comment": { + "description": "Comment, additional information" + }, + "topSet": "Najboljši niz: {value}", + "@topSet": { + "description": "Value is a representation of the set, like '10 x 80kg'", + "type": "text", + "placeholders": { + "value": { + "type": "String" + } + } + }, + "impressionGood": "Dober", + "impressionNeutral": "Nevtralen", + "impressionBad": "Slab", + "impression": "Vtis", + "@impression": { + "description": "General impression (e.g. for a workout session) such as good, bad, etc." + }, + "notes": "Opombe", + "@notes": { + "description": "Personal notes, e.g. for a workout session" + }, + "workoutSession": "Seja treninga", + "@workoutSession": { + "description": "A (logged) workout session" + }, + "restDay": "Dan počitka", + "isRestDay": "Je dan počitka", + "isRestDayHelp": "Upoštevajte, da bodo vsi nizi in vaje odstranjeni, ko označite dan kot dan počitka.", + "needsLogsToAdvance": "Za napredovanje potrebuje dnevnike", + "needsLogsToAdvanceHelp": "Izberite, če želite da rutina napreduje na naslednji dan v razporedu, samo če ste v dnevnik vnesli trening za ta dan", + "routineDays": "Dnevi v rutini", + "resultingRoutine": "Končna rutina", + "newDay": "Nov dan", + "newSet": "Nov niz", + "@newSet": { + "description": "Header when adding a new set to a workout day" + }, + "personalRecords": "Osebni rekordi", + "gymMode": "Način telovadbe", + "@gymMode": { + "description": "Label when starting the gym mode" + }, + "gymModeShowExercises": "Prikaži strani pregleda vaj", + "gymModeShowTimer": "Prikaži časomer med nizi", + "gymModeShowWorkoutDuration": "Prikaži trajanje treninga", + "gymModeTimerType": "Vrsta časomera", + "gymModeTimerTypeHelText": "Če ima niz čas premora, se vedno uporabi odštevanje.", + "countdown": "Odštevanje", + "stopwatch": "Štoparica", + "gymModeDefaultCountdownTime": "Privzeti čas za odštevanje, v sekundah", + "gymModeNotifyOnCountdownFinish": "Opomnik ob koncu odštevanja", + "duration": "Trajanje", + "durationHoursMinutes": "{hours} h {minutes} min", + "@durationHoursMinutes": { + "description": "A duration, in hours and minutes", + "type": "text", + "placeholders": { + "hours": { + "type": "int" + }, + "minutes": { + "type": "int" + } + } + }, + "volume": "Volumen", + "@volume": { + "description": "The volume of a workout or set, i.e. weight x reps" + }, + "workoutCompleted": "Trening zaključen", + "plateCalculator": "Plošče", + "@plateCalculator": { + "description": "Label used for the plate calculator in the gym mode" + }, + "plateCalculatorNotDivisible": "Z razpoložljivimi ploščami ni moč doseči želene teže", + "@plateCalculatorNotDivisible": { + "description": "Error message when the current weight is not reachable with plates (e.g. 33.1 kg)" + }, + "pause": "Premor", + "@pause": { + "description": "Noun, not an imperative! Label used for the pause when using the gym mode" + }, + "jumpTo": "Skoči na", + "@jumpTo": { + "description": "Imperative. Label used in popup allowing the user to jump to a specific exercise while in the gym mode" + }, + "todaysWorkout": "Vaš današnji trening", + "logHelpEntries": "Če je v enem dnevu več vnosov z enakim številom ponovitev a drugimi utežmi, je v diagramu prikazan samo vnos z višjo težo.", + "logHelpEntriesUnits": "Vedite, da je so prikazani samo vnosi z enoto teže (kg ali lb) in ponovitvami. Druge kombinacije (kot sta čas in do neuspeha) so tu prezrte.", + "description": "Opis", + "name": "Ime", + "@name": { + "description": "Name for a workout or nutritional plan" + }, + "save": "Shrani", + "verify": "Potrdi", + "addSet": "Dodaj niz", + "@addSet": { + "description": "Label for the button that adds a set (to a workout day)" + }, + "gymModeLogScope": "Prejšnji dnevniki", + "gymModeLogScopeHelp": "Kateri dnevniki naj bodo med treningom prikazani kot referenčni", + "gymModeLogScopeCurrentRoutine": "Trenutna rutina", + "gymModeLogScopeWeeks": "Zadnjih {weeks} tednov", + "@gymModeLogScopeWeeks": { + "placeholders": { + "weeks": { + "type": "int" + } + } + }, + "gymModeDistinctLogs": "Skrij podvojene vrednosti", + "addMeal": "Dodaj obrok", + "mealLogged": "Obrok zabeležen v dnevnik", + "ingredientLogged": "Sestavina zabeležena v dnevnik", + "logMeal": "Zabeleži obrok v dnevnik prehrane", + "addIngredient": "Dodaj sestavino", + "logIngredient": "Zabeleži sestavino v dnevnik prehrane", + "searchIngredient": "Poišči sestavino", + "@searchIngredient": { + "description": "Label (or Hint text) on ingredient search form" + }, + "nutritionalPlan": "Prehranski načrt", + "nutritionalDiary": "Dnevnik prehrane", + "nutritionalPlans": "Prehranski načrti", + "noNutritionalPlans": "Nimate še nobenega prehranskega načrta", + "@noNutritionalPlans": { + "description": "Message shown when the user has no nutritional plans" + }, + "clearSearchTerm": "Počisti iskalni niz (besedilo)", + "@clearSearchTerm": { + "description": "Tooltip for the icon-button that clears the ingredient search text field" + }, + "ingredients": "Sestavine", + "@ingredients": { + "description": "Plural title for the ingredients overview screen" + }, + "onlyLogging": "Sledi samo kalorijam", + "onlyLoggingHelpText": "Označite polje, če želite beležiti samo kalorije in ne želite nastaviti podrobnega prehranskega načrta s posameznimi obroki", + "goalMacro": "Makro cilji", + "@goalMacro": { + "description": "The goal for macronutrients" + }, + "selectMealToLog": "Izberite obrok za zapis v dnevnik", + "yourCurrentNutritionPlanHasNoMealsDefinedYet": "Vaš trenutni prehranski načrt še nima določenega nobenega obroka", + "@yourCurrentNutritionPlanHasNoMealsDefinedYet": { + "description": "Message shown when a nutrition plan doesn't have any meals" + }, + "toAddMealsToThePlanGoToNutritionalPlanDetails": "Da v načrt dodate obroke, odprite podrobnosti prehranskega načrta", + "@toAddMealsToThePlanGoToNutritionalPlanDetails": { + "description": "Message shown to guide users to the nutritional plan details page to add meals" + }, + "planDateRange": "od {startDate} do {endDate}", + "@planDateRange": { + "description": "Label for the start and end date range of a plan", + "placeholders": { + "startDate": { + "type": "String" + }, + "endDate": { + "type": "String" + } + } + }, + "planStartDate": "od {startDate}", + "@planStartDate": { + "description": "Label for the start date of a plan", + "placeholders": { + "startDate": { + "type": "String" + } + } + }, + "otherLogs": "Drugi dnevniki", + "@otherLogs": { + "description": "Other unassigned logs. Label for the pseudo-meal section that groups all nutritional diary entries not assigned to a specific meal" + }, + "goalEnergy": "Cilj vnesene energije", + "goalProtein": "Cilj beljakovin", + "goalCarbohydrates": "Cilj ogljikovih hidratov", + "goalFat": "Cilj maščob", + "goalFiber": "Cilj vlaknin", + "anErrorOccurred": "Prišlo je do napake!", + "errorRawSource": "Izvorno", + "@errorRawSource": { + "description": "Tab label for showing an HTML error response in its raw (unrendered) form, opposite of 'Preview'." + }, + "errorInfoDescription": "Se opravičujemo, a nekaj je šlo narobe. Napako nam lahko pomagate odpraviti, s tem, da jo vnesete na spletno stran GitHub.", + "errorInfoDescription2": "Lahko nadaljujete z uporabo aplikacije, vendar nekatere možnosti morda ne bodo delovale.", + "errorViewDetails": "Tehnične podrobnosti", + "applicationLogs": "Dnevniki aplikacije", + "errorCouldNotConnectToServer": "Ni se bilo moč povezati na strežnik", + "copyToClipboard": "Skopiraj na odložišče", + "weight": "Teža", + "@weight": { + "description": "The weight of a workout log or body weight entry" + }, + "min": "Min.", + "max": "Maks.", + "chartAllTimeTitle": "{name} – ves čas", + "@chartAllTimeTitle": { + "description": "All-time chart of 'name' (e.g. 'weight', 'body fat' etc.)", + "type": "text", + "placeholders": { + "name": { + "type": "String" + } + } + }, + "chart30DaysTitle": "{name} – zadnjih 30 dni", + "@chart30DaysTitle": { + "description": "last 30 days chart of 'name' (e.g. 'weight', 'body fat' etc.)", + "type": "text", + "placeholders": { + "name": { + "type": "String" + } + } + }, + "chartDuringPlanTitle": "{chartName} – med prehranskim načrtom {planName}", + "@chartDuringPlanTitle": { + "description": "chart of 'chartName' (e.g. 'weight', 'body fat' etc.) logged during plan", + "type": "text", + "placeholders": { + "chartName": { + "type": "String" + }, + "planName": { + "type": "String" + } + } + }, + "measurement": "Meritve", + "measurements": "Meritve", + "@measurements": { + "description": "Categories for the measurements such as biceps size, body fat, etc." + }, + "measurementCategoriesHelpText": "Kategorija meritev, npr »biceps« ali »telesna maščoba«", + "measurementEntriesHelpText": "Enota za meritve znotraj kategorije, npr. »cm« ali »%«", + "date": "Datum", + "@date": { + "description": "The date of a workout log or body weight entry" + }, + "endDate": "Končni datum", + "@endDate": { + "description": "The End date of a nutritional plan or routine" + }, + "endBeforeStart": "Končna vrednost ne more biti pred začetkom", + "@endBeforeStart": { + "description": "Validation error shown when a plan or routine end date is before its start date" + }, + "minLengthRoutine": "Rutina mora trajati vsaj {number} tednov", + "@minLengthRoutine": { + "description": "Validation error when a routine is shorter than the minimum allowed duration", + "placeholders": { + "number": { + "type": "int" + } + } + }, + "maxLengthRoutine": "Rutina lahko traja največ {number} tednov", + "@maxLengthRoutine": { + "description": "Validation error when a routine is longer than the maximum allowed duration", + "placeholders": { + "number": { + "type": "int" + } + } + }, + "openEnded": "Nima konca", + "@openEnded": { + "description": "When a nutrition plan has no pre-defined end date" + }, + "value": "Vrednost", + "@value": { + "description": "The value of a measurement entry" + }, + "start": "Začetek", + "@start": { + "description": "Label on button to start the gym mode (i.e., an imperative)" + }, + "time": "Čas", + "@time": { + "description": "The time of a meal or workout" + }, + "timeStart": "Začetni čas", + "@timeStart": { + "description": "The starting time of a workout" + }, + "timeEnd": "Končni čas", + "@timeEnd": { + "description": "The end time of a workout" + } +} From d939989d315997ec0bf5b0e0aad24bead4008110 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 18:23:59 +0200 Subject: [PATCH 066/484] Add language key --- android/app/src/main/res/xml/locales_config.xml | 1 + ios/Runner/Info.plist | 1 + lib/l10n/language_native_names.dart | 1 + 3 files changed, 3 insertions(+) diff --git a/android/app/src/main/res/xml/locales_config.xml b/android/app/src/main/res/xml/locales_config.xml index 5d088c4ae..0d2a41a64 100644 --- a/android/app/src/main/res/xml/locales_config.xml +++ b/android/app/src/main/res/xml/locales_config.xml @@ -30,6 +30,7 @@ + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index d67830a17..82371b5f1 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -44,6 +44,7 @@ ro ru sk + sl sn ta th diff --git a/lib/l10n/language_native_names.dart b/lib/l10n/language_native_names.dart index 2be5c239a..e5a93cbf0 100644 --- a/lib/l10n/language_native_names.dart +++ b/lib/l10n/language_native_names.dart @@ -48,6 +48,7 @@ const Map languageNativeNames = { 'ro': 'Română', 'ru': 'Русский', 'sk': 'Slovenčina', + 'sl': 'Slovenščina', 'sn': 'chiShona', 'ta': 'தமிழ்', 'th': 'ไทย', From 24c3a93d9738c6a84dcba6b39d3aa9c5eca64e7b Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 11:38:57 +0200 Subject: [PATCH 067/484] Filter out empty logs Closes #1293 --- lib/features/routines/widgets/charts.dart | 10 ++- .../routines/widgets/charts_test.dart | 73 +++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 test/features/routines/widgets/charts_test.dart diff --git a/lib/features/routines/widgets/charts.dart b/lib/features/routines/widgets/charts.dart index 2fcb7bcd4..b189ee4c1 100644 --- a/lib/features/routines/widgets/charts.dart +++ b/lib/features/routines/widgets/charts.dart @@ -1,13 +1,13 @@ /* * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -37,6 +37,12 @@ class LogChartWidgetFl extends StatefulWidget { class _LogChartWidgetFlState extends State { @override Widget build(BuildContext context) { + // Exercises whose logs all lack repetitions or a weight are grouped into an + // empty map, there is nothing to plot then + if (widget._data.isEmpty) { + return const SizedBox.shrink(); + } + return AspectRatio( aspectRatio: 1.70, child: Padding( diff --git a/test/features/routines/widgets/charts_test.dart b/test/features/routines/widgets/charts_test.dart new file mode 100644 index 000000000..50dbb1bbf --- /dev/null +++ b/test/features/routines/widgets/charts_test.dart @@ -0,0 +1,73 @@ +/* + * 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:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/routines/models/log.dart'; +import 'package:wger/features/routines/widgets/charts.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +void main() { + Widget createChartScreen(Map> data) { + return MaterialApp( + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Center( + child: SizedBox( + height: 300, + width: 300, + child: LogChartWidgetFl(data), + ), + ), + ), + ); + } + + Log makeLog(num repetitions, num weight, DateTime date) => Log( + exerciseId: 1, + repetitions: repetitions, + weight: weight, + date: date, + ); + + testWidgets('renders a chart with logs', (WidgetTester tester) async { + await tester.pumpWidget( + createChartScreen({ + 10: [ + makeLog(10, 100, DateTime(2026, 7, 1)), + makeLog(10, 110, DateTime(2026, 7, 8)), + ], + 8: [makeLog(8, 120, DateTime(2026, 7, 15))], + }), + ); + await tester.pumpAndSettle(); + + expect(find.byType(LineChart), findsOneWidget); + }); + + testWidgets('does not crash without any logs', (WidgetTester tester) async { + await tester.pumpWidget(createChartScreen({})); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.byType(LineChart), findsNothing); + }); +} From fb43a9fdd225ad835c6687699c3f761b5491b136 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 12:30:02 +0200 Subject: [PATCH 068/484] Allow setting the meal when logging individual ingredients --- .../providers/nutrition_notifier.dart | 3 +- lib/features/nutrition/widgets/forms.dart | 44 ++++++++-- lib/l10n/app_de.arb | 1 + lib/l10n/app_en.arb | 2 + lib/l10n/app_es.arb | 1 + lib/l10n/app_fr.arb | 1 + .../nutritional_meal_item_form_test.dart | 81 +++++++++++++++++++ 7 files changed, 127 insertions(+), 6 deletions(-) diff --git a/lib/features/nutrition/providers/nutrition_notifier.dart b/lib/features/nutrition/providers/nutrition_notifier.dart index 03b4fdc0d..a5313455e 100644 --- a/lib/features/nutrition/providers/nutrition_notifier.dart +++ b/lib/features/nutrition/providers/nutrition_notifier.dart @@ -200,9 +200,10 @@ class NutritionNotifier extends _$NutritionNotifier { MealItem mealItem, String planId, [ DateTime? dateTime, + String? mealId, ]) async { final repo = ref.read(nutritionRepositoryProvider); - final log = LogItem.fromMealItem(mealItem, planId, null, dateTime); + final log = LogItem.fromMealItem(mealItem, planId, mealId, dateTime); await repo.addLogLocalDrift(log); } diff --git a/lib/features/nutrition/widgets/forms.dart b/lib/features/nutrition/widgets/forms.dart index 8c30ee816..cc7db695d 100644 --- a/lib/features/nutrition/widgets/forms.dart +++ b/lib/features/nutrition/widgets/forms.dart @@ -112,7 +112,7 @@ Widget getMealItemForm( // 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) { + onSave: (BuildContext context, WidgetRef ref, MealItem mealItem, DateTime? dt, String? mealId) { mealItem.mealId = meal.id!; ref.read(nutritionProvider.notifier).addMealItem(mealItem, meal); }, @@ -125,8 +125,9 @@ Widget getMealItemForm( Widget getIngredientLogForm(NutritionalPlan plan) { return IngredientForm( recent: plan.dedupDiaryEntries, - onSave: (BuildContext context, WidgetRef ref, MealItem mealItem, DateTime? dt) { - ref.read(nutritionProvider.notifier).logIngredientToDiary(mealItem, plan.id!, dt); + meals: plan.meals, + onSave: (BuildContext context, WidgetRef ref, MealItem mealItem, DateTime? dt, String? mealId) { + ref.read(nutritionProvider.notifier).logIngredientToDiary(mealItem, plan.id!, dt, mealId); showSnackbar(context, AppLocalizations.of(context).ingredientLogged, center: true); }, withDate: true, @@ -136,18 +137,29 @@ Widget getIngredientLogForm(NutritionalPlan plan) { /// IngredientForm is a form that lets the user pick an ingredient (and amount) to /// log to the diary or to add to a meal. class IngredientForm extends ConsumerStatefulWidget { - final Function(BuildContext context, WidgetRef ref, MealItem mealItem, DateTime? dt) onSave; + final Function( + BuildContext context, + WidgetRef ref, + MealItem mealItem, + DateTime? dt, + String? mealId, + ) + onSave; final List recent; final bool withDate; final String barcode; final bool test; + /// When not empty, the form offers to assign the entry to one of these meals + final List meals; + const IngredientForm({ required this.recent, required this.onSave, required this.withDate, this.barcode = '', this.test = false, + this.meals = const [], }); @override @@ -165,6 +177,7 @@ class IngredientFormState extends ConsumerState { var _searchQuery = ''; // copy from typeahead. for filtering suggestions List _weightUnits = []; IngredientWeightUnit? _selectedWeightUnit; + String? _selectedMealId; @override void dispose() { @@ -333,6 +346,27 @@ class IngredientFormState extends ConsumerState { ), ], ), + if (widget.meals.isNotEmpty) + DropdownButtonFormField( + key: const Key('field-meal'), + initialValue: _selectedMealId, + decoration: InputDecoration(labelText: i18n.meal), + items: [ + DropdownMenuItem( + value: null, + child: Text(i18n.otherLogs), + ), + ...widget.meals.map( + (meal) => DropdownMenuItem( + value: meal.id, + child: Text( + meal.name.isNotEmpty ? meal.name : meal.time?.format(context) ?? '', + ), + ), + ), + ], + onChanged: (value) => setState(() => _selectedMealId = value), + ), if (ingredientIdController.text.isNotEmpty && _amountController.text.isNotEmpty && _mealItem.ingredient != null) @@ -368,7 +402,7 @@ class IngredientFormState extends ConsumerState { _time.hour, _time.minute, ); - widget.onSave(context, ref, _mealItem, loggedDate); + widget.onSave(context, ref, _mealItem, loggedDate, _selectedMealId); Navigator.of(context).pop(); }, diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 37f3cc372..9c882bf79 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -100,6 +100,7 @@ "description": "Label when starting the gym mode" }, "addMeal": "Mahlzeit hinzufügen", + "meal": "Mahlzeit", "add": "Hinzufügen", "cancel": "Abbrechen", "save": "Speichern", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 1b3ebcd57..4500f6370 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -426,6 +426,8 @@ "gymModeDistinctLogs": "Hide duplicate values", "addMeal": "Add meal", "@addMeal": {}, + "meal": "Meal", + "@meal": {}, "mealLogged": "Meal logged to diary", "@mealLogged": {}, "ingredientLogged": "Ingredient logged to diary", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 82fe3fc47..379ac8391 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -152,6 +152,7 @@ "logMeal": "Registrar esta comida", "mealLogged": "Comida registrada en el diario", "addMeal": "Agregar comida", + "meal": "Comida", "addSet": "Agregar serie", "@addSet": { "description": "Label for the button that adds a set (to a workout day)" diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 469adaca9..1c8d48d30 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -110,6 +110,7 @@ "addIngredient": "Ajouter ingrédients", "mealLogged": "Repas journalisé", "addMeal": "Ajouter un repas", + "meal": "Repas", "add": "Ajouter", "cancel": "Supprimer", "save": "Sauvegarder", diff --git a/test/features/nutrition/widgets/nutritional_meal_item_form_test.dart b/test/features/nutrition/widgets/nutritional_meal_item_form_test.dart index 49a79da72..b7a0bed33 100644 --- a/test/features/nutrition/widgets/nutritional_meal_item_form_test.dart +++ b/test/features/nutrition/widgets/nutritional_meal_item_form_test.dart @@ -31,6 +31,7 @@ import 'package:shared_preferences_platform_interface/in_memory_shared_preferenc import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:wger/core/consts.dart'; import 'package:wger/features/nutrition/models/ingredient.dart'; +import 'package:wger/features/nutrition/models/log.dart'; import 'package:wger/features/nutrition/models/meal.dart'; import 'package:wger/features/nutrition/models/meal_item.dart'; import 'package:wger/features/nutrition/models/nutritional_plan.dart'; @@ -184,6 +185,29 @@ void main() { ); } + Widget createIngredientLogFormScreen(NutritionalPlan plan, {locale = 'en'}) { + final key = GlobalKey(); + + return UncontrolledProviderScope( + container: container, + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + navigatorKey: key, + home: Scaffold( + body: Scrollable( + viewportBuilder: (BuildContext context, ViewportOffset position) => + getIngredientLogForm(plan), + ), + ), + routes: { + NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), + }, + ), + ); + } + testWidgets('Test the widgets on the meal item form', (WidgetTester tester) async { await tester.pumpWidget(createMealItemFormScreen(meal1, '', true)); await tester.pumpAndSettle(); @@ -192,10 +216,67 @@ void main() { expect(find.byType(TextFormField), findsWidgets); expect(find.byKey(const Key('scan-button')), findsOneWidget); expect(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), findsOneWidget); + // Adding to a meal has the meal fixed, so no selector is offered + expect(find.byKey(const Key('field-meal')), findsNothing); expect(meal1.mealItems.length, 2); }); + group('Test logging a single ingredient', () { + testWidgets('the meal can be selected and is logged with the entry', ( + WidgetTester tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + tester.view.devicePixelRatio = 1.0; + when(mockRepo.addLogLocalDrift(any)).thenAnswer((_) async => Future.value()); + + await tester.pumpWidget(createIngredientLogFormScreen(plan1)); + await tester.pumpAndSettle(); + + // The plan's meals are offered, defaulting to no meal ("other logs") + expect(find.byKey(const Key('field-meal')), findsOneWidget); + await tester.tap(find.byKey(const Key('field-meal'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Initial Name 2').last); + await tester.pumpAndSettle(); + + final IngredientFormState formState = tester.state(find.byType(IngredientForm)); + formState.selectIngredient(ingredient, 50); + await tester.enterText(find.byKey(const Key('field-weight')), '50'); + await mockNetworkImagesFor(() => tester.pumpAndSettle()); + + await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); + await tester.pump(); + + final log = verify(mockRepo.addLogLocalDrift(captureAny)).captured.single as LogItem; + expect(log.mealId, testMealUuid2); + expect(log.ingredientId, ingredient.id); + expect(log.amount, 50); + }); + + testWidgets('without picking a meal the entry is logged without one', ( + WidgetTester tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + tester.view.devicePixelRatio = 1.0; + when(mockRepo.addLogLocalDrift(any)).thenAnswer((_) async => Future.value()); + + await tester.pumpWidget(createIngredientLogFormScreen(plan1)); + await tester.pumpAndSettle(); + + final IngredientFormState formState = tester.state(find.byType(IngredientForm)); + formState.selectIngredient(ingredient, 50); + await tester.enterText(find.byKey(const Key('field-weight')), '50'); + await mockNetworkImagesFor(() => tester.pumpAndSettle()); + + await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); + await tester.pump(); + + final log = verify(mockRepo.addLogLocalDrift(captureAny)).captured.single as LogItem; + expect(log.mealId, isNull); + }); + }); + group('Test the AlertDialogs for scanning result', () { // TODO: why do we need to support empty barcodes? testWidgets('with empty code', (WidgetTester tester) async { From 3a574795850eae5461a440532840e2f08c277873 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 13:57:41 +0200 Subject: [PATCH 069/484] Scope the self-signed setting to one host and apply without a restart --- lib/core/app_settings_notifier.dart | 8 +- lib/core/http_overrides.dart | 65 +++++++++++--- lib/core/network/auth_notifier.dart | 6 ++ lib/features/auth/widgets/advanced_sheet.dart | 31 ++++--- lib/main.dart | 12 ++- test/core/http_overrides_test.dart | 87 ++++++++++++++++--- .../auth/screens/auth_screen_test.dart | 30 +++++-- 7 files changed, 184 insertions(+), 55 deletions(-) diff --git a/lib/core/app_settings_notifier.dart b/lib/core/app_settings_notifier.dart index 2f3225bf5..8be792443 100644 --- a/lib/core/app_settings_notifier.dart +++ b/lib/core/app_settings_notifier.dart @@ -205,16 +205,16 @@ class AppSettingsNotifier extends _$AppSettingsNotifier { Future _loadAllowSelfSignedCerts() async { final value = (await _prefs.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS)) ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT; - // Keep the global override in sync with the persisted value so the very - // first HTTP request after build() honours the setting. - applySelfSignedCertOverride(value); + // The override reads a static, so mirror the setting on both load and write + // and it can never drift from this provider. + WgerHttpOverrides.allowSelfSignedCerts = value; return value; } Future setAllowSelfSignedCerts(bool value) async { final current = state.asData?.value ?? const AppSettings(); state = AsyncData(current.copyWith(allowSelfSignedCerts: value)); - applySelfSignedCertOverride(value); + WgerHttpOverrides.allowSelfSignedCerts = value; await _prefs.setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, value); } diff --git a/lib/core/http_overrides.dart b/lib/core/http_overrides.dart index 1a6263212..6f8d49baf 100644 --- a/lib/core/http_overrides.dart +++ b/lib/core/http_overrides.dart @@ -19,31 +19,68 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; +import 'package:wger/core/consts.dart'; -/// [HttpOverrides] that accepts self-signed / otherwise invalid TLS -/// certificates. +/// [HttpOverrides] that accepts a self-signed / otherwise invalid TLS +/// certificate, but only from [trustedHost] and only while +/// [allowSelfSignedCerts] is set. /// -/// Installing this as [HttpOverrides.global] makes *every* `dart:io` -/// `HttpClient` skip certificate validation, which transparently covers both -/// the `http` package client used for API calls and the `HttpClient` that -/// `NetworkImage` / `extended_image` use to load images. Native media players +/// Installed as [HttpOverrides.global], so every `dart:io` `HttpClient` routes +/// through it: both the `http` package client used for API calls and the +/// `HttpClient` behind `NetworkImage` / `extended_image`. Native media players /// (e.g. the `video_player` plugin on Android/iOS) use their own networking -/// stack and are not affected by this override. +/// stack and are not affected. class WgerHttpOverrides extends HttpOverrides { + /// Whether the user opted into trusting an invalid certificate. + /// + /// Both this and [trustedHost] are read when the handshake happens rather + /// than when the client is built, so changing either also applies to clients + /// that already exist. dart:io reads [HttpOverrides.current] once in the + /// `HttpClient` constructor, and the auth client is built during startup, so + /// swapping the override itself would only take effect after a restart. + static bool allowSelfSignedCerts = ALLOW_SELF_SIGNED_CERTS_DEFAULT; + + /// Host the opt-in applies to. While null, every invalid certificate is + /// rejected no matter what [allowSelfSignedCerts] says. + static String? trustedHost; + + /// Narrows [trustedHost] to the host of [serverUrl]. A null, empty or + /// hostless URL clears it. + static void trustServer(String? serverUrl) { + final host = serverUrl == null ? null : Uri.tryParse(serverUrl)?.host; + trustedHost = (host == null || host.isEmpty) ? null : host; + } + + /// Hosts the opt-in can never apply to. The servers we run ourselves have a + /// valid certificate, so an invalid one there is a genuine problem and not + /// something a self-hosting setting may wave through. + static final Set _officialHosts = { + Uri.parse(DEFAULT_SERVER_PROD).host, + Uri.parse(DEFAULT_SERVER_TEST).host, + }; + + /// Whether an invalid certificate presented by [host] is accepted. + /// + /// Installed as the `badCertificateCallback` of every client, so it runs per + /// handshake and sees the current [allowSelfSignedCerts] / [trustedHost] + /// rather than the values from when the client was built. + static bool acceptsBadCertificate(X509Certificate cert, String host, int port) => + allowSelfSignedCerts && host == trustedHost && !_officialHosts.contains(host); + @override HttpClient createHttpClient(SecurityContext? context) { - return super.createHttpClient(context) - ..badCertificateCallback = (X509Certificate cert, String host, int port) => true; + return super.createHttpClient(context)..badCertificateCallback = acceptsBadCertificate; } } -/// Installs or removes [WgerHttpOverrides] based on [allow]. +/// Routes all `dart:io` HTTP traffic through [WgerHttpOverrides]. /// -/// No-op on the web, where `dart:io` networking (and thus [HttpOverrides]) does -/// not apply. Passing `false` restores the default certificate validation. -void applySelfSignedCertOverride(bool allow) { +/// Must run before the first `HttpClient` is created, since dart:io only +/// consults [HttpOverrides.current] in the client constructor. No-op on the +/// web, where `dart:io` networking (and thus [HttpOverrides]) does not apply. +void installHttpOverrides() { if (kIsWeb) { return; } - HttpOverrides.global = allow ? WgerHttpOverrides() : null; + HttpOverrides.global = WgerHttpOverrides(); } diff --git a/lib/core/network/auth_notifier.dart b/lib/core/network/auth_notifier.dart index 99879f60f..e53dad9a5 100644 --- a/lib/core/network/auth_notifier.dart +++ b/lib/core/network/auth_notifier.dart @@ -33,6 +33,7 @@ import 'package:wger/core/errors.dart'; import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/core/exceptions/mfa_required_exception.dart'; import 'package:wger/core/helpers.dart'; +import 'package:wger/core/http_overrides.dart'; import 'package:wger/core/network/auth_credentials_storage.dart'; import 'package:wger/core/network/auth_http_client.dart'; import 'package:wger/core/network/auth_state.dart'; @@ -198,6 +199,11 @@ class AuthNotifier extends _$AuthNotifier { String serverUrl, PackageInfo appVersion, ) async { + // Narrow the certificate opt-in to the server we are about to talk to. This + // is the single point every auth entry point passes through, and it runs + // before the first request to that host. + WgerHttpOverrides.trustServer(serverUrl); + final gate = await _gating.serverVersionGate(serverUrl); if (gate.tooOld) { _logger.info('login blocked: server ${gate.version} below $MIN_SERVER_VERSION'); diff --git a/lib/features/auth/widgets/advanced_sheet.dart b/lib/features/auth/widgets/advanced_sheet.dart index 0fea90a9f..01251621e 100644 --- a/lib/features/auth/widgets/advanced_sheet.dart +++ b/lib/features/auth/widgets/advanced_sheet.dart @@ -158,20 +158,27 @@ class _AdvancedSheetState extends State { padding: const EdgeInsets.only(top: 2, bottom: 4), child: ServerField(controller: widget.serverUrlController), ), - if (!_hideCustomServer) - SwitchListTile( - key: const Key('allowSelfSignedCertsSwitch'), - contentPadding: EdgeInsets.zero, - title: Text(i18n.allowSelfSignedCertsTitle), - subtitle: Text( - i18n.allowSelfSignedCertsDetail, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.error, - ), + // Stays visible for the official server so the option is + // discoverable, but disabled: wger.de has a valid certificate and + // is never trusted through this setting. The stored preference is + // kept, so switching back to self-hosted restores it. + SwitchListTile( + key: const Key('allowSelfSignedCertsSwitch'), + contentPadding: EdgeInsets.zero, + title: Text(i18n.allowSelfSignedCertsTitle), + subtitle: Text( + i18n.allowSelfSignedCertsDetail, + style: theme.textTheme.bodySmall?.copyWith( + color: _hideCustomServer + ? theme.colorScheme.onSurfaceVariant + : theme.colorScheme.error, ), - value: _allowSelfSignedCerts, - onChanged: (value) => _set(() => _allowSelfSignedCerts = value), ), + value: !_hideCustomServer && _allowSelfSignedCerts, + onChanged: _hideCustomServer + ? null + : (value) => _set(() => _allowSelfSignedCerts = value), + ), if (widget.loginMode) ...[ _SectionLabel(text: i18n.signInMethodSectionLabel), _OptionRow( diff --git a/lib/main.dart b/lib/main.dart index a75df6882..ea966a53a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -101,6 +101,10 @@ void main() async { // Needs to be called before runApp WidgetsFlutterBinding.ensureInitialized(); + // Has to happen before anything creates an HttpClient: dart:io only reads + // HttpOverrides.current in the client constructor, never again. + installHttpOverrides(); + // Logger _setupLogging(); @@ -109,12 +113,12 @@ void main() async { // SharedPreferences to SharedPreferencesAsync migration function await PreferenceHelper.instance.migrationSupportFunctionForSharedPreferences(); - // Install the self-signed certificate override before any network request - // (e.g. the auto-login probe) is made, based on the persisted preference. - final allowSelfSignedCerts = + // Seed the certificate opt-in from the prefs so the auto-login probe already + // honours it; AppSettingsNotifier keeps it in sync from here on. + WgerHttpOverrides.allowSelfSignedCerts = await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS) ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT; - applySelfSignedCertOverride(allowSelfSignedCerts); + WgerHttpOverrides.trustServer(await AuthNotifier.getServerUrlFromPrefs()); // Catch errors from Flutter itself (widget build, layout, paint, etc.) FlutterError.onError = (FlutterErrorDetails details) { diff --git a/test/core/http_overrides_test.dart b/test/core/http_overrides_test.dart index 0b588ac79..0b55dbd73 100644 --- a/test/core/http_overrides_test.dart +++ b/test/core/http_overrides_test.dart @@ -19,27 +19,86 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/core/consts.dart'; import 'package:wger/core/http_overrides.dart'; -void main() { - // Restore the default networking after each test so we don't leak the - // certificate override into other tests sharing the same isolate. - final HttpOverrides? original = HttpOverrides.current; - tearDown(() => HttpOverrides.global = original); +class _FakeCertificate extends Fake implements X509Certificate {} - test('applySelfSignedCertOverride(true) installs WgerHttpOverrides', () { - applySelfSignedCertOverride(true); +void main() { + final cert = _FakeCertificate(); + + // Restore the default networking and the opt-in so nothing leaks into other + // tests sharing the same isolate. The test binding installs its own overrides + // to keep tests off the network, so put back what was there rather than null. + final HttpOverrides? originalOverrides = HttpOverrides.current; + tearDown(() { + HttpOverrides.global = originalOverrides; + WgerHttpOverrides.allowSelfSignedCerts = false; + WgerHttpOverrides.trustedHost = null; + }); + + /// The decision the TLS handshake would make for [host]. + bool accepts(String host) => WgerHttpOverrides.acceptsBadCertificate(cert, host, 443); + + test('installHttpOverrides routes traffic through WgerHttpOverrides', () { + installHttpOverrides(); expect(HttpOverrides.current, isA()); }); - test('applySelfSignedCertOverride(false) removes the override', () { - applySelfSignedCertOverride(true); - applySelfSignedCertOverride(false); - expect(HttpOverrides.current, isNull); + test('rejects a bad certificate by default', () { + expect(accepts('gym.example.com'), isFalse); }); - test('WgerHttpOverrides creates a usable HttpClient', () { - final client = WgerHttpOverrides().createHttpClient(null); - expect(client, isA()); + test('accepts the trusted host once opted in', () { + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.trustServer('https://gym.example.com:8000'); + + expect(accepts('gym.example.com'), isTrue); + }); + + test('rejects any other host while opted in', () { + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.trustServer('https://gym.example.com'); + + expect(accepts('other.example.com'), isFalse); + }); + + test('never trusts the official servers, even when they are the trusted host', () { + // Reachable by typing wger.de into the self-hosted field with the opt-in on. + WgerHttpOverrides.allowSelfSignedCerts = true; + + for (final url in [DEFAULT_SERVER_PROD, DEFAULT_SERVER_TEST]) { + WgerHttpOverrides.trustServer(url); + expect(accepts(Uri.parse(url).host), isFalse, reason: 'for $url'); + } + }); + + test('rejects the trusted host again once opted out', () { + WgerHttpOverrides.trustServer('https://gym.example.com'); + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.allowSelfSignedCerts = false; + + expect(accepts('gym.example.com'), isFalse); + }); + + test('the decision is re-read per call, not baked in when it is handed out', () { + // The regression that matters: dart:io reads HttpOverrides.current in the + // HttpClient constructor only, and the auth client is built during startup. + // A client therefore holds this callback from before the user can opt in, + // exactly like the reference grabbed here. + const held = WgerHttpOverrides.acceptsBadCertificate; + expect(held(cert, 'gym.example.com', 443), isFalse); + + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.trustServer('https://gym.example.com'); + + expect(held(cert, 'gym.example.com', 443), isTrue); + }); + + test('trustServer clears the host for a null, empty or hostless URL', () { + for (final url in [null, '', 'not a url']) { + WgerHttpOverrides.trustServer(url); + expect(WgerHttpOverrides.trustedHost, isNull, reason: 'for ${url ?? 'null'}'); + } }); } diff --git a/test/features/auth/screens/auth_screen_test.dart b/test/features/auth/screens/auth_screen_test.dart index caa9708d6..76bfd8e1b 100644 --- a/test/features/auth/screens/auth_screen_test.dart +++ b/test/features/auth/screens/auth_screen_test.dart @@ -17,7 +17,6 @@ */ import 'dart:convert'; -import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -33,6 +32,7 @@ import 'package:shared_preferences_platform_interface/in_memory_shared_preferenc import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:wger/core/consts.dart'; +import 'package:wger/core/http_overrides.dart'; import 'package:wger/core/network/auth_notifier.dart'; import 'package:wger/core/network/network_provider.dart'; import 'package:wger/core/network/secure_token_storage.dart'; @@ -556,9 +556,9 @@ void main() { testWidgets('Self-hosted exposes the self-signed-cert toggle and persists it', ( WidgetTester tester, ) async { - // Toggling the switch installs a global HttpOverrides; undo it so the - // override does not leak into later tests in this isolate. - addTearDown(() => HttpOverrides.global = null); + // Toggling the switch flips a static the override reads; reset it so it + // does not leak into later tests in this isolate. + addTearDown(() => WgerHttpOverrides.allowSelfSignedCerts = false); await tester.binding.setSurfaceSize(const Size(1080, 1920)); tester.view.devicePixelRatio = 1.0; @@ -568,12 +568,15 @@ void main() { await tester.tap(find.byKey(const Key('advancedButton'))); await tester.pumpAndSettle(); - // The toggle only exists once a self-hosted server is selected. + // Visible for the official server, but off and not interactive. final toggle = find.byKey(const Key('allowSelfSignedCertsSwitch')); - expect(toggle, findsNothing); + expect(toggle, findsOneWidget); + expect(tester.widget(toggle).onChanged, isNull); + expect(tester.widget(toggle).value, isFalse); + await tester.tap(find.text('Self-hosted')); await tester.pumpAndSettle(); - expect(toggle, findsOneWidget); + expect(tester.widget(toggle).onChanged, isNotNull); await tester.tap(toggle); await tester.pumpAndSettle(); @@ -582,6 +585,19 @@ void main() { await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), isTrue, ); + expect(WgerHttpOverrides.allowSelfSignedCerts, isTrue); + + // Back on the official server it reads as off again, while the stored + // preference survives for the next self-hosted login. + await tester.tap(find.text('wger.de')); + await tester.pumpAndSettle(); + + expect(tester.widget(toggle).value, isFalse); + expect(tester.widget(toggle).onChanged, isNull); + expect( + await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + isTrue, + ); }); testWidgets('Sheet pre-selects Self-hosted for a custom last-used server', ( From 0ecd06ff3c5ed323de76cce1fe3208b43840930a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 14:06:19 +0200 Subject: [PATCH 070/484] Read the certificate setting from the provider instead of mirroring it --- lib/features/auth/widgets/auth_card.dart | 31 +++++++++---------- .../auth/screens/auth_screen_test.dart | 11 +++++++ 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/lib/features/auth/widgets/auth_card.dart b/lib/features/auth/widgets/auth_card.dart index aa3373adf..1d735abb2 100644 --- a/lib/features/auth/widgets/auth_card.dart +++ b/lib/features/auth/widgets/auth_card.dart @@ -70,7 +70,6 @@ class _AuthCardState extends ConsumerState { bool _autoValidate = false; bool _hideCustomServer = true; bool _useUsernameAndPassword = true; - bool _allowSelfSignedCerts = ALLOW_SELF_SIGNED_CERTS_DEFAULT; var _isLoading = false; final _usernameController = TextEditingController(); @@ -107,13 +106,6 @@ class _AuthCardState extends ConsumerState { } }); - // Surface the persisted self-signed-cert preference in the advanced sheet. - ref.read(appSettingsProvider.future).then((settings) { - if (mounted) { - setState(() => _allowSelfSignedCerts = settings.allowSelfSignedCerts); - } - }); - _preFillTextFields(); } @@ -256,23 +248,25 @@ class _AuthCardState extends ConsumerState { } /// Opens the advanced bottom sheet (server + sign-in-method selection). - void _showAdvancedSheet() { + /// + /// [allowSelfSignedCerts] is the persisted setting, passed in from `build` so + /// the sheet opens on the current value. + void _showAdvancedSheet(bool allowSelfSignedCerts) { showAdvancedSheet( context: context, initialHideCustomServer: _hideCustomServer, initialUsePassword: _useUsernameAndPassword, - initialAllowSelfSignedCerts: _allowSelfSignedCerts, + initialAllowSelfSignedCerts: allowSelfSignedCerts, loginMode: _authMode == AuthMode.login, serverUrlController: _serverUrlController, - onChanged: (hideCustomServer, usePassword, allowSelfSignedCerts) { + onChanged: (hideCustomServer, usePassword, allowSelfSigned) { setState(() { _hideCustomServer = hideCustomServer; _useUsernameAndPassword = usePassword; - _allowSelfSignedCerts = allowSelfSignedCerts; }); - // Persist immediately and install the override so the next login - // request (still made from this screen) trusts the self-signed cert. - ref.read(appSettingsProvider.notifier).setAllowSelfSignedCerts(allowSelfSignedCerts); + // Persist immediately so the next login request, still made from this + // screen, already trusts the certificate. + ref.read(appSettingsProvider.notifier).setAllowSelfSignedCerts(allowSelfSigned); }, ).then((_) { if (mounted) { @@ -288,6 +282,11 @@ class _AuthCardState extends ConsumerState { // Login/registration both need the server, so disable the action while // there is no connectivity. final isOnline = ref.watch(networkStatusProvider); + final allowSelfSignedCerts = ref.watch( + appSettingsProvider.select( + (s) => s.value?.allowSelfSignedCerts ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT, + ), + ); Widget errorMessage = const SizedBox.shrink(); if (_httpError != null) { @@ -391,7 +390,7 @@ class _AuthCardState extends ConsumerState { isCustomServer: !_hideCustomServer, isTokenMode: _authMode == AuthMode.login && !_useUsernameAndPassword, serverUrl: _serverUrlController.text, - onTap: _showAdvancedSheet, + onTap: () => _showAdvancedSheet(allowSelfSignedCerts), ), ], ), diff --git a/test/features/auth/screens/auth_screen_test.dart b/test/features/auth/screens/auth_screen_test.dart index 76bfd8e1b..4b8f0dd5b 100644 --- a/test/features/auth/screens/auth_screen_test.dart +++ b/test/features/auth/screens/auth_screen_test.dart @@ -598,6 +598,17 @@ void main() { await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), isTrue, ); + + // Reopening seeds the sheet from the provider, so the earlier opt-in is + // still there for a self-hosted server. + await tester.tap(find.byKey(const Key('advancedCloseButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Self-hosted')); + await tester.pumpAndSettle(); + + expect(tester.widget(toggle).value, isTrue); }); testWidgets('Sheet pre-selects Self-hosted for a custom last-used server', ( From 1a58dd8f71bd9bcb033491edd21fdc1a0cdff9c5 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 14:23:37 +0200 Subject: [PATCH 071/484] Warn in the settings while certificates are not being verified --- lib/core/http_overrides.dart | 27 ++++- lib/features/account/widgets/settings.dart | 4 + .../widgets/settings/certs_not_verified.dart | 63 +++++++++++ lib/l10n/app_de.arb | 6 +- lib/l10n/app_en.arb | 14 +++ lib/l10n/app_es.arb | 6 +- lib/l10n/app_fr.arb | 6 +- test/core/http_overrides_test.dart | 23 ++++ .../settings/certs_not_verified_test.dart | 107 ++++++++++++++++++ 9 files changed, 247 insertions(+), 9 deletions(-) create mode 100644 lib/features/account/widgets/settings/certs_not_verified.dart create mode 100644 test/features/account/widgets/settings/certs_not_verified_test.dart diff --git a/lib/core/http_overrides.dart b/lib/core/http_overrides.dart index 6f8d49baf..5cf51ed36 100644 --- a/lib/core/http_overrides.dart +++ b/lib/core/http_overrides.dart @@ -46,10 +46,7 @@ class WgerHttpOverrides extends HttpOverrides { /// Narrows [trustedHost] to the host of [serverUrl]. A null, empty or /// hostless URL clears it. - static void trustServer(String? serverUrl) { - final host = serverUrl == null ? null : Uri.tryParse(serverUrl)?.host; - trustedHost = (host == null || host.isEmpty) ? null : host; - } + static void trustServer(String? serverUrl) => trustedHost = _hostOf(serverUrl); /// Hosts the opt-in can never apply to. The servers we run ourselves have a /// valid certificate, so an invalid one there is a genuine problem and not @@ -59,13 +56,31 @@ class WgerHttpOverrides extends HttpOverrides { Uri.parse(DEFAULT_SERVER_TEST).host, }; + static String? _hostOf(String? serverUrl) { + final host = serverUrl == null ? null : Uri.tryParse(serverUrl)?.host; + return (host == null || host.isEmpty) ? null : host; + } + + static bool _accepts(String host) => + allowSelfSignedCerts && host == trustedHost && !_officialHosts.contains(host); + /// Whether an invalid certificate presented by [host] is accepted. /// /// Installed as the `badCertificateCallback` of every client, so it runs per /// handshake and sees the current [allowSelfSignedCerts] / [trustedHost] /// rather than the values from when the client was built. - static bool acceptsBadCertificate(X509Certificate cert, String host, int port) => - allowSelfSignedCerts && host == trustedHost && !_officialHosts.contains(host); + static bool acceptsBadCertificate(X509Certificate cert, String host, int port) => _accepts(host); + + /// The host of [serverUrl] while it is exempt from certificate validation, + /// null otherwise. + /// + /// Answers the same question as [acceptsBadCertificate], so a UI built on this + /// cannot warn about an exemption that does not exist, or stay silent about + /// one that does. + static String? exemptHost(String? serverUrl) { + final host = _hostOf(serverUrl); + return (host != null && _accepts(host)) ? host : null; + } @override HttpClient createHttpClient(SecurityContext? context) { diff --git a/lib/features/account/widgets/settings.dart b/lib/features/account/widgets/settings.dart index 697e3bf4e..d8cc3cee9 100644 --- a/lib/features/account/widgets/settings.dart +++ b/lib/features/account/widgets/settings.dart @@ -18,6 +18,7 @@ import 'package:flutter/material.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/features/account/widgets/settings/certs_not_verified.dart'; import 'package:wger/features/account/widgets/settings/data_privacy.dart'; import 'package:wger/features/account/widgets/settings/image_cache.dart'; import 'package:wger/features/account/widgets/settings/language.dart'; @@ -39,6 +40,9 @@ class SettingsPage extends StatelessWidget { body: WidescreenWrapper( child: ListView( children: [ + // Collapses to nothing unless certificates are actually going + // unverified, so it sits above the first section rather than in one. + const SettingsCertsNotVerified(), ListTile( title: Text( i18n.settingsCacheTitle, diff --git a/lib/features/account/widgets/settings/certs_not_verified.dart b/lib/features/account/widgets/settings/certs_not_verified.dart new file mode 100644 index 000000000..869dd999c --- /dev/null +++ b/lib/features/account/widgets/settings/certs_not_verified.dart @@ -0,0 +1,63 @@ +/* + * This file is part of wger Workout Manager . + * 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 + * 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/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/core/app_settings_notifier.dart'; +import 'package:wger/core/consts.dart'; +import 'package:wger/core/http_overrides.dart'; +import 'package:wger/core/network/auth_notifier.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Warns that invalid TLS certificates are currently being accepted, naming the +/// host it applies to. Renders nothing while certificates are verified normally. +/// +/// Read-only on purpose: the opt-in belongs to the login screen. Switching it off +/// here would cut the connection to the very server the user is logged into, and +/// getting back in would need a logout anyway. +class SettingsCertsNotVerified extends ConsumerWidget { + const SettingsCertsNotVerified({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); + + // The opt-in is watched to rebuild on a change; whether it actually takes + // effect for this server is up to the override. + final allowSelfSignedCerts = ref.watch( + appSettingsProvider.select( + (s) => s.value?.allowSelfSignedCerts ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT, + ), + ); + final serverUrl = ref.watch(authProvider.select((s) => s.value?.serverUrl)); + final host = allowSelfSignedCerts ? WgerHttpOverrides.exemptHost(serverUrl) : null; + + if (host == null) { + return const SizedBox.shrink(); + } + + return ListTile( + textColor: theme.colorScheme.error, + key: const ValueKey('certsNotVerifiedWarning'), + leading: Icon(Icons.gpp_bad_outlined, color: theme.colorScheme.error), + title: Text(i18n.certsNotVerifiedTitle), + subtitle: Text(i18n.certsNotVerifiedDetail(host)), + ); + } +} diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 9c882bf79..b9844e330 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1162,5 +1162,9 @@ "gymModeLogScopeCurrentRoutine": "Aktuelle Routine", "gymModeLogScopeWeeks": "Letzte {weeks} Wochen", "gymModeDistinctLogs": "Doppelte Werte ausblenden", - "gymModeShowWorkoutDuration": "Trainingsdauer anzeigen" + "gymModeShowWorkoutDuration": "Trainingsdauer anzeigen", + "allowSelfSignedCertsTitle": "Selbstsignierte Zertifikate erlauben", + "allowSelfSignedCertsDetail": "Deaktiviert die Validierung des TLS-Zertifikats. Aktiviere das nur für einen Server, dem du vertraust.", + "certsNotVerifiedTitle": "Zertifikatsvalidierung ist deaktiviert", + "certsNotVerifiedDetail": "Zertifikate für {host} werden nicht geprüft. Zum Ändern melde dich ab und passe die Option im Anmeldebildschirm an." } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 570723da6..3aa58560d 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -136,6 +136,20 @@ "@allowSelfSignedCertsTitle": {}, "allowSelfSignedCertsDetail": "Disables TLS certificate validation. Only enable this for a server you trust.", "@allowSelfSignedCertsDetail": {}, + "certsNotVerifiedTitle": "Certificate validation is off", + "@certsNotVerifiedTitle": { + "description": "Warning shown in the settings while the app accepts invalid TLS certificates from the server the user is logged into." + }, + "certsNotVerifiedDetail": "Certificates for {host} are not checked. To change this, log out and adjust the option on the login screen.", + "@certsNotVerifiedDetail": { + "description": "Explains the certificate warning. The option can only be set before logging in, hence the hint to log out.", + "type": "text", + "placeholders": { + "host": { + "type": "String" + } + } + }, "authOptionPasswordTitle": "Username and password", "@authOptionPasswordTitle": {}, "signInWithToken": "Sign in with token", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 379ac8391..0d9cbd9bd 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1201,5 +1201,9 @@ "gymModeLogScopeCurrentRoutine": "Rutina actual", "gymModeLogScopeWeeks": "Últimas {weeks} semanas", "gymModeDistinctLogs": "Ocultar valores duplicados", - "gymModeShowWorkoutDuration": "Mostrar la duración del entrenamiento" + "gymModeShowWorkoutDuration": "Mostrar la duración del entrenamiento", + "allowSelfSignedCertsTitle": "Permitir certificados autofirmados", + "allowSelfSignedCertsDetail": "Desactiva la validación del certificado TLS. Actívalo solo para un servidor de confianza.", + "certsNotVerifiedTitle": "La validación de certificados está desactivada", + "certsNotVerifiedDetail": "Los certificados de {host} no se comprueban. Para cambiarlo, cierra la sesión y ajusta la opción en la pantalla de inicio de sesión." } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 1c8d48d30..3ac5b3442 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1172,5 +1172,9 @@ "gymModeLogScopeCurrentRoutine": "Routine actuelle", "gymModeLogScopeWeeks": "{weeks} dernières semaines", "gymModeDistinctLogs": "Masquer les valeurs en double", - "gymModeShowWorkoutDuration": "Afficher la durée de l'entraînement" + "gymModeShowWorkoutDuration": "Afficher la durée de l'entraînement", + "allowSelfSignedCertsTitle": "Autoriser les certificats auto-signés", + "allowSelfSignedCertsDetail": "Désactive la validation du certificat TLS. Ne l'activez que pour un serveur de confiance.", + "certsNotVerifiedTitle": "La validation des certificats est désactivée", + "certsNotVerifiedDetail": "Les certificats de {host} ne sont pas vérifiés. Pour changer cela, déconnectez-vous et modifiez l'option sur l'écran de connexion." } diff --git a/test/core/http_overrides_test.dart b/test/core/http_overrides_test.dart index 0b55dbd73..f234a8494 100644 --- a/test/core/http_overrides_test.dart +++ b/test/core/http_overrides_test.dart @@ -95,6 +95,29 @@ void main() { expect(held(cert, 'gym.example.com', 443), isTrue); }); + group('exemptHost', () { + test('names the host while it is exempt', () { + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.trustServer('https://gym.example.com:8000'); + + expect(WgerHttpOverrides.exemptHost('https://gym.example.com:8000'), 'gym.example.com'); + }); + + test('is null whenever the handshake would reject', () { + // Same rule as acceptsBadCertificate, so the warning cannot drift from it. + WgerHttpOverrides.allowSelfSignedCerts = false; + WgerHttpOverrides.trustServer('https://gym.example.com'); + expect(WgerHttpOverrides.exemptHost('https://gym.example.com'), isNull); + + WgerHttpOverrides.allowSelfSignedCerts = true; + expect(WgerHttpOverrides.exemptHost('https://other.example.com'), isNull); + expect(WgerHttpOverrides.exemptHost(null), isNull); + + WgerHttpOverrides.trustServer(DEFAULT_SERVER_PROD); + expect(WgerHttpOverrides.exemptHost(DEFAULT_SERVER_PROD), isNull); + }); + }); + test('trustServer clears the host for a null, empty or hostless URL', () { for (final url in [null, '', 'not a url']) { WgerHttpOverrides.trustServer(url); diff --git a/test/features/account/widgets/settings/certs_not_verified_test.dart b/test/features/account/widgets/settings/certs_not_verified_test.dart new file mode 100644 index 000000000..8e7b1dbf3 --- /dev/null +++ b/test/features/account/widgets/settings/certs_not_verified_test.dart @@ -0,0 +1,107 @@ +/* + * This file is part of wger Workout Manager . + * 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 + * 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/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; +import 'package:wger/core/app_settings_notifier.dart'; +import 'package:wger/core/consts.dart'; +import 'package:wger/core/http_overrides.dart'; +import 'package:wger/core/network/auth_notifier.dart'; +import 'package:wger/core/network/auth_state.dart'; +import 'package:wger/features/account/widgets/settings/certs_not_verified.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +class _FakeAuthNotifier extends AuthNotifier { + _FakeAuthNotifier(this._state); + + final AuthState _state; + + @override + Future build() async => _state; +} + +void main() { + const selfHosted = 'https://gym.example.com'; + + setUp(() { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + }); + + tearDown(() { + WgerHttpOverrides.allowSelfSignedCerts = false; + WgerHttpOverrides.trustedHost = null; + }); + + Future pumpWidget(WidgetTester tester, {required String serverUrl}) async { + final prefs = SharedPreferencesAsync(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + appSettingsPrefsProvider.overrideWithValue(prefs), + authProvider.overrideWith( + () => _FakeAuthNotifier( + AuthState(status: AuthStatus.loggedIn, serverUrl: serverUrl), + ), + ), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: Locale('en'), + home: Scaffold(body: SettingsCertsNotVerified()), + ), + ), + ); + await tester.pumpAndSettle(); + } + + final warning = find.byKey(const ValueKey('certsNotVerifiedWarning')); + + testWidgets('stays hidden while certificates are verified', (tester) async { + await pumpWidget(tester, serverUrl: selfHosted); + + expect(warning, findsNothing); + }); + + testWidgets('warns and names the host while the exemption is in effect', (tester) async { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + await SharedPreferencesAsync().setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, true); + WgerHttpOverrides.trustServer(selfHosted); + + await pumpWidget(tester, serverUrl: selfHosted); + + expect(warning, findsOneWidget); + expect(find.textContaining('gym.example.com'), findsOneWidget); + }); + + testWidgets('stays hidden on the official server even with the opt-in stored', (tester) async { + // The preference survives a switch back to wger.de, but the override never + // exempts it, so warning about it would be a lie. + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + await SharedPreferencesAsync().setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, true); + WgerHttpOverrides.trustServer(DEFAULT_SERVER_PROD); + + await pumpWidget(tester, serverUrl: DEFAULT_SERVER_PROD); + + expect(warning, findsNothing); + }); +} From b732b619c206f3dbdb2ba2302481a040107702a7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 15:02:04 +0200 Subject: [PATCH 072/484] Describe updated behaviour in comments --- lib/core/app_settings_notifier.dart | 4 ++-- lib/core/app_settings_notifier.freezed.dart | 8 ++++---- lib/core/app_settings_notifier.g.dart | 2 +- lib/core/consts.dart | 8 ++++---- lib/core/network/auth_notifier.g.dart | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/core/app_settings_notifier.dart b/lib/core/app_settings_notifier.dart index 8be792443..358d9d0ba 100644 --- a/lib/core/app_settings_notifier.dart +++ b/lib/core/app_settings_notifier.dart @@ -84,8 +84,8 @@ sealed class AppSettings with _$AppSettings { /// of wiping it, so the same user signing back in resumes incrementally. @Default(KEEP_DATA_ON_LOGOUT_DEFAULT) bool keepDataOnLogout, - /// When true, TLS certificate validation is disabled so the app can - /// connect to self-hosted instances using a self-signed certificate. + /// When true, an invalid TLS certificate is accepted from the self-hosted + /// server the app is configured for. Never applies to the official servers. @Default(ALLOW_SELF_SIGNED_CERTS_DEFAULT) bool allowSelfSignedCerts, }) = _AppSettings; } diff --git a/lib/core/app_settings_notifier.freezed.dart b/lib/core/app_settings_notifier.freezed.dart index 31ec0b079..7c18c83ce 100644 --- a/lib/core/app_settings_notifier.freezed.dart +++ b/lib/core/app_settings_notifier.freezed.dart @@ -17,8 +17,8 @@ mixin _$AppSettings { ThemeMode get themeMode; List get dashboardItems;/// Locale override. Null means the app follows the system locale. Locale? get userLocale;/// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. - bool get keepDataOnLogout;/// When true, TLS certificate validation is disabled so the app can -/// connect to self-hosted instances using a self-signed certificate. + bool get keepDataOnLogout;/// When true, an invalid TLS certificate is accepted from the self-hosted +/// server the app is configured for. Never applies to the official servers. bool get allowSelfSignedCerts; /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. @@ -225,8 +225,8 @@ class _AppSettings implements AppSettings { /// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. @override@JsonKey() final bool keepDataOnLogout; -/// When true, TLS certificate validation is disabled so the app can -/// connect to self-hosted instances using a self-signed certificate. +/// When true, an invalid TLS certificate is accepted from the self-hosted +/// server the app is configured for. Never applies to the official servers. @override@JsonKey() final bool allowSelfSignedCerts; /// Create a copy of AppSettings diff --git a/lib/core/app_settings_notifier.g.dart b/lib/core/app_settings_notifier.g.dart index 0e698d183..ead2c8f16 100644 --- a/lib/core/app_settings_notifier.g.dart +++ b/lib/core/app_settings_notifier.g.dart @@ -33,7 +33,7 @@ final class AppSettingsNotifierProvider AppSettingsNotifier create() => AppSettingsNotifier(); } -String _$appSettingsNotifierHash() => r'2ba0d53f1a48ba6876571c965e9e804c04be5645'; +String _$appSettingsNotifierHash() => r'499323f5b84feb0c395538db14e4d0a7de831b7c'; abstract class _$AppSettingsNotifier extends $AsyncNotifier { FutureOr build(); diff --git a/lib/core/consts.dart b/lib/core/consts.dart index f63b3f1d4..ac324bd3a 100644 --- a/lib/core/consts.dart +++ b/lib/core/consts.dart @@ -79,10 +79,10 @@ const PREFS_DB_OWNER_USER_ID = 'dbOwnerUserId'; const PREFS_KEEP_DATA_ON_LOGOUT = 'keepDataOnLogout'; const KEEP_DATA_ON_LOGOUT_DEFAULT = true; -/// User preference: trust self-signed/invalid TLS certificates so the app can -/// connect to self-hosted instances behind a self-signed cert. Off by default -/// since it disables certificate validation. Defaults to -/// [ALLOW_SELF_SIGNED_CERTS_DEFAULT]. +/// User preference: accept an invalid TLS certificate from the configured +/// self-hosted server, so the app can reach instances behind a self-signed +/// cert. Off by default, and never applies to the official servers. Defaults +/// to [ALLOW_SELF_SIGNED_CERTS_DEFAULT]. const PREFS_ALLOW_SELF_SIGNED_CERTS = 'allowSelfSignedCerts'; const ALLOW_SELF_SIGNED_CERTS_DEFAULT = false; diff --git a/lib/core/network/auth_notifier.g.dart b/lib/core/network/auth_notifier.g.dart index d1cfe2bb9..86ce6eeff 100644 --- a/lib/core/network/auth_notifier.g.dart +++ b/lib/core/network/auth_notifier.g.dart @@ -32,7 +32,7 @@ final class AuthNotifierProvider extends $AsyncNotifierProvider AuthNotifier(); } -String _$authNotifierHash() => r'720d6e804991e1b0c0b0bbd2a2077ed8422c0e39'; +String _$authNotifierHash() => r'19bf6776a00c5a7374ddc918f55709ee3a193b3f'; abstract class _$AuthNotifier extends $AsyncNotifier { FutureOr build(); From 914e9ac575294bce9b8e7347c81df058dffb59e8 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 15:47:04 +0200 Subject: [PATCH 073/484] Surface involuntary logouts and revalidate the session on app resume This makes it obvious why users are redirected to the auth screen, since the snackbar could be easily missed. See #1265 --- lib/core/network/auth_notifier.dart | 31 +++++- lib/core/network/auth_state.dart | 6 + lib/core/network/auth_state.freezed.dart | 47 +++++--- lib/features/auth/widgets/auth_card.dart | 17 +++ .../network/auth_notifier_powersync_test.dart | 104 ++++++++++++++++++ 5 files changed, 184 insertions(+), 21 deletions(-) diff --git a/lib/core/network/auth_notifier.dart b/lib/core/network/auth_notifier.dart index e53dad9a5..0908a91b3 100644 --- a/lib/core/network/auth_notifier.dart +++ b/lib/core/network/auth_notifier.dart @@ -22,6 +22,7 @@ import 'dart:io'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:flutter/foundation.dart' show visibleForTesting; +import 'package:flutter/widgets.dart' show AppLifecycleListener; import 'package:flutter_riverpod/flutter_riverpod.dart' show Provider; import 'package:http/http.dart' as http; import 'package:logging/logging.dart'; @@ -644,6 +645,22 @@ class AuthNotifier extends _$AuthNotifier { } }); ref.onDispose(sub.cancel); + + // A warm resume must also revalidate: the process can stay alive in the + // background for days, so the tokens may have expired without any cold + // start noticing. The app is offline-first, so without this a dead + // session would only surface once some server-backed action happens to + // run. Gated on needsRefresh so quick app switches stay request-free. + final lifecycleListener = AppLifecycleListener( + onResume: () { + final credential = state.asData?.value.credential; + if (credential?.needsRefresh(refreshLeeway) ?? false) { + _logger.fine('revalidation: app resumed with stale access token'); + revalidationDone = _revalidate(); + } + }, + ); + ref.onDispose(lifecycleListener.dispose); } /// Revalidates the restored session against the server. Fire-and-forget: it @@ -887,12 +904,15 @@ class AuthNotifier extends _$AuthNotifier { /// Called from refresh-token failures, repeated 401s on the HTTP /// client, and revalidation rejections. The UI logout button must use /// [logout] instead, which performs a full wipe. - Future clearSessionOnly() => _resetSession(wipeLocalData: false); + Future clearSessionOnly() => _resetSession(wipeLocalData: false, sessionExpired: true); /// Shared body for [logout] and [clearSessionOnly]. PowerSync is touched /// before the state mutation so a reader observing the post-reset state /// can never race ahead and re-attach to a DB we're about to wipe. - Future _resetSession({required bool wipeLocalData}) async { + /// + /// [sessionExpired] marks the reset as involuntary in the published state, + /// so the login screen can tell the user why they were logged out. + Future _resetSession({required bool wipeLocalData, bool sessionExpired = false}) async { _logger.fine(wipeLocalData ? 'logging out' : 'clearing session, keeping local DB'); // A failed wipe still logs the user out, but the data is left on disk: the @@ -910,7 +930,12 @@ class AuthNotifier extends _$AuthNotifier { await _disconnectPowerSyncIfBuilt(); } - state = AsyncData(AuthState(applicationVersion: _currentOrBlank().applicationVersion)); + state = AsyncData( + AuthState( + applicationVersion: _currentOrBlank().applicationVersion, + sessionExpired: sessionExpired, + ), + ); if (wipeLocalData) { await _storage.clearAll(); // Drop the marker only when the data was actually removed, keeping the diff --git a/lib/core/network/auth_state.dart b/lib/core/network/auth_state.dart index e0f282186..6cc5b3d72 100644 --- a/lib/core/network/auth_state.dart +++ b/lib/core/network/auth_state.dart @@ -67,6 +67,12 @@ sealed class AuthState with _$AuthState { String? serverVersion, PackageInfo? applicationVersion, @Default(false) bool serverConfigWarning, + + /// True when the previous session ended involuntarily (expired or + /// revoked tokens). The login screen shows a hint so the user knows + /// why they have to log in again. Reset by the next login, which + /// builds a fresh state. + @Default(false) bool sessionExpired, }) = _AuthState; const AuthState._(); diff --git a/lib/core/network/auth_state.freezed.dart b/lib/core/network/auth_state.freezed.dart index 38d05b6cb..56028625b 100644 --- a/lib/core/network/auth_state.freezed.dart +++ b/lib/core/network/auth_state.freezed.dart @@ -14,7 +14,11 @@ T _$identity(T value) => value; /// @nodoc mixin _$AuthState { - AuthStatus get status; AuthCredential? get credential; String? get serverUrl; String? get serverVersion; PackageInfo? get applicationVersion; bool get serverConfigWarning; + AuthStatus get status; AuthCredential? get credential; String? get serverUrl; String? get serverVersion; PackageInfo? get applicationVersion; bool get serverConfigWarning;/// True when the previous session ended involuntarily (expired or +/// revoked tokens). The login screen shows a hint so the user knows +/// why they have to log in again. Reset by the next login, which +/// builds a fresh state. + bool get sessionExpired; /// Create a copy of AuthState /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -25,16 +29,16 @@ $AuthStateCopyWith get copyWith => _$AuthStateCopyWithImpl @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthState&&(identical(other.status, status) || other.status == status)&&(identical(other.credential, credential) || other.credential == credential)&&(identical(other.serverUrl, serverUrl) || other.serverUrl == serverUrl)&&(identical(other.serverVersion, serverVersion) || other.serverVersion == serverVersion)&&(identical(other.applicationVersion, applicationVersion) || other.applicationVersion == applicationVersion)&&(identical(other.serverConfigWarning, serverConfigWarning) || other.serverConfigWarning == serverConfigWarning)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthState&&(identical(other.status, status) || other.status == status)&&(identical(other.credential, credential) || other.credential == credential)&&(identical(other.serverUrl, serverUrl) || other.serverUrl == serverUrl)&&(identical(other.serverVersion, serverVersion) || other.serverVersion == serverVersion)&&(identical(other.applicationVersion, applicationVersion) || other.applicationVersion == applicationVersion)&&(identical(other.serverConfigWarning, serverConfigWarning) || other.serverConfigWarning == serverConfigWarning)&&(identical(other.sessionExpired, sessionExpired) || other.sessionExpired == sessionExpired)); } @override -int get hashCode => Object.hash(runtimeType,status,credential,serverUrl,serverVersion,applicationVersion,serverConfigWarning); +int get hashCode => Object.hash(runtimeType,status,credential,serverUrl,serverVersion,applicationVersion,serverConfigWarning,sessionExpired); @override String toString() { - return 'AuthState(status: $status, credential: $credential, serverUrl: $serverUrl, serverVersion: $serverVersion, applicationVersion: $applicationVersion, serverConfigWarning: $serverConfigWarning)'; + return 'AuthState(status: $status, credential: $credential, serverUrl: $serverUrl, serverVersion: $serverVersion, applicationVersion: $applicationVersion, serverConfigWarning: $serverConfigWarning, sessionExpired: $sessionExpired)'; } @@ -45,7 +49,7 @@ abstract mixin class $AuthStateCopyWith<$Res> { factory $AuthStateCopyWith(AuthState value, $Res Function(AuthState) _then) = _$AuthStateCopyWithImpl; @useResult $Res call({ - AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning + AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired }); @@ -62,7 +66,7 @@ class _$AuthStateCopyWithImpl<$Res> /// Create a copy of AuthState /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? status = null,Object? credential = freezed,Object? serverUrl = freezed,Object? serverVersion = freezed,Object? applicationVersion = freezed,Object? serverConfigWarning = null,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? status = null,Object? credential = freezed,Object? serverUrl = freezed,Object? serverVersion = freezed,Object? applicationVersion = freezed,Object? serverConfigWarning = null,Object? sessionExpired = null,}) { return _then(_self.copyWith( status: null == status ? _self.status : status // ignore: cast_nullable_to_non_nullable as AuthStatus,credential: freezed == credential ? _self.credential : credential // ignore: cast_nullable_to_non_nullable @@ -70,6 +74,7 @@ as AuthCredential?,serverUrl: freezed == serverUrl ? _self.serverUrl : serverUrl as String?,serverVersion: freezed == serverVersion ? _self.serverVersion : serverVersion // ignore: cast_nullable_to_non_nullable as String?,applicationVersion: freezed == applicationVersion ? _self.applicationVersion : applicationVersion // ignore: cast_nullable_to_non_nullable as PackageInfo?,serverConfigWarning: null == serverConfigWarning ? _self.serverConfigWarning : serverConfigWarning // ignore: cast_nullable_to_non_nullable +as bool,sessionExpired: null == sessionExpired ? _self.sessionExpired : sessionExpired // ignore: cast_nullable_to_non_nullable as bool, )); } @@ -164,10 +169,10 @@ return $default(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen(TResult Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning)? $default,{required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen(TResult Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired)? $default,{required TResult orElse(),}) {final _that = this; switch (_that) { case _AuthState() when $default != null: -return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning);case _: +return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning,_that.sessionExpired);case _: return orElse(); } @@ -185,10 +190,10 @@ return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersio /// } /// ``` -@optionalTypeArgs TResult when(TResult Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning) $default,) {final _that = this; +@optionalTypeArgs TResult when(TResult Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired) $default,) {final _that = this; switch (_that) { case _AuthState(): -return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning);} +return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning,_that.sessionExpired);} } /// A variant of `when` that fallback to returning `null` /// @@ -202,10 +207,10 @@ return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersio /// } /// ``` -@optionalTypeArgs TResult? whenOrNull(TResult? Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning)? $default,) {final _that = this; +@optionalTypeArgs TResult? whenOrNull(TResult? Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired)? $default,) {final _that = this; switch (_that) { case _AuthState() when $default != null: -return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning);case _: +return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning,_that.sessionExpired);case _: return null; } @@ -217,7 +222,7 @@ return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersio class _AuthState extends AuthState { - const _AuthState({this.status = AuthStatus.loggedOut, this.credential, this.serverUrl, this.serverVersion, this.applicationVersion, this.serverConfigWarning = false}): super._(); + const _AuthState({this.status = AuthStatus.loggedOut, this.credential, this.serverUrl, this.serverVersion, this.applicationVersion, this.serverConfigWarning = false, this.sessionExpired = false}): super._(); @override@JsonKey() final AuthStatus status; @@ -226,6 +231,11 @@ class _AuthState extends AuthState { @override final String? serverVersion; @override final PackageInfo? applicationVersion; @override@JsonKey() final bool serverConfigWarning; +/// True when the previous session ended involuntarily (expired or +/// revoked tokens). The login screen shows a hint so the user knows +/// why they have to log in again. Reset by the next login, which +/// builds a fresh state. +@override@JsonKey() final bool sessionExpired; /// Create a copy of AuthState /// with the given fields replaced by the non-null parameter values. @@ -237,16 +247,16 @@ _$AuthStateCopyWith<_AuthState> get copyWith => __$AuthStateCopyWithImpl<_AuthSt @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is _AuthState&&(identical(other.status, status) || other.status == status)&&(identical(other.credential, credential) || other.credential == credential)&&(identical(other.serverUrl, serverUrl) || other.serverUrl == serverUrl)&&(identical(other.serverVersion, serverVersion) || other.serverVersion == serverVersion)&&(identical(other.applicationVersion, applicationVersion) || other.applicationVersion == applicationVersion)&&(identical(other.serverConfigWarning, serverConfigWarning) || other.serverConfigWarning == serverConfigWarning)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is _AuthState&&(identical(other.status, status) || other.status == status)&&(identical(other.credential, credential) || other.credential == credential)&&(identical(other.serverUrl, serverUrl) || other.serverUrl == serverUrl)&&(identical(other.serverVersion, serverVersion) || other.serverVersion == serverVersion)&&(identical(other.applicationVersion, applicationVersion) || other.applicationVersion == applicationVersion)&&(identical(other.serverConfigWarning, serverConfigWarning) || other.serverConfigWarning == serverConfigWarning)&&(identical(other.sessionExpired, sessionExpired) || other.sessionExpired == sessionExpired)); } @override -int get hashCode => Object.hash(runtimeType,status,credential,serverUrl,serverVersion,applicationVersion,serverConfigWarning); +int get hashCode => Object.hash(runtimeType,status,credential,serverUrl,serverVersion,applicationVersion,serverConfigWarning,sessionExpired); @override String toString() { - return 'AuthState(status: $status, credential: $credential, serverUrl: $serverUrl, serverVersion: $serverVersion, applicationVersion: $applicationVersion, serverConfigWarning: $serverConfigWarning)'; + return 'AuthState(status: $status, credential: $credential, serverUrl: $serverUrl, serverVersion: $serverVersion, applicationVersion: $applicationVersion, serverConfigWarning: $serverConfigWarning, sessionExpired: $sessionExpired)'; } @@ -257,7 +267,7 @@ abstract mixin class _$AuthStateCopyWith<$Res> implements $AuthStateCopyWith<$Re factory _$AuthStateCopyWith(_AuthState value, $Res Function(_AuthState) _then) = __$AuthStateCopyWithImpl; @override @useResult $Res call({ - AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning + AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired }); @@ -274,7 +284,7 @@ class __$AuthStateCopyWithImpl<$Res> /// Create a copy of AuthState /// with the given fields replaced by the non-null parameter values. -@override @pragma('vm:prefer-inline') $Res call({Object? status = null,Object? credential = freezed,Object? serverUrl = freezed,Object? serverVersion = freezed,Object? applicationVersion = freezed,Object? serverConfigWarning = null,}) { +@override @pragma('vm:prefer-inline') $Res call({Object? status = null,Object? credential = freezed,Object? serverUrl = freezed,Object? serverVersion = freezed,Object? applicationVersion = freezed,Object? serverConfigWarning = null,Object? sessionExpired = null,}) { return _then(_AuthState( status: null == status ? _self.status : status // ignore: cast_nullable_to_non_nullable as AuthStatus,credential: freezed == credential ? _self.credential : credential // ignore: cast_nullable_to_non_nullable @@ -282,6 +292,7 @@ as AuthCredential?,serverUrl: freezed == serverUrl ? _self.serverUrl : serverUrl as String?,serverVersion: freezed == serverVersion ? _self.serverVersion : serverVersion // ignore: cast_nullable_to_non_nullable as String?,applicationVersion: freezed == applicationVersion ? _self.applicationVersion : applicationVersion // ignore: cast_nullable_to_non_nullable as PackageInfo?,serverConfigWarning: null == serverConfigWarning ? _self.serverConfigWarning : serverConfigWarning // ignore: cast_nullable_to_non_nullable +as bool,sessionExpired: null == sessionExpired ? _self.sessionExpired : sessionExpired // ignore: cast_nullable_to_non_nullable as bool, )); } diff --git a/lib/features/auth/widgets/auth_card.dart b/lib/features/auth/widgets/auth_card.dart index 1d735abb2..f42369b4f 100644 --- a/lib/features/auth/widgets/auth_card.dart +++ b/lib/features/auth/widgets/auth_card.dart @@ -288,6 +288,14 @@ class _AuthCardState extends ConsumerState { ), ); + // Involuntary logout (expired/revoked tokens): tell the user why they + // are looking at the login form. The transient snackbar shown at the + // moment of the logout is easy to miss, this hint persists until the + // next login. + final sessionExpired = ref.watch( + authProvider.select((s) => s.value?.sessionExpired ?? false), + ); + Widget errorMessage = const SizedBox.shrink(); if (_httpError != null) { errorMessage = FormHttpErrorsWidget(_httpError!); @@ -322,6 +330,15 @@ class _AuthCardState extends ConsumerState { child: AutofillGroup( child: Column( children: [ + if (sessionExpired && _authMode == AuthMode.login) + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Text( + i18n.sessionExpired, + textAlign: TextAlign.center, + style: TextStyle(color: Theme.of(context).colorScheme.primary), + ), + ), errorMessage, if (_useUsernameAndPassword) UsernameField(controller: _usernameController), if (_authMode == AuthMode.register) EmailField(controller: _emailController), diff --git a/test/core/network/auth_notifier_powersync_test.dart b/test/core/network/auth_notifier_powersync_test.dart index aa88b0412..959c52b7c 100644 --- a/test/core/network/auth_notifier_powersync_test.dart +++ b/test/core/network/auth_notifier_powersync_test.dart @@ -22,6 +22,7 @@ import 'dart:io'; import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart'; import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart' show AppLifecycleState; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; @@ -1307,6 +1308,109 @@ void main() { ).called(1); }); }); + + group('involuntary logout surfacing', () { + String makeJwt(Map payload) { + String enc(Map m) => + base64Url.encode(utf8.encode(jsonEncode(m))).replaceAll('=', ''); + return '${enc({'alg': 'HS256', 'typ': 'JWT'})}.${enc(payload)}.signature'; + } + + /// Replaces the legacy seed from setUp with a restored headless-JWT + /// session whose access token expires at [expiresAt]. + Future seedJwtSession({required DateTime expiresAt}) async { + final prefs = PreferenceHelper.asyncPref; + await prefs.remove(PREFS_USER); + await prefs.setString( + PREFS_ACCESS_TOKEN, + makeJwt({'sub': '42', 'exp': expiresAt.millisecondsSinceEpoch ~/ 1000}), + ); + await prefs.setInt(PREFS_ACCESS_EXPIRES_AT, expiresAt.millisecondsSinceEpoch); + await prefs.setString(PREFS_TOKEN_TYPE, AuthTokenType.headlessJwt.name); + await prefs.setString(PREFS_SERVER_URL, serverUrl); + } + + setUp(() async { + await PreferenceHelper.asyncPref.setBool(PREFS_HAS_EVER_SYNCED, true); + }); + + test('revalidation rejection sets sessionExpired for the login screen', () async { + when( + mockClient.head(tProbe, headers: anyNamed('headers')), + ).thenAnswer((_) async => Response('Unauthorized', 401)); + + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).revalidationDone; + + final state = container.read(authProvider).value; + expect(state?.status, AuthStatus.loggedOut); + expect(state?.sessionExpired, true); + }); + + test('user-driven logout does not set sessionExpired', () async { + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).revalidationDone; + await container.read(authProvider.notifier).logout(); + + final state = container.read(authProvider).value; + expect(state?.status, AuthStatus.loggedOut); + expect(state?.sessionExpired, false); + }); + + test( + 'app resume with a stale token revalidates; a rejected refresh ends the session', + () async { + // The access token expires inside the pre-emptive refresh leeway, so + // the startup revalidation and the resume hook both treat it as stale. + final expiry = DateTime.now().add(const Duration(seconds: 10)); + await seedJwtSession(expiresAt: expiry); + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'stored-refresh'); + + // Startup revalidation refreshes successfully; the minted token is + // again short-lived so the resume hook sees it as stale too. + final freshJwt = makeJwt({'sub': '42', 'exp': expiry.millisecondsSinceEpoch ~/ 1000}); + when( + mockClient.post(tHeadlessRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) async => Response( + jsonEncode({ + 'status': 200, + 'data': {'access_token': freshJwt, 'refresh_token': 'rotated'}, + }), + 200, + ), + ); + + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).revalidationDone; + expect(container.read(authProvider).value?.status, AuthStatus.loggedIn); + + // The server now rejects the refresh token (expired server-side). + when( + mockClient.post(tHeadlessRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer((_) async => Response('{"status": 400}', 400)); + + // Background -> foreground transition must trigger the resume hook. + // The intermediate states mirror what the engine dispatches; jumping + // straight to resumed would violate AppLifecycleListener's asserts. + final binding = TestWidgetsFlutterBinding.instance; + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await container.read(authProvider.notifier).revalidationDone; + + final state = container.read(authProvider).value; + expect(state?.status, AuthStatus.loggedOut); + expect(state?.sessionExpired, true); + }, + ); + }); } /// Connectivity stub backed by a caller-controlled stream so reconnect events From b86c1e7e0e43f333401904969d8efbeb49719425 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 17:28:01 +0200 Subject: [PATCH 074/484] Store body weight in the official measurements category --- lib/core/network/auth_notifier.g.dart | 2 +- lib/core/network/network_provider.g.dart | 2 +- lib/core/widgets/dashboard/calendar.dart | 28 +- .../dashboard/widgets/measurements.dart | 7 +- .../widgets/dashboard/widgets/weight.dart | 31 +- lib/database/powersync/database.dart | 5 - lib/database/powersync/database.g.dart | 399 +++--------------- lib/database/powersync/powersync.g.dart | 2 +- .../powersync/tables/measurements.dart | 6 + lib/database/powersync/tables/weight.dart | 40 -- lib/features/health/models/health_metric.dart | 4 +- .../health/providers/health_sync.dart | 18 +- .../models/measurement_category.dart | 11 + .../models/measurement_category.freezed.dart | 17 +- .../providers/measurement_notifier.dart | 7 +- .../providers/measurement_notifier.g.dart | 2 +- .../measurement_category_sort_screen.dart | 5 +- .../measurements/widgets/categories.dart | 6 +- lib/features/measurements/widgets/forms.dart | 12 +- .../providers/nutrition_notifier.g.dart | 2 +- .../widgets/nutritional_plan_detail.dart | 10 +- .../widgets/nutritional_plans_list.dart | 6 +- .../providers/gym_log_notifier.g.dart | 2 +- lib/features/weight/models/weight_entry.dart | 57 --- .../providers/body_weight_notifier.g.dart | 54 --- ...otifier.dart => body_weight_provider.dart} | 41 +- .../providers/body_weight_provider.g.dart | 75 ++++ .../providers/body_weight_repository.dart | 62 --- .../weight/screens/weight_screen.dart | 31 +- lib/features/weight/widgets/forms.dart | 164 ++++--- .../weight/widgets/weight_overview.dart | 33 +- lib/powersync/schema.dart | 4 - test/core/helpers_test.dart | 6 +- test/core/validators_test.mocks.dart | 300 ++++--------- .../health/models/health_metric_test.dart | 6 +- .../health/providers/health_sync_test.dart | 60 +++ .../models/measurement_category_test.dart | 18 + .../providers/measurement_notifier_test.dart | 11 + .../measurement_repository_test.dart | 18 + .../measurements/widgets/forms_test.dart | 33 ++ .../screens/nutritional_plan_screen_test.dart | 18 +- .../nutritional_plan_screen_test.mocks.dart | 92 +++- .../nutritional_plans_screen_test.dart | 12 +- .../nutritional_plans_screen_test.mocks.dart | 106 ++++- .../routines_repository_test.mocks.dart | 243 +++++------ .../providers/body_weight_notifier_test.dart | 60 --- .../body_weight_notifier_test.mocks.dart | 69 --- .../providers/body_weight_provider_test.dart | 74 ++++ .../body_weight_provider_test.mocks.dart | 139 ++++++ .../body_weight_repository_test.dart | 127 ------ .../weight/screens/weight_screen_test.dart | 35 +- .../screens/weight_screen_test.mocks.dart | 106 ++++- test/features/weight/widgets/forms_test.dart | 36 +- .../weight/widgets/forms_test.mocks.dart | 92 +++- .../screenshots/screenshots_01_dashboard.dart | 17 +- .../screenshots_01_dashboard.mocks.dart | 158 +++---- .../screenshots_05_nutritional_plan.dart | 12 +- ...screenshots_05_nutritional_plan.mocks.dart | 92 +++- test/screenshots/screenshots_06_weight.dart | 12 +- .../screenshots_06_weight.mocks.dart | 220 ++++++---- test_data/body_weight.dart | 78 ++-- 61 files changed, 1722 insertions(+), 1673 deletions(-) delete mode 100644 lib/database/powersync/tables/weight.dart delete mode 100644 lib/features/weight/models/weight_entry.dart delete mode 100644 lib/features/weight/providers/body_weight_notifier.g.dart rename lib/features/weight/providers/{body_weight_notifier.dart => body_weight_provider.dart} (52%) create mode 100644 lib/features/weight/providers/body_weight_provider.g.dart delete mode 100644 lib/features/weight/providers/body_weight_repository.dart delete mode 100644 test/features/weight/providers/body_weight_notifier_test.dart delete mode 100644 test/features/weight/providers/body_weight_notifier_test.mocks.dart create mode 100644 test/features/weight/providers/body_weight_provider_test.dart create mode 100644 test/features/weight/providers/body_weight_provider_test.mocks.dart delete mode 100644 test/features/weight/providers/body_weight_repository_test.dart diff --git a/lib/core/network/auth_notifier.g.dart b/lib/core/network/auth_notifier.g.dart index 86ce6eeff..7d29a5ac1 100644 --- a/lib/core/network/auth_notifier.g.dart +++ b/lib/core/network/auth_notifier.g.dart @@ -32,7 +32,7 @@ final class AuthNotifierProvider extends $AsyncNotifierProvider AuthNotifier(); } -String _$authNotifierHash() => r'19bf6776a00c5a7374ddc918f55709ee3a193b3f'; +String _$authNotifierHash() => r'2e848f93a2dec9ca9c98ce85e860864c58fa0a2b'; abstract class _$AuthNotifier extends $AsyncNotifier { FutureOr build(); diff --git a/lib/core/network/network_provider.g.dart b/lib/core/network/network_provider.g.dart index e84356690..c67d1f49d 100644 --- a/lib/core/network/network_provider.g.dart +++ b/lib/core/network/network_provider.g.dart @@ -40,7 +40,7 @@ final class NetworkStatusProvider extends $NotifierProvider } } -String _$networkStatusHash() => r'2abc19df2e0e679222609fec1d637ae131ef4ac1'; +String _$networkStatusHash() => r'091ee41de990a1e6ff0ff3915656d41ea2d1a6e5'; abstract class _$NetworkStatus extends $Notifier { bool build(); diff --git a/lib/core/widgets/dashboard/calendar.dart b/lib/core/widgets/dashboard/calendar.dart index 719a2a4ae..8b6b81410 100644 --- a/lib/core/widgets/dashboard/calendar.dart +++ b/lib/core/widgets/dashboard/calendar.dart @@ -30,8 +30,6 @@ import 'package:wger/features/nutrition/models/nutritional_plan.dart'; import 'package:wger/features/nutrition/providers/nutrition_notifier.dart'; import 'package:wger/features/routines/models/session.dart'; import 'package:wger/features/routines/providers/routines_notifier.dart'; -import 'package:wger/features/weight/models/weight_entry.dart'; -import 'package:wger/features/weight/providers/body_weight_notifier.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/theme/theme.dart'; @@ -78,7 +76,6 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState> _buildEvents({ required BuildContext context, - required List entries, required List categories, required List sessions, required List plans, @@ -87,21 +84,22 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState>{}; - for (final entry in entries) { - final date = DateFormatLists.format(entry.date); - events.putIfAbsent(date, () => []); - events[date]!.add(Event(EventType.weight, '${numberFormat.format(entry.weight)} kg')); - } - for (final category in categories) { + // Body weight entries live in the official category but keep their own + // event type (and no category-name prefix) for (final entry in category.entries) { final date = DateFormatLists.format(entry.date); events.putIfAbsent(date, () => []); events[date]!.add( - Event( - EventType.measurement, - '${category.name}: ${numberFormat.format(entry.value)} ${category.unit}', - ), + category.isOfficialBodyWeight + ? Event( + EventType.weight, + '${numberFormat.format(entry.value)} ${category.unit}', + ) + : Event( + EventType.measurement, + '${category.name}: ${numberFormat.format(entry.value)} ${category.unit}', + ), ); } } @@ -187,20 +185,18 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState c.parentId == null).toList(); + // Children of multi-value groups are shown inside their parent's card. + // Body weight has its own dashboard widget. + final categoriesList = allCategories + .where((c) => c.parentId == null && !c.isOfficialBodyWeight) + .toList(); if (categoriesList.isEmpty) { return NothingFound( diff --git a/lib/core/widgets/dashboard/widgets/weight.dart b/lib/core/widgets/dashboard/widgets/weight.dart index efe3caf1f..a8aae61a5 100644 --- a/lib/core/widgets/dashboard/widgets/weight.dart +++ b/lib/core/widgets/dashboard/widgets/weight.dart @@ -25,10 +25,10 @@ import 'package:wger/core/widgets/error.dart'; import 'package:wger/core/widgets/progress_indicator.dart'; import 'package:wger/features/account/models/user_profile.dart'; import 'package:wger/features/account/providers/user_profile_notifier.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; import 'package:wger/features/measurements/widgets/charts.dart'; import 'package:wger/features/measurements/widgets/helpers.dart'; -import 'package:wger/features/weight/models/weight_entry.dart'; -import 'package:wger/features/weight/providers/body_weight_notifier.dart'; +import 'package:wger/features/weight/providers/body_weight_provider.dart'; import 'package:wger/features/weight/screens/weight_screen.dart'; import 'package:wger/features/weight/widgets/forms.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -59,21 +59,21 @@ class DashboardWeightWidget extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final entriesAsync = ref.watch(weightEntryProvider); + final categoryAsync = ref.watch(bodyWeightCategoryProvider); final profileAsync = ref.watch(userProfileProvider); // Composite loading / error / data resolution. We need both providers - // ready before we can render the chart (entries → series, profile → + // ready before we can render the chart (category → series, profile → // unit). Treating them independently with a nested .when() is what gave // us the eternal-spinner bug when fetchProfile() returned null, so we // funnel everything through a single decision tree here. - if (entriesAsync.isLoading || profileAsync.isLoading) { + if (categoryAsync.isLoading || profileAsync.isLoading) { return _shell(context, const BoxedProgressIndicator()); } - if (entriesAsync.hasError) { + if (categoryAsync.hasError) { return _shell( context, - StreamErrorIndicator(entriesAsync.error!, stacktrace: entriesAsync.stackTrace), + StreamErrorIndicator(categoryAsync.error!, stacktrace: categoryAsync.stackTrace), ); } if (profileAsync.hasError) { @@ -88,25 +88,32 @@ class DashboardWeightWidget extends ConsumerWidget { // way we treat a server error so the user isn't stuck on a spinner. return _shell(context, const StreamErrorIndicator('User profile is unavailable')); } + final category = categoryAsync.value; + if (category == null) { + // The official body weight category is created by the server; it is + // missing only while the initial sync is still running. + return _shell(context, const BoxedProgressIndicator()); + } - return _shell(context, _buildContent(context, entriesAsync.value!, profile)); + return _shell(context, _buildContent(context, category, profile)); } Widget _buildContent( BuildContext context, - List entriesList, + MeasurementCategory category, UserProfile profile, ) { + final entriesList = category.entries; if (entriesList.isEmpty) { return NothingFound( AppLocalizations.of(context).noWeightEntries, AppLocalizations.of(context).newEntry, - WeightForm(), + WeightForm(category.id!), ); } final (entriesAll, entries7dAvg) = sensibleRange( - entriesList.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(), + entriesList.map((e) => MeasurementChartEntry(e.value, e.date)).toList(), ); return Column( @@ -151,7 +158,7 @@ class DashboardWeightWidget extends ConsumerWidget { FormScreen.routeName, arguments: FormScreenArguments( AppLocalizations.of(context).newEntry, - WeightForm(), + WeightForm(category.id!), ), ); }, diff --git a/lib/database/powersync/database.dart b/lib/database/powersync/database.dart index 4ae7088a5..f19c9aa5a 100644 --- a/lib/database/powersync/database.dart +++ b/lib/database/powersync/database.dart @@ -52,7 +52,6 @@ import 'package:wger/features/routines/models/repetition_unit.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/session.dart'; import 'package:wger/features/routines/models/weight_unit.dart'; -import 'package:wger/features/weight/models/weight_entry.dart'; import 'powersync.dart'; import 'tables/exercise.dart'; @@ -64,7 +63,6 @@ import 'tables/measurements.dart'; import 'tables/nutrition.dart'; import 'tables/routines.dart'; import 'tables/user_profile.dart'; -import 'tables/weight.dart'; part 'database.g.dart'; @@ -89,9 +87,6 @@ part 'database.g.dart'; ExerciseImageTable, ExerciseVideoTable, - // Body weight - WeightEntryTable, - // Measurements MeasurementCategoryTable, MeasurementEntryTable, diff --git a/lib/database/powersync/database.g.dart b/lib/database/powersync/database.g.dart index cdb1eb13d..7c0b41479 100644 --- a/lib/database/powersync/database.g.dart +++ b/lib/database/powersync/database.g.dart @@ -4674,178 +4674,6 @@ class ExerciseVideoTableCompanion extends UpdateCompanion