feat(app): offline-кэш GET-запросов на дашборде — фаза 5
CacheInterceptor кэширует каждый успешный GET по путь+параметры в drift (sqlite нативно, wasm+OPFS в браузере) и подменяет им сетевую ошибку; провайдер отдаёт Cached<T>, экран показывает баннер «данные на …». Контракт для остальных экранов — docs/ai/offline-cache.md. flake.nix: libsecret/pkg-config для линуксовой сборки, jq/curl для just app-web-assets (сборка sqlite3.wasm + drift_worker.js).
This commit is contained in:
@@ -7,11 +7,13 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/auth/auth_controller.dart';
|
||||
import '../../core/cache/cached.dart';
|
||||
import '../../core/theme/chart_colors.dart';
|
||||
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 '../../core/api/api_client.dart';
|
||||
import 'providers.dart';
|
||||
|
||||
@@ -109,6 +111,17 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
final dataQuality = ref.watch(dataQualityProvider);
|
||||
final portfolio = ref.watch(portfolioSummaryHomeProvider);
|
||||
|
||||
final stale = oldestFetch([
|
||||
breakdown.valueOrNull?.fetchedAt,
|
||||
series.valueOrNull?.fetchedAt,
|
||||
thisMonth.valueOrNull?.fetchedAt,
|
||||
last12.valueOrNull?.fetchedAt,
|
||||
runway.valueOrNull?.fetchedAt,
|
||||
status.valueOrNull?.fetchedAt,
|
||||
dataQuality.valueOrNull?.fetchedAt,
|
||||
portfolio.valueOrNull?.fetchedAt,
|
||||
]);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Обзор'),
|
||||
@@ -128,13 +141,15 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
if (stale != null) StaleBanner(fetchedAt: stale),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: AsyncValueView(
|
||||
value: status,
|
||||
onRetry: () => ref.invalidate(metricsStatusProvider),
|
||||
data: (log) {
|
||||
data: (cached) {
|
||||
final log = cached.data;
|
||||
final at = log?.finishedAt ?? log?.startedAt;
|
||||
final text = at == null
|
||||
? 'Данные ещё не пересчитывались'
|
||||
@@ -145,15 +160,18 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
),
|
||||
AsyncValueView(
|
||||
value: dataQuality,
|
||||
data: (rows) => ActionChip(
|
||||
avatar: Icon(
|
||||
rows.isEmpty ? Icons.check_circle_outline : Icons.warning_amber_outlined,
|
||||
size: 18,
|
||||
color: rows.isEmpty ? Colors.green : _severityColor(rows.first.severity),
|
||||
),
|
||||
label: Text(rows.isEmpty ? 'ок' : '${rows.length} замечаний'),
|
||||
onPressed: rows.isEmpty ? null : () => _showDataQuality(rows),
|
||||
),
|
||||
data: (cached) {
|
||||
final rows = cached.data;
|
||||
return ActionChip(
|
||||
avatar: Icon(
|
||||
rows.isEmpty ? Icons.check_circle_outline : Icons.warning_amber_outlined,
|
||||
size: 18,
|
||||
color: rows.isEmpty ? Colors.green : _severityColor(rows.first.severity),
|
||||
),
|
||||
label: Text(rows.isEmpty ? 'ок' : '${rows.length} замечаний'),
|
||||
onPressed: rows.isEmpty ? null : () => _showDataQuality(rows),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -161,7 +179,7 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
AsyncValueView(
|
||||
value: breakdown,
|
||||
onRetry: () => ref.invalidate(netWorthBreakdownProvider),
|
||||
data: (b) => _NetWorthTiles(breakdown: b),
|
||||
data: (cached) => _NetWorthTiles(breakdown: cached.data),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
@@ -170,7 +188,7 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
child: AsyncValueView(
|
||||
value: thisMonth,
|
||||
onRetry: () => ref.invalidate(cashflowThisMonthProvider),
|
||||
data: (m) => _MonthTiles(month: m),
|
||||
data: (cached) => _MonthTiles(month: cached.data),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -179,13 +197,14 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
AsyncValueView(
|
||||
value: portfolio,
|
||||
onRetry: () => ref.invalidate(portfolioSummaryHomeProvider),
|
||||
data: (s) => s == null ? const SizedBox.shrink() : _PortfolioTiles(summary: s),
|
||||
data: (cached) =>
|
||||
cached.data == null ? const SizedBox.shrink() : _PortfolioTiles(summary: cached.data!),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
AsyncValueView(
|
||||
value: runway,
|
||||
onRetry: () => ref.invalidate(runwayProvider),
|
||||
data: (r) => _RunwayTile(runway: r),
|
||||
data: (cached) => _RunwayTile(runway: cached.data),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
LayoutBuilder(
|
||||
@@ -196,9 +215,9 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
child: AsyncValueView(
|
||||
value: series,
|
||||
onRetry: () => ref.invalidate(netWorthSeriesProvider),
|
||||
data: (rows) => rows.isEmpty
|
||||
data: (cached) => cached.data.isEmpty
|
||||
? const EmptyState(icon: Icons.show_chart, message: 'Пока нет данных.')
|
||||
: _NetWorthChart(rows: rows),
|
||||
: _NetWorthChart(rows: cached.data),
|
||||
),
|
||||
);
|
||||
final cashflowChart = _ChartCard(
|
||||
@@ -206,9 +225,9 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
child: AsyncValueView(
|
||||
value: last12,
|
||||
onRetry: () => ref.invalidate(cashflowLast12Provider),
|
||||
data: (rows) => rows.isEmpty
|
||||
data: (cached) => cached.data.isEmpty
|
||||
? const EmptyState(icon: Icons.bar_chart, message: 'Пока нет данных.')
|
||||
: _IncomeExpenseChart(rows: rows),
|
||||
: _IncomeExpenseChart(rows: cached.data),
|
||||
),
|
||||
);
|
||||
if (wide) {
|
||||
|
||||
@@ -3,54 +3,58 @@ 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';
|
||||
|
||||
final netWorthBreakdownProvider = FutureProvider.autoDispose<NetWorthBreakdown>((ref) async {
|
||||
/// Every provider below returns `Cached<T>`, not `T`: `HomePage` reads
|
||||
/// `.data` for the tiles and `.fetchedAt` (via `oldestFetch`) for the one
|
||||
/// offline banner at the top. See `docs/ai/offline-cache.md`.
|
||||
final netWorthBreakdownProvider = FutureProvider.autoDispose<Cached<NetWorthBreakdown>>((ref) async {
|
||||
final r = await ref.watch(apiProvider).getNetworthApi().networthBreakdown();
|
||||
return r.data!;
|
||||
return r.cached;
|
||||
});
|
||||
|
||||
/// Daily net worth for the last 365 days.
|
||||
final netWorthSeriesProvider = FutureProvider.autoDispose<List<NetWorthDay>>((ref) async {
|
||||
final netWorthSeriesProvider = FutureProvider.autoDispose<Cached<List<NetWorthDay>>>((ref) async {
|
||||
final now = DateTime.now();
|
||||
final r = await ref.watch(apiProvider).getNetworthApi().networthSeries(
|
||||
from: now.subtract(const Duration(days: 365)),
|
||||
to: now,
|
||||
);
|
||||
return r.data ?? const [];
|
||||
return Cached(r.data ?? const [], fetchedAt: r.extra['fetchedAt'] as DateTime?);
|
||||
});
|
||||
|
||||
/// The current (partial) month's cashflow, or null before any data exists.
|
||||
final cashflowThisMonthProvider = FutureProvider.autoDispose<CashFlowMonth?>((ref) async {
|
||||
final cashflowThisMonthProvider = FutureProvider.autoDispose<Cached<CashFlowMonth?>>((ref) async {
|
||||
final r = await ref.watch(apiProvider).getCashflowApi().cashflowMonthly(months: 1);
|
||||
final rows = r.data ?? const [];
|
||||
return rows.isEmpty ? null : rows.last;
|
||||
return Cached(rows.isEmpty ? null : rows.last, fetchedAt: r.extra['fetchedAt'] as DateTime?);
|
||||
});
|
||||
|
||||
/// The last 12 months, for the income-vs-expense bar chart.
|
||||
final cashflowLast12Provider = FutureProvider.autoDispose<List<CashFlowMonth>>((ref) async {
|
||||
final cashflowLast12Provider = FutureProvider.autoDispose<Cached<List<CashFlowMonth>>>((ref) async {
|
||||
final r = await ref.watch(apiProvider).getCashflowApi().cashflowMonthly(months: 12);
|
||||
return r.data ?? const [];
|
||||
return Cached(r.data ?? const [], fetchedAt: r.extra['fetchedAt'] as DateTime?);
|
||||
});
|
||||
|
||||
final runwayProvider = FutureProvider.autoDispose<RunwayOut>((ref) async {
|
||||
final runwayProvider = FutureProvider.autoDispose<Cached<RunwayOut>>((ref) async {
|
||||
final r = await ref.watch(apiProvider).getCashflowApi().cashflowRunway();
|
||||
return r.data!;
|
||||
return r.cached;
|
||||
});
|
||||
|
||||
/// When the metric tables were last rebuilt; null before the first refresh.
|
||||
final metricsStatusProvider = FutureProvider.autoDispose<RefreshLogOut?>((ref) async {
|
||||
final metricsStatusProvider = FutureProvider.autoDispose<Cached<RefreshLogOut?>>((ref) async {
|
||||
try {
|
||||
final r = await ref.watch(apiProvider).getMetricsApi().metricsStatus();
|
||||
return r.data;
|
||||
return r.cached;
|
||||
} on DioException catch (e) {
|
||||
if (e.response?.statusCode == 404) return null;
|
||||
if (e.response?.statusCode == 404) return const Cached(null);
|
||||
rethrow;
|
||||
}
|
||||
});
|
||||
|
||||
final dataQualityProvider = FutureProvider.autoDispose<List<DataQualityRow>>((ref) async {
|
||||
final dataQualityProvider = FutureProvider.autoDispose<Cached<List<DataQualityRow>>>((ref) async {
|
||||
final r = await ref.watch(apiProvider).getMetricsApi().metricsDataQuality();
|
||||
return r.data ?? const [];
|
||||
return Cached(r.data ?? const [], fetchedAt: r.extra['fetchedAt'] as DateTime?);
|
||||
});
|
||||
|
||||
/// Every dashboard provider, refreshed together after a manual
|
||||
@@ -68,12 +72,12 @@ void invalidateHomeProviders(WidgetRef ref) {
|
||||
|
||||
/// The investment side of the dashboard: one scope-wide summary, `all` by default.
|
||||
/// Null when the ledger is empty, which is the normal state before a broker sync.
|
||||
final portfolioSummaryHomeProvider = FutureProvider.autoDispose<SummaryOut?>((ref) async {
|
||||
final portfolioSummaryHomeProvider = FutureProvider.autoDispose<Cached<SummaryOut?>>((ref) async {
|
||||
try {
|
||||
final r = await ref.watch(apiProvider).getAnalyticsApi().analyticsSummary();
|
||||
return r.data;
|
||||
return r.cached;
|
||||
} on DioException catch (e) {
|
||||
if (e.response?.statusCode == 404) return null;
|
||||
if (e.response?.statusCode == 404) return const Cached(null);
|
||||
rethrow;
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user