feat(app): offline-кэш на остальных экранах — фаза 5

accounts, cashflow, categories, goals, income, portfolio (+instrument),
rebalance, tax, rules переведены на Cached<T> по контракту
docs/ai/offline-cache.md. Общие/второстепенные селекторы (scopesProvider,
categoriesListProvider и т.п.) оставлены как есть — не основной контент
экрана. sync_page.dart и settings_page.dart не тронуты (первый — заменён
health-page отдельно, второй — чистые действия без списка для баннера).
This commit is contained in:
Dmitry
2026-09-19 14:00:13 +03:00
parent ffc5ed959a
commit 7b419f4188
39 changed files with 388 additions and 186 deletions
@@ -36,7 +36,8 @@ class AllocationTab extends ConsumerWidget {
child: AsyncValueView(
value: allocation,
onRetry: () => ref.invalidate(allocationProvider),
data: (rows) {
data: (cached) {
final rows = cached.data;
if (rows.isEmpty) {
return ListView(
children: const [
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/api/api_client.dart';
import '../../core/cache/cached.dart';
import '../../core/utils/ru_date.dart';
import '../../core/widgets/async_value_view.dart';
import '../../core/widgets/empty_state.dart';
@@ -13,8 +14,9 @@ final benchmarksApiProvider =
Provider<BenchmarksApi>((ref) => BenchmarksApi(ref.watch(apiProvider).dio));
/// Benchmark comparison for the current scope. Part of Портфель, not a screen of its own:
/// «на сколько я обогнал индекс» is a property of the portfolio, not a separate subject.
final benchmarkRowsProvider = FutureProvider.autoDispose<List<BenchmarkRow>>((ref) async {
/// «на сколько я обогнал индекс» is a property of the portfolio, not a separate subject. See
/// `docs/ai/offline-cache.md`.
final benchmarkRowsProvider = FutureProvider.autoDispose<Cached<List<BenchmarkRow>>>((ref) async {
final scope = ref.watch(scopeProvider);
return ref.watch(benchmarksApiProvider).compare(scope: scope);
});
@@ -34,7 +36,7 @@ class BenchmarksCard extends ConsumerWidget {
return AsyncValueView(
value: rows,
onRetry: () => ref.invalidate(benchmarkRowsProvider),
data: (data) => data.isEmpty
data: (cached) => cached.data.isEmpty
? const EmptyState(
icon: Icons.compare_arrows,
message: 'Бенчмарки не настроены — сравнивать не с чем.',
@@ -42,7 +44,7 @@ class BenchmarksCard extends ConsumerWidget {
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final row in data)
for (final row in cached.data)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: _PeriodBlock(row: row),
@@ -10,6 +10,7 @@ library;
import 'package:dio/dio.dart';
import '../../../core/cache/cached.dart';
import '../../../core/utils/json.dart';
/// One benchmark inside one period row.
@@ -92,7 +93,9 @@ class BenchmarksApi {
final Dio _dio;
Future<List<BenchmarkRow>> compare({
/// See `docs/ai/offline-cache.md`: this hand-written client returns `Cached<T>` directly
/// (there is no generated `Response<T>` for `BenchmarksCard` to unwrap `r.cached` from).
Future<Cached<List<BenchmarkRow>>> compare({
String scope = 'all',
List<String> periods = const ['1m', 'ytd', '1y', 'all'],
}) async {
@@ -101,6 +104,7 @@ class BenchmarksApi {
// `period` is repeatable; Dio serialises a list as repeated query parameters.
queryParameters: {'scope': scope, 'period': periods},
);
return asObjects((r.data ?? const {})['rows']).map(BenchmarkRow.fromJson).toList();
final rows = asObjects((r.data ?? const {})['rows']).map(BenchmarkRow.fromJson).toList();
return Cached(rows, fetchedAt: r.extra['fetchedAt'] as DateTime?);
}
}
+7 -7
View File
@@ -35,7 +35,7 @@ class HoldingsTab extends ConsumerWidget {
AsyncValueView(
value: summary,
onRetry: () => ref.invalidate(portfolioSummaryProvider),
data: (s) => _SummaryTiles(summary: s),
data: (cached) => _SummaryTiles(summary: cached.data),
),
const SizedBox(height: 20),
_Card(
@@ -43,9 +43,9 @@ class HoldingsTab extends ConsumerWidget {
child: AsyncValueView(
value: series,
onRetry: () => ref.invalidate(valueSeriesProvider),
data: (rows) => rows.isEmpty
data: (cached) => cached.data.isEmpty
? const EmptyState(icon: Icons.show_chart, message: 'Пока нет данных.')
: _ValueChart(rows: rows),
: _ValueChart(rows: cached.data),
),
),
const SizedBox(height: 16),
@@ -54,9 +54,9 @@ class HoldingsTab extends ConsumerWidget {
child: AsyncValueView(
value: returns,
onRetry: () => ref.invalidate(portfolioReturnsProvider),
data: (rows) => rows.isEmpty
data: (cached) => cached.data.isEmpty
? const EmptyState(icon: Icons.percent, message: 'Пока нечего считать.')
: _ReturnsTable(rows: rows),
: _ReturnsTable(rows: cached.data),
),
),
const SizedBox(height: 16),
@@ -70,12 +70,12 @@ class HoldingsTab extends ConsumerWidget {
child: AsyncValueView(
value: holdings,
onRetry: () => ref.invalidate(holdingsProvider),
data: (rows) => rows.isEmpty
data: (cached) => cached.data.isEmpty
? const EmptyState(
icon: Icons.inventory_2_outlined,
message: 'Открытых позиций нет — нужна синхронизация брокера.',
)
: _HoldingsTable(rows: rows),
: _HoldingsTable(rows: cached.data),
),
),
],
+37 -32
View File
@@ -9,6 +9,7 @@ import '../../core/utils/ru_date.dart';
import '../../core/widgets/async_value_view.dart';
import '../../core/widgets/empty_state.dart';
import '../../core/widgets/money_text.dart';
import '../../core/widgets/stale_banner.dart';
import 'labels.dart';
import 'providers.dart';
@@ -28,43 +29,47 @@ class InstrumentPage extends ConsumerWidget {
return Scaffold(
appBar: AppBar(
title: Text(detail.valueOrNull?.instrument.ticker ??
detail.valueOrNull?.instrument.name ??
title: Text(detail.valueOrNull?.data.instrument.ticker ??
detail.valueOrNull?.data.instrument.name ??
'Инструмент'),
),
body: AsyncValueView(
value: detail,
onRetry: () => ref.invalidate(instrumentProvider(instrumentId)),
data: (d) => ListView(
padding: const EdgeInsets.all(16),
children: [
_Header(instrument: d.instrument, holding: d.holding),
const SizedBox(height: 16),
_Section(
title: 'Цена',
child: d.prices.isEmpty
? const EmptyState(
icon: Icons.show_chart,
message: 'Цен нет — стоимость позиции неизвестна.',
)
: _PriceChart(prices: d.prices),
),
const SizedBox(height: 16),
_Section(
title: 'Лоты',
child: d.lots.isEmpty
? const EmptyState(icon: Icons.layers_outlined, message: 'Лотов нет.')
: _LotsTable(lots: d.lots),
),
const SizedBox(height: 16),
_Section(
title: 'События',
child: d.events.isEmpty
? const EmptyState(icon: Icons.receipt_long, message: 'Событий нет.')
: _EventsTable(events: d.events),
),
],
),
data: (cached) {
final d = cached.data;
return ListView(
padding: const EdgeInsets.all(16),
children: [
if (cached.fetchedAt != null) StaleBanner(fetchedAt: cached.fetchedAt!),
_Header(instrument: d.instrument, holding: d.holding),
const SizedBox(height: 16),
_Section(
title: 'Цена',
child: d.prices.isEmpty
? const EmptyState(
icon: Icons.show_chart,
message: 'Цен нет — стоимость позиции неизвестна.',
)
: _PriceChart(prices: d.prices),
),
const SizedBox(height: 16),
_Section(
title: 'Лоты',
child: d.lots.isEmpty
? const EmptyState(icon: Icons.layers_outlined, message: 'Лотов нет.')
: _LotsTable(lots: d.lots),
),
const SizedBox(height: 16),
_Section(
title: 'События',
child: d.events.isEmpty
? const EmptyState(icon: Icons.receipt_long, message: 'Событий нет.')
: _EventsTable(events: d.events),
),
],
);
},
),
);
}
+27 -1
View File
@@ -2,8 +2,11 @@ import 'package:fintracker_api/fintracker_api.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/cache/cached.dart';
import '../../core/widgets/async_value_view.dart';
import '../../core/widgets/stale_banner.dart';
import 'allocation_tab.dart';
import 'benchmarks_card.dart';
import 'holdings_tab.dart';
import 'providers.dart';
@@ -12,11 +15,23 @@ import 'providers.dart';
/// They are tabs rather than two navigation destinations because they answer two halves of
/// the same question, and because a tenth item in the bottom bar would leave 40 px per
/// label on a phone.
///
/// One offline banner covers both tabs (`docs/ai/offline-cache.md`) — `TabBarView` builds
/// both eagerly anyway, so watching every provider here to compute it costs nothing extra.
class PortfolioPage extends ConsumerWidget {
const PortfolioPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final stale = oldestFetch([
ref.watch(portfolioSummaryProvider).valueOrNull?.fetchedAt,
ref.watch(holdingsProvider).valueOrNull?.fetchedAt,
ref.watch(valueSeriesProvider).valueOrNull?.fetchedAt,
ref.watch(portfolioReturnsProvider).valueOrNull?.fetchedAt,
ref.watch(benchmarkRowsProvider).valueOrNull?.fetchedAt,
ref.watch(allocationProvider).valueOrNull?.fetchedAt,
]);
return DefaultTabController(
length: 2,
child: Scaffold(
@@ -27,7 +42,18 @@ class PortfolioPage extends ConsumerWidget {
tabs: [Tab(text: 'Позиции'), Tab(text: 'Аллокация')],
),
),
body: const TabBarView(children: [HoldingsTab(), AllocationTab()]),
body: Column(
children: [
if (stale != null)
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: StaleBanner(fetchedAt: stale),
),
const Expanded(
child: TabBarView(children: [HoldingsTab(), AllocationTab()]),
),
],
),
),
);
}
+18 -12
View File
@@ -2,6 +2,7 @@ import 'package:fintracker_api/fintracker_api.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/api/api_client.dart';
import '../../core/cache/cached.dart';
import 'benchmarks_card.dart' show benchmarkRowsProvider;
/// The reporting unit every portfolio screen is scoped to: `all`, `account:<id>` or
@@ -9,37 +10,42 @@ import 'benchmarks_card.dart' show benchmarkRowsProvider;
/// and the instrument card — three screens showing different scopes would be a trap.
final scopeProvider = StateProvider<String>((ref) => 'all');
/// A small cross-screen selector (Портфель, Доходы, Налоги, the goal dialog), not a screen's
/// own primary read — left un-cached per `docs/ai/offline-cache.md`. The underlying `GET`
/// still gets served from the shared cache transparently on a network failure; this provider
/// just does not surface `fetchedAt` for a banner.
final scopesProvider = FutureProvider.autoDispose<List<ScopeOut>>((ref) async {
final r = await ref.watch(apiProvider).getAnalyticsApi().analyticsScopes();
return r.data ?? const [];
});
final portfolioSummaryProvider = FutureProvider.autoDispose<SummaryOut>((ref) async {
/// See `docs/ai/offline-cache.md`.
final portfolioSummaryProvider = FutureProvider.autoDispose<Cached<SummaryOut>>((ref) async {
final scope = ref.watch(scopeProvider);
final r = await ref.watch(apiProvider).getAnalyticsApi().analyticsSummary(scope: scope);
return r.data!;
return r.cached;
});
final holdingsProvider = FutureProvider.autoDispose<List<HoldingOut>>((ref) async {
final holdingsProvider = FutureProvider.autoDispose<Cached<List<HoldingOut>>>((ref) async {
final scope = ref.watch(scopeProvider);
final r = await ref.watch(apiProvider).getAnalyticsApi().analyticsHoldings(scope: scope);
return r.data ?? const [];
return Cached(r.data ?? const [], fetchedAt: r.extra['fetchedAt'] as DateTime?);
});
final portfolioReturnsProvider = FutureProvider.autoDispose<List<ReturnsOut>>((ref) async {
final portfolioReturnsProvider = FutureProvider.autoDispose<Cached<List<ReturnsOut>>>((ref) async {
final scope = ref.watch(scopeProvider);
final r = await ref.watch(apiProvider).getAnalyticsApi().analyticsReturns(scope: scope);
return r.data ?? const [];
return Cached(r.data ?? const [], fetchedAt: r.extra['fetchedAt'] as DateTime?);
});
final allocationProvider = FutureProvider.autoDispose<List<AllocationBucket>>((ref) async {
final allocationProvider = FutureProvider.autoDispose<Cached<List<AllocationBucket>>>((ref) async {
final scope = ref.watch(scopeProvider);
final r = await ref.watch(apiProvider).getAnalyticsApi().analyticsAllocation(scope: scope);
return r.data ?? const [];
return Cached(r.data ?? const [], fetchedAt: r.extra['fetchedAt'] as DateTime?);
});
/// Daily portfolio value for the last year, for the chart on Позиции.
final valueSeriesProvider = FutureProvider.autoDispose<List<ValueDay>>((ref) async {
final valueSeriesProvider = FutureProvider.autoDispose<Cached<List<ValueDay>>>((ref) async {
final scope = ref.watch(scopeProvider);
final now = DateTime.now();
final r = await ref.watch(apiProvider).getAnalyticsApi().analyticsValueSeries(
@@ -47,17 +53,17 @@ final valueSeriesProvider = FutureProvider.autoDispose<List<ValueDay>>((ref) asy
from: now.subtract(const Duration(days: 365)),
to: now,
);
return r.data ?? const [];
return Cached(r.data ?? const [], fetchedAt: r.extra['fetchedAt'] as DateTime?);
});
final instrumentProvider =
FutureProvider.autoDispose.family<InstrumentDetail, int>((ref, instrumentId) async {
FutureProvider.autoDispose.family<Cached<InstrumentDetail>, int>((ref, instrumentId) async {
final scope = ref.watch(scopeProvider);
final r = await ref
.watch(apiProvider)
.getInstrumentsApi()
.instrumentsGet(instrumentId: instrumentId, scope: scope);
return r.data!;
return r.cached;
});
/// Every portfolio provider, refreshed together after a metrics rebuild or a pull-to-refresh.