Skip to content

Offline gym log for Android. No account, no ads, no internet.

Reports for any dates as PDF or CSV

InlitX62893deb805f
diff --git a/lib/services/plan_pdf.dart b/lib/services/plan_pdf.dart
index ad17113..57aa01a 100644
--- a/lib/services/plan_pdf.dart
+++ b/lib/services/plan_pdf.dart
@@ -18,6 +18,8 @@ import '../widgets/exercise_art.dart';
import '../widgets/routine_folder.dart';
import '../widgets/ui_kit.dart';
+part 'report_pdf.dart';
+
const _pageW = 595.28;
const _pageH = 841.89;
const _margin = 40.0;
@@ -69,6 +71,13 @@ Future<Uint8List> buildPlanPdf(List<Routine> routines, {bool week = false, DateT
}
final doc = _PlanDoc(runner, arts, rtl: const {'ar', 'fa'}.contains(appLanguage));
doc.lay(routines, week: week, now: now ?? DateTime.now());
+ final pages = await _rasterize(doc);
+ runner.dispose();
+ final title = week ? sentenceCase(t.weeklyPlan) : fit.routineTitle(routines.first);
+ return _writePdf(pages, title, now ?? DateTime.now());
+}
+
+Future<List<(int, int, Uint8List)>> _rasterize(_PlanDoc doc) async {
final pages = <(int, int, Uint8List)>[];
for (var i = 0; i < doc.pages.length; i++) {
final w = (_pageW * _scale).round(), h = (_pageH * _scale).round();
@@ -85,9 +94,7 @@ Future<Uint8List> buildPlanPdf(List<Routine> routines, {bool week = false, DateT
pages.add((w, h, await Isolate.run(() => _deflateRgb(rgba))));
}
doc.dispose();
- runner.dispose();
- final title = week ? sentenceCase(t.weeklyPlan) : fit.routineTitle(routines.first);
- return _writePdf(pages, title, now ?? DateTime.now());
+ return pages;
}
Uint8List _deflateRgb(Uint8List rgba) {
@@ -649,7 +656,7 @@ String _xmp(String title, String subject, String keywords, String lang, DateTime
</x:xmpmeta>
<?xpacket end="w"?>''';
-Uint8List _writePdf(List<(int, int, Uint8List)> pages, String title, DateTime now) {
+Uint8List _writePdf(List<(int, int, Uint8List)> pages, String title, DateTime now, {String? kicker}) {
final out = BytesBuilder(copy: false);
final offsets = <int>[];
void raw(List<int> b) => out.add(b);
@@ -681,8 +688,9 @@ Uint8List _writePdf(List<(int, int, Uint8List)> pages, String title, DateTime no
raw([0x25, 0xE2, 0xE3, 0xCF, 0xD3, 0x0A]);
final n = pages.length;
final lang = intlLocale.replaceAll('_', '-');
- final subject = '${sentenceCase(t.pdfKicker)} · $_app';
- final keywords = '$_app, ${t.pdfKicker.toLowerCase()}';
+ final kind = kicker ?? t.pdfKicker;
+ final subject = '${sentenceCase(kind)} · $_app';
+ final keywords = '$_app, ${kind.toLowerCase()}';
final date = _pdfDate(now);
final xmp = Uint8List.fromList(utf8.encode(_xmp(title, subject, keywords, lang, now)));
final kids = [for (var i = 0; i < n; i++) '${5 + i * 3} 0 R'].join(' ');
diff --git a/lib/services/report_pdf.dart b/lib/services/report_pdf.dart
new file mode 100644
index 0000000..e9caad6
--- /dev/null
+++ b/lib/services/report_pdf.dart
@@ -0,0 +1,222 @@
+part of 'plan_pdf.dart';
+
+String reportRangeLabel(RangeReport r) => r.from.year == r.to.year
+ ? '${t.shortDate(r.from)} – ${t.shortDateYear(r.to)}'
+ : '${t.shortDateYear(r.from)} – ${t.shortDateYear(r.to)}';
+
+Future<Uint8List> buildReportPdf(RangeReport r, {DateTime? now}) async {
+ final runner = await _loadImage('assets/img/runner.png');
+ final doc = _ReportDoc(runner, rtl: const {'ar', 'fa'}.contains(appLanguage));
+ doc.layReport(r, now ?? DateTime.now());
+ final pages = await _rasterize(doc);
+ runner.dispose();
+ return _writePdf(pages, '${sentenceCase(t.reportKicker)} · ${reportRangeLabel(r)}', now ?? DateTime.now(),
+ kicker: t.reportKicker);
+}
+
+Future<void> shareReport(RangeReport r, {required bool pdf, required bool csv}) async {
+ try {
+ final dir = await getTemporaryDirectory();
+ final stamp = '${_isoDay(r.from)}_${_isoDay(r.to)}';
+ final files = <XFile>[];
+ if (pdf) {
+ final file = File('${dir.path}/gymmane-report-$stamp.pdf');
+ await file.writeAsBytes(await buildReportPdf(r));
+ files.add(XFile(file.path, mimeType: 'application/pdf'));
+ }
+ if (csv) {
+ if (r.sessions > 0) {
+ final file = File('${dir.path}/gymmane-workouts-$stamp.csv');
+ await file.writeAsString(fit.reportWorkoutsCsv(r));
+ files.add(XFile(file.path, mimeType: 'text/csv'));
+ }
+ if (r.food != null) {
+ final file = File('${dir.path}/gymmane-nutrition-$stamp.csv');
+ await file.writeAsString(fit.reportNutritionCsv(r));
+ files.add(XFile(file.path, mimeType: 'text/csv'));
+ }
+ }
+ if (files.isEmpty) return;
+ await SharePlus.instance.share(ShareParams(files: files, subject: '${sentenceCase(t.reportKicker)} · ${reportRangeLabel(r)}'));
+ } catch (_) {}
+}
+
+String _isoDay(DateTime d) => '${d.year}-${_two(d.month)}-${_two(d.day)}';
+
+class _ReportDoc extends _PlanDoc {
+ _ReportDoc(ui.Image runner, {required bool rtl}) : super(runner, const {}, rtl: rtl);
+
+ void layReport(RangeReport r, DateTime now) {
+ _newPage();
+ final logo = Rect.fromLTWH(_x(_margin, 26), _y, 26, 26);
+ _add((c) => _logo(c, logo));
+ _text('GymMane', _st(14, weight: FontWeight.w900), _margin + 34, _y + 4, 140);
+ final who = [if (fit.profile.name.trim().isNotEmpty) fit.profile.name.trim(), t.shortDateYear(now)].join(' · ');
+ _text(who, _st(9, color: _faint), _pageW - _margin - 220, _y + 8, 220, align: TextAlign.end);
+ _y += 50;
+ _y += _text(t.reportKicker, _st(8.5, weight: FontWeight.w800, color: _accent, spacing: 1.8), _margin, _y, _contentW);
+ _y += 4;
+ _y += _text(reportRangeLabel(r), _st(28, weight: FontWeight.w900, height: 1.1), _margin, _y, _contentW, maxLines: 2);
+ _y += 2;
+ _y += _text(t.reportDays(r.days), _st(11, color: _sub), _margin, _y, _contentW);
+ _y += 16;
+
+ String pct(num now, num before) {
+ if (before <= 0) return '';
+ final p = ((now / before - 1) * 100).round();
+ return '${p >= 0 ? '+' : ''}$p %';
+ }
+
+ final prev = r.prev;
+ _stats([
+ ('${r.sessions}', t.reportWorkouts, prev == null ? '' : pct(r.sessions, prev.sessions)),
+ ('${r.sets}', t.setsCaps, prev == null ? '' : pct(r.sets, prev.sets)),
+ (fit.volumeLabel(r.volume), t.volume, prev == null ? '' : pct(r.volume, prev.volume)),
+ (decimalText(r.perWeek.toStringAsFixed(1)), t.reportPerWeek, ''),
+ if (r.minutes > 0) (decimalText((r.minutes / 60).toStringAsFixed(r.minutes < 600 ? 1 : 0)), t.reportHours, ''),
+ ]);
+ if (prev != null) {
+ _y += _text(t.reportVsPrev, _st(8.5, color: _faint), _margin, _y, _contentW);
+ _y += 10;
+ }
+
+ if (r.records.isNotEmpty) {
+ _section(t.reportRecords);
+ for (final rec in r.records.take(12)) {
+ _room(20);
+ _text(rec.name, _st(11, weight: FontWeight.w800), _margin, _y, _contentW - 200);
+ _text(fit.weightLabel(rec.kg), _st(11, weight: FontWeight.w900, color: _accent), _pageW - _margin - 190, _y, 90,
+ align: TextAlign.end, ltr: true);
+ _text(t.shortDate(rec.date), _st(9.5, color: _sub), _pageW - _margin - 90, _y + 1, 90, align: TextAlign.end);
+ _y += 18;
+ _rect(_margin, _y - 3, _contentW, 0.6, _line);
+ }
+ _y += 10;
+ }
+
+ if (r.lifts.isNotEmpty) {
+ _section(t.reportLifts);
+ const cS = 250.0, cT = 310.0, cB = 370.0, cC = 450.0;
+ final head = _st(7.5, weight: FontWeight.w800, color: _faint, spacing: 0.8);
+ void tableHead() {
+ _text(t.exercisesCaps, head, _margin, _y, cS - 8);
+ _text(t.reportSessionsCol, head, _margin + cS, _y, 56, align: TextAlign.center);
+ _text(t.setsCaps, head, _margin + cT, _y, 56, align: TextAlign.center);
+ _text(t.reportBestCol, head, _margin + cB, _y, 76, align: TextAlign.center);
+ _text(t.reportChangeCol, head, _margin + cC, _y, _contentW - cC, align: TextAlign.center);
+ _y += 14;
+ _rect(_margin, _y, _contentW, 0.8, _line);
+ _y += 5;
+ }
+
+ tableHead();
+ var i = 0;
+ for (final l in r.lifts.take(25)) {
+ _room(22, onBreak: tableHead);
+ if (i.isOdd) _rect(_margin, _y - 4, _contentW, 22, _zebra, radius: 4);
+ final body = _st(10.5, weight: FontWeight.w700);
+ _text(l.name, _st(10.5, weight: FontWeight.w800), _margin + 4, _y, cS - 12);
+ _text('${l.sessions}', body, _margin + cS, _y, 56, align: TextAlign.center, ltr: true);
+ _text('${l.sets}', body, _margin + cT, _y, 56, align: TextAlign.center, ltr: true);
+ _text(l.best > 0 ? fit.weightLabel(l.best) : '–', body, _margin + cB, _y, 76, align: TextAlign.center, ltr: true);
+ final ch = l.change;
+ _text(
+ ch == null ? '–' : '${ch >= 0 ? '+' : ''}${ch.round()} %',
+ _st(10.5, weight: FontWeight.w800, color: ch == null ? _faint : (ch >= 0 ? _accent : _sub)),
+ _margin + cC,
+ _y,
+ _contentW - cC,
+ align: TextAlign.center,
+ ltr: true,
+ );
+ _y += 22;
+ i++;
+ }
+ _y += 6;
+ _y += _text(t.reportBestHint, _st(8.5, color: _faint), _margin, _y, _contentW, maxLines: 2);
+ _y += 12;
+ }
+
+ if (r.muscles.isNotEmpty) {
+ _section(t.reportMuscles);
+ final top = r.muscles.take(10).toList();
+ final max = top.first.sets;
+ for (final m in top) {
+ _room(18);
+ _text(t.muscle(m.muscle), _st(10.5, weight: FontWeight.w700), _margin, _y, 140);
+ final barW = _contentW - 200;
+ _rect(_margin + 150, _y + 4, barW, 6, _soft, radius: 3);
+ _rect(_margin + 150, _y + 4, math.max(6, barW * m.sets / max), 6, _accent, radius: 3);
+ _text(decimalText(m.sets.toStringAsFixed(m.sets % 1 == 0 ? 0 : 1)), _st(10, weight: FontWeight.w800),
+ _pageW - _margin - 40, _y, 40, align: TextAlign.end, ltr: true);
+ _y += 18;
+ }
+ _y += 10;
+ }
+
+ final body = <(String, String)>[
+ if (r.weightFrom != null)
+ (
+ t.bodyweightLabel,
+ r.weightTo == null
+ ? fit.weightLabel(r.weightFrom!)
+ : '${fit.weightLabel(r.weightFrom!)} → ${fit.weightLabel(r.weightTo!)}'
+ ' (${r.weightTo! >= r.weightFrom! ? '+' : '−'}${fit.weightLabel((r.weightTo! - r.weightFrom!).abs())})',
+ ),
+ if (r.sleep != null) (t.checkInSleep, '${decimalText(r.sleep!.toStringAsFixed(1))} / 5'),
+ if (r.energy != null) (t.checkInEnergy, '${decimalText(r.energy!.toStringAsFixed(1))} / 5'),
+ ];
+ if (body.isNotEmpty) {
+ _section(t.reportBody);
+ _pairs(body);
+ }
+
+ final food = r.food;
+ if (food != null) {
+ _section(t.reportFood(food.days));
+ _pairs([
+ (sentenceCase(t.kcalLabel), '${fit.energyOf(food.kcal)} ${fit.energyUnit}'),
+ (sentenceCase(t.macroProtein), '${food.protein.round()} g'),
+ (sentenceCase(t.macroCarbs), '${food.carbs.round()} g'),
+ (sentenceCase(t.macroFat), '${food.fat.round()} g'),
+ if (food.waterMl > 0) (sentenceCase(t.waterLabel), fit.waterLabel(food.waterMl)),
+ ]);
+ }
+ }
+
+ void _stats(List<(String, String, String)> stats) {
+ const gap = 8.0, h = 60.0;
+ _room(h + 10);
+ final w = (_contentW - gap * (stats.length - 1)) / stats.length;
+ for (var i = 0; i < stats.length; i++) {
+ final left = _margin + i * (w + gap);
+ _rect(left, _y, w, h, _soft, radius: 12);
+ _text(stats[i].$1, _st(17, weight: FontWeight.w900), left + 10, _y + 9, w - 20,
+ ltr: true, align: rtl ? TextAlign.right : TextAlign.left);
+ _text(stats[i].$2, _st(7, weight: FontWeight.w800, color: _faint, spacing: 1), left + 10, _y + 32, w - 20);
+ if (stats[i].$3.isNotEmpty) {
+ _text(stats[i].$3, _st(8, weight: FontWeight.w800, color: stats[i].$3.startsWith('-') ? _sub : _accent),
+ left + 10, _y + 44, w - 20, ltr: true, align: rtl ? TextAlign.right : TextAlign.left);
+ }
+ }
+ _y += h + 8;
+ }
+
+ void _section(String title) {
+ _room(60);
+ _y += 8;
+ _y += _text(title.toUpperCase(), _st(8.5, weight: FontWeight.w800, color: _accent, spacing: 1.6), _margin, _y, _contentW);
+ _y += 8;
+ }
+
+ void _pairs(List<(String, String)> rows) {
+ for (final (k, v) in rows) {
+ _room(20);
+ _text(k, _st(10.5, color: _sub), _margin, _y, 180);
+ _text(v, _st(11, weight: FontWeight.w800), _margin + 180, _y, _contentW - 180, align: TextAlign.end);
+ _y += 18;
+ _rect(_margin, _y - 3, _contentW, 0.6, _line);
+ }
+ _y += 12;
+ }
+}
diff --git a/lib/state/report_state.dart b/lib/state/report_state.dart
new file mode 100644
index 0000000..694e08f
--- /dev/null
+++ b/lib/state/report_state.dart
@@ -0,0 +1,201 @@
+part of 'fit_state.dart';
+
+typedef ReportLift = ({String id, String name, int sessions, int sets, double volume, double best, double? change});
+typedef ReportRecord = ({String id, String name, double kg, DateTime date});
+typedef ReportFood = ({int days, double kcal, double protein, double carbs, double fat, int waterMl});
+
+class RangeReport {
+ RangeReport({
+ required this.from,
+ required this.to,
+ required this.sessions,
+ required this.sets,
+ required this.volume,
+ required this.minutes,
+ required this.activeDays,
+ required this.lifts,
+ required this.records,
+ required this.muscles,
+ this.weightFrom,
+ this.weightTo,
+ this.food,
+ this.sleep,
+ this.energy,
+ this.prev,
+ });
+
+ final DateTime from;
+ final DateTime to;
+ final int sessions;
+ final int sets;
+ final double volume;
+ final int minutes;
+ final int activeDays;
+ final List<ReportLift> lifts;
+ final List<ReportRecord> records;
+ final List<({String muscle, double sets})> muscles;
+ final double? weightFrom;
+ final double? weightTo;
+ final ReportFood? food;
+ final double? sleep;
+ final double? energy;
+ final ({int sessions, int sets, double volume})? prev;
+
+ int get days => to.difference(from).inDays + 1;
+ double get perWeek => sessions / math.max(1, days) * 7;
+ bool get empty => sessions == 0 && food == null && weightFrom == null;
+}
+
+mixin ReportState on FitCore, ToolsState, LibraryState, SettingsState, TimelineState, StatsState, NutritionState {
+ RangeReport rangeReport(DateTime from, DateTime to) {
+ final a = _dayKey(from), b = _dayKey(to);
+ final end = shiftDays(b, 1);
+ bool inside(DateTime d) => !d.isBefore(a) && d.isBefore(end);
+ final picked = [for (final s in sessions) if (inside(s.day)) s];
+
+ var sets = 0, seconds = 0;
+ var volume = 0.0;
+ final days = <DateTime>{};
+ final perLift = <String, List<(DateTime, LoggedExercise)>>{};
+ for (final s in picked) {
+ sets += s.setCount;
+ volume += s.volume;
+ seconds += s.durationSec;
+ days.add(_dayKey(s.day));
+ for (final e in s.exercises) {
+ if (e.workingSets.isEmpty) continue;
+ (perLift[e.id] ??= []).add((s.date, e));
+ }
+ }
+
+ final lifts = <ReportLift>[];
+ final records = <ReportRecord>[];
+ for (final MapEntry(key: id, value: list) in perLift.entries) {
+ final ex = exerciseById(id);
+ final name = ex == null ? list.first.$2.name : t.catalogName(ex.id, ex.name);
+ final best = list.map((x) => x.$2.bestOneRm).fold(0.0, math.max);
+ final first = list.first.$2.bestOneRm, last = list.last.$2.bestOneRm;
+ lifts.add((
+ id: id,
+ name: name,
+ sessions: list.length,
+ sets: list.fold(0, (n, x) => n + x.$2.workingSets.length),
+ volume: list.fold(0.0, (v, x) => v + x.$2.volume),
+ best: best,
+ change: list.length >= 2 && first > 0 && last > 0 ? (last / first - 1) * 100 : null,
+ ));
+ var before = 0.0;
+ var seen = false;
+ for (final s in sessions) {
+ if (!s.day.isBefore(a)) break;
+ for (final e in s.exercises) {
+ if (e.id != id) continue;
+ seen = true;
+ before = math.max(before, e.topWeight);
+ }
+ }
+ if (!seen) continue;
+ (DateTime, double)? top;
+ for (final (date, e) in list) {
+ final w = e.topWeight;
+ if (w > before && (top == null || w > top.$2)) top = (date, w);
+ }
+ if (top != null) records.add((id: id, name: name, kg: top.$2, date: top.$1));
+ }
+ lifts.sort((x, y) => y.sets.compareTo(x.sets));
+ records.sort((x, y) => x.date.compareTo(y.date));
+
+ final muscles = [
+ for (final MapEntry(key: m, value: v) in muscleSetsBetween(a, b).entries)
+ if (v > 0) (muscle: m, sets: v),
+ ]..sort((x, y) => y.sets.compareTo(x.sets));
+
+ final weights = [for (final w in bodyweight) if (inside(w.date)) w]..sort((x, y) => x.date.compareTo(y.date));
+
+ ReportFood? food;
+ if (nutritionBeta) {
+ var n = 0;
+ var water = 0;
+ var total = Macros.zero;
+ for (var d = a; !d.isAfter(b); d = shiftDays(d, 1)) {
+ final list = entriesOn(d);
+ if (list.isEmpty) continue;
+ n++;
+ total = total + totalOn(d);
+ water += waterOn(d);
+ }
+ if (n > 0) {
+ food = (
+ days: n,
+ kcal: total.kcal / n,
+ protein: total.protein / n,
+ carbs: total.carbs / n,
+ fat: total.fat / n,
+ waterMl: water ~/ n,
+ );
+ }
+ }
+
+ double? avg(Iterable<int?> v) {
+ final l = v.nonNulls.toList();
+ return l.isEmpty ? null : l.reduce((x, y) => x + y) / l.length;
+ }
+
+ final span = b.difference(a).inDays + 1;
+ final pa = shiftDays(a, -span);
+ final previous = [for (final s in sessions) if (!s.day.isBefore(pa) && s.day.isBefore(a)) s];
+
+ return RangeReport(
+ from: a,
+ to: b,
+ sessions: picked.length,
+ sets: sets,
+ volume: volume,
+ minutes: seconds ~/ 60,
+ activeDays: days.length,
+ lifts: lifts,
+ records: records,
+ muscles: muscles,
+ weightFrom: weights.isEmpty ? null : weights.first.kg,
+ weightTo: weights.length < 2 ? null : weights.last.kg,
+ food: food,
+ sleep: avg(picked.map((s) => s.sleep)),
+ energy: avg(picked.map((s) => s.energy)),
+ prev: previous.isEmpty
+ ? null
+ : (
+ sessions: previous.length,
+ sets: previous.fold(0, (n, s) => n + s.setCount),
+ volume: previous.fold(0.0, (v, s) => v + s.volume),
+ ),
+ );
+ }
+
+ String reportWorkoutsCsv(RangeReport r) {
+ final end = shiftDays(r.to, 1);
+ return Store.instance
+ .exportCsv([for (final s in sessions) if (!s.day.isBefore(r.from) && s.day.isBefore(end)) s]);
+ }
+
+ String reportNutritionCsv(RangeReport r) {
+ final rows = StringBuffer('date,kcal,protein_g,carbs_g,fat_g,fiber_g,water_ml,foods\n');
+ for (var d = r.from; !d.isAfter(r.to); d = shiftDays(d, 1)) {
+ final list = entriesOn(d);
+ final water = waterOn(d);
+ if (list.isEmpty && water == 0) continue;
+ final m = totalOn(d);
+ String n(double v) => v.toStringAsFixed(1).replaceFirst(RegExp(r'\.0$'), '');
+ rows.writeln([
+ NutritionState._dk(d),
+ m.kcal.round(),
+ n(m.protein),
+ n(m.carbs),
+ n(m.fat),
+ n(m.fiber),
+ water,
+ list.length,
+ ].join(','));
+ }
+ return rows.toString();
+ }
+}
diff --git a/lib/widgets/report_sheet.dart b/lib/widgets/report_sheet.dart
new file mode 100644
index 0000000..0d94adb
--- /dev/null
+++ b/lib/widgets/report_sheet.dart
@@ -0,0 +1,191 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
+
+import '../l10n/l10n.dart';
+import '../services/plan_pdf.dart';
+import '../state/fit_state.dart';
+import '../theme/app_colors.dart';
+import '../theme/app_theme.dart';
+import 'glass.dart';
+import 'ui_kit.dart';
+
+void showReportSheet(BuildContext context) {
+ showAppSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => const ReportSheet(),
+ );
+}
+
+class ReportSheet extends StatefulWidget {
+ const ReportSheet({super.key});
+
+ @override
+ State<ReportSheet> createState() => _ReportSheetState();
+}
+
+class _ReportSheetState extends State<ReportSheet> {
+ static const _presets = [30, 90, 365];
+ int _preset = 30;
+ late DateTimeRange _range = _last(30);
+ bool _busy = false;
+
+ static DateTimeRange _last(int days) {
+ final now = DateTime.now();
+ final end = DateTime(now.year, now.month, now.day);
+ return DateTimeRange(start: end.subtract(Duration(days: days - 1)), end: end);
+ }
+
+ String _presetLabel(int d) => switch (d) {
+ 30 => t.days30,
+ 90 => t.days90,
+ _ => t.days365,
+ };
+
+ Future<void> _pickRange() async {
+ final now = DateTime.now();
+ final first = fit.sessions.isEmpty ? DateTime(now.year - 1) : fit.sessions.first.day;
+ final picked = await showDateRangePicker(
+ context: context,
+ firstDate: DateTime(first.year, first.month, first.day).subtract(const Duration(days: 365)),
+ lastDate: DateTime(now.year, now.month, now.day),
+ initialDateRange: _range,
+ helpText: t.reportPickRange,
+ );
+ if (picked == null || !mounted) return;
+ setState(() {
+ _preset = 0;
+ _range = picked;
+ });
+ }
+
+ Future<void> _share({required bool pdf}) async {
+ if (_busy) return;
+ setState(() => _busy = true);
+ HapticFeedback.mediumImpact();
+ await shareReport(fit.rangeReport(_range.start, _range.end), pdf: pdf, csv: !pdf);
+ if (mounted) setState(() => _busy = false);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final r = fit.rangeReport(_range.start, _range.end);
+ Widget stat(String label, String value) => Expanded(
+ child: Container(
+ padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(14)),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ FitText(label, style: AppTheme.f(10, weight: FontWeight.w700, color: gc.textSecondary, letterSpacing: 0.4)),
+ const SizedBox(height: 3),
+ FitText(value, style: AppTheme.f(17, weight: FontWeight.w800, color: gc.text)),
+ ]),
+ ),
+ );
+ Widget line(IconData icon, String text) => Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Row(children: [
+ Icon(icon, size: 15, color: gc.textSecondary),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(text,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(13, weight: FontWeight.w600, color: gc.text, height: 1.3)),
+ ),
+ ]),
+ );
+ final food = r.food;
+ return Container(
+ padding: sheetPad(context),
+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.88),
+ decoration: sheetDecoration(gc),
+ child: SingleChildScrollView(
+ child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ const SheetHandle(),
+ const SizedBox(height: 16),
+ SheetTitle(t.reportTitle, subtitle: t.reportHint),
+ const SizedBox(height: 16),
+ Center(
+ child: SegToggle([
+ for (final d in _presets)
+ SegOption(_presetLabel(d), _preset == d, () {
+ HapticFeedback.selectionClick();
+ setState(() {
+ _preset = d;
+ _range = _last(d);
+ });
+ }),
+ SegOption(t.reportCustom, _preset == 0, _pickRange),
+ ]),
+ ),
+ const SizedBox(height: 14),
+ Semantics(
+ button: true,
+ label: t.reportPickRange,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: _pickRange,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Flexible(
+ child: Text(reportRangeLabel(r),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(17, weight: FontWeight.w800, color: gc.text)),
+ ),
+ const SizedBox(width: 8),
+ Icon(PhosphorIconsRegular.calendarBlank, size: 16, color: gc.textSecondary),
+ ]),
+ ),
+ ),
+ ),
+ const SizedBox(height: 12),
+ if (r.empty)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 18),
+ child: Text(t.reportEmpty,
+ textAlign: TextAlign.center, style: AppTheme.s(13, color: gc.textSecondary, height: 1.4)),
+ )
+ else ...[
+ Row(children: [
+ stat(t.reportWorkouts, '${r.sessions}'),
+ const SizedBox(width: 8),
+ stat(t.setsCaps, '${r.sets}'),
+ const SizedBox(width: 8),
+ stat(t.volume, fit.volumeLabel(r.volume)),
+ ]),
+ if (r.records.isNotEmpty) line(PhosphorIconsRegular.trophy, t.reportRecordsLine(r.records.length)),
+ if (r.lifts.isNotEmpty) line(PhosphorIconsRegular.barbell, t.reportLiftsLine(r.lifts.length)),
+ if (r.weightFrom != null && r.weightTo != null)
+ line(PhosphorIconsRegular.scales, '${fit.weightLabel(r.weightFrom!)} → ${fit.weightLabel(r.weightTo!)}'),
+ if (food != null)
+ line(PhosphorIconsRegular.forkKnife,
+ t.reportFoodLine('${fit.energyOf(food.kcal)} ${fit.energyUnit}', food.protein.round(), food.days)),
+ if (r.sleep != null || r.energy != null)
+ line(PhosphorIconsRegular.moon, [
+ if (r.sleep != null) '${t.checkInSleep} ${decimalText(r.sleep!.toStringAsFixed(1))}',
+ if (r.energy != null) '${t.checkInEnergy} ${decimalText(r.energy!.toStringAsFixed(1))}',
+ ].join(' · ')),
+ const SizedBox(height: 20),
+ AnimatedOpacity(
+ duration: const Duration(milliseconds: 160),
+ opacity: _busy ? 0.5 : 1,
+ child: PrimaryButton(label: t.reportSharePdf, height: 52, onTap: () => _share(pdf: true)),
+ ),
+ const SizedBox(height: 10),
+ GhostButton(
+ label: food != null && r.sessions > 0 ? t.reportShareCsvBoth : t.reportShareCsv,
+ icon: PhosphorIconsRegular.fileCsv,
+ onTap: () => _share(pdf: false),
+ ),
+ ],
+ const SizedBox(height: 4),
+ ]),
+ ),
+ );
+ }
+}
diff --git a/test/report_test.dart b/test/report_test.dart
new file mode 100644
index 0000000..d10e57d
--- /dev/null
+++ b/test/report_test.dart
@@ -0,0 +1,73 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:gymmane/models/workout.dart';
+import 'package:gymmane/services/local_store.dart';
+import 'package:gymmane/state/fit_state.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ final today = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);
+
+ setUp(() async {
+ SharedPreferences.setMockInitialValues({});
+ await Store.instance.init();
+ fit.resetAllData();
+ fit.setUnits('kg');
+ });
+
+ void log(int daysAgo, double kg, {int reps = 5}) {
+ fit.sessions.add(LoggedSession(
+ today.subtract(Duration(days: daysAgo)).add(const Duration(hours: 19)),
+ 3600,
+ [LoggedExercise('EIeI8Vf', 'Barbell Bench Press', 'chest', [LoggedSet(reps, kg), LoggedSet(reps, kg)])],
+ ));
+ fit.sessions.sort((a, b) => a.date.compareTo(b.date));
+ }
+
+ test('solo cuenta lo que cae dentro de las fechas', () {
+ log(40, 100);
+ log(10, 100);
+ log(3, 105);
+ final r = fit.rangeReport(today.subtract(const Duration(days: 13)), today);
+ expect(r.days, 14);
+ expect(r.sessions, 2);
+ expect(r.sets, 4);
+ expect(r.volume, closeTo(2 * 500 + 2 * 525, 0.01));
+ expect(r.minutes, 120);
+ expect(r.lifts.single.sessions, 2);
+ expect(r.lifts.single.change, greaterThan(0));
+ expect(r.prev, isNull, reason: 'los 14 días de antes están vacíos');
+ });
+
+ test('un récord es superar lo que ya tenías antes del informe', () {
+ log(40, 100);
+ log(3, 105);
+ final r = fit.rangeReport(today.subtract(const Duration(days: 6)), today);
+ expect(r.records.single.kg, 105);
+ final first = fit.rangeReport(today.subtract(const Duration(days: 60)), today);
+ expect(first.records, isEmpty, reason: 'sin historia previa no hay récord que batir');
+ });
+
+ test('el CSV del informe solo lleva sus días', () {
+ log(40, 100);
+ log(3, 105);
+ final r = fit.rangeReport(today.subtract(const Duration(days: 6)), today);
+ final csv = fit.reportWorkoutsCsv(r).trim().split('\n');
+ expect(csv, hasLength(3), reason: 'cabecera y las dos series del día 3');
+ expect(csv.skip(1).every((l) => l.contains(',105,')), true);
+ });
+
+ test('peso al principio y al final', () {
+ log(3, 100);
+ fit.bodyweight.addAll([
+ BodyweightEntry(today.subtract(const Duration(days: 5)), 82),
+ BodyweightEntry(today.subtract(const Duration(days: 1)), 81),
+ ]);
+ final r = fit.rangeReport(today.subtract(const Duration(days: 6)), today);
+ expect(r.weightFrom, 82);
+ expect(r.weightTo, 81);
+ expect(fit.rangeReport(today.subtract(const Duration(days: 100)), today.subtract(const Duration(days: 90))).empty,
+ true);
+ });
+}