Tidy up the measurement and health helpers

This commit is contained in:
Roland Geider
2026-08-06 21:11:09 +02:00
parent 98ff130e24
commit a0fddd62c9
13 changed files with 93 additions and 67 deletions

View File

@@ -56,21 +56,35 @@ enum DailyAggregation {
class HealthMetric {
const HealthMetric({
required this.metricType,
required this.dataType,
required HealthDataType this.dataType,
required this.toCategoryValue,
this.components = const [],
this.dailyAggregation,
this.dayRollsOverAtHour,
this.enabled = false,
this.disabledReason,
this.readWindow = defaultReadWindow,
});
}) : components = const [];
/// A metric whose readings are split over several categories, e.g. blood
/// pressure. It has no platform type of its own: what it reads is what its
/// [components] read.
const HealthMetric.group({
required this.metricType,
required this.components,
required this.toCategoryValue,
this.dailyAggregation,
this.dayRollsOverAtHour,
this.enabled = false,
this.disabledReason,
this.readWindow = defaultReadWindow,
}) : dataType = null;
/// Metric type stored on the category, e.g. [MetricType.bodyFat].
final MetricType metricType;
/// Health platform type this metric reads.
final HealthDataType dataType;
/// Health platform type this metric reads, null for a group, whose
/// components carry theirs.
final HealthDataType? dataType;
/// Name and unit the category is created under. They belong to the metric
/// type, so a category the user creates by hand looks the same.
@@ -118,8 +132,10 @@ class HealthMetric {
/// All platform types this metric reads (the components' for a group), each
/// one once even when several components read it.
List<HealthDataType> get dataTypes =>
components.isEmpty ? [dataType] : components.expand((c) => c.dataTypes).toSet().toList();
List<HealthDataType> get dataTypes {
final type = dataType;
return type != null ? [type] : components.expand((c) => c.dataTypes).toSet().toList();
}
}
/// One component of a multi-value metric (e.g. systolic), imported into its
@@ -168,9 +184,8 @@ const List<HealthMetric> healthMetrics = [
toCategoryValue: _identity,
enabled: true,
),
HealthMetric(
HealthMetric.group(
metricType: MetricType.bloodPressure,
dataType: HealthDataType.BLOOD_PRESSURE_SYSTOLIC,
toCategoryValue: _identity,
// Both platforms report mmHg; a reading is the systolic/diastolic pair
// sharing one timestamp.
@@ -201,7 +216,7 @@ const List<HealthMetric> healthMetrics = [
toCategoryValue: _identity,
enabled: true,
),
HealthMetric(
HealthMetric.group(
// SLEEP_ASLEEP is not the whole night, it is the coarsest stage: the
// plugin filters it down to HealthKit's asleepUnspecified and to Health
// Connect's STAGE_TYPE_SLEEPING. Anything writing a real hypnogram (an
@@ -210,7 +225,6 @@ const List<HealthMetric> healthMetrics = [
// total therefore rolls the stages up, and each stage also gets its own
// category. All types report minutes on both platforms.
metricType: MetricType.sleep,
dataType: HealthDataType.SLEEP_ASLEEP,
toCategoryValue: _identity,
components: [
HealthMetricComponent(

View File

@@ -293,7 +293,7 @@ class HealthSyncNotifier extends _$HealthSyncNotifier {
// own category, or one child per component for a group metric.
final List<(MeasurementCategory, Iterable<HealthReading>)> targets;
if (metric.components.isEmpty) {
final metricReadings = readings.where((r) => r.type == metric.dataType);
final metricReadings = readings.where((r) => metric.dataTypes.contains(r.type));
if (metricReadings.isEmpty) {
if (readsFullHistory && withoutCategory.contains(metric.metricType.name)) {
knownEmpty.add(metric.metricType.name);

View File

@@ -56,7 +56,7 @@ final class HealthSyncNotifierProvider
}
}
String _$healthSyncNotifierHash() => r'ccc81caa4644114131dece9668817c26bf126932';
String _$healthSyncNotifierHash() => r'299b7408f5fe389d19bd3b371c1972a977b8c3b0';
/// Imports body metrics from Apple Health / Health Connect into measurement
/// categories. Read-only: reads the platform (via [HealthRepository]), writes to

View File

@@ -554,8 +554,9 @@ class MeasurementCategory with _$MeasurementCategory {
copyWith(chartConfig: {...?chartConfig, key: value});
/// `true` for group parents (blood pressure etc.), which hold no entries of
/// their own
bool get isGroup => children.isNotEmpty;
/// their own. Answers for this row: a group whose components have not synced
/// yet has none, unlike the structural [MetricType.isGroup].
bool get hasChildren => children.isNotEmpty;
/// The user's body weight category. It has its own screens (weight feature)
/// and is hidden from the general measurements UI.
@@ -567,7 +568,8 @@ class MeasurementCategory with _$MeasurementCategory {
/// differently, and a group has neither: its name and unit come from the
/// metric type and its chart from what its components are to each other.
bool get isEditable =>
metricType == MetricType.custom || (!isGroup && metricType.availableChartTypes.isNotEmpty);
metricType == MetricType.custom ||
(!hasChildren && metricType.availableChartTypes.isNotEmpty);
MeasurementEntry findEntryById(String id) {
return entries.firstWhere(

View File

@@ -133,11 +133,6 @@ final class MeasurementNotifier extends _$MeasurementNotifier {
return _repo.watchAll();
}
Stream<MeasurementCategory?> watchCategoryById(String id) {
_logger.finer('Watching local measurement category $id');
return _repo.watchLocalDriftCategoryById(id);
}
Future<MeasurementCategory?> getCategoryById(String id) async {
// Data already loaded
final categories = state.asData?.value;
@@ -193,13 +188,13 @@ final class MeasurementNotifier extends _$MeasurementNotifier {
final parent = category.copyWith(
id: category.id ?? deterministicCategoryId(userId, category.metricType),
);
await _repo.addLocalDriftCategory(parent);
// A group is a container, its readings live in one child per component.
// The server creates them as well, on the same ids, so whichever side
// gets there first wins and the other is acknowledged as a no-op
for (final (order, metricType) in parent.metricType.components.indexed) {
await _repo.addLocalDriftCategory(
await _repo.addLocalDriftCategoryGroup([
parent,
for (final (order, metricType) in parent.metricType.components.indexed)
MeasurementCategory(
id: deterministicCategoryId(userId, metricType),
name: metricType.canonicalName,
@@ -208,8 +203,7 @@ final class MeasurementNotifier extends _$MeasurementNotifier {
parentId: parent.id,
order: order,
),
);
}
]);
return parent.id;
}

View File

@@ -734,7 +734,7 @@ final class MeasurementNotifierProvider
MeasurementNotifier create() => MeasurementNotifier();
}
String _$measurementNotifierHash() => r'c34dc2058c56e502cba8f1d84d867347dcc02f79';
String _$measurementNotifierHash() => r'afc8a100a40967bd8e7ea41bdd1985502878fc12';
abstract class _$MeasurementNotifier extends $StreamNotifier<List<MeasurementCategory>> {
Stream<List<MeasurementCategory>> build();

View File

@@ -562,6 +562,17 @@ class MeasurementRepository {
await _db.into(_db.measurementCategoryTable).insert(category.toCompanion());
}
/// Inserts a group together with its components, in a single transaction so
/// a group is never left without the children its readings live in.
Future<void> addLocalDriftCategoryGroup(List<MeasurementCategory> categories) async {
_logger.finer('Adding a local measurement group of ${categories.length} categories');
await _db.transaction(() async {
for (final category in categories) {
await _db.into(_db.measurementCategoryTable).insert(category.toCompanion());
}
});
}
/// 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.

View File

@@ -138,7 +138,7 @@ class _MeasurementEntriesScreenState extends ConsumerState<MeasurementEntriesScr
AppLocalizations.of(context).newEntry,
// A group holds no entries itself: one reading is a value
// per component, entered in one go
category.isGroup
category.hasChildren
? GroupMeasurementEntryForm(category)
: MeasurementEntryForm(_categoryId),
),

View File

@@ -45,7 +45,7 @@ class CategoriesCard extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
if (currentCategory.isGroup) {
if (currentCategory.hasChildren) {
return _buildGroupCard(context, ref);
}

View File

@@ -82,7 +82,7 @@ class EntriesList extends ConsumerWidget {
// A group carries no entries of its own, its readings live in the
// components, so everything below would chart an empty list
if (category.isGroup) {
if (category.hasChildren) {
return _buildGroup(context, ref, category);
}
@@ -137,13 +137,13 @@ class EntriesList extends ConsumerWidget {
final settings = category.chartSettings;
final (:entries, :average) = chartSeriesFor(allPoints, range, settings);
return getOverviewWidgetsSeries(
name,
entries,
average,
planPeriods,
unitLabel,
return buildSeriesChartSection(
context,
name: name,
entriesAll: entries,
average: average,
unit: unitLabel,
planPeriods: planPeriods,
metricType: category.metricType,
mainChartTitle: range.chartTitle(AppLocalizations.of(context), name),
chartType: category.chartType,

View File

@@ -291,12 +291,17 @@ class _MeasurementEntryFormState extends ConsumerState<MeasurementEntryForm> {
num? _value;
String _notes = '';
/// Read once: a future built in build() is a new one on every rebuild, which
/// sends the FutureBuilder back to its loading state.
late final Future<MeasurementCategory?> _categoryFuture;
@override
void initState() {
super.initState();
_value = widget._entry?.value;
_notes = widget._entry?.notes ?? '';
_notesController.text = _notes;
_categoryFuture = ref.read(measurementProvider.notifier).getCategoryById(widget._categoryId);
}
@override
@@ -308,12 +313,9 @@ class _MeasurementEntryFormState extends ConsumerState<MeasurementEntryForm> {
@override
Widget build(BuildContext context) {
final notifier = ref.read(measurementProvider.notifier);
final Future<MeasurementCategory?> categoryFuture = notifier.getCategoryById(
widget._categoryId,
);
return FutureBuilder(
future: categoryFuture,
future: _categoryFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const BoxedProgressIndicator();

View File

@@ -13,12 +13,13 @@ import 'package:wger/features/measurements/widgets/chart_range_selector.dart';
import 'package:wger/features/measurements/widgets/charts.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
List<Widget> getOverviewWidgets(
String title,
List<MeasurementChartEntry> raw,
List<MeasurementChartEntry> avg,
String unit,
/// A titled chart with the overall change below it, for a Column to spread.
List<Widget> buildChartSection(
BuildContext context, {
required String title,
required List<MeasurementChartEntry> raw,
required List<MeasurementChartEntry> avg,
required String unit,
MetricType metricType = MetricType.custom,
List<PlanPeriod> planPeriods = const [],
List<MeasurementChartEntry>? trend,
@@ -61,13 +62,15 @@ List<Widget> getOverviewWidgets(
];
}
List<Widget> getOverviewWidgetsSeries(
String name,
List<MeasurementChartEntry> entriesAll,
List<MeasurementChartEntry> average,
List<PlanPeriod> planPeriods,
String unit,
/// The chart of a measurement series: [buildChartSection] for the chart the
/// type resolves to, plus the legend naming the lines it draws.
List<Widget> buildSeriesChartSection(
BuildContext context, {
required String name,
required List<MeasurementChartEntry> entriesAll,
required List<MeasurementChartEntry> average,
required String unit,
List<PlanPeriod> planPeriods = const [],
MetricType metricType = MetricType.custom,
String? mainChartTitle,
ChartType chartType = ChartType.auto,
@@ -86,21 +89,21 @@ List<Widget> getOverviewWidgetsSeries(
if (resolved == ChartType.heatmap ||
resolved == ChartType.delta ||
resolved == ChartType.distribution) {
return getOverviewWidgets(
return buildChartSection(
context,
// The selector right above names the range, so the title says what the
// bars are instead
switch (resolved) {
title: switch (resolved) {
ChartType.delta => AppLocalizations.of(context).chartWeeklyChangeTitle(name),
ChartType.distribution => AppLocalizations.of(context).chartDistributionTitle(name),
_ => title,
},
entriesAll,
raw: entriesAll,
// The overall change is the one-number version of the change chart. Over
// a grid it measures a line that is not drawn, and a summed metric has no
// level to change.
resolved == ChartType.delta && !metricType.isSummedPerDay ? average : const [],
unit,
context,
avg: resolved == ChartType.delta && !metricType.isSummedPerDay ? average : const [],
unit: unit,
metricType: metricType,
chartType: chartType,
settings: settings,
@@ -113,12 +116,12 @@ List<Widget> getOverviewWidgetsSeries(
final summed = metricType.isSummedPerDay;
final trendAll = summed ? null : smoothedTrendline(entriesAll, period: settings.trend.emaPeriod);
return [
...getOverviewWidgets(
title,
entriesAll,
average,
unit,
...buildChartSection(
context,
title: title,
raw: entriesAll,
avg: average,
unit: unit,
metricType: metricType,
planPeriods: planPeriods,
trend: trendAll,

View File

@@ -67,12 +67,12 @@ class PlanWeightChart extends ConsumerWidget {
final avg = movingAverage(points, days: settings.averageWindow);
return Column(
children: getOverviewWidgets(
AppLocalizations.of(context).weight,
points,
avg,
weightUnit(profile.isMetric, context),
children: buildChartSection(
context,
title: AppLocalizations.of(context).weight,
raw: points,
avg: avg,
unit: weightUnit(profile.isMetric, context),
metricType: category.metricType,
settings: settings,
),