mirror of
https://github.com/wger-project/flutter.git
synced 2026-12-03 02:24:30 +01:00
feat(measurements): implement measurement groups, dynamic formula evaluation
This commit is contained in:
@@ -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<MeasurementEntry> 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<MeasurementEntry>? 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<String, dynamic> toJson() => _$MeasurementCategoryToJson(this);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, name, unit, entries];
|
||||
List<Object?> 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<MeasurementEntry> _) => null;
|
||||
|
||||
@@ -12,6 +12,14 @@ MeasurementCategory _$MeasurementCategoryFromJson(Map<String, dynamic> 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<String, dynamic>,
|
||||
),
|
||||
formula: json['formula'] as String?,
|
||||
isDynamic: json['is_dynamic'] as bool? ?? false,
|
||||
entries:
|
||||
(json['entries'] as List<dynamic>?)
|
||||
?.map((e) => MeasurementEntry.fromJson(e as Map<String, dynamic>))
|
||||
@@ -26,5 +34,7 @@ Map<String, dynamic> _$MeasurementCategoryToJson(
|
||||
'id': instance.id,
|
||||
'name': instance.name,
|
||||
'unit': instance.unit,
|
||||
'group': instance.groupId,
|
||||
'formula': instance.formula,
|
||||
'entries': MeasurementCategory._nullValue(instance.entries),
|
||||
};
|
||||
|
||||
37
lib/models/measurements/measurement_group.dart
Normal file
37
lib/models/measurements/measurement_group.dart
Normal file
@@ -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<String, dynamic> json) =>
|
||||
_$MeasurementGroupFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$MeasurementGroupToJson(this);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, uuid, name, description];
|
||||
}
|
||||
25
lib/models/measurements/measurement_group.g.dart
Normal file
25
lib/models/measurements/measurement_group.g.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'measurement_group.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
MeasurementGroup _$MeasurementGroupFromJson(Map<String, dynamic> 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<String, dynamic> _$MeasurementGroupToJson(MeasurementGroup instance) =>
|
||||
<String, dynamic>{
|
||||
'id': instance.id,
|
||||
'uuid': instance.uuid,
|
||||
'name': instance.name,
|
||||
'description': instance.description,
|
||||
};
|
||||
@@ -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<MeasurementCategory> _categories = [];
|
||||
List<MeasurementGroup> _groups = [];
|
||||
|
||||
MeasurementProvider(this.baseProvider);
|
||||
|
||||
List<MeasurementCategory> get categories => _categories;
|
||||
List<MeasurementGroup> 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<void> 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<void> 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<dynamic> data = rawData is List ? rawData : (rawData['results'] ?? []);
|
||||
|
||||
final List<MeasurementEntry> computedEntries = data
|
||||
.map((e) => MeasurementEntry.fromJson(e as Map<String, dynamic>))
|
||||
.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<void> 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<void> editCategory(int id, String? newName, String? newUnit) async {
|
||||
Future<void> 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<void> 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<void> addGroup(MeasurementGroup group) async {
|
||||
final Uri postUri = baseProvider.makeUrl(_groupUrl);
|
||||
final Map<String, dynamic> 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<void> 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<String, dynamic> 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<void> 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<void> addEntry(MeasurementEntry entry) async {
|
||||
final Uri postUri = baseProvider.makeUrl(_entryUrl);
|
||||
|
||||
@@ -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<MeasurementCategoriesScreen> createState() => _MeasurementCategoriesScreenState();
|
||||
}
|
||||
|
||||
class _MeasurementCategoriesScreenState extends State<MeasurementCategoriesScreen> {
|
||||
int? _selectedGroupId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
@@ -49,7 +57,42 @@ class MeasurementCategoriesScreen extends StatelessWidget {
|
||||
),
|
||||
body: WidescreenWrapper(
|
||||
child: Consumer<MeasurementProvider>(
|
||||
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),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -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<MeasurementProvider>(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]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -80,8 +80,8 @@ class EntriesList extends StatelessWidget {
|
||||
arguments: FormScreenArguments(
|
||||
AppLocalizations.of(context).edit,
|
||||
MeasurementEntryForm(
|
||||
currentEntry.category,
|
||||
currentEntry,
|
||||
categoryId: currentEntry.category,
|
||||
entry: currentEntry,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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<FormState>();
|
||||
final nameController = TextEditingController();
|
||||
final unitController = TextEditingController();
|
||||
class MeasurementCategoryForm extends StatefulWidget {
|
||||
final MeasurementCategory? category;
|
||||
|
||||
final Map<String, dynamic> categoryData = {
|
||||
'id': null,
|
||||
'name': '',
|
||||
'unit': '',
|
||||
const MeasurementCategoryForm({
|
||||
super.key,
|
||||
this.category,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MeasurementCategoryForm> createState() => _MeasurementCategoryFormState();
|
||||
}
|
||||
|
||||
class _MeasurementCategoryFormState extends State<MeasurementCategoryForm> {
|
||||
final List<MeasurementGroup> _dummyGroups = [
|
||||
const MeasurementGroup(uuid: '1', id: 1, name: 'Dummy: Bodyweight'),
|
||||
const MeasurementGroup(uuid: '2', id: 2, name: 'Dummy: Strength'),
|
||||
];
|
||||
|
||||
final _form = GlobalKey<FormState>();
|
||||
late final TextEditingController nameController;
|
||||
late final TextEditingController unitController;
|
||||
|
||||
int? _categoryId;
|
||||
|
||||
int? _selectedGroupId;
|
||||
String? _selectedFormula;
|
||||
bool _isSubmitting = false;
|
||||
|
||||
static const Map<String, String> _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<MeasurementProvider>(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<int?>(
|
||||
initialValue: _selectedGroupId,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Group (optional)',
|
||||
helperText: 'Link this category to a group e.g. "Blood Pressure"',
|
||||
),
|
||||
items: [
|
||||
const DropdownMenuItem<int?>(
|
||||
value: null,
|
||||
child: Text('- No group -'),
|
||||
),
|
||||
...groups.map(
|
||||
(g) => DropdownMenuItem<int?>(
|
||||
value: g.id,
|
||||
child: Text(g.name),
|
||||
),
|
||||
),
|
||||
],
|
||||
onChanged: (val) => setState(() => _selectedGroupId = val),
|
||||
),
|
||||
|
||||
// Formula dropdown
|
||||
const SizedBox(height: 12),
|
||||
DropdownButtonFormField<String?>(
|
||||
initialValue: _selectedFormula,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Auto-calculate from formula (optional)',
|
||||
helperText: 'values are computed automatically, no entry needed.',
|
||||
),
|
||||
items: [
|
||||
const DropdownMenuItem<String?>(
|
||||
value: null,
|
||||
child: Text('- Manual entry -'),
|
||||
),
|
||||
..._formulaLabels.entries.map(
|
||||
(e) => DropdownMenuItem<String?>(
|
||||
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<MeasurementProvider>(context, listen: false);
|
||||
|
||||
// Save the entry on the server
|
||||
categoryData['id'] == null
|
||||
? await Provider.of<MeasurementProvider>(
|
||||
context,
|
||||
listen: false,
|
||||
).addCategory(
|
||||
MeasurementCategory(
|
||||
id: categoryData['id'],
|
||||
name: categoryData['name'],
|
||||
unit: categoryData['unit'],
|
||||
),
|
||||
)
|
||||
: await Provider.of<MeasurementProvider>(
|
||||
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<MeasurementEntryForm> createState() => _MeasurementEntryFormState();
|
||||
}
|
||||
|
||||
class _MeasurementEntryFormState extends State<MeasurementEntryForm> {
|
||||
final _form = GlobalKey<FormState>();
|
||||
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<String, dynamic> _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<MeasurementProvider>(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<MeasurementProvider>(
|
||||
context,
|
||||
listen: false,
|
||||
).addEntry(
|
||||
MeasurementEntry(
|
||||
id: _entryData['id'],
|
||||
category: _entryData['category'],
|
||||
date: _entryData['date'],
|
||||
value: _entryData['value'],
|
||||
notes: _entryData['notes'],
|
||||
),
|
||||
)
|
||||
: await Provider.of<MeasurementProvider>(
|
||||
context,
|
||||
listen: false,
|
||||
).editEntry(
|
||||
_entryData['id'],
|
||||
_entryData['category'],
|
||||
_entryData['value'],
|
||||
_entryData['notes'],
|
||||
_entryData['date'],
|
||||
);
|
||||
final provider = Provider.of<MeasurementProvider>(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),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user