merge upstream

This commit is contained in:
2026-11-16 13:42:34 +00:00
77 changed files with 8772 additions and 1571 deletions

View File

@@ -200,7 +200,7 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
);
return;
}
GoRouter.of(context).push(UserDiaryScreen.path, extra: {'diaryId': day.$2.id,});
GoRouter.of(context).push(UserDiaryScreen.path, extra: {'diaryId': day.$2.id, 'ownerSlug': widget.consultationsModel.userSlug});
},
borderRadius: BorderRadius.circular(100),
child: Ink(
@@ -283,7 +283,7 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
.where((e) => e.$2.state == DiaryStateEnum.finished || e.$2.state == DiaryStateEnum.lastDayFinished)
.lastOrNull;
if (lastActiveDay != null) {
GoRouter.of(context).push(UserDiaryScreen.path, extra: {'diaryId': lastActiveDay.$2.id,});
GoRouter.of(context).push(UserDiaryScreen.path, extra: {'diaryId': lastActiveDay.$2.id, 'ownerSlug': widget.consultationsModel.userSlug});
return;
}
showErrorDialog(

View File

@@ -17,6 +17,9 @@ abstract class DiaryDayEntity with _$DiaryDayEntity {
@JsonKey(name: "chosen_plan_id") required int? chosenPlanId,
@JsonKey(name: "day_of_chosen_diet") required int? dayOfChosenDiet,
@JsonKey(name: "chosen_diet", fromJson: parseDiet) required DiaryDietModel? diet,
/// Slug владельца дневника; `null`, если сервер его не вернул.
String? ownerSlug,
}) = _DiaryDayEntity;
const DiaryDayEntity._();

View File

@@ -48,6 +48,10 @@ abstract class DiaryDayModel with _$DiaryDayModel {
@JsonKey(name: "chosen_plan_id") required int? chosenPlanId,
@JsonKey(name: "day_of_chosen_diet") required int? dayOfChosenDiet,
@JsonKey(name: "chosen_diet", fromJson: parseDiet) required DiaryDietModel? diet,
/// Владелец дневника (`user` в `DiaryResource`): по `slug` консультант
/// запрашивает `/api/profile/insights/{slug}`.
@JsonKey(name: "user") DiaryOwnerModel? owner,
}) = _DiaryDayModel;
const DiaryDayModel._();
factory DiaryDayModel.fromJson(Map<String, dynamic> json) => _$DiaryDayModelFromJson(json);
@@ -68,6 +72,7 @@ abstract class DiaryDayModel with _$DiaryDayModel {
wakeup: wakeup,
retire: retire,
diet: diet,
ownerSlug: owner?.slug,
);
}
@@ -81,6 +86,13 @@ DiaryDietModel? parseDiet(dynamic json) {
return DiaryDietModel.fromJson(json['diet']);
}
@freezed
abstract class DiaryOwnerModel with _$DiaryOwnerModel {
const factory DiaryOwnerModel({int? id, String? slug}) = _DiaryOwnerModel;
factory DiaryOwnerModel.fromJson(Map<String, dynamic> json) => _$DiaryOwnerModelFromJson(json);
}
@freezed
abstract class DiaryDietModel with _$DiaryDietModel {
const factory DiaryDietModel({required int id, required int duration, required String name}) = _DiaryDietModel;

View File

@@ -20,7 +20,9 @@ import 'package:eatvio_app/features/diary/presentation/widgets/day_comment_widge
import 'package:eatvio_app/features/diary/presentation/widgets/finish_day_button_widget.dart';
import 'package:eatvio_app/features/diary/presentation/widgets/meal_widget.dart';
import 'package:eatvio_app/features/diary/presentation/widgets/wakeup_and_retire_widget.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -36,18 +38,27 @@ class DiaryScreen extends StatelessWidget {
class UserDiaryScreen extends StatelessWidget {
static const path = '/user-diary-screen';
static const name = 'userDiaryScreen';
const UserDiaryScreen({super.key, required this.diaryId});
const UserDiaryScreen({super.key, required this.diaryId, this.ownerSlug});
final int diaryId;
/// Slug владельца дневника (клиента) — нужен консультанту для блока «Аналитика».
final String? ownerSlug;
@override
Widget build(BuildContext context) {
return DiaryScreenContent(diaryId: diaryId);
return DiaryScreenContent(diaryId: diaryId, ownerSlug: ownerSlug);
}
}
class DiaryScreenContent extends StatefulWidget {
const DiaryScreenContent({super.key, this.diaryId, this.date});
const DiaryScreenContent({
super.key,
this.diaryId,
this.date,
this.ownerSlug,
});
final int? diaryId;
final DateTime? date;
final String? ownerSlug;
@override
State<DiaryScreenContent> createState() => _DiaryScreenContentState();
}
@@ -55,6 +66,16 @@ class DiaryScreenContent extends StatefulWidget {
class _DiaryScreenContentState extends State<DiaryScreenContent> {
bool _isDiaryFinishing = false;
/// Slug владельца: из `user.slug` дневника, иначе из параметра экрана.
String? _ownerSlug(DiaryStateLoaded state) {
return state.diary.ownerSlug ?? widget.ownerSlug;
}
/// Консультант видит аналитику клиента только при известном slug владельца.
bool _canShowInsights(DiaryStateLoaded state) {
return !state.isConsultantView || _ownerSlug(state) != null;
}
@override
Widget build(BuildContext context) {
final s = S.of(context);
@@ -110,6 +131,15 @@ class _DiaryScreenContentState extends State<DiaryScreenContent> {
const SizedBox(height: 60),
const Loader(),
],
if (state is DiaryStateLoaded && _canShowInsights(state))
Padding(
padding: const EdgeInsets.fromLTRB(4, 12, 4, 12),
child: _DiaryInsights(
slug: state.isConsultantView ? _ownerSlug(state) : null,
canAdd: !state.isConsultantView,
diaryDate: state.diary.date,
),
),
if (state is DiaryStateLoaded)
WakeupAndRetireWidget(
isEnabled:
@@ -249,3 +279,53 @@ class _DiaryScreenContentState extends State<DiaryScreenContent> {
);
}
}
/// Блок «Аналитика» в дневнике. Для своего дневника перезапрашивает данные,
/// когда в том же дне меняются приёмы пищи или время подъёма/отбоя: от них
/// зависят КБЖУ-графики. Чужой дневник консультант не редактирует.
class _DiaryInsights extends StatefulWidget {
const _DiaryInsights({
required this.slug,
required this.canAdd,
required this.diaryDate,
});
final String? slug;
final bool canAdd;
/// Дата открытого дня дневника (`YYYY-MM-DD`) — стартовый день «В течение дня».
final String diaryDate;
@override
State<_DiaryInsights> createState() => _DiaryInsightsState();
}
class _DiaryInsightsState extends State<_DiaryInsights> {
int _refreshToken = 0;
bool _isOwnDiaryMutation(DiaryState previous, DiaryState current) {
if (!widget.canAdd ||
previous is! DiaryStateLoaded ||
current is! DiaryStateLoaded ||
previous.diary.id != current.diary.id) {
return false;
}
return !listEquals(previous.diary.meals, current.diary.meals) ||
previous.diary.wakeup != current.diary.wakeup ||
previous.diary.retire != current.diary.retire;
}
@override
Widget build(BuildContext context) {
return BlocListener<DiaryCubit, DiaryState>(
listenWhen: _isOwnDiaryMutation,
listener: (context, state) => setState(() => _refreshToken++),
child: InsightsCard(
slug: widget.slug,
canAdd: widget.canAdd,
refreshToken: _refreshToken,
initialIntraDate: widget.diaryDate,
),
);
}
}

View File

@@ -0,0 +1,222 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/models/insights_period.dart';
import 'package:eatvio_app/features/profile/models/circumference_model.dart';
import 'package:eatvio_app/features/profile/models/weight_model.dart';
import 'package:eatvio_app/generated/l10n.dart';
/// Собирает [InsightsPayloadModel] из сырых точек мобильного API.
///
/// Зеркало веб-`UserInsightsService`: порог изменения [deltaEpsilon], минимум две
/// точки для дельты, те же категории ИМТ и формат подписей.
class InsightsTextBuilder {
InsightsTextBuilder(this.s);
final S s;
static const double deltaEpsilon = 0.05;
static const String _emptyHeadline = '—';
InsightsPayloadModel build({
required List<WeightModel> weights,
required List<CircumferenceModel> circumferences,
required BodyPeriod period,
int? heightCm,
}) {
final sortedWeights = [...weights]
..sort((a, b) => a.createdAt.compareTo(b.createdAt));
final sortedCircumferences = [...circumferences]
..sort((a, b) => a.createdAt.compareTo(b.createdAt));
return InsightsPayloadModel(
weight: buildWeight(sortedWeights, period),
bmi: buildBmi(sortedWeights, period, heightCm),
measure: buildMeasure(sortedCircumferences, period),
);
}
WeightChartModel buildWeight(List<WeightModel> weights, BodyPeriod period) {
final values = weights.map((e) => e.weight).toList();
final last = values.isEmpty ? null : values.last;
final delta = values.length < 2 ? null : _round(values.last - values.first);
return WeightChartModel(
labels: weights.map((e) => formatLabel(e.createdAt)).toList(),
values: values,
last: last,
delta: delta,
headline: last == null ? _emptyHeadline : last.toStringAsFixed(1),
unit: s.insights_unit_kg,
deltaText: _weightDeltaText(values, period),
);
}
BmiChartModel buildBmi(
List<WeightModel> weights,
BodyPeriod period,
int? heightCm,
) {
final hasHeight = heightCm != null && heightCm > 0;
if (!hasHeight) {
return BmiChartModel(
headline: _emptyHeadline,
deltaText: s.insights_need_height,
hint: s.insights_need_height,
);
}
final points = weights.where((e) => e.bmi != null).toList();
final values = points.map((e) => e.bmi!).toList();
final last = values.isEmpty ? null : values.last;
final delta = values.length < 2 ? null : _round(values.last - values.first);
final category = last == null ? null : bmiCategory(last);
return BmiChartModel(
labels: points.map((e) => formatLabel(e.createdAt)).toList(),
values: values,
last: last,
delta: delta,
headline: last == null ? _emptyHeadline : last.toStringAsFixed(1),
category: category,
deltaText: _bmiDeltaText(values, period, category),
hint: s.insights_bmi_hint(heightCm.toString()),
);
}
MeasureChartModel buildMeasure(
List<CircumferenceModel> circumferences,
BodyPeriod period,
) {
final waist = circumferences.map((e) => e.waistCircumference).toList();
final chest = circumferences.map((e) => e.chestCircumference).toList();
final hips = circumferences.map((e) => e.hipCircumference).toList();
return MeasureChartModel(
labels: circumferences.map((e) => formatLabel(e.createdAt)).toList(),
waist: waist,
chest: chest,
hips: hips,
headline: waist.isEmpty ? _emptyHeadline : waist.last.round().toString(),
deltaText: _measureDeltaText(
waist: waist,
chest: chest,
hips: hips,
period: period,
),
);
}
/// Категория по таблице ВОЗ из постановки #2120.
String bmiCategory(double bmi) {
if (bmi < 16) {
return s.insights_bmi_severe_underweight;
}
if (bmi < 18.5) {
return s.insights_bmi_underweight;
}
if (bmi < 25) {
return s.insights_bmi_normal;
}
if (bmi < 30) {
return s.insights_bmi_overweight;
}
if (bmi < 35) {
return s.insights_bmi_obesity_1;
}
if (bmi < 40) {
return s.insights_bmi_obesity_2;
}
return s.insights_bmi_obesity_3;
}
String periodLabel(BodyPeriod period) {
switch (period) {
case BodyPeriod.month:
return s.insights_period_label_1;
case BodyPeriod.threeMonths:
return s.insights_period_label_3;
case BodyPeriod.sixMonths:
return s.insights_period_label_6;
case BodyPeriod.year:
return s.insights_period_label_12;
case BodyPeriod.all:
return s.insights_period_label_all;
}
}
String formatLabel(DateTime date) {
final local = date.toLocal();
final day = local.day.toString().padLeft(2, '0');
final month = local.month.toString().padLeft(2, '0');
return '$day.$month';
}
/// Одна цифра после запятой без хвостового нуля: `3`, `3.5`.
String formatNumber(double value) {
final text = value.toStringAsFixed(1);
return text.endsWith('.0') ? text.substring(0, text.length - 2) : text;
}
String _weightDeltaText(List<double> values, BodyPeriod period) {
if (values.length < 2) {
return s.insights_not_enough;
}
final diff = values.last - values.first;
final periodText = periodLabel(period);
if (diff.abs() < deltaEpsilon) {
return s.insights_weight_same(periodText);
}
final value = formatNumber(diff.abs());
return diff < 0
? s.insights_weight_lost(value, periodText)
: s.insights_weight_gained(value, periodText);
}
String _bmiDeltaText(
List<double> values,
BodyPeriod period,
String? category,
) {
if (values.length < 2 || category == null) {
return s.insights_not_enough;
}
final diff = values.last - values.first;
final periodText = periodLabel(period);
if (diff.abs() < deltaEpsilon) {
return s.insights_bmi_same(periodText, category);
}
final value = formatNumber(diff.abs());
return diff < 0
? s.insights_bmi_lower(value, periodText, category)
: s.insights_bmi_higher(value, periodText, category);
}
String _measureDeltaText({
required List<double> waist,
required List<double> chest,
required List<double> hips,
required BodyPeriod period,
}) {
if (waist.length < 2) {
return s.insights_not_enough;
}
final parts = [
_measurePart(s.insights_series_waist, waist),
_measurePart(s.insights_series_chest, chest),
_measurePart(s.insights_series_hips, hips),
];
return s.insights_measures_summary(parts.join(', '), periodLabel(period));
}
String _measurePart(String name, List<double> values) {
final diff = values.last - values.first;
if (diff.abs() < deltaEpsilon) {
return s.insights_measure_same(name);
}
final value = formatNumber(diff.abs());
return diff < 0
? s.insights_measure_less(name, value)
: s.insights_measure_more(name, value);
}
double _round(double value) => (value * 10).round() / 10;
}

View File

@@ -0,0 +1,8 @@
/// Флаги поэтапного включения аналитики.
abstract final class InsightsFeatureFlags {
/// Вкладки «КБЖУ по дням» и «В течение дня». При `true` весь блок берёт
/// данные и тексты с сервера (`GET /api/profile/insights*`, eatvio/eatvio#3017),
/// при `false` — вкладки скрыты, а вес/ИМТ/замеры собираются на клиенте из
/// `/api/profile/measure/*`.
static const bool kbjuEnabled = true;
}

View File

@@ -0,0 +1,132 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'insights_payload_model.freezed.dart';
part 'insights_payload_model.g.dart';
/// Структура повторяет веб-`UserInsightsService::chartPayload()`, чтобы во второй
/// итерации заменить только источник данных.
@freezed
abstract class InsightsPayloadModel with _$InsightsPayloadModel {
const factory InsightsPayloadModel({
required WeightChartModel weight,
required BmiChartModel bmi,
required MeasureChartModel measure,
DailyChartModel? daily,
IntraChartModel? intra,
}) = _InsightsPayloadModel;
factory InsightsPayloadModel.fromJson(Map<String, dynamic> json) =>
_$InsightsPayloadModelFromJson(json);
}
@freezed
abstract class WeightChartModel with _$WeightChartModel {
const factory WeightChartModel({
@Default([]) List<String> labels,
@Default([]) List<double> values,
double? last,
double? delta,
@Default('') String headline,
@Default('') String unit,
@Default('') String deltaText,
}) = _WeightChartModel;
factory WeightChartModel.fromJson(Map<String, dynamic> json) =>
_$WeightChartModelFromJson(json);
}
@freezed
abstract class BmiChartModel with _$BmiChartModel {
const factory BmiChartModel({
@Default([]) List<String> labels,
@Default([]) List<double> values,
double? last,
double? delta,
@Default('') String headline,
String? category,
@Default('') String deltaText,
@Default('') String hint,
}) = _BmiChartModel;
factory BmiChartModel.fromJson(Map<String, dynamic> json) =>
_$BmiChartModelFromJson(json);
}
@freezed
abstract class MeasureChartModel with _$MeasureChartModel {
const factory MeasureChartModel({
@Default([]) List<String> labels,
@Default([]) List<double> waist,
@Default([]) List<double> chest,
@Default([]) List<double> hips,
@Default('') String headline,
@Default('') String deltaText,
}) = _MeasureChartModel;
factory MeasureChartModel.fromJson(Map<String, dynamic> json) =>
_$MeasureChartModelFromJson(json);
}
@freezed
abstract class DailyChartModel with _$DailyChartModel {
const factory DailyChartModel({
@Default([]) List<String> labels,
@Default([]) List<double> kcal,
@Default([]) List<double> proteins,
@Default([]) List<double> fats,
@Default([]) List<double> carbs,
double? average,
double? percent,
@Default('') String headline,
@Default('') String deltaText,
}) = _DailyChartModel;
factory DailyChartModel.fromJson(Map<String, dynamic> json) =>
_$DailyChartModelFromJson(json);
}
@freezed
abstract class IntraChartModel with _$IntraChartModel {
const factory IntraChartModel({
@Default([]) List<IntraBarModel> bars,
@Default([]) List<ScalePointModel> satiety,
@Default([]) List<ScalePointModel> mood,
double? wake,
double? sleep,
String? wakeLabel,
String? sleepLabel,
String? wakeText,
String? sleepText,
@Default('') String date,
@Default('') String maxDate,
@Default('') String dateLabel,
@Default(false) bool isToday,
}) = _IntraChartModel;
factory IntraChartModel.fromJson(Map<String, dynamic> json) =>
_$IntraChartModelFromJson(json);
}
/// Приём пищи: время `x` (часы 0–24) и калории из белков/жиров/углеводов.
@freezed
abstract class IntraBarModel with _$IntraBarModel {
const factory IntraBarModel({
required double x,
@Default(0) double p,
@Default(0) double f,
@Default(0) double c,
}) = _IntraBarModel;
factory IntraBarModel.fromJson(Map<String, dynamic> json) =>
_$IntraBarModelFromJson(json);
}
/// Точка шкалы 0–5 (сытость/настроение) в момент времени `x`.
@freezed
abstract class ScalePointModel with _$ScalePointModel {
const factory ScalePointModel({required double x, required double y}) =
_ScalePointModel;
factory ScalePointModel.fromJson(Map<String, dynamic> json) =>
_$ScalePointModelFromJson(json);
}

View File

@@ -0,0 +1,46 @@
import 'package:eatvio_app/generated/l10n.dart';
/// Период для вкладок «Вес», «ИМТ» и «Замеры». Значение совпадает с `{period}` в
/// `/api/profile/measure/weight/{period}`.
enum BodyPeriod {
month('1'),
threeMonths('3'),
sixMonths('6'),
year('12'),
all('all');
const BodyPeriod(this.apiValue);
final String apiValue;
/// Подпись пилюли периода.
String pillLabel(S s) => switch (this) {
month => s.insights_period_1m,
threeMonths => s.insights_period_3m,
sixMonths => s.insights_period_6m,
year => s.insights_period_1y,
all => s.insights_period_all,
};
}
/// Период для вкладки «КБЖУ по дням». Значение совпадает с `daily_period` в `/api/profile/insights`.
enum DailyPeriod {
week('7'),
twoWeeks('14'),
month('30'),
threeMonths('90'),
all('all');
const DailyPeriod(this.apiValue);
final String apiValue;
/// Подпись пилюли периода.
String pillLabel(S s) => switch (this) {
week => s.insights_period_1w,
twoWeeks => s.insights_period_2w,
month => s.insights_period_1m,
threeMonths => s.insights_period_3m,
all => s.insights_period_all,
};
}

View File

@@ -0,0 +1,36 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'insights_response_model.freezed.dart';
part 'insights_response_model.g.dart';
/// Ответ `GET /api/profile/insights[/{slug}]`: `{ "data": { weight, bmi, measure, daily, intra } }`.
@freezed
abstract class InsightsResponseModel with _$InsightsResponseModel {
const factory InsightsResponseModel({required InsightsPayloadModel data}) =
_InsightsResponseModel;
factory InsightsResponseModel.fromJson(Map<String, dynamic> json) =>
_$InsightsResponseModelFromJson(json);
}
/// Ответ `GET /api/profile/insights/intra` и `/insights/{slug}/intra`:
/// `{ "data": { "intra": { ... } } }`.
@freezed
abstract class InsightsIntraResponseModel with _$InsightsIntraResponseModel {
const factory InsightsIntraResponseModel({
required InsightsIntraDataModel data,
}) = _InsightsIntraResponseModel;
factory InsightsIntraResponseModel.fromJson(Map<String, dynamic> json) =>
_$InsightsIntraResponseModelFromJson(json);
}
@freezed
abstract class InsightsIntraDataModel with _$InsightsIntraDataModel {
const factory InsightsIntraDataModel({required IntraChartModel intra}) =
_InsightsIntraDataModel;
factory InsightsIntraDataModel.fromJson(Map<String, dynamic> json) =>
_$InsightsIntraDataModelFromJson(json);
}

View File

@@ -0,0 +1,91 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
/// График ИМТ с цветными зонами: норма 18.5–25, избыточная масса 25–30, ожирение 30–40.
class BmiChart extends StatelessWidget {
const BmiChart({super.key, required this.model});
final BmiChartModel model;
@override
Widget build(BuildContext context) {
final points = buildPoints(model.labels, model.values);
if (points.isEmpty) {
return InsightsChartPlaceholder(text: model.deltaText);
}
final s = S.of(context);
final dataRange = paddedRange(points.map((e) => e.value), minPadding: 2);
// Ось всегда покрывает зоны нормы/избытка/ожирения, иначе при ИМТ ≈30
// зелёная полоса 18.5–25 уезжает за нижний край графика.
const zoneMin = 18.5;
const zoneMax = 40.0;
final min = dataRange.min < zoneMin ? dataRange.min : zoneMin;
final max = dataRange.max > zoneMax ? dataRange.max : zoneMax;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: insightsChartHeight,
child: SfCartesianChart(
key: const Key('insights_bmi_chart'),
margin: insightsChartMargin,
plotAreaBorderWidth: 0,
primaryXAxis: buildInsightsIndexAxis(model.labels),
primaryYAxis: buildInsightsValueAxis(
unit: s.insights_unit_bmi,
min: min,
max: max,
plotBands: const [
PlotBand(
start: 18.5,
end: 25,
color: InsightsColors.bmiNormalZone,
),
PlotBand(
start: 25,
end: 30,
color: InsightsColors.bmiOverweightZone,
),
PlotBand(
start: 30,
end: 40,
color: InsightsColors.bmiObesityZone,
),
],
),
trackballBehavior: buildInsightsTrackball(),
series: <CartesianSeries<InsightsPoint, num>>[
SplineAreaSeries<InsightsPoint, num>(
name: s.insights_tab_bmi,
dataSource: points,
xValueMapper: (point, _) => point.index,
yValueMapper: (point, _) => point.value,
splineType: insightsSplineType,
borderColor: InsightsColors.blue,
borderWidth: 3,
gradient: buildInsightsAreaGradient(InsightsColors.blue),
markerSettings: buildInsightsMarker(InsightsColors.blue),
),
],
),
),
if (model.hint.isNotEmpty) ...[
const SizedBox(height: 8),
Text(
model.hint,
key: const Key('insights_bmi_hint'),
style: const TextStyle(
fontSize: 13,
color: InsightsColors.subtitle,
),
),
],
],
);
}
}

View File

@@ -0,0 +1,135 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
/// КБЖУ по дням: калории — площадь на левой оси («ккал»), Б/Ж/У — линии на
/// правой оси («граммы»). [visibility] — Калории, Белки, Жиры, Углеводы.
class DailyKbjuChart extends StatelessWidget {
const DailyKbjuChart({
super.key,
required this.model,
required this.visibility,
});
final DailyChartModel model;
final List<bool> visibility;
static const String _gramsAxisName = 'grams';
@override
Widget build(BuildContext context) {
final s = S.of(context);
final calories = buildPoints(model.labels, model.kcal);
if (calories.isEmpty) {
return InsightsChartPlaceholder(text: s.insights_not_enough);
}
final proteins = buildPoints(model.labels, model.proteins);
final fats = buildPoints(model.labels, model.fats);
final carbs = buildPoints(model.labels, model.carbs);
// Локальный диапазон по данным (как на вебе), не ось от нуля.
// Кривую ниже точек держит insightsSplineType (monotonic).
final kcalRange = paddedRange(
calories.map((e) => e.value),
minPadding: 50,
clampZero: true,
);
final gramValues = [
...proteins.map((e) => e.value),
...fats.map((e) => e.value),
...carbs.map((e) => e.value),
];
final gramsRange = paddedRange(
gramValues,
minPadding: 5,
clampZero: true,
);
final grams = [
(
name: s.insights_series_proteins,
color: InsightsColors.proteins,
points: proteins,
),
(name: s.insights_series_fats, color: InsightsColors.fats, points: fats),
(
name: s.insights_series_carbs,
color: InsightsColors.carbs,
points: carbs,
),
];
return SizedBox(
height: insightsChartHeight,
child: SfCartesianChart(
key: const Key('insights_daily_chart'),
margin: insightsChartMargin,
plotAreaBorderWidth: 0,
primaryXAxis: buildInsightsIndexAxis(model.labels),
primaryYAxis: NumericAxis(
title: AxisTitle(
text: s.insights_unit_kcal,
textStyle: insightsAxisLabelStyle,
),
labelStyle: insightsAxisLabelStyle,
minimum: kcalRange.min,
maximum: kcalRange.max,
majorTickLines: const MajorTickLines(size: 0),
axisLine: const AxisLine(width: 0),
majorGridLines: MajorGridLines(
color: InsightsColors.border.withValues(alpha: 0.8),
dashArray: const [4, 4],
),
),
axes: <ChartAxis>[
NumericAxis(
name: _gramsAxisName,
opposedPosition: true,
minimum: gramsRange.min,
maximum: gramsRange.max,
title: AxisTitle(
text: s.insights_unit_grams,
textStyle: insightsAxisLabelStyle,
),
labelStyle: insightsAxisLabelStyle,
majorTickLines: const MajorTickLines(size: 0),
axisLine: const AxisLine(width: 0),
majorGridLines: const MajorGridLines(width: 0),
),
],
trackballBehavior: buildInsightsTrackball(),
series: <CartesianSeries<InsightsPoint, num>>[
if (_isVisible(0))
SplineAreaSeries<InsightsPoint, num>(
name: s.insights_series_calories,
dataSource: calories,
xValueMapper: (point, _) => point.index,
yValueMapper: (point, _) => point.value,
splineType: insightsSplineType,
borderColor: InsightsColors.calories,
borderWidth: 3,
gradient: buildInsightsAreaGradient(InsightsColors.calories),
),
for (var i = 0; i < grams.length; i++)
if (_isVisible(i + 1))
SplineSeries<InsightsPoint, num>(
name: grams[i].name,
yAxisName: _gramsAxisName,
dataSource: grams[i].points,
xValueMapper: (point, _) => point.index,
yValueMapper: (point, _) => point.value,
splineType: insightsSplineType,
color: grams[i].color,
width: 2.5,
),
],
),
);
}
bool _isVisible(int index) =>
index < visibility.length ? visibility[index] : true;
}

View File

@@ -0,0 +1,180 @@
import 'dart:math' as math;
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
/// Точка графика: индекс по оси X (как у Chart.js), подпись `dd.MM` и значение.
///
/// Индекс обязателен: Syncfusion `CategoryAxis` склеивает одинаковые строки
/// (`05.07` несколько раз → одна категория). На вебе labels идут по индексу,
/// поэтому здесь X = index, а дата рисуется через [axisLabelFormatter].
class InsightsPoint {
const InsightsPoint({
required this.index,
required this.label,
required this.value,
});
final int index;
final String label;
final double value;
}
/// Склеивает `labels[]` и `values[]` (по минимальной длине).
List<InsightsPoint> buildPoints(List<String> labels, List<double> values) {
final count = math.min(labels.length, values.length);
return [
for (var i = 0; i < count; i++)
InsightsPoint(index: i, label: labels[i], value: values[i]),
];
}
/// Локальный диапазон оси Y вокруг данных (не от нуля), с запасом под сплайн.
///
/// [clampZero] — не уводить минимум в минус на осях КБЖУ (ккал/граммы ≥ 0).
({double min, double max}) paddedRange(
Iterable<double> values, {
double minPadding = 1,
bool clampZero = false,
}) {
if (values.isEmpty) {
return (min: 0, max: 1);
}
final lowest = values.reduce(math.min);
final highest = values.reduce(math.max);
final padding = math.max((highest - lowest) * 0.2, minPadding);
var min = lowest - padding;
var max = highest + padding;
if (clampZero) {
min = math.max(0, min);
}
if (max <= min) {
max = min + minPadding;
}
return (min: min, max: max);
}
const SplineType insightsSplineType = SplineType.monotonic;
const TextStyle insightsAxisLabelStyle = TextStyle(
fontSize: 11,
color: InsightsColors.subtitle,
);
/// Ось X по индексу точки; подпись — дата из [labels].
///
/// Так даты `05.07`, `06.07`, … не схлопываются и не размножаются, когда на
/// графике несколько серий с одним и тем же набором labels (КБЖУ, замеры).
NumericAxis buildInsightsIndexAxis(List<String> labels) {
final lastIndex = math.max(labels.length - 1, 0).toDouble();
// На узком экране не подписываем каждую точку: ~6 подписей, как авто-тики Chart.js.
final interval = labels.length <= 7
? 1.0
: (labels.length / 6).ceilToDouble();
return NumericAxis(
minimum: 0,
maximum: lastIndex,
interval: interval,
labelStyle: insightsAxisLabelStyle,
majorGridLines: const MajorGridLines(width: 0),
majorTickLines: const MajorTickLines(size: 0),
axisLine: const AxisLine(color: InsightsColors.border, width: 1),
edgeLabelPlacement: EdgeLabelPlacement.shift,
axisLabelFormatter: (details) {
final index = details.value.round();
if (index < 0 || index >= labels.length) {
return ChartAxisLabel('', details.textStyle);
}
// Промежуточные дробные тики (если Syncfusion их поставит) не подписываем.
if ((details.value - index).abs() > 0.01) {
return ChartAxisLabel('', details.textStyle);
}
return ChartAxisLabel(labels[index], insightsAxisLabelStyle);
},
);
}
NumericAxis buildInsightsValueAxis({
required String unit,
required double min,
required double max,
List<PlotBand> plotBands = const [],
}) {
return NumericAxis(
minimum: min,
maximum: max,
// Доп. воздух, чтобы сплайн не врезался в край plot area.
rangePadding: ChartRangePadding.additional,
labelFormat: '{value} $unit',
labelStyle: insightsAxisLabelStyle,
majorTickLines: const MajorTickLines(size: 0),
axisLine: const AxisLine(width: 0),
majorGridLines: MajorGridLines(
color: InsightsColors.border.withValues(alpha: 0.8),
dashArray: const [4, 4],
),
plotBands: plotBands,
);
}
/// Небольшой внутренний отступ, чтобы кривая и подписи не резались контейнером.
const EdgeInsets insightsChartMargin = EdgeInsets.fromLTRB(0, 8, 0, 4);
TrackballBehavior buildInsightsTrackball() {
return TrackballBehavior(
enable: true,
activationMode: ActivationMode.singleTap,
tooltipDisplayMode: TrackballDisplayMode.groupAllPoints,
lineType: TrackballLineType.vertical,
tooltipSettings: const InteractiveTooltip(),
);
}
MarkerSettings buildInsightsMarker(Color color) {
return MarkerSettings(
isVisible: true,
width: 4,
height: 4,
color: Colors.white,
borderColor: color,
borderWidth: 2,
);
}
LinearGradient buildInsightsAreaGradient(Color color) {
return LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [color.withValues(alpha: 0.18), color.withValues(alpha: 0)],
);
}
/// Пустое состояние графика (нет данных).
class InsightsChartPlaceholder extends StatelessWidget {
const InsightsChartPlaceholder({super.key, required this.text});
final String text;
@override
Widget build(BuildContext context) {
return SizedBox(
height: insightsChartHeight,
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 14,
color: InsightsColors.subtitle,
),
),
),
),
);
}
}

View File

@@ -0,0 +1,214 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
/// График «В течение дня»: столбики Б/Ж/У (ккал) по приёмам пищи на оси 0–24 ч,
/// линии сытости и настроения (шкала 0–5) и затемнение времени сна.
///
/// [visibility] — Белки, Жиры, Углеводы, Сытость, Настроение.
class IntraDayChart extends StatelessWidget {
const IntraDayChart({
super.key,
required this.model,
required this.visibility,
required this.showSleep,
});
final IntraChartModel model;
final List<bool> visibility;
final bool showSleep;
static const String _scaleAxisName = 'scale';
static const double _barWidthPx = 26;
static const double _axesReservedWidthPx = 80;
@override
Widget build(BuildContext context) {
final s = S.of(context);
if (model.bars.isEmpty &&
model.satiety.isEmpty &&
model.mood.isEmpty &&
model.wake == null &&
model.sleep == null) {
return InsightsChartPlaceholder(text: s.insights_not_enough);
}
return SizedBox(
height: insightsChartHeight,
child: LayoutBuilder(
builder: (context, constraints) {
final plotWidth = (constraints.maxWidth - _axesReservedWidthPx).clamp(
120.0,
double.infinity,
);
final barFraction = (_barWidthPx / (plotWidth / 24)).clamp(0.1, 1.0);
return SfCartesianChart(
key: const Key('insights_intra_chart'),
margin: insightsChartMargin,
plotAreaBorderWidth: 0,
primaryXAxis: NumericAxis(
minimum: 0,
maximum: 24,
interval: 2,
labelStyle: insightsAxisLabelStyle,
majorGridLines: const MajorGridLines(width: 0),
majorTickLines: const MajorTickLines(size: 0),
axisLine: const AxisLine(color: InsightsColors.border, width: 1),
axisLabelFormatter: (details) => ChartAxisLabel(
'${details.value.toInt().toString().padLeft(2, '0')}:00',
details.textStyle,
),
plotBands: _sleepBands(),
),
primaryYAxis: NumericAxis(
minimum: 0,
title: AxisTitle(
text: s.insights_unit_kcal_per_meal,
textStyle: insightsAxisLabelStyle,
),
labelStyle: insightsAxisLabelStyle,
majorTickLines: const MajorTickLines(size: 0),
axisLine: const AxisLine(width: 0),
majorGridLines: MajorGridLines(
color: InsightsColors.border.withValues(alpha: 0.8),
dashArray: const [4, 4],
),
),
axes: const <ChartAxis>[
NumericAxis(
name: _scaleAxisName,
opposedPosition: true,
minimum: 0,
maximum: 5,
interval: 1,
labelStyle: insightsAxisLabelStyle,
majorTickLines: MajorTickLines(size: 0),
axisLine: AxisLine(width: 0),
majorGridLines: MajorGridLines(width: 0),
),
],
trackballBehavior: buildInsightsTrackball(),
series: <CartesianSeries<dynamic, double>>[
if (_isVisible(0))
_barSeries(
s.insights_series_proteins,
InsightsColors.proteins,
(bar) => bar.p,
barFraction,
),
if (_isVisible(1))
_barSeries(
s.insights_series_fats,
InsightsColors.fats,
(bar) => bar.f,
barFraction,
),
if (_isVisible(2))
_barSeries(
s.insights_series_carbs,
InsightsColors.carbs,
(bar) => bar.c,
barFraction,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(6),
),
),
if (_isVisible(3) && model.satiety.isNotEmpty)
_scaleSeries(
s.insights_series_satiety,
InsightsColors.satiety,
model.satiety,
),
if (_isVisible(4) && model.mood.isNotEmpty)
_scaleSeries(
s.insights_series_mood,
InsightsColors.mood,
model.mood,
),
],
);
},
),
);
}
bool _isVisible(int index) =>
index < visibility.length ? visibility[index] : true;
CartesianSeries<IntraBarModel, double> _barSeries(
String name,
Color color,
double Function(IntraBarModel bar) valueOf,
double widthFraction, {
BorderRadius borderRadius = BorderRadius.zero,
}) {
return StackedColumnSeries<IntraBarModel, double>(
name: name,
dataSource: model.bars,
xValueMapper: (bar, _) => bar.x,
yValueMapper: (bar, _) => valueOf(bar),
color: color,
width: widthFraction,
spacing: 0,
borderRadius: borderRadius,
);
}
CartesianSeries<ScalePointModel, double> _scaleSeries(
String name,
Color color,
List<ScalePointModel> points,
) {
return SplineSeries<ScalePointModel, double>(
name: name,
yAxisName: _scaleAxisName,
dataSource: points,
xValueMapper: (point, _) => point.x,
yValueMapper: (point, _) => point.y,
splineType: insightsSplineType,
color: color,
width: 2.5,
markerSettings: MarkerSettings(
isVisible: true,
width: 3,
height: 3,
color: color,
borderColor: color,
),
);
}
/// Затемнение `[0, wake]` и `[sleep, 24]` плюс пунктиры подъёма и отхода ко сну.
List<PlotBand> _sleepBands() {
if (!showSleep) {
return const [];
}
final wake = model.wake;
final sleep = model.sleep;
return [
if (wake != null && wake > 0)
PlotBand(start: 0, end: wake, color: InsightsColors.sleepShade),
if (sleep != null && sleep < 24 && (wake == null || sleep > wake))
PlotBand(start: sleep, end: 24, color: InsightsColors.sleepShade),
if (wake != null)
PlotBand(
start: wake,
end: wake,
borderColor: InsightsColors.wake,
borderWidth: 1.5,
dashArray: const [5, 4],
),
if (sleep != null)
PlotBand(
start: sleep,
end: sleep,
borderColor: InsightsColors.sleepLine,
borderWidth: 1.5,
dashArray: const [5, 4],
),
];
}
}

View File

@@ -0,0 +1,87 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
/// Три линии: талия, грудь, бёдра. [visibility] — видимость серий в этом порядке.
class MeasureChart extends StatelessWidget {
const MeasureChart({
super.key,
required this.model,
required this.visibility,
required this.emptyText,
});
final MeasureChartModel model;
final List<bool> visibility;
final String emptyText;
@override
Widget build(BuildContext context) {
final waist = buildPoints(model.labels, model.waist);
final chest = buildPoints(model.labels, model.chest);
final hips = buildPoints(model.labels, model.hips);
if (waist.isEmpty && chest.isEmpty && hips.isEmpty) {
return InsightsChartPlaceholder(text: emptyText);
}
final s = S.of(context);
final series = [
(
name: s.insights_series_waist,
color: InsightsColors.waist,
points: waist,
),
(
name: s.insights_series_chest,
color: InsightsColors.chest,
points: chest,
),
(name: s.insights_series_hips, color: InsightsColors.hips, points: hips),
];
final visibleValues = <double>[
for (var i = 0; i < series.length; i++)
if (_isVisible(i)) ...series[i].points.map((e) => e.value),
];
final range = paddedRange(
visibleValues.isEmpty
? series.expand((e) => e.points).map((e) => e.value)
: visibleValues,
minPadding: 2,
);
return SizedBox(
height: insightsChartHeight,
child: SfCartesianChart(
key: const Key('insights_measure_chart'),
margin: insightsChartMargin,
plotAreaBorderWidth: 0,
primaryXAxis: buildInsightsIndexAxis(model.labels),
primaryYAxis: buildInsightsValueAxis(
unit: s.insights_unit_cm,
min: range.min,
max: range.max,
),
trackballBehavior: buildInsightsTrackball(),
series: <CartesianSeries<InsightsPoint, num>>[
for (var i = 0; i < series.length; i++)
if (_isVisible(i))
SplineSeries<InsightsPoint, num>(
name: series[i].name,
dataSource: series[i].points,
xValueMapper: (point, _) => point.index,
yValueMapper: (point, _) => point.value,
splineType: insightsSplineType,
color: series[i].color,
width: 3,
markerSettings: buildInsightsMarker(series[i].color),
),
],
),
);
}
bool _isVisible(int index) =>
index < visibility.length ? visibility[index] : true;
}

View File

@@ -0,0 +1,54 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
class WeightChart extends StatelessWidget {
const WeightChart({super.key, required this.model, required this.emptyText});
final WeightChartModel model;
/// Текст при отсутствии точек («Добавьте Ваш вес»).
final String emptyText;
@override
Widget build(BuildContext context) {
final points = buildPoints(model.labels, model.values);
if (points.isEmpty) {
return InsightsChartPlaceholder(text: emptyText);
}
final s = S.of(context);
final range = paddedRange(points.map((e) => e.value));
return SizedBox(
height: insightsChartHeight,
child: SfCartesianChart(
key: const Key('insights_weight_chart'),
margin: insightsChartMargin,
plotAreaBorderWidth: 0,
primaryXAxis: buildInsightsIndexAxis(model.labels),
primaryYAxis: buildInsightsValueAxis(
unit: s.insights_unit_kg,
min: range.min,
max: range.max,
),
trackballBehavior: buildInsightsTrackball(),
series: <CartesianSeries<InsightsPoint, num>>[
SplineAreaSeries<InsightsPoint, num>(
name: s.insights_tab_weight,
dataSource: points,
xValueMapper: (point, _) => point.index,
yValueMapper: (point, _) => point.value,
splineType: insightsSplineType,
borderColor: InsightsColors.blue,
borderWidth: 3,
gradient: buildInsightsAreaGradient(InsightsColors.blue),
markerSettings: buildInsightsMarker(InsightsColors.blue),
),
],
),
);
}
}

View File

@@ -0,0 +1,400 @@
import 'dart:developer';
import 'package:eatvio_app/core/error_reporting/report_from.dart';
import 'package:eatvio_app/features/insights/insights_feature_flags.dart';
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/models/insights_period.dart';
import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart';
import 'package:eatvio_app/features/insights/presentation/cubit/insights_state.dart';
import 'package:eatvio_app/features/insights/repositories/insights_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class InsightsCubit extends Cubit<InsightsState> {
InsightsCubit({
required this.repository,
this.slug,
this.canAdd = false,
this.kbjuEnabled = InsightsFeatureFlags.kbjuEnabled,
}) : super(const InsightsState.initial());
final InsightsRepository repository;
/// `null` — собственные данные, иначе slug владельца (консультант → клиент).
final String? slug;
/// Показывать ли кнопку «+» (только владелец).
final bool canAdd;
final bool kbjuEnabled;
bool _isHeightLoaded = false;
int? _heightCm;
/// Полный payload и вкладка «В течение дня» координируются отдельно: смена
/// дня не должна отменять загрузку периода, и наоборот.
int _fullRequestId = 0;
int _intraRequestId = 0;
int _inflightFull = 0;
int _inflightIntra = 0;
List<InsightsPanel> get panels =>
InsightsPanel.available(kbjuEnabled: kbjuEnabled);
bool get _isBusy => _inflightFull > 0 || _inflightIntra > 0;
Future<void> load({String? intraDate}) async {
emit(const InsightsState.loading());
await _fetch(
bodyPeriod: BodyPeriod.threeMonths,
dailyPeriod: DailyPeriod.twoWeeks,
intraDate: intraDate,
isInitial: true,
);
}
/// Перезапрашивает данные, сохраняя вкладку, период, серии и раскрытие.
Future<void> refresh() async {
final current = state;
if (current is InsightsStateLoading || current is InsightsStateHidden) {
return;
}
if (current is! InsightsStateLoaded) {
return load();
}
await _fetch(
bodyPeriod: current.bodyPeriod,
dailyPeriod: current.dailyPeriod,
intraDate: current.intraDate,
isInitial: false,
);
}
Future<void> setBodyPeriod(BodyPeriod period) async {
final current = state;
if (current is! InsightsStateLoaded || current.bodyPeriod == period) {
return;
}
emit(current.copyWith(bodyPeriod: period, isRefreshing: true));
await _fetch(
bodyPeriod: period,
dailyPeriod: current.dailyPeriod,
intraDate: current.intraDate,
isInitial: false,
);
}
/// Период вкладки «КБЖУ по дням». Работает только с серверными данными.
Future<void> setDailyPeriod(DailyPeriod period) async {
final current = state;
if (!kbjuEnabled ||
current is! InsightsStateLoaded ||
current.dailyPeriod == period) {
return;
}
emit(current.copyWith(dailyPeriod: period, isRefreshing: true));
await _fetch(
bodyPeriod: current.bodyPeriod,
dailyPeriod: period,
intraDate: current.intraDate,
isInitial: false,
);
}
/// Показывает вкладку «В течение дня» за [day] (запрашивается только она).
Future<void> setIntraDate(DateTime day) {
return _loadIntra(_formatDate(day));
}
Future<void> showPreviousDay() async {
final base = _currentIntraDay();
if (base != null) {
await setIntraDate(DateTime(base.year, base.month, base.day - 1));
}
}
Future<void> showNextDay() async {
final current = state;
final base = _currentIntraDay();
if (base == null ||
current is! InsightsStateLoaded ||
!_canGoToNextDay(current, base)) {
return;
}
await setIntraDate(DateTime(base.year, base.month, base.day + 1));
}
/// База для листания: сначала оптимистично запрошенная дата, иначе ответ сервера.
DateTime? _currentIntraDay() {
final current = state;
if (!kbjuEnabled || current is! InsightsStateLoaded) {
return null;
}
final optimistic = current.intraDate;
if (optimistic != null && optimistic.isNotEmpty) {
return DateTime.tryParse(optimistic);
}
return DateTime.tryParse(current.payload.intra?.date ?? '');
}
bool _canGoToNextDay(InsightsStateLoaded current, DateTime base) {
final maxRaw =
current.payload.intra?.maxDate ?? current.payload.intra?.date ?? '';
final maxDate = DateTime.tryParse(maxRaw);
if (maxDate == null) {
return !(current.payload.intra?.isToday ?? true);
}
final baseDay = DateTime(base.year, base.month, base.day);
final maxDay = DateTime(maxDate.year, maxDate.month, maxDate.day);
return baseDay.isBefore(maxDay);
}
Future<void> _loadIntra(String date) async {
final current = state;
if (!kbjuEnabled || current is! InsightsStateLoaded) {
return;
}
final requestId = ++_intraRequestId;
_inflightIntra++;
final previousIntraDate = current.intraDate;
// Оптимистично фиксируем запрошенный день до ответа, чтобы быстрые
// нажатия «‹ ›» считали базу от него, а не от устаревшего payload.
emit(current.copyWith(intraDate: date, isRefreshing: true));
try {
final intra = await repository.fetchIntra(slug: slug, intraDate: date);
if (requestId != _intraRequestId || isClosed) {
return;
}
final latest = state;
if (latest is! InsightsStateLoaded) {
return;
}
emit(
latest.copyWith(
payload: latest.payload.copyWith(intra: intra),
intraDate: intra.isToday
? null
: (intra.date.isEmpty ? date : intra.date),
isRefreshing: _inflightFull > 0 || _inflightIntra > 1,
),
);
} on InsightsForbidden {
if (requestId == _intraRequestId && !isClosed) {
emit(const InsightsState.hidden());
}
} catch (e, st) {
await reportFrom(e, st, this);
log(e.toString(), stackTrace: st);
if (requestId == _intraRequestId && !isClosed) {
final latest = state;
if (latest is InsightsStateLoaded) {
emit(
latest.copyWith(
intraDate: previousIntraDate,
isRefreshing: _inflightFull > 0 || _inflightIntra > 1,
),
);
}
}
} finally {
_inflightIntra--;
_syncRefreshingFlag();
}
}
static String _formatDate(DateTime day) {
final month = day.month.toString().padLeft(2, '0');
final dayOfMonth = day.day.toString().padLeft(2, '0');
return '${day.year.toString().padLeft(4, '0')}-$month-$dayOfMonth';
}
void toggleExpanded() {
final current = state;
if (current is InsightsStateLoaded) {
emit(current.copyWith(isExpanded: !current.isExpanded));
}
}
void setPanel(InsightsPanel panel) {
final current = state;
if (current is! InsightsStateLoaded || !panels.contains(panel)) {
return;
}
emit(current.copyWith(panel: panel));
}
/// Включает/выключает серию [index] на вкладке [panel].
void toggleSeries(InsightsPanel panel, int index) {
final current = state;
if (current is! InsightsStateLoaded) {
return;
}
final visibility = current.seriesVisibility;
final source = switch (panel) {
InsightsPanel.measures => visibility.measure,
InsightsPanel.daily => visibility.daily,
InsightsPanel.intra => visibility.intra,
_ => null,
};
if (source == null || index < 0 || index >= source.length) {
return;
}
final updated = [...source]..[index] = !source[index];
final nextVisibility = switch (panel) {
InsightsPanel.measures => visibility.copyWith(measure: updated),
InsightsPanel.daily => visibility.copyWith(daily: updated),
_ => visibility.copyWith(intra: updated),
};
emit(current.copyWith(seriesVisibility: nextVisibility));
}
void toggleSleep() {
final current = state;
if (current is InsightsStateLoaded) {
emit(current.copyWith(showSleep: !current.showSleep));
}
}
/// Сохраняет вес и обновляет данные. Возвращает `false`, если сохранить не удалось.
Future<bool> addWeight({required double weight}) {
return _add(() => repository.addWeight(weight: weight));
}
/// Сохраняет замеры и обновляет данные. Возвращает `false`, если сохранить не удалось.
Future<bool> addCircumference({
required int chestCircumference,
required int waistCircumference,
required int hipCircumference,
}) {
return _add(
() => repository.addCircumference(
chestCircumference: chestCircumference,
waistCircumference: waistCircumference,
hipCircumference: hipCircumference,
),
);
}
Future<bool> _add(Future<void> Function() action) async {
try {
await action();
} catch (e, st) {
await reportFrom(e, st, this);
log(e.toString(), stackTrace: st);
return false;
}
await refresh();
return true;
}
Future<InsightsPayloadModel> _requestPayload({
required BodyPeriod bodyPeriod,
required DailyPeriod dailyPeriod,
required String? intraDate,
}) async {
if (kbjuEnabled) {
return repository.fetchInsights(
slug: slug,
bodyPeriod: bodyPeriod,
dailyPeriod: dailyPeriod,
intraDate: intraDate,
);
}
if (!_isHeightLoaded) {
_heightCm = await repository.getHeightCm(slug: slug);
_isHeightLoaded = true;
}
return repository.getInsights(
slug: slug,
bodyPeriod: bodyPeriod,
heightCm: _heightCm,
);
}
Future<void> _fetch({
required BodyPeriod bodyPeriod,
required DailyPeriod dailyPeriod,
required String? intraDate,
required bool isInitial,
}) async {
final requestId = ++_fullRequestId;
final intraGenerationAtStart = _intraRequestId;
_inflightFull++;
final before = state;
if (before is InsightsStateLoaded && !before.isRefreshing) {
emit(before.copyWith(isRefreshing: true));
}
try {
final payload = await _requestPayload(
bodyPeriod: bodyPeriod,
dailyPeriod: dailyPeriod,
intraDate: intraDate,
);
if (requestId != _fullRequestId || isClosed) {
return;
}
final latest = state;
if (latest is InsightsStateLoaded) {
// Более свежий intra-запрос не перезаписываем полным ответом.
final keepIntra = _intraRequestId > intraGenerationAtStart;
emit(
latest.copyWith(
payload: keepIntra
? payload.copyWith(intra: latest.payload.intra)
: payload,
bodyPeriod: bodyPeriod,
dailyPeriod: dailyPeriod,
intraDate: keepIntra ? latest.intraDate : intraDate,
isRefreshing: _inflightIntra > 0 || _inflightFull > 1,
),
);
} else if (isInitial || latest is! InsightsStateError) {
emit(
InsightsState.loaded(
payload: payload,
bodyPeriod: bodyPeriod,
dailyPeriod: dailyPeriod,
intraDate: intraDate,
),
);
}
} on InsightsForbidden {
if (requestId == _fullRequestId && !isClosed) {
emit(const InsightsState.hidden());
}
} catch (e, st) {
await reportFrom(e, st, this);
log(e.toString(), stackTrace: st);
if (requestId != _fullRequestId || isClosed) {
return;
}
final latest = state;
// Ошибка перезапроса не должна стирать уже показанные данные и UI-выбор.
if (latest is InsightsStateLoaded) {
emit(
latest.copyWith(
isRefreshing: _inflightIntra > 0 || _inflightFull > 1,
),
);
} else if (isInitial) {
emit(InsightsState.error(message: e.toString()));
}
} finally {
_inflightFull--;
_syncRefreshingFlag();
}
}
void _syncRefreshingFlag() {
if (isClosed) {
return;
}
final current = state;
if (current is! InsightsStateLoaded) {
return;
}
final busy = _isBusy;
if (current.isRefreshing != busy) {
emit(current.copyWith(isRefreshing: busy));
}
}
}

View File

@@ -0,0 +1,29 @@
import 'package:eatvio_app/generated/l10n.dart';
/// Вкладки блока «Аналитика».
enum InsightsPanel {
weight,
bmi,
measures,
daily,
intra;
/// Вкладки КБЖУ доступны только при включённом флаге.
bool get isKbju => this == daily || this == intra;
/// Кнопка «+» есть только у вкладок с ручным вводом.
bool get supportsAdd => this == weight || this == measures;
/// Подпись вкладки.
String label(S s) => switch (this) {
weight => s.insights_tab_weight,
bmi => s.insights_tab_bmi,
measures => s.insights_tab_measures,
daily => s.insights_tab_daily,
intra => s.insights_tab_intra,
};
static List<InsightsPanel> available({required bool kbjuEnabled}) {
return values.where((panel) => kbjuEnabled || !panel.isKbju).toList();
}
}

View File

@@ -0,0 +1,51 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/models/insights_period.dart';
import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'insights_state.freezed.dart';
/// Видимость серий (чипы под графиком): `true` — серия показана.
@freezed
abstract class InsightsSeriesVisibility with _$InsightsSeriesVisibility {
const factory InsightsSeriesVisibility({
/// Талия, Грудь, Бёдра.
@Default([true, true, true]) List<bool> measure,
/// Калории, Белки, Жиры, Углеводы.
@Default([true, true, true, true]) List<bool> daily,
/// Белки, Жиры, Углеводы, Сытость, Настроение.
@Default([true, true, true, true, true]) List<bool> intra,
}) = _InsightsSeriesVisibility;
}
@freezed
abstract class InsightsState with _$InsightsState {
const factory InsightsState.initial() = InsightsStateInitial;
const factory InsightsState.loading() = InsightsStateLoading;
/// 403: данные недоступны, блок не показывается.
const factory InsightsState.hidden() = InsightsStateHidden;
const factory InsightsState.error({required String message}) =
InsightsStateError;
const factory InsightsState.loaded({
required InsightsPayloadModel payload,
@Default(BodyPeriod.threeMonths) BodyPeriod bodyPeriod,
@Default(DailyPeriod.twoWeeks) DailyPeriod dailyPeriod,
/// День вкладки «В течение дня» (`YYYY-MM-DD`); `null` — сегодня.
String? intraDate,
@Default(InsightsPanel.weight) InsightsPanel panel,
@Default(InsightsSeriesVisibility())
InsightsSeriesVisibility seriesVisibility,
@Default(true) bool showSleep,
@Default(false) bool isExpanded,
/// Идёт перезапрос (смена периода / обновление) — старые данные остаются на экране.
@Default(false) bool isRefreshing,
}) = InsightsStateLoaded;
}

View File

@@ -0,0 +1,175 @@
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
const int _minValue = 20;
const int _maxValue = 199;
/// Значения замеров в сантиметрах.
typedef CircumferenceValues = ({int chest, int waist, int hip});
/// Выбор замеров груди, талии и бёдер. [onSave] вызывается после закрытия шторки.
Future<void> showAddCircumferenceBottomSheet(
BuildContext context, {
CircumferenceValues? initial,
required Future<void> Function(CircumferenceValues values) onSave,
}) {
return showModalBottomSheet<void>(
useRootNavigator: true,
context: context,
builder: (_) =>
AddCircumferenceBottomSheet(initial: initial, onSave: onSave),
);
}
class AddCircumferenceBottomSheet extends StatefulWidget {
const AddCircumferenceBottomSheet({
super.key,
this.initial,
required this.onSave,
});
final CircumferenceValues? initial;
final Future<void> Function(CircumferenceValues values) onSave;
@override
State<AddCircumferenceBottomSheet> createState() =>
_AddCircumferenceBottomSheetState();
}
class _AddCircumferenceBottomSheetState
extends State<AddCircumferenceBottomSheet> {
late final FixedExtentScrollController _chestController;
late final FixedExtentScrollController _waistController;
late final FixedExtentScrollController _hipController;
late int _chest;
late int _waist;
late int _hip;
@override
void initState() {
super.initState();
_chest = _clamp(widget.initial?.chest);
_waist = _clamp(widget.initial?.waist);
_hip = _clamp(widget.initial?.hip);
_chestController = FixedExtentScrollController(
initialItem: _chest - _minValue,
);
_waistController = FixedExtentScrollController(
initialItem: _waist - _minValue,
);
_hipController = FixedExtentScrollController(initialItem: _hip - _minValue);
}
@override
void dispose() {
_chestController.dispose();
_waistController.dispose();
_hipController.dispose();
super.dispose();
}
int _clamp(int? value) => (value ?? _minValue).clamp(_minValue, _maxValue);
void _save() {
final values = (chest: _chest, waist: _waist, hip: _hip);
Navigator.of(context).pop();
widget.onSave(values);
}
@override
Widget build(BuildContext context) {
final s = S.of(context);
return SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
child: Row(
children: [
for (final title in [
s.insights_series_chest,
s.insights_series_waist,
s.insights_series_hips,
])
Expanded(
child: Center(
child: Text(
title,
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
),
],
),
),
SizedBox(
height: 200,
child: Row(
children: [
_picker(
const Key('add_circumference_chest_picker'),
_chestController,
(value) => _chest = value,
),
_picker(
const Key('add_circumference_waist_picker'),
_waistController,
(value) => _waist = value,
),
_picker(
const Key('add_circumference_hip_picker'),
_hipController,
(value) => _hip = value,
),
],
),
),
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: InkWell(
key: const Key('add_sheet_save'),
onTap: _save,
borderRadius: BorderRadius.circular(16),
child: Ink(
width: MediaQuery.of(context).size.width - 32,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(16),
),
child: Center(
child: Text(
s.save,
style: const TextStyle(color: Colors.white),
),
),
),
),
),
],
),
);
}
Widget _picker(
Key key,
FixedExtentScrollController controller,
ValueChanged<int> onChanged,
) {
return Expanded(
child: CupertinoPicker(
key: key,
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
scrollController: controller,
itemExtent: 24,
onSelectedItemChanged: (index) => onChanged(index + _minValue),
children: [for (int i = _minValue; i <= _maxValue; i++) Text('$i')],
),
);
}
}

View File

@@ -0,0 +1,147 @@
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
const int _minKilo = 20;
const int _maxKilo = 299;
/// Выбор веса (кг + десятые). [onSave] вызывается после закрытия шторки.
Future<void> showAddWeightBottomSheet(
BuildContext context, {
double? initialWeight,
required Future<void> Function(double weight) onSave,
}) {
return showModalBottomSheet<void>(
useRootNavigator: true,
context: context,
builder: (_) =>
AddWeightBottomSheet(initialWeight: initialWeight, onSave: onSave),
);
}
class AddWeightBottomSheet extends StatefulWidget {
const AddWeightBottomSheet({
super.key,
this.initialWeight,
required this.onSave,
});
final double? initialWeight;
final Future<void> Function(double weight) onSave;
@override
State<AddWeightBottomSheet> createState() => _AddWeightBottomSheetState();
}
class _AddWeightBottomSheetState extends State<AddWeightBottomSheet> {
late final FixedExtentScrollController _kiloController;
late final FixedExtentScrollController _gramsController;
late int _kilo;
late int _grams;
@override
void initState() {
super.initState();
final initial = widget.initialWeight;
final tenths = initial == null
? 0
: (initial * 10).round().clamp(_minKilo * 10, _maxKilo * 10 + 9);
_kilo = initial == null ? _minKilo : tenths ~/ 10;
_grams = initial == null ? 0 : tenths % 10;
_kiloController = FixedExtentScrollController(
initialItem: _kilo - _minKilo,
);
_gramsController = FixedExtentScrollController(initialItem: _grams);
}
@override
void dispose() {
_kiloController.dispose();
_gramsController.dispose();
super.dispose();
}
void _save() {
final weight = double.parse('$_kilo.$_grams');
Navigator.of(context).pop();
widget.onSave(weight);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: 200,
child: Row(
children: [
Expanded(
child: CupertinoPicker(
key: const Key('add_weight_kilo_picker'),
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
scrollController: _kiloController,
itemExtent: 24,
onSelectedItemChanged: (value) => _kilo = value + _minKilo,
children: [
for (int i = _minKilo; i <= _maxKilo; i++) Text('$i'),
],
),
),
Expanded(
child: CupertinoPicker(
key: const Key('add_weight_grams_picker'),
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
scrollController: _gramsController,
itemExtent: 24,
onSelectedItemChanged: (value) => _grams = value,
children: [for (int i = 0; i < 10; i++) Text('$i')],
),
),
],
),
),
_SaveButton(onTap: _save),
],
),
);
}
}
class _SaveButton extends StatelessWidget {
const _SaveButton({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: InkWell(
key: const Key('add_sheet_save'),
onTap: onTap,
borderRadius: BorderRadius.circular(16),
child: Ink(
width: MediaQuery.of(context).size.width - 32,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(16),
),
child: Center(
child: Text(
S.of(context).save,
style: const TextStyle(color: Colors.white),
),
),
),
),
);
}
}

View File

@@ -0,0 +1,640 @@
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/utils/toasts.dart';
import 'package:eatvio_app/features/insights/insights_feature_flags.dart';
import 'package:eatvio_app/features/insights/models/insights_period.dart';
import 'package:eatvio_app/features/insights/presentation/charts/bmi_chart.dart';
import 'package:eatvio_app/features/insights/presentation/charts/daily_kbju_chart.dart';
import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart';
import 'package:eatvio_app/features/insights/presentation/charts/intra_day_chart.dart';
import 'package:eatvio_app/features/insights/presentation/charts/measure_chart.dart';
import 'package:eatvio_app/features/insights/presentation/charts/weight_chart.dart';
import 'package:eatvio_app/features/insights/presentation/cubit/insights_cubit.dart';
import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart';
import 'package:eatvio_app/features/insights/presentation/cubit/insights_state.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/add_circumference_bottom_sheet.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/add_weight_bottom_sheet.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_fab.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_head.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_tabs.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/intra_date_nav.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/intra_legend.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/period_pills.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/series_chips.dart';
import 'package:eatvio_app/features/insights/repositories/insights_repository.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
/// Сворачиваемый блок «Аналитика» (вес, ИМТ, замеры).
///
/// [slug] — владелец данных (`null` — текущий пользователь). При 403 блок
/// скрывается целиком. [canAdd] включает кнопку «+» на вкладках «Вес» и «Замеры».
class InsightsCard extends StatelessWidget {
const InsightsCard({
super.key,
this.slug,
this.canAdd = false,
this.repository,
this.kbjuEnabled = InsightsFeatureFlags.kbjuEnabled,
this.refreshToken = 0,
this.initialIntraDate,
});
final String? slug;
final bool canAdd;
final InsightsRepository? repository;
final bool kbjuEnabled;
/// При смене значения блок перезапрашивает данные (например, после правок
/// в дневнике), сохраняя вкладку, период и выбранный день.
final int refreshToken;
/// День вкладки «В течение дня» при первой загрузке (`YYYY-MM-DD`).
/// В дневнике совпадает с открытой датой; `null` — сегодня.
final String? initialIntraDate;
@override
Widget build(BuildContext context) {
return KeyedSubtree(
key: ValueKey('insights_card_$slug'),
child: BlocProvider<InsightsCubit>(
create: (_) => InsightsCubit(
repository: repository ?? sl<InsightsRepository>(),
slug: slug,
canAdd: canAdd,
kbjuEnabled: kbjuEnabled,
)..load(intraDate: initialIntraDate),
child: _InsightsView(
refreshToken: refreshToken,
initialIntraDate: initialIntraDate,
),
),
);
}
}
class _InsightsView extends StatefulWidget {
const _InsightsView({
required this.refreshToken,
required this.initialIntraDate,
});
final int refreshToken;
final String? initialIntraDate;
@override
State<_InsightsView> createState() => _InsightsViewState();
}
class _InsightsViewState extends State<_InsightsView> {
@override
void didUpdateWidget(covariant _InsightsView oldWidget) {
super.didUpdateWidget(oldWidget);
final cubit = context.read<InsightsCubit>();
if (oldWidget.refreshToken != widget.refreshToken) {
cubit.refresh();
}
final nextDate = widget.initialIntraDate;
if (nextDate != null &&
nextDate.isNotEmpty &&
oldWidget.initialIntraDate != nextDate) {
final parsed = DateTime.tryParse(nextDate);
if (parsed != null) {
cubit.setIntraDate(parsed);
}
}
}
@override
Widget build(BuildContext context) {
return BlocBuilder<InsightsCubit, InsightsState>(
builder: (context, state) {
return switch (state) {
InsightsStateLoaded() => _CardShell(
child: _LoadedContent(state: state),
),
InsightsStateError() => const _CardShell(child: _ErrorContent()),
_ => const SizedBox.shrink(),
};
},
);
}
}
class _CardShell extends StatelessWidget {
const _CardShell({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return Container(
key: const Key('insights_card'),
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: const [
BoxShadow(
color: InsightsColors.cardShadow,
blurRadius: 4,
offset: Offset(0, 2),
),
],
),
child: child,
);
}
}
class _ErrorContent extends StatelessWidget {
const _ErrorContent();
@override
Widget build(BuildContext context) {
final s = S.of(context);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Expanded(
child: Text(
s.insights_load_error,
style: const TextStyle(
fontSize: 14,
color: InsightsColors.subtitle,
),
),
),
TextButton(
key: const Key('insights_retry'),
onPressed: () => context.read<InsightsCubit>().load(),
child: Text(s.insights_retry),
),
],
),
);
}
}
class _LoadedContent extends StatelessWidget {
const _LoadedContent({required this.state});
final InsightsStateLoaded state;
@override
Widget build(BuildContext context) {
final cubit = context.read<InsightsCubit>();
final showFab = cubit.canAdd && state.panel.supportsAdd;
return Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_Toggle(isExpanded: state.isExpanded, onTap: cubit.toggleExpanded),
AnimatedSize(
duration: const Duration(milliseconds: 200),
alignment: Alignment.topCenter,
child: state.isExpanded
? Padding(
padding: EdgeInsets.fromLTRB(
16,
0,
16,
showFab ? 24 + 44 : 24,
),
child: _Body(state: state),
)
: const SizedBox(width: double.infinity),
),
],
),
if (showFab && state.isExpanded)
Positioned(
right: 16,
bottom: 16,
child: InsightsFab(
tooltip: S.of(context).insights_add_record,
onPressed: () => _onAddPressed(context, cubit, state),
),
),
],
);
}
void _onAddPressed(
BuildContext context,
InsightsCubit cubit,
InsightsStateLoaded state,
) {
final s = S.of(context);
if (state.panel == InsightsPanel.weight) {
showAddWeightBottomSheet(
context,
initialWeight: state.payload.weight.last,
onSave: (weight) async {
if (!await cubit.addWeight(weight: weight)) {
showErrorToast(s.insights_save_error);
}
},
);
} else if (state.panel == InsightsPanel.measures) {
final measure = state.payload.measure;
showAddCircumferenceBottomSheet(
context,
initial:
measure.waist.isEmpty ||
measure.chest.isEmpty ||
measure.hips.isEmpty
? null
: (
chest: measure.chest.last.round(),
waist: measure.waist.last.round(),
hip: measure.hips.last.round(),
),
onSave: (values) async {
final isSaved = await cubit.addCircumference(
chestCircumference: values.chest,
waistCircumference: values.waist,
hipCircumference: values.hip,
);
if (!isSaved) {
showErrorToast(s.insights_save_error);
}
},
);
}
}
}
class _Toggle extends StatelessWidget {
const _Toggle({required this.isExpanded, required this.onTap});
final bool isExpanded;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final s = S.of(context);
return InkWell(
key: const Key('insights_toggle'),
borderRadius: BorderRadius.circular(8),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Row(
children: [
Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: InsightsColors.accentBackground,
borderRadius: BorderRadius.circular(10),
),
child: const Icon(
Icons.show_chart_rounded,
size: 20,
color: InsightsColors.blue,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.insights_title,
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w700,
color: InsightsColors.title,
),
),
const SizedBox(height: 2),
Text(
key: const Key('insights_subtitle'),
isExpanded
? s.insights_subtitle_open
: s.insights_subtitle_closed,
style: const TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: InsightsColors.subtitle,
),
),
],
),
),
AnimatedRotation(
turns: isExpanded ? 0 : 0.5,
duration: const Duration(milliseconds: 200),
child: const Icon(
Icons.keyboard_arrow_up_rounded,
size: 26,
color: InsightsColors.blue,
),
),
],
),
),
);
}
}
class _Body extends StatelessWidget {
const _Body({required this.state});
final InsightsStateLoaded state;
@override
Widget build(BuildContext context) {
final cubit = context.read<InsightsCubit>();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InsightsTabs(
panels: cubit.panels,
selected: state.panel,
onSelected: cubit.setPanel,
),
const SizedBox(height: 12),
AnimatedOpacity(
duration: const Duration(milliseconds: 150),
opacity: state.isRefreshing ? 0.5 : 1,
child: _PanelContent(state: state, canAdd: cubit.canAdd),
),
],
);
}
}
class _PanelContent extends StatelessWidget {
const _PanelContent({required this.state, required this.canAdd});
final InsightsStateLoaded state;
final bool canAdd;
@override
Widget build(BuildContext context) {
final cubit = context.read<InsightsCubit>();
final s = S.of(context);
final payload = state.payload;
final Widget content;
switch (state.panel) {
case InsightsPanel.weight:
content = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InsightsHead(
headline: payload.weight.headline,
unit: payload.weight.unit,
deltaText: payload.weight.deltaText,
isDeltaHighlighted: payload.weight.delta != null,
),
const SizedBox(height: 12),
WeightChart(
model: payload.weight,
emptyText: canAdd
? s.insights_add_weight_empty
: s.insights_not_enough,
),
],
);
case InsightsPanel.bmi:
content = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (payload.bmi.values.isNotEmpty) ...[
InsightsHead(
headline: payload.bmi.headline,
unit: s.insights_unit_bmi,
deltaText: payload.bmi.deltaText,
isDeltaHighlighted: payload.bmi.delta != null,
),
const SizedBox(height: 12),
],
BmiChart(model: payload.bmi),
],
);
case InsightsPanel.measures:
final visibility = state.seriesVisibility.measure;
content = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InsightsHead(
headline: payload.measure.headline,
unit: s.insights_unit_cm_waist,
deltaText: payload.measure.deltaText,
isDeltaHighlighted: payload.measure.waist.length > 1,
),
const SizedBox(height: 12),
SeriesChips(
chips: [
SeriesChipData(
label: s.insights_series_waist,
color: InsightsColors.waist,
isVisible: visibility[0],
),
SeriesChipData(
label: s.insights_series_chest,
color: InsightsColors.chest,
isVisible: visibility[1],
),
SeriesChipData(
label: s.insights_series_hips,
color: InsightsColors.hips,
isVisible: visibility[2],
),
],
onToggle: (index) =>
cubit.toggleSeries(InsightsPanel.measures, index),
),
const SizedBox(height: 12),
MeasureChart(
model: payload.measure,
visibility: visibility,
emptyText: canAdd
? s.insights_add_measures_empty
: s.insights_not_enough,
),
],
);
case InsightsPanel.daily:
return _DailyPanel(state: state);
case InsightsPanel.intra:
return _IntraPanel(state: state);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
PeriodPills<BodyPeriod>(
periods: BodyPeriod.values,
selected: state.bodyPeriod,
labelOf: (period) => period.pillLabel(s),
keyOf: (period) => period.apiValue,
onSelected: cubit.setBodyPeriod,
),
const SizedBox(height: 16),
content,
],
);
}
}
/// «КБЖУ по дням». Смена периода перезапрашивает `GET /api/profile/insights`.
class _DailyPanel extends StatelessWidget {
const _DailyPanel({required this.state});
final InsightsStateLoaded state;
@override
Widget build(BuildContext context) {
final s = S.of(context);
final cubit = context.read<InsightsCubit>();
final daily = state.payload.daily;
final visibility = state.seriesVisibility.daily;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
PeriodPills<DailyPeriod>(
periods: DailyPeriod.values,
selected: state.dailyPeriod,
labelOf: (period) => period.pillLabel(s),
keyOf: (period) => period.apiValue,
onSelected: cubit.setDailyPeriod,
),
const SizedBox(height: 16),
if (daily == null)
InsightsChartPlaceholder(text: s.insights_not_enough)
else ...[
InsightsHead(
headline: daily.headline,
unit: s.insights_unit_kcal_avg,
deltaText: daily.deltaText,
isDeltaHighlighted: (daily.percent ?? 0) != 0,
),
const SizedBox(height: 12),
SeriesChips(
chips: [
SeriesChipData(
label: s.insights_series_calories,
color: InsightsColors.calories,
isVisible: visibility[0],
),
SeriesChipData(
label: s.insights_series_proteins,
color: InsightsColors.proteins,
isVisible: visibility[1],
),
SeriesChipData(
label: s.insights_series_fats,
color: InsightsColors.fats,
isVisible: visibility[2],
),
SeriesChipData(
label: s.insights_series_carbs,
color: InsightsColors.carbs,
isVisible: visibility[3],
),
],
onToggle: (index) => cubit.toggleSeries(InsightsPanel.daily, index),
),
const SizedBox(height: 12),
DailyKbjuChart(model: daily, visibility: visibility),
],
],
);
}
}
/// «В течение дня». Листание дней запрашивает только `/insights/intra`.
class _IntraPanel extends StatelessWidget {
const _IntraPanel({required this.state});
final InsightsStateLoaded state;
@override
Widget build(BuildContext context) {
final s = S.of(context);
final cubit = context.read<InsightsCubit>();
final intra = state.payload.intra;
final visibility = state.seriesVisibility.intra;
if (intra == null) {
return InsightsChartPlaceholder(text: s.insights_not_enough);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IntraDateNav(
model: intra,
onPreviousDay: cubit.showPreviousDay,
onNextDay: cubit.showNextDay,
onDatePicked: cubit.setIntraDate,
),
const SizedBox(height: 16),
SeriesChips(
chips: [
SeriesChipData(
label: s.insights_series_proteins,
color: InsightsColors.proteins,
isVisible: visibility[0],
),
SeriesChipData(
label: s.insights_series_fats,
color: InsightsColors.fats,
isVisible: visibility[1],
),
SeriesChipData(
label: s.insights_series_carbs,
color: InsightsColors.carbs,
isVisible: visibility[2],
),
SeriesChipData(
label: s.insights_series_satiety,
color: InsightsColors.satiety,
isVisible: visibility[3],
),
SeriesChipData(
label: s.insights_series_mood,
color: InsightsColors.mood,
isVisible: visibility[4],
),
SeriesChipData(
label: s.insights_series_sleep,
color: InsightsColors.sleepLine,
isVisible: state.showSleep,
),
],
onToggle: (index) {
if (index == 5) {
cubit.toggleSleep();
} else {
cubit.toggleSeries(InsightsPanel.intra, index);
}
},
),
const SizedBox(height: 12),
IntraDayChart(
model: intra,
visibility: visibility,
showSleep: state.showSleep,
),
const SizedBox(height: 8),
IntraLegend(model: intra),
const SizedBox(height: 8),
Text(
s.insights_intra_hint,
key: const Key('insights_intra_hint'),
style: const TextStyle(fontSize: 13, color: InsightsColors.subtitle),
),
],
);
}
}

View File

@@ -0,0 +1,36 @@
import 'package:flutter/painting.dart';
/// Токены из `latest-tmpls/src/scss/pages/diary.scss` (`&__analytics*`).
abstract final class InsightsColors {
static const Color blue = Color(0xFF2F80ED);
static const Color accentBackground = Color(0xFFF6FAFF);
static const Color title = Color(0xFF323F4B);
static const Color subtitle = Color(0xFF7B8794);
static const Color border = Color(0xFFE6E6E6);
static const Color positive = Color(0xFF019A3E);
static const Color calories = Color(0xFF323F4B);
static const Color proteins = Color(0xFF2F80ED);
static const Color fats = Color(0xFFF2994A);
static const Color carbs = Color(0xFF0D6EFD);
static const Color satiety = Color(0xFF019A3E);
static const Color mood = Color(0xFFEB555C);
static const Color waist = Color(0xFF2F80ED);
static const Color chest = Color(0xFF9B51E0);
static const Color hips = Color(0xFFF2994A);
static const Color wake = Color(0xFFF2994A);
static const Color sleepLine = Color(0xFF7B8794);
static const Color sleepShade = Color(0x1A7B8794);
static const Color bmiNormalZone = Color(0x14019A3E);
static const Color bmiOverweightZone = Color(0x1AF2994A);
static const Color bmiObesityZone = Color(0x14EB555C);
static const Color cardShadow = Color(0x26000000);
static const Color fabShadow = Color(0x592F80ED);
}
/// Высота области графика.
const double insightsChartHeight = 270;

View File

@@ -0,0 +1,42 @@
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:flutter/material.dart';
/// Круглая кнопка «+» (52px) справа-снизу карточки.
class InsightsFab extends StatelessWidget {
const InsightsFab({super.key, required this.onPressed, this.tooltip});
final VoidCallback onPressed;
final String? tooltip;
@override
Widget build(BuildContext context) {
return Tooltip(
message: tooltip ?? '',
child: Container(
width: 52,
height: 52,
decoration: const BoxDecoration(
color: InsightsColors.blue,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: InsightsColors.fabShadow,
blurRadius: 20,
offset: Offset(0, 8),
),
],
),
child: Material(
color: Colors.transparent,
shape: const CircleBorder(),
child: InkWell(
key: const Key('insights_fab'),
customBorder: const CircleBorder(),
onTap: onPressed,
child: const Icon(Icons.add, color: Colors.white, size: 28),
),
),
),
);
}
}

View File

@@ -0,0 +1,70 @@
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:flutter/material.dart';
/// Крупное число + единица + строка с дельтой.
class InsightsHead extends StatelessWidget {
const InsightsHead({
super.key,
required this.headline,
required this.unit,
required this.deltaText,
this.isDeltaHighlighted = true,
});
final String headline;
final String unit;
final String deltaText;
/// Зелёная дельта при наличии изменения, иначе нейтральный серый.
final bool isDeltaHighlighted;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
headline,
key: const Key('insights_headline'),
style: const TextStyle(
fontSize: 34,
fontWeight: FontWeight.w800,
color: InsightsColors.title,
height: 1.1,
),
),
if (unit.isNotEmpty) ...[
const SizedBox(width: 6),
Text(
unit,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
color: InsightsColors.subtitle,
),
),
],
],
),
if (deltaText.isNotEmpty) ...[
const SizedBox(height: 4),
Text(
deltaText,
key: const Key('insights_delta'),
style: TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w700,
color: isDeltaHighlighted
? InsightsColors.positive
: InsightsColors.subtitle,
),
),
],
],
);
}
}

View File

@@ -0,0 +1,63 @@
import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
/// Горизонтально прокручиваемые вкладки (`l-tab`).
class InsightsTabs extends StatelessWidget {
const InsightsTabs({
super.key,
required this.panels,
required this.selected,
required this.onSelected,
});
final List<InsightsPanel> panels;
final InsightsPanel selected;
final ValueChanged<InsightsPanel> onSelected;
@override
Widget build(BuildContext context) {
final s = S.of(context);
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final panel in panels)
InkWell(
key: Key('insights_tab_${panel.name}'),
onTap: () => onSelected(panel),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 10,
),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: panel == selected
? InsightsColors.blue
: Colors.transparent,
width: 2,
),
),
),
child: Text(
panel.label(s),
style: TextStyle(
fontSize: 13,
fontWeight: panel == selected
? FontWeight.w700
: FontWeight.w600,
color: panel == selected
? InsightsColors.blue
: InsightsColors.subtitle,
),
),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,130 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
/// Навигация по дням для вкладки «В течение дня»: `‹ дата ›` и выбор даты.
///
/// Колбэки `null` — навигация неактивна (данные других дней ещё не подключены).
class IntraDateNav extends StatelessWidget {
const IntraDateNav({
super.key,
required this.model,
this.onPreviousDay,
this.onNextDay,
this.onDatePicked,
});
final IntraChartModel model;
final VoidCallback? onPreviousDay;
final VoidCallback? onNextDay;
final ValueChanged<DateTime>? onDatePicked;
@override
Widget build(BuildContext context) {
final s = S.of(context);
final canGoNext = !model.isToday && onNextDay != null;
return Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: InsightsColors.accentBackground,
borderRadius: BorderRadius.circular(999),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_NavButton(
key: const Key('insights_intra_prev'),
icon: Icons.chevron_left_rounded,
tooltip: s.insights_prev_day,
onPressed: onPreviousDay,
),
InkWell(
key: const Key('insights_intra_pick'),
borderRadius: BorderRadius.circular(999),
onTap: onDatePicked == null ? null : () => _pickDate(context),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 72),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.calendar_today_rounded,
size: 14,
color: InsightsColors.blue,
),
const SizedBox(width: 6),
Text(
model.dateLabel,
key: const Key('insights_intra_date_label'),
style: const TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w700,
color: InsightsColors.title,
),
),
],
),
),
),
),
_NavButton(
key: const Key('insights_intra_next'),
icon: Icons.chevron_right_rounded,
tooltip: s.insights_next_day,
onPressed: canGoNext ? onNextDay : null,
),
],
),
);
}
Future<void> _pickDate(BuildContext context) async {
final lastDate = DateTime.tryParse(model.maxDate) ?? DateTime.now();
final current = DateTime.tryParse(model.date) ?? lastDate;
final picked = await showDatePicker(
context: context,
initialDate: current.isAfter(lastDate) ? lastDate : current,
firstDate: DateTime(2000),
lastDate: lastDate,
helpText: S.of(context).insights_pick_date,
);
if (picked != null) {
onDatePicked?.call(picked);
}
}
}
class _NavButton extends StatelessWidget {
const _NavButton({
super.key,
required this.icon,
required this.tooltip,
required this.onPressed,
});
final IconData icon;
final String tooltip;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return Opacity(
opacity: onPressed == null ? 0.35 : 1,
child: SizedBox(
width: 36,
height: 36,
child: IconButton(
padding: EdgeInsets.zero,
tooltip: tooltip,
onPressed: onPressed,
icon: Icon(icon, color: InsightsColors.blue),
),
),
);
}
}

View File

@@ -0,0 +1,96 @@
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
/// Легенда под графиком «В течение дня»: подъём, отход ко сну, затемнение сна.
class IntraLegend extends StatelessWidget {
const IntraLegend({super.key, required this.model});
final IntraChartModel model;
@override
Widget build(BuildContext context) {
final s = S.of(context);
final wakeText =
model.wakeText ??
(model.wakeLabel == null ? null : s.insights_wake_at(model.wakeLabel!));
final sleepText =
model.sleepText ??
(model.sleepLabel == null
? null
: s.insights_sleep_at(model.sleepLabel!));
return Wrap(
spacing: 16,
runSpacing: 6,
children: [
if (wakeText != null)
_LegendItem(
key: const Key('insights_legend_wake'),
color: InsightsColors.wake,
text: wakeText,
isDashed: true,
),
if (sleepText != null)
_LegendItem(
key: const Key('insights_legend_sleep'),
color: InsightsColors.sleepLine,
text: sleepText,
isDashed: true,
),
_LegendItem(
key: const Key('insights_legend_shade'),
color: InsightsColors.sleepShade,
text: s.insights_sleep_shade,
),
],
);
}
}
class _LegendItem extends StatelessWidget {
const _LegendItem({
super.key,
required this.color,
required this.text,
this.isDashed = false,
});
final Color color;
final String text;
final bool isDashed;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
isDashed
? Container(
width: 18,
height: 0,
decoration: BoxDecoration(
border: Border(top: BorderSide(color: color, width: 2)),
),
)
: Container(
width: 18,
height: 10,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(width: 6),
Text(
text,
style: const TextStyle(
fontSize: 12.5,
color: InsightsColors.subtitle,
),
),
],
);
}
}

View File

@@ -0,0 +1,79 @@
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:flutter/material.dart';
/// Пилюли выбора периода (`1М 3М 6М 1Г Всё время`).
class PeriodPills<T> extends StatelessWidget {
const PeriodPills({
super.key,
required this.periods,
required this.selected,
required this.labelOf,
required this.keyOf,
this.onSelected,
});
final List<T> periods;
final T selected;
final String Function(T period) labelOf;
final String Function(T period) keyOf;
/// `null` — пилюли неинтерактивны (данные для периода ещё не подключены).
final ValueChanged<T>? onSelected;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final period in periods)
Padding(
padding: const EdgeInsets.only(right: 6),
child: _Pill(
key: Key('insights_period_${keyOf(period)}'),
label: labelOf(period),
isActive: period == selected,
onTap: onSelected == null ? null : () => onSelected!(period),
),
),
],
),
);
}
}
class _Pill extends StatelessWidget {
const _Pill({
super.key,
required this.label,
required this.isActive,
required this.onTap,
});
final String label;
final bool isActive;
final VoidCallback? onTap;
@override
Widget build(BuildContext context) {
return Material(
color: isActive ? InsightsColors.blue : InsightsColors.accentBackground,
borderRadius: BorderRadius.circular(999),
child: InkWell(
borderRadius: BorderRadius.circular(999),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 7),
child: Text(
label,
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: isActive ? Colors.white : InsightsColors.subtitle,
),
),
),
),
);
}
}

View File

@@ -0,0 +1,76 @@
import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart';
import 'package:flutter/material.dart';
class SeriesChipData {
const SeriesChipData({
required this.label,
required this.color,
required this.isVisible,
});
final String label;
final Color color;
final bool isVisible;
}
/// Чипы-переключатели серий под графиком.
class SeriesChips extends StatelessWidget {
const SeriesChips({super.key, required this.chips, required this.onToggle});
final List<SeriesChipData> chips;
final ValueChanged<int> onToggle;
@override
Widget build(BuildContext context) {
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (var i = 0; i < chips.length; i++)
Opacity(
opacity: chips[i].isVisible ? 1 : 0.45,
child: InkWell(
key: Key('insights_series_$i'),
borderRadius: BorderRadius.circular(999),
onTap: () => onToggle(i),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 7,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(999),
border: Border.all(color: InsightsColors.border, width: 1.5),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 10,
height: 10,
decoration: BoxDecoration(
color: chips[i].color,
shape: BoxShape.circle,
),
),
const SizedBox(width: 8),
Text(
chips[i].label,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: InsightsColors.title,
decoration: chips[i].isVisible
? TextDecoration.none
: TextDecoration.lineThrough,
),
),
],
),
),
),
),
],
);
}
}

View File

@@ -0,0 +1,103 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/features/insights/domain/insights_text_builder.dart';
import 'package:eatvio_app/features/insights/models/insights_payload_model.dart';
import 'package:eatvio_app/features/insights/models/insights_period.dart';
import 'package:eatvio_app/features/insights/services/insights_service.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
import 'package:eatvio_app/generated/l10n.dart';
/// Данные аналитики недоступны текущему пользователю (HTTP 403): консультация
/// не активна либо это чужой профиль без доступа.
class InsightsForbidden implements Exception {
const InsightsForbidden();
@override
String toString() => 'InsightsForbidden';
}
typedef InsightsTextBuilderFactory = InsightsTextBuilder Function();
/// Источники данных блока «Аналитика»:
/// - [fetchInsights] / [fetchIntra] — серверные `GET /api/profile/insights*`
/// (графики и тексты считает `UserInsightsService`, включая КБЖУ);
/// - [getInsights] — собирает payload на клиенте из эндпоинтов веса и замеров
/// (используется, пока выключен `InsightsFeatureFlags.kbjuEnabled`).
class InsightsRepository {
InsightsRepository({required this.profileRepository, required this.insightsService, InsightsTextBuilderFactory? textBuilderFactory})
: _textBuilderFactory = textBuilderFactory ?? (() => InsightsTextBuilder(S.current));
final ProfileRepository profileRepository;
final InsightsService insightsService;
final InsightsTextBuilderFactory _textBuilderFactory;
/// Рост в сантиметрах для расчёта подсказки ИМТ; `null`, если не указан или
/// профиль не удалось загрузить (кроме 403 — он пробрасывается как [InsightsForbidden]).
Future<int?> getHeightCm({String? slug}) async {
try {
final details = slug == null ? await profileRepository.getMyProfileDetails() : await profileRepository.getProfileDetailsBySlug(slug);
return details.height > 0 ? details.height : null;
} on DioException catch (e) {
_throwIfForbidden(e);
return null;
} catch (_) {
return null;
}
}
Future<InsightsPayloadModel> getInsights({String? slug, required BodyPeriod bodyPeriod, int? heightCm}) async {
try {
final (weights, circumferences) = await (
profileRepository.getWeight(period: bodyPeriod.apiValue, slug: slug),
profileRepository.getCircumferences(period: bodyPeriod.apiValue, slug: slug),
).wait;
return _textBuilderFactory().build(weights: weights, circumferences: circumferences, period: bodyPeriod, heightCm: heightCm);
} on DioException catch (e) {
_throwIfForbidden(e);
rethrow;
}
}
/// Полный payload с сервера. [intraDate] — `YYYY-MM-DD`, `null` — сегодня.
Future<InsightsPayloadModel> fetchInsights({String? slug, required BodyPeriod bodyPeriod, required DailyPeriod dailyPeriod, String? intraDate}) async {
try {
final response = slug == null
? await insightsService.getInsights(bodyPeriod: bodyPeriod.apiValue, dailyPeriod: dailyPeriod.apiValue, intraDate: intraDate)
: await insightsService.getInsightsBySlug(slug: slug, bodyPeriod: bodyPeriod.apiValue, dailyPeriod: dailyPeriod.apiValue, intraDate: intraDate);
return response.data;
} on DioException catch (e) {
_throwIfForbidden(e);
rethrow;
}
}
/// Только вкладка «В течение дня» за [intraDate] (`YYYY-MM-DD`).
Future<IntraChartModel> fetchIntra({String? slug, String? intraDate}) async {
try {
final response = slug == null
? await insightsService.getIntra(intraDate: intraDate)
: await insightsService.getIntraBySlug(slug: slug, intraDate: intraDate);
return response.data.intra;
} on DioException catch (e) {
_throwIfForbidden(e);
rethrow;
}
}
Future<void> addWeight({required double weight}) {
return profileRepository.addWeight(weight: weight);
}
Future<void> addCircumference({required int chestCircumference, required int waistCircumference, required int hipCircumference}) {
return profileRepository.addCircumference(
chestCircumference: chestCircumference,
waistCircumference: waistCircumference,
hipCircumference: hipCircumference,
);
}
void _throwIfForbidden(DioException e) {
if (e.response?.statusCode == 403) {
throw const InsightsForbidden();
}
}
}

View File

@@ -0,0 +1,43 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/features/insights/models/insights_response_model.dart';
import 'package:retrofit/retrofit.dart';
part 'insights_service.g.dart';
/// Эндпоинты инсайтов (eatvio/eatvio#3017). Сервер приводит будущую
/// `intra_date` к сегодняшней, неверные значения периода дают 422, чужой
/// недоступный профиль — 403.
@RestApi()
abstract class InsightsService {
factory InsightsService(Dio dio, {String baseUrl}) = _InsightsService;
/// Свои графики целиком.
@GET('/api/profile/insights')
Future<InsightsResponseModel> getInsights({
@Query('body_period') String? bodyPeriod,
@Query('daily_period') String? dailyPeriod,
@Query('intra_date') String? intraDate,
});
/// Чужие графики целиком (клиент консультанта; остальным 403).
@GET('/api/profile/insights/{slug}')
Future<InsightsResponseModel> getInsightsBySlug({
@Path() required String slug,
@Query('body_period') String? bodyPeriod,
@Query('daily_period') String? dailyPeriod,
@Query('intra_date') String? intraDate,
});
/// Только «в течение дня» для себя.
@GET('/api/profile/insights/intra')
Future<InsightsIntraResponseModel> getIntra({
@Query('intra_date') String? intraDate,
});
/// Только «в течение дня» для другого пользователя.
@GET('/api/profile/insights/{slug}/intra')
Future<InsightsIntraResponseModel> getIntraBySlug({
@Path() required String slug,
@Query('intra_date') String? intraDate,
});
}

View File

@@ -9,9 +9,9 @@ abstract class CircumferenceModel with _$CircumferenceModel {
const factory CircumferenceModel({
@JsonKey(name: "id") required int id,
@JsonKey(name: "user_id") required int userId,
@JsonKey(name: "chest_circumference") required int chestCircumference,
@JsonKey(name: "waist_circumference") required int waistCircumference,
@JsonKey(name: "hip_circumference") required int hipCircumference,
@JsonKey(name: "chest_circumference") required double chestCircumference,
@JsonKey(name: "waist_circumference") required double waistCircumference,
@JsonKey(name: "hip_circumference") required double hipCircumference,
@JsonKey(name: "created_at") required DateTime createdAt,
@JsonKey(name: "updated_at") required DateTime updatedAt,
}) = _CircumferenceModel;

View File

@@ -9,10 +9,10 @@ abstract class WeightModel with _$WeightModel {
const factory WeightModel({
@JsonKey(name: "id") required int id,
@JsonKey(name: "user_id") required int userId,
@JsonKey(name: "weight") required int weight,
@JsonKey(name: "weight") required double weight,
@JsonKey(name: "created_at") required DateTime createdAt,
@JsonKey(name: "updated_at") required DateTime updatedAt,
@JsonKey(name: "bmi") required double bmi,
@JsonKey(name: "bmi") double? bmi,
}) = _WeightModel;
factory WeightModel.fromJson(Map<String, dynamic> json) => _$WeightModelFromJson(json);

View File

@@ -17,7 +17,6 @@ class ProfileCubit extends Cubit<ProfileState> {
final ProfileRepository profileRepository;
final ChatRepository chatRepository;
final ConsultantRepository consultantRepository;
String _currentPeriod = '1';
/// Bottom-nav / own profile instance, used to refresh posts after create/update/delete.
static ProfileCubit? myProfileCubit;
@@ -55,10 +54,9 @@ class ProfileCubit extends Cubit<ProfileState> {
}
}
Future<void> getMyProfile({String period = '1'}) async {
Future<void> getMyProfile() async {
myProfileCubit = this;
emit(const ProfileState.loading());
_currentPeriod = period;
try {
final profile = await profileRepository.getMyProfile();
List<ConsultantCertPhotoModel> certPhotos = await consultantRepository.getConsultantCertPhotos();
@@ -69,8 +67,6 @@ class ProfileCubit extends Cubit<ProfileState> {
isMyProfile: true,
profileDetails: await profileRepository.getMyProfileDetails(),
blogPosts: await profileRepository.getBlogPostsByAuthorSlug(slug: profile.slug),
weightPoints: await profileRepository.getWeight(period: period),
circumferencePoints: await profileRepository.getCircumferences(period: period),
consultantInfo: profile.roles.contains('consultant') ? await consultantRepository.getConsultantRequestStatus(profile.slug) : null,
certPhotos: certPhotos,
),
@@ -110,8 +106,6 @@ class ProfileCubit extends Cubit<ProfileState> {
profile: (state as ProfileStateLoaded).profile,
profileDetails: (state as ProfileStateLoaded).profileDetails,
blogPosts: feedBlogPostList,
weightPoints: (state as ProfileStateLoaded).weightPoints,
circumferencePoints: (state as ProfileStateLoaded).circumferencePoints,
consultantInfo: (state as ProfileStateLoaded).consultantInfo,
isMyProfile: (state as ProfileStateLoaded).isMyProfile,
certPhotos: (state as ProfileStateLoaded).certPhotos,
@@ -126,7 +120,6 @@ class ProfileCubit extends Cubit<ProfileState> {
waistCircumference: waistCircumference,
hipCircumference: hipCircumference,
);
await getMyProfile(period: _currentPeriod);
} catch (e, st) {
await reportFrom(e, st, this);
emit(ProfileState.error(errorMessage: e.toString()));
@@ -136,7 +129,6 @@ class ProfileCubit extends Cubit<ProfileState> {
Future<void> addWeight({required double weight}) async {
try {
await profileRepository.addWeight(weight: weight);
await getMyProfile(period: _currentPeriod);
} catch (e, st) {
await reportFrom(e, st, this);
emit(ProfileState.error(errorMessage: e.toString()));

View File

@@ -1,9 +1,7 @@
import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart';
import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/profile/models/circumference_model.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/profile/models/weight_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'profile_state.freezed.dart';
@@ -20,8 +18,6 @@ abstract class ProfileState with _$ProfileState {
required List<FeedBlogPostModel> blogPosts,
required bool isMyProfile,
required List<ConsultantCertPhotoModel> certPhotos,
List<WeightModel>? weightPoints,
List<CircumferenceModel>? circumferencePoints,
ConsultationRequestModel? consultantInfo,
}) = ProfileStateLoaded;

View File

@@ -18,21 +18,17 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/prof
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
import 'package:eatvio_app/features/complaining/presentation/complaining_bottom_sheet.dart';
import 'package:eatvio_app/features/feed/presentation/widgets/plan_widget.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart';
import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_cubit.dart';
import 'package:eatvio_app/features/profile/models/circumference_model.dart';
import 'package:eatvio_app/features/profile/models/weight_model.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/pages/subs_screen.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/circumference_chart_widget.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/expandable_page_view.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/imt_chart_widget.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/profile_blog_post_widget.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/toggle_cert_photo_bottom_sheet.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/weight_chart_widget.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/generated/l10n.dart';
@@ -60,21 +56,8 @@ class ProfileScreen extends StatefulWidget {
class _ProfileScreenState extends State<ProfileScreen> {
late final ProfileCubit profileCubit = sl<ProfileCubit>();
final PlansCubit plansCubit = sl<PlansCubit>();
final List<String> chipsLabelList = ['Вес', 'Замеры', 'ИМТ'];
final List<String> chipsIntervalLabelList = [
'1М',
'3М',
'6М',
'1Г',
'ВСЁ ВРЕМЯ',
];
final List<String> chipsIntervalList = ['1', '3', '6', '12', 'all'];
final TextEditingController controller = TextEditingController();
List<WeightModel> weightPoints = [];
List<CircumferenceModel> circumferencePoints = [];
int _selectedChipIndex = 0;
int _selectedIntervalChipIndex = 0;
late bool canSub;
bool isFirstFetch = true;
int _currentBullet = 0;
@@ -96,10 +79,6 @@ class _ProfileScreenState extends State<ProfileScreen> {
bloc: profileCubit,
builder: (BuildContext context, ProfileState state) {
if (state is ProfileStateLoaded) {
if (state.circumferencePoints != null) {
circumferencePoints = state.circumferencePoints!;
weightPoints = state.weightPoints!;
}
if (isFirstFetch) {
canSub = !state.profile.isEntitySubscribedByMe;
if (state.profile.roles.contains('consultant') && !hidePlans) {
@@ -281,6 +260,14 @@ class _ProfileScreenState extends State<ProfileScreen> {
padding: const EdgeInsets.only(bottom: 16),
child: _badges(state),
),
// Доступ решает сервер (UserPolicy::viewInsights): консультант видит
// клиента, пока консультация не завершена; всем остальным 403 и блок скрыт.
if (!state.profile.isBlockedByMe &&
!state.profile.isBlockedByAuthor)
Padding(
padding: const EdgeInsets.only(bottom: 16),
child: InsightsCard(slug: state.profile.slug),
),
if (state.profile.isBlockedByAuthor)
Column(
mainAxisAlignment: MainAxisAlignment.center,
@@ -442,10 +429,11 @@ class _ProfileScreenState extends State<ProfileScreen> {
child: _badges(state),
),
if (state.profile.roles.contains('consultant')) _socialLinks(state),
Padding(
padding: const EdgeInsets.only(bottom: 16),
child: _charts(),
),
if (state.isMyProfile)
const Padding(
padding: EdgeInsets.only(bottom: 16),
child: InsightsCard(canAdd: true),
),
if (state.profile.roles.contains('consultant')) _education(state),
if (state.profile.roles.contains('consultant'))
_diplomasAndCertificates(state),
@@ -1722,114 +1710,4 @@ class _ProfileScreenState extends State<ProfileScreen> {
],
);
}
Material _charts() {
return Material(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 8),
SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 16),
scrollDirection: Axis.horizontal,
child: Row(
children: [
_choiceChipWidget(0),
const SizedBox(width: 8),
_choiceChipWidget(1),
const SizedBox(width: 8),
_choiceChipWidget(2),
],
),
),
Builder(
builder: (context) {
switch (_selectedChipIndex) {
case 0:
return WeightChartWidget(
weightPoints: weightPoints,
profileCubit: profileCubit,
);
case 1:
return CircumferenceChartWidget(
circumferencePoints: circumferencePoints,
profileCubit: profileCubit,
);
case 2:
return ImtChartWidget(weightPoints: weightPoints);
default:
return const SizedBox.shrink();
}
},
),
const SizedBox(height: 8),
Row(
children: [
const SizedBox(width: 16),
_choiceIntervalChipWidget(0),
const SizedBox(width: 8),
_choiceIntervalChipWidget(1),
const SizedBox(width: 8),
_choiceIntervalChipWidget(2),
const SizedBox(width: 8),
_choiceIntervalChipWidget(3),
const SizedBox(width: 8),
_choiceIntervalChipWidget(4),
],
),
const SizedBox(height: 8),
],
),
);
}
ChoiceChip _choiceIntervalChipWidget(int index) {
return ChoiceChip(
selectedColor: Colors.grey.withValues(alpha: 0.1),
pressElevation: 0,
showCheckmark: false,
side: BorderSide.none,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
label: Text(chipsIntervalLabelList[index]),
labelStyle: TextStyle(
color: appTheme.gray600,
fontWeight: FontWeight.w500,
fontSize: 12,
),
selected: _selectedIntervalChipIndex == index,
onSelected: (bool selected) {
profileCubit.getMyProfile(period: chipsIntervalList[index]);
setState(() {
_selectedIntervalChipIndex = index;
});
},
);
}
ChoiceChip _choiceChipWidget(int index) {
return ChoiceChip(
selectedColor: appTheme.blueA400,
pressElevation: 0,
showCheckmark: false,
side: BorderSide.none,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
label: Text(chipsLabelList[index]),
labelStyle: TextStyle(
color: index == _selectedChipIndex ? Colors.white : appTheme.gray600,
fontWeight: FontWeight.w500,
fontSize: 12,
),
selected: _selectedChipIndex == index,
backgroundColor: appTheme.gray100,
onSelected: (bool selected) {
setState(() {
_selectedChipIndex = index;
});
},
);
}
}

View File

@@ -1,389 +0,0 @@
import 'package:eatvio_app/features/profile/models/circumference_model.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
class CircumferenceChartWidget extends StatefulWidget {
final List<CircumferenceModel> circumferencePoints;
final ProfileCubit? profileCubit;
const CircumferenceChartWidget({
super.key,
required this.circumferencePoints,
this.profileCubit,
});
@override
State<CircumferenceChartWidget> createState() => _CircumferenceChartWidgetState();
}
class _CircumferenceChartWidgetState extends State<CircumferenceChartWidget> {
late FixedExtentScrollController chestController;
late FixedExtentScrollController waistController;
late FixedExtentScrollController hipController;
late int chest;
late int waist;
late int hip;
@override
Widget build(BuildContext context) {
return Column(
children: [
if (widget.circumferencePoints.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
children: [
Text(
'${widget.circumferencePoints.last.chestCircumference}',
style: const TextStyle(
color: Colors.black,
fontSize: 40,
fontWeight: FontWeight.w500,
),
),
if (widget.circumferencePoints.length == 1)
Container(
margin: const EdgeInsets.symmetric(horizontal: 12),
width: 8,
height: 8,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.black12,
),
),
if (widget.circumferencePoints.length > 1)
widget.circumferencePoints.last.chestCircumference > widget.circumferencePoints[widget.circumferencePoints.length - 2].chestCircumference
? const Icon(
Icons.arrow_drop_up,
size: 40,
color: Colors.grey,
)
: const Icon(
Icons.arrow_drop_down,
size: 40,
color: Colors.grey,
),
Text(
'${widget.circumferencePoints.last.waistCircumference}',
style: const TextStyle(
color: Colors.black,
fontSize: 40,
fontWeight: FontWeight.w500,
),
),
if (widget.circumferencePoints.length == 1)
Container(
margin: const EdgeInsets.symmetric(horizontal: 12),
width: 8,
height: 8,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.black12,
),
),
if (widget.circumferencePoints.length > 1)
widget.circumferencePoints.last.waistCircumference > widget.circumferencePoints[widget.circumferencePoints.length - 2].waistCircumference
? const Icon(
Icons.arrow_drop_up,
size: 40,
color: Colors.grey,
)
: const Icon(
Icons.arrow_drop_down,
size: 40,
color: Colors.grey,
),
Text(
'${widget.circumferencePoints.last.hipCircumference}',
style: const TextStyle(
color: Colors.black,
fontSize: 40,
fontWeight: FontWeight.w500,
),
),
if (widget.circumferencePoints.length == 1)
Container(
margin: const EdgeInsets.symmetric(horizontal: 12),
width: 8,
height: 8,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.black12,
),
),
if (widget.circumferencePoints.length > 1)
widget.circumferencePoints.last.hipCircumference > widget.circumferencePoints[widget.circumferencePoints.length - 2].hipCircumference
? const Icon(
Icons.arrow_drop_up,
size: 40,
color: Colors.grey,
)
: const Icon(
Icons.arrow_drop_down,
size: 40,
color: Colors.grey,
),
],
),
),
Stack(
alignment: Alignment.center,
children: [
SfCartesianChart(
margin: const EdgeInsets.symmetric(horizontal: 8),
enableAxisAnimation: true,
plotAreaBorderWidth: 0,
trackballBehavior: TrackballBehavior(
enable: true,
activationMode: ActivationMode.singleTap,
tooltipDisplayMode: TrackballDisplayMode.groupAllPoints,
tooltipSettings: const InteractiveTooltip(),
lineType: TrackballLineType.vertical,
),
primaryXAxis: DateTimeCategoryAxis(
tickPosition: TickPosition.inside,
majorTickLines: const MajorTickLines(
size: 0,
),
edgeLabelPlacement: EdgeLabelPlacement.shift,
dateFormat: DateFormat.MMMd('ru'),
labelStyle: const TextStyle(
color: Colors.grey,
),
majorGridLines: MajorGridLines(dashArray: const [1], color: Colors.grey.withValues(alpha: 0.3)),
axisLine: AxisLine(
color: Colors.grey.withValues(alpha: 0.3),
width: 0.4,
),
),
primaryYAxis: const NumericAxis(
isVisible: false,
labelFormat: '{value} см',
axisLine: AxisLine(
width: 1,
),
majorTickLines: MajorTickLines(size: 0),
),
series: _getSplineSeries(),
tooltipBehavior: TooltipBehavior(enable: true),
),
if (widget.profileCubit != null)
Positioned(
right: 16,
bottom: 16,
child: FloatingActionButton.small(
heroTag: 'addCircumference',
onPressed: () {
if (widget.circumferencePoints.isNotEmpty) {
chest = widget.circumferencePoints.last.chestCircumference;
waist = widget.circumferencePoints.last.waistCircumference;
hip = widget.circumferencePoints.last.hipCircumference;
chestController = FixedExtentScrollController(initialItem: chest - 20);
waistController = FixedExtentScrollController(initialItem: waist - 20);
hipController = FixedExtentScrollController(initialItem: hip - 20);
} else {
chestController = FixedExtentScrollController();
waistController = FixedExtentScrollController();
hipController = FixedExtentScrollController();
}
showModalBottomSheet(
useRootNavigator: true,
context: context,
builder: (context) {
return SafeArea(
child: Column(
children: [
Expanded(
child: Row(
children: [
Expanded(
child: CupertinoPicker(
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
scrollController: chestController,
itemExtent: 24,
onSelectedItemChanged: (int value) {
chest = value;
},
children: [
for (int i = 20; i < 200; i++) Text('$i'),
],
),
),
Expanded(
child: CupertinoPicker(
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
scrollController: waistController,
itemExtent: 24,
onSelectedItemChanged: (int value) {
waist = value;
},
children: [
for (int i = 20; i < 200; i++) Text('$i'),
],
),
),
Expanded(
child: CupertinoPicker(
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
scrollController: hipController,
itemExtent: 24,
onSelectedItemChanged: (int value) {
hip = value;
},
children: [
for (int i = 20; i < 200; i++) Text('$i'),
],
),
),
],
),
),
InkWell(
onTap: () {
widget.profileCubit?.addCircumference(
chestCircumference: chest + 20,
waistCircumference: waist + 20,
hipCircumference: hip + 20,
);
Navigator.of(context).pop();
},
borderRadius: BorderRadius.circular(16),
child: Ink(
width: MediaQuery.of(context).size.width - 32,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(16),
),
child: const Center(
child: Text(
'Сохранить',
style: TextStyle(
color: Colors.white,
),
),
),
),
),
],
),
);
},
);
},
backgroundColor: appTheme.blueA400,
shape: const CircleBorder(),
child: const Icon(
Icons.add,
color: Colors.white,
),
),
),
if (widget.circumferencePoints.isEmpty)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 48),
child: Text(
'Добавьте Ваши замеры',
textAlign: TextAlign.center,
),
),
],
),
],
);
}
List<CartesianSeries<CircumferenceModel, DateTime>> _getSplineSeries() {
const Color seriesColor1 = Colors.red;
final Color seriesColor2 = appTheme.blueA400;
const Color seriesColor3 = Colors.green;
return <CartesianSeries<CircumferenceModel, DateTime>>[
SplineAreaSeries<CircumferenceModel, DateTime>(
markerSettings: const MarkerSettings(
isVisible: true,
color: seriesColor1,
height: 8,
width: 8,
),
dataLabelSettings: const DataLabelSettings(
labelAlignment: ChartDataLabelAlignment.top,
isVisible: true,
),
dataSource: widget.circumferencePoints,
borderColor: seriesColor1,
gradient: LinearGradient(
colors: [
seriesColor1.withValues(alpha: 0.14),
Colors.transparent,
],
begin: Alignment.topCenter,
end: const Alignment(0, 0.6),
),
name: 'Грудь',
xValueMapper: (CircumferenceModel value, int index) => value.createdAt,
yValueMapper: (CircumferenceModel value, int index) => value.chestCircumference,
),
SplineAreaSeries<CircumferenceModel, DateTime>(
markerSettings: MarkerSettings(
isVisible: true,
color: seriesColor2,
height: 8,
width: 8,
),
dataLabelSettings: const DataLabelSettings(
labelAlignment: ChartDataLabelAlignment.top,
isVisible: true,
),
dataSource: widget.circumferencePoints,
borderColor: seriesColor2,
gradient: LinearGradient(
colors: [
seriesColor2.withValues(alpha: 0.14),
Colors.transparent,
],
begin: Alignment.topCenter,
end: const Alignment(0, 0.6),
),
name: 'Талия',
xValueMapper: (CircumferenceModel value, int index) => value.createdAt,
yValueMapper: (CircumferenceModel value, int index) => value.waistCircumference,
),
SplineAreaSeries<CircumferenceModel, DateTime>(
markerSettings: const MarkerSettings(
isVisible: true,
color: seriesColor3,
height: 8,
width: 8,
),
dataLabelSettings: const DataLabelSettings(
labelAlignment: ChartDataLabelAlignment.top,
isVisible: true,
),
dataSource: widget.circumferencePoints,
borderColor: seriesColor3,
gradient: LinearGradient(
colors: [
seriesColor3.withValues(alpha: 0.14),
Colors.transparent,
],
begin: Alignment.topCenter,
end: const Alignment(0, 0.6),
),
name: 'Бёдра',
xValueMapper: (CircumferenceModel value, int index) => value.createdAt,
yValueMapper: (CircumferenceModel value, int index) => value.hipCircumference,
),
];
}
}

View File

@@ -1,127 +0,0 @@
import 'package:eatvio_app/features/profile/models/weight_model.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:intl/intl.dart';
class ImtChartWidget extends StatelessWidget {
final List<WeightModel> weightPoints;
const ImtChartWidget({
super.key,
required this.weightPoints,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
children: [
if (weightPoints.isNotEmpty)
Text(
weightPoints.last.bmi.toStringAsFixed(2),
style: const TextStyle(
color: Colors.black,
fontSize: 40,
fontWeight: FontWeight.w500,
),
),
if (weightPoints.length > 1)
weightPoints.last.bmi > weightPoints[weightPoints.length - 2].bmi
? const Icon(
Icons.arrow_drop_up,
size: 40,
color: Colors.grey,
)
: const Icon(
Icons.arrow_drop_down,
size: 40,
color: Colors.grey,
),
],
),
),
Stack(
alignment: Alignment.center,
children: [
SfCartesianChart(
margin: const EdgeInsets.symmetric(horizontal: 8),
enableAxisAnimation: true,
plotAreaBorderWidth: 0,
trackballBehavior: TrackballBehavior(
enable: true,
activationMode: ActivationMode.singleTap,
tooltipDisplayMode: TrackballDisplayMode.groupAllPoints,
tooltipSettings: const InteractiveTooltip(),
lineType: TrackballLineType.vertical,
),
primaryXAxis: DateTimeCategoryAxis(
tickPosition: TickPosition.inside,
majorTickLines: const MajorTickLines(
size: 0,
),
edgeLabelPlacement: EdgeLabelPlacement.shift,
dateFormat: DateFormat.MMMd('ru'),
labelStyle: const TextStyle(
color: Colors.grey,
),
majorGridLines: MajorGridLines(dashArray: const [1], color: Colors.grey.withValues(alpha: 0.3)),
axisLine: AxisLine(
color: Colors.grey.withValues(alpha: 0.3),
width: 0.4,
),
),
primaryYAxis: const NumericAxis(
isVisible: false,
),
series: _getSplineSeries(),
tooltipBehavior: TooltipBehavior(enable: true),
),
if (weightPoints.isEmpty)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 32),
child: Text(
'Индекс Массы Тела рассчитывается при указанных весе и росте',
textAlign: TextAlign.center,
),
),
],
),
],
);
}
List<CartesianSeries<WeightModel, DateTime>> _getSplineSeries() {
return <CartesianSeries<WeightModel, DateTime>>[
SplineAreaSeries<WeightModel, DateTime>(
markerSettings: MarkerSettings(
isVisible: true,
color: appTheme.blueA400,
height: 8,
width: 8,
),
dataLabelSettings: const DataLabelSettings(
labelAlignment: ChartDataLabelAlignment.top,
isVisible: true,
),
dataSource: weightPoints,
borderColor: appTheme.blueA400,
gradient: LinearGradient(
colors: [
appTheme.blueA400.withValues(alpha: 0.14),
Colors.transparent,
],
begin: Alignment.topCenter,
end: const Alignment(0, 0.6),
),
name: 'ИМТ',
xValueMapper: (WeightModel value, int index) => value.createdAt,
yValueMapper: (WeightModel value, int index) => double.parse(value.bmi.toStringAsFixed(2)),
),
];
}
}

View File

@@ -1,250 +0,0 @@
import 'package:eatvio_app/features/profile/models/weight_model.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
class WeightChartWidget extends StatefulWidget {
final List<WeightModel> weightPoints;
final ProfileCubit? profileCubit;
const WeightChartWidget({
super.key,
required this.weightPoints,
this.profileCubit,
});
@override
State<WeightChartWidget> createState() => _WeightChartWidgetState();
}
class _WeightChartWidgetState extends State<WeightChartWidget> {
late FixedExtentScrollController weightKiloController;
late FixedExtentScrollController weightGramsController;
int weightKilo = 20;
int weightGrams = 0;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (widget.weightPoints.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
children: [
Text(
'${widget.weightPoints.last.weight.toStringAsFixed(1)} кг',
style: const TextStyle(
color: Colors.black,
fontSize: 40,
fontWeight: FontWeight.w500,
),
),
if (widget.weightPoints.length == 1)
Container(
margin: const EdgeInsets.symmetric(horizontal: 12),
width: 8,
height: 8,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.black12,
),
),
if (widget.weightPoints.length > 1)
widget.weightPoints.last.weight > widget.weightPoints[widget.weightPoints.length - 2].weight
? Icon(
Icons.arrow_drop_up,
size: 40,
color: Colors.grey.withValues(alpha: 0.4),
)
: Icon(
Icons.arrow_drop_down,
size: 40,
color: Colors.grey.withValues(alpha: 0.4),
),
],
),
),
Stack(
alignment: Alignment.center,
children: [
SfCartesianChart(
margin: const EdgeInsets.symmetric(horizontal: 8),
enableAxisAnimation: true,
plotAreaBorderWidth: 0,
trackballBehavior: TrackballBehavior(
enable: true,
activationMode: ActivationMode.singleTap,
tooltipDisplayMode: TrackballDisplayMode.groupAllPoints,
tooltipSettings: const InteractiveTooltip(),
lineType: TrackballLineType.vertical,
),
primaryXAxis: DateTimeCategoryAxis(
tickPosition: TickPosition.inside,
majorTickLines: const MajorTickLines(
size: 0,
),
edgeLabelPlacement: EdgeLabelPlacement.shift,
dateFormat: DateFormat.MMMd('ru'),
labelStyle: const TextStyle(
color: Colors.grey,
),
majorGridLines: MajorGridLines(dashArray: const [1], color: Colors.grey.withValues(alpha: 0.3)),
axisLine: AxisLine(
color: Colors.grey.withValues(alpha: 0.3),
width: 0.4,
),
),
primaryYAxis: const NumericAxis(
isVisible: false,
labelFormat: '{value} кг',
majorGridLines: MajorGridLines(dashArray: [1], color: Colors.grey),
axisLine: AxisLine(
width: 1,
),
majorTickLines: MajorTickLines(size: 0),
),
series: _getSplineSeries(),
tooltipBehavior: TooltipBehavior(enable: true),
),
if (widget.profileCubit != null)
Positioned(
right: 16,
bottom: 16,
child: FloatingActionButton.small(
heroTag: 'addWeight',
onPressed: () {
if (widget.weightPoints.isNotEmpty) {
try {
weightKilo = int.parse(widget.weightPoints.last.weight.toString().split('.')[0]);
weightGrams = int.parse(widget.weightPoints.last.weight.toString().split('.')[1][0]);
} catch (e) {
weightGrams = 0;
}
weightKiloController = FixedExtentScrollController(initialItem: weightKilo - 20);
weightGramsController = FixedExtentScrollController(initialItem: weightGrams);
} else {
weightKiloController = FixedExtentScrollController();
weightGramsController = FixedExtentScrollController();
}
showModalBottomSheet(
useRootNavigator: true,
context: context,
builder: (context) {
return SafeArea(
child: Column(
children: [
Expanded(
child: Row(
children: [
Expanded(
child: CupertinoPicker(
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
scrollController: weightKiloController,
itemExtent: 24,
onSelectedItemChanged: (int value) {
weightKilo = value + 20;
},
children: [
for (int i = 20; i < 300; i++) Text('$i'),
],
),
),
Expanded(
child: CupertinoPicker(
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
scrollController: weightGramsController,
itemExtent: 24,
onSelectedItemChanged: (int value) {
weightGrams = value;
},
children: [
for (int i = 0; i < 10; i++) Text('$i'),
],
),
),
],
),
),
InkWell(
onTap: () {
widget.profileCubit?.addWeight(weight: double.parse('$weightKilo.$weightGrams'));
Navigator.of(context).pop();
},
borderRadius: BorderRadius.circular(16),
child: Ink(
width: MediaQuery.of(context).size.width - 32,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(16),
),
child: const Center(
child: Text(
'Сохранить',
style: TextStyle(
color: Colors.white,
),
),
),
),
),
],
),
);
},
);
},
backgroundColor: appTheme.blueA400,
shape: const CircleBorder(),
child: const Icon(
Icons.add,
color: Colors.white,
),
),
),
if (widget.weightPoints.isEmpty) const Text('Добавьте Ваш вес'),
],
),
],
);
}
List<CartesianSeries<WeightModel, DateTime>> _getSplineSeries() {
return <CartesianSeries<WeightModel, DateTime>>[
SplineAreaSeries<WeightModel, DateTime>(
markerSettings: MarkerSettings(
isVisible: true,
color: appTheme.blueA400,
height: 8,
width: 8,
),
dataLabelSettings: const DataLabelSettings(
labelAlignment: ChartDataLabelAlignment.top,
isVisible: true,
),
dataSource: widget.weightPoints,
borderColor: appTheme.blueA400,
gradient: LinearGradient(
colors: [
appTheme.blueA400.withValues(alpha: 0.14),
Colors.transparent,
],
begin: Alignment.topCenter,
end: const Alignment(0, 0.6),
),
name: 'Вес',
xValueMapper: (WeightModel value, int index) => value.createdAt,
yValueMapper: (WeightModel value, int index) => value.weight,
),
];
}
}

View File

@@ -14,23 +14,10 @@ class UserDetailsCubit extends Cubit<UserDetailsState> {
try {
final profileDetails = await profileRepository.getProfileDetailsBySlug(slug);
emit(state.copyWith(profileDetails: profileDetails, isLoading: false));
getChartData(slug: slug);
} catch (e, st) {
await reportFrom(e, st, this);
log(e.toString());
emit(state.copyWith(error: e.toString(), isLoading: false));
}
}
void getChartData({String period = '1', required String slug}) async {
try {
final weightPoints = await profileRepository.getWeight(period: period, slug: slug);
final circumferencePoints = await profileRepository.getCircumferences(period: period, slug: slug);
emit(state.copyWith(weightPoints: weightPoints, circumferencePoints: circumferencePoints));
} catch (e, stackTrace) {
await reportFrom(e, stackTrace, this);
log(e.toString(), stackTrace: stackTrace);
emit(state.copyWith(error: e.toString(), isLoading: false));
}
}
}

View File

@@ -1,6 +1,4 @@
import 'package:eatvio_app/features/profile/models/circumference_model.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/profile/models/weight_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user_details_state.freezed.dart';
@@ -11,7 +9,5 @@ abstract class UserDetailsState with _$UserDetailsState {
@Default(false) bool isLoading,
String? error,
ProfileDetailsModel? profileDetails,
List<WeightModel>? weightPoints,
List<CircumferenceModel>? circumferencePoints,
}) = _UserDetailsState;
}

View File

@@ -8,11 +8,7 @@ import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/core/widgets/data_error_widget.dart';
import 'package:eatvio_app/core/widgets/loader.dart';
import 'package:eatvio_app/features/diets/presentation/widgets/more_options.dart';
import 'package:eatvio_app/features/profile/models/circumference_model.dart';
import 'package:eatvio_app/features/profile/models/weight_model.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/circumference_chart_widget.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/imt_chart_widget.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/weight_chart_widget.dart';
import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart';
import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart';
import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_state.dart';
import 'package:eatvio_app/features/user_details/presentation/widgets/expandable_bouble.dart';
@@ -44,13 +40,6 @@ class UserDetailsContent extends StatefulWidget {
}
class _UserDetailsContentState extends State<UserDetailsContent> {
final List<String> chipsLabelList = ['Вес', 'Замеры', 'ИМТ'];
final List<String> chipsIntervalLabelList = ['1М', '3М', '6М', '1Г', 'ВСЁ ВРЕМЯ'];
final List<String> chipsIntervalList = ['1', '3', '6', '12', 'all'];
List<WeightModel> weightPoints = [];
List<CircumferenceModel> circumferencePoints = []; int _selectedChipIndex = 0;
int _selectedIntervalChipIndex = 0;
bool isMoreOptionsVisible = false;
@override
Widget build(BuildContext context) {
@@ -59,8 +48,6 @@ class _UserDetailsContentState extends State<UserDetailsContent> {
builder: (context, state) {
final profileDetails = state.profileDetails;
if (profileDetails != null && state.isLoading == false) {
weightPoints = state.weightPoints ?? [];
circumferencePoints = state.circumferencePoints ?? [];
return Scaffold(
backgroundColor: appTheme.gray100,
appBar: AppBar(
@@ -104,7 +91,7 @@ class _UserDetailsContentState extends State<UserDetailsContent> {
spacing: 12,
children: [
const SizedBox.shrink(),
_charts(),
InsightsCard(slug: widget.slug),
ExpandableBouble(
initiallyExpanded: true,
title: s.general_info,
@@ -309,92 +296,4 @@ class _UserDetailsContentState extends State<UserDetailsContent> {
},
);
}
Material _charts() {
return Material(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 8),
SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 16),
scrollDirection: Axis.horizontal,
child: Row(children: [_choiceChipWidget(0), const SizedBox(width: 8), _choiceChipWidget(1), const SizedBox(width: 8), _choiceChipWidget(2)]),
),
Builder(
builder: (context) {
switch (_selectedChipIndex) {
case 0:
return WeightChartWidget(weightPoints: weightPoints);
case 1:
return CircumferenceChartWidget(circumferencePoints: circumferencePoints);
case 2:
return ImtChartWidget(weightPoints: weightPoints);
default:
return const SizedBox.shrink();
}
},
),
const SizedBox(height: 8),
Row(
children: [
const SizedBox(width: 16),
_choiceIntervalChipWidget(0),
const SizedBox(width: 8),
_choiceIntervalChipWidget(1),
const SizedBox(width: 8),
_choiceIntervalChipWidget(2),
const SizedBox(width: 8),
_choiceIntervalChipWidget(3),
const SizedBox(width: 8),
_choiceIntervalChipWidget(4),
],
),
const SizedBox(height: 8),
],
),
);
}
ChoiceChip _choiceIntervalChipWidget(int index) {
return ChoiceChip(
selectedColor: Colors.grey.withValues(alpha: 0.1),
pressElevation: 0,
showCheckmark: false,
side: BorderSide.none,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
label: Text(chipsIntervalLabelList[index]),
labelStyle: TextStyle(color: appTheme.gray600, fontWeight: FontWeight.w500, fontSize: 12),
selected: _selectedIntervalChipIndex == index,
onSelected: (bool selected) {
context.read<UserDetailsCubit>().getChartData(period: chipsIntervalList[index], slug: widget.slug);
setState(() {
_selectedIntervalChipIndex = index;
});
},
);
}
ChoiceChip _choiceChipWidget(int index) {
return ChoiceChip(
selectedColor: appTheme.blueA400,
pressElevation: 0,
showCheckmark: false,
side: BorderSide.none,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
label: Text(chipsLabelList[index]),
labelStyle: TextStyle(color: index == _selectedChipIndex ? Colors.white : appTheme.gray600, fontWeight: FontWeight.w500, fontSize: 12),
selected: _selectedChipIndex == index,
backgroundColor: appTheme.gray100,
onSelected: (bool selected) {
setState(() {
_selectedChipIndex = index;
});
},
);
}
}