forked from eatvio/eatvio_app
feat(insights): added kbju fetching for analitics
This commit is contained in:
@@ -2,6 +2,7 @@ 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';
|
||||
@@ -35,17 +36,30 @@ class InsightsCubit extends Cubit<InsightsState> {
|
||||
|
||||
Future<void> load() async {
|
||||
emit(const InsightsState.loading());
|
||||
await _fetch(bodyPeriod: BodyPeriod.threeMonths, previous: null);
|
||||
await _fetch(
|
||||
bodyPeriod: BodyPeriod.threeMonths,
|
||||
dailyPeriod: DailyPeriod.twoWeeks,
|
||||
intraDate: null,
|
||||
previous: null,
|
||||
);
|
||||
}
|
||||
|
||||
/// Перезапрашивает данные, сохраняя вкладку, период, серии и раскрытие.
|
||||
Future<void> refresh() async {
|
||||
final current = state;
|
||||
if (current is InsightsStateLoading || current is InsightsStateHidden) {
|
||||
return;
|
||||
}
|
||||
if (current is! InsightsStateLoaded) {
|
||||
return load();
|
||||
}
|
||||
emit(current.copyWith(isRefreshing: true));
|
||||
await _fetch(bodyPeriod: current.bodyPeriod, previous: current);
|
||||
await _fetch(
|
||||
bodyPeriod: current.bodyPeriod,
|
||||
dailyPeriod: current.dailyPeriod,
|
||||
intraDate: current.intraDate,
|
||||
previous: current,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setBodyPeriod(BodyPeriod period) async {
|
||||
@@ -54,7 +68,100 @@ class InsightsCubit extends Cubit<InsightsState> {
|
||||
return;
|
||||
}
|
||||
emit(current.copyWith(bodyPeriod: period, isRefreshing: true));
|
||||
await _fetch(bodyPeriod: period, previous: current);
|
||||
await _fetch(
|
||||
bodyPeriod: period,
|
||||
dailyPeriod: current.dailyPeriod,
|
||||
intraDate: current.intraDate,
|
||||
previous: current,
|
||||
);
|
||||
}
|
||||
|
||||
/// Период вкладки «КБЖУ по дням». Работает только с серверными данными.
|
||||
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,
|
||||
previous: current,
|
||||
);
|
||||
}
|
||||
|
||||
/// Показывает вкладку «В течение дня» за [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 ||
|
||||
(current.payload.intra?.isToday ?? true)) {
|
||||
return;
|
||||
}
|
||||
await setIntraDate(DateTime(base.year, base.month, base.day + 1));
|
||||
}
|
||||
|
||||
DateTime? _currentIntraDay() {
|
||||
final current = state;
|
||||
if (!kbjuEnabled || current is! InsightsStateLoaded) {
|
||||
return null;
|
||||
}
|
||||
return DateTime.tryParse(current.payload.intra?.date ?? '');
|
||||
}
|
||||
|
||||
Future<void> _loadIntra(String date) async {
|
||||
final current = state;
|
||||
if (!kbjuEnabled || current is! InsightsStateLoaded) {
|
||||
return;
|
||||
}
|
||||
final requestId = ++_requestId;
|
||||
emit(current.copyWith(isRefreshing: true));
|
||||
try {
|
||||
final intra = await repository.fetchIntra(slug: slug, intraDate: date);
|
||||
if (requestId != _requestId || isClosed) {
|
||||
return;
|
||||
}
|
||||
emit(
|
||||
current.copyWith(
|
||||
payload: current.payload.copyWith(intra: intra),
|
||||
intraDate: intra.isToday
|
||||
? null
|
||||
: (intra.date.isEmpty ? date : intra.date),
|
||||
isRefreshing: false,
|
||||
),
|
||||
);
|
||||
} on InsightsForbidden {
|
||||
if (requestId == _requestId && !isClosed) {
|
||||
emit(const InsightsState.hidden());
|
||||
}
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString(), stackTrace: st);
|
||||
if (requestId == _requestId && !isClosed) {
|
||||
emit(current.copyWith(isRefreshing: false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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() {
|
||||
@@ -136,30 +243,59 @@ class InsightsCubit extends Cubit<InsightsState> {
|
||||
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 InsightsStateLoaded? previous,
|
||||
}) async {
|
||||
final requestId = ++_requestId;
|
||||
try {
|
||||
if (!_isHeightLoaded) {
|
||||
_heightCm = await repository.getHeightCm(slug: slug);
|
||||
_isHeightLoaded = true;
|
||||
}
|
||||
final payload = await repository.getInsights(
|
||||
slug: slug,
|
||||
final payload = await _requestPayload(
|
||||
bodyPeriod: bodyPeriod,
|
||||
heightCm: _heightCm,
|
||||
dailyPeriod: dailyPeriod,
|
||||
intraDate: intraDate,
|
||||
);
|
||||
if (requestId != _requestId || isClosed) {
|
||||
return;
|
||||
}
|
||||
emit(
|
||||
previous == null
|
||||
? InsightsState.loaded(payload: payload, bodyPeriod: bodyPeriod)
|
||||
? InsightsState.loaded(
|
||||
payload: payload,
|
||||
bodyPeriod: bodyPeriod,
|
||||
dailyPeriod: dailyPeriod,
|
||||
intraDate: intraDate,
|
||||
)
|
||||
: previous.copyWith(
|
||||
payload: payload,
|
||||
bodyPeriod: bodyPeriod,
|
||||
dailyPeriod: dailyPeriod,
|
||||
intraDate: intraDate,
|
||||
isRefreshing: false,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -35,6 +35,10 @@ abstract class InsightsState with _$InsightsState {
|
||||
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,
|
||||
|
||||
@@ -37,6 +37,7 @@ class InsightsCard extends StatelessWidget {
|
||||
this.canAdd = false,
|
||||
this.repository,
|
||||
this.kbjuEnabled = InsightsFeatureFlags.kbjuEnabled,
|
||||
this.refreshToken = 0,
|
||||
});
|
||||
|
||||
final String? slug;
|
||||
@@ -44,6 +45,10 @@ class InsightsCard extends StatelessWidget {
|
||||
final InsightsRepository? repository;
|
||||
final bool kbjuEnabled;
|
||||
|
||||
/// При смене значения блок перезапрашивает данные (например, после правок
|
||||
/// в дневнике), сохраняя вкладку, период и выбранный день.
|
||||
final int refreshToken;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return KeyedSubtree(
|
||||
@@ -55,14 +60,29 @@ class InsightsCard extends StatelessWidget {
|
||||
canAdd: canAdd,
|
||||
kbjuEnabled: kbjuEnabled,
|
||||
)..load(),
|
||||
child: const _InsightsView(),
|
||||
child: _InsightsView(refreshToken: refreshToken),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _InsightsView extends StatelessWidget {
|
||||
const _InsightsView();
|
||||
class _InsightsView extends StatefulWidget {
|
||||
const _InsightsView({required this.refreshToken});
|
||||
|
||||
final int refreshToken;
|
||||
|
||||
@override
|
||||
State<_InsightsView> createState() => _InsightsViewState();
|
||||
}
|
||||
|
||||
class _InsightsViewState extends State<_InsightsView> {
|
||||
@override
|
||||
void didUpdateWidget(covariant _InsightsView oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.refreshToken != widget.refreshToken) {
|
||||
context.read<InsightsCubit>().refresh();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -113,7 +133,7 @@ class _ErrorContent extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
@@ -158,9 +178,9 @@ class _LoadedContent extends StatelessWidget {
|
||||
child: state.isExpanded
|
||||
? Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
16,
|
||||
0,
|
||||
20,
|
||||
16,
|
||||
showFab ? 24 + 44 : 24,
|
||||
),
|
||||
child: _Body(state: state),
|
||||
@@ -241,7 +261,7 @@ class _Toggle extends StatelessWidget {
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
@@ -443,8 +463,7 @@ class _PanelContent extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// «КБЖУ по дням». Период пока фиксирован: перезапрос появится вместе с
|
||||
/// эндпоинтом `GET /api/profile/insights` (итерация 2).
|
||||
/// «КБЖУ по дням». Смена периода перезапрашивает `GET /api/profile/insights`.
|
||||
class _DailyPanel extends StatelessWidget {
|
||||
const _DailyPanel({required this.state});
|
||||
|
||||
@@ -462,9 +481,10 @@ class _DailyPanel extends StatelessWidget {
|
||||
children: [
|
||||
PeriodPills<DailyPeriod>(
|
||||
periods: DailyPeriod.values,
|
||||
selected: DailyPeriod.twoWeeks,
|
||||
selected: state.dailyPeriod,
|
||||
labelOf: (period) => period.pillLabel(s),
|
||||
keyOf: (period) => period.apiValue,
|
||||
onSelected: cubit.setDailyPeriod,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (daily == null)
|
||||
@@ -474,7 +494,7 @@ class _DailyPanel extends StatelessWidget {
|
||||
headline: daily.headline,
|
||||
unit: s.insights_unit_kcal_avg,
|
||||
deltaText: daily.deltaText,
|
||||
isDeltaHighlighted: daily.percent != null,
|
||||
isDeltaHighlighted: (daily.percent ?? 0) != 0,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SeriesChips(
|
||||
@@ -510,7 +530,7 @@ class _DailyPanel extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// «В течение дня». Навигация по датам неактивна до итерации 2.
|
||||
/// «В течение дня». Листание дней запрашивает только `/insights/intra`.
|
||||
class _IntraPanel extends StatelessWidget {
|
||||
const _IntraPanel({required this.state});
|
||||
|
||||
@@ -530,7 +550,12 @@ class _IntraPanel extends StatelessWidget {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
IntraDateNav(model: intra),
|
||||
IntraDateNav(
|
||||
model: intra,
|
||||
onPreviousDay: cubit.showPreviousDay,
|
||||
onNextDay: cubit.showNextDay,
|
||||
onDatePicked: cubit.setIntraDate,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SeriesChips(
|
||||
chips: [
|
||||
|
||||
Reference in New Issue
Block a user