feat(app): новый визуальный язык, верхняя навигация, портфели, создание счетов и ручные события
Тема и общие виджеты (AssetIcon, ServiceMark, HelpTip, глоссарий), верхняя панель TopNav и вкладки Аналитики вместо NavSidebar, иконки PWA. Экраны: портфели, создание брокерского счёта, ручное событие, правка инструмента, Обзор карточками по скоупам и таблица активов, пересчёт метрик с опросом /metrics/status. design-system.md обновлён.
This commit is contained in:
@@ -20,9 +20,13 @@ import '../../core/widgets/tile_carousel.dart';
|
||||
import '../../core/api/api_client.dart';
|
||||
import '../health/data_quality_list.dart' show severityColor;
|
||||
import 'providers.dart';
|
||||
import 'scope_cards.dart';
|
||||
|
||||
double _d(String s) => Decimal.parse(s).toDouble();
|
||||
|
||||
/// The refresh log row can be a run still in progress, which has no failed step yet.
|
||||
String _failedStepNote(String? step) => step == null ? '' : ' (шаг «$step»)';
|
||||
|
||||
/// Обзор: the dashboard landing page — net worth, this month's cashflow,
|
||||
/// runway, a net worth line chart, a 12-month income/expense bar chart, and
|
||||
/// a data-quality summary linking to the findings.
|
||||
@@ -39,10 +43,28 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
Future<void> _refresh() async {
|
||||
setState(() => _refreshing = true);
|
||||
try {
|
||||
await ref.read(apiProvider).getMetricsApi().metricsRefresh();
|
||||
final metrics = ref.read(apiProvider).getMetricsApi();
|
||||
await metrics
|
||||
.metricsRefresh(); // 202: only queued, the worker does the rebuild
|
||||
final done = await waitForMetricsRefresh(
|
||||
() async => (await metrics.metricsStatus()).data!,
|
||||
);
|
||||
if (mounted) {
|
||||
final message = done == null
|
||||
? 'Пересчёт идёт дольше обычного — данные обновятся, когда он закончится'
|
||||
: done.consistent
|
||||
? null
|
||||
: 'Пересчёт не завершён${_failedStepNote(done.lastRefresh?.failedStep)} — '
|
||||
'часть метрик может не сходиться';
|
||||
if (message != null) {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(problemMessage(e))));
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(problemMessage(e))));
|
||||
} finally {
|
||||
if (mounted) setState(() => _refreshing = false);
|
||||
invalidateHomeProviders(ref);
|
||||
@@ -59,6 +81,7 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
final status = ref.watch(metricsStatusProvider);
|
||||
final dataQuality = ref.watch(dataQualityProvider);
|
||||
final portfolio = ref.watch(portfolioSummaryHomeProvider);
|
||||
final cards = ref.watch(scopeCardsProvider);
|
||||
|
||||
final stale = oldestFetch([
|
||||
breakdown.valueOrNull?.fetchedAt,
|
||||
@@ -69,6 +92,7 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
status.valueOrNull?.fetchedAt,
|
||||
dataQuality.valueOrNull?.fetchedAt,
|
||||
portfolio.valueOrNull?.fetchedAt,
|
||||
cards.valueOrNull?.fetchedAt,
|
||||
]);
|
||||
|
||||
return Scaffold(
|
||||
@@ -79,7 +103,10 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
tooltip: 'Пересчитать метрики',
|
||||
icon: _refreshing
|
||||
? const SizedBox(
|
||||
width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh),
|
||||
onPressed: _refreshing ? null : _refresh,
|
||||
),
|
||||
@@ -98,12 +125,21 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
value: status,
|
||||
onRetry: () => ref.invalidate(metricsStatusProvider),
|
||||
data: (cached) {
|
||||
final log = cached.data;
|
||||
final status = cached.data;
|
||||
final log = status.lastRefresh;
|
||||
final at = log?.finishedAt ?? log?.startedAt;
|
||||
final text = at == null
|
||||
? 'Данные ещё не пересчитывались'
|
||||
: 'Данные на ${ruDate(at.toLocal())} ${at.toLocal().hour.toString().padLeft(2, '0')}:${at.toLocal().minute.toString().padLeft(2, '0')}';
|
||||
return Text(text, style: Theme.of(context).textTheme.bodySmall);
|
||||
final style = Theme.of(context).textTheme.bodySmall;
|
||||
if (status.consistent) return Text(text, style: style);
|
||||
return Text(
|
||||
'$text · пересчёт не завершён${_failedStepNote(log?.failedStep)}, '
|
||||
'часть метрик может не сходиться',
|
||||
style: style?.copyWith(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -113,20 +149,43 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
final rows = cached.data;
|
||||
return ActionChip(
|
||||
avatar: Icon(
|
||||
rows.isEmpty ? Icons.check_circle_outline : Icons.warning_amber_outlined,
|
||||
rows.isEmpty
|
||||
? Icons.check_circle_outline
|
||||
: Icons.warning_amber_outlined,
|
||||
size: 18,
|
||||
color: rows.isEmpty ? ChartColors.slot3Aqua : severityColor(rows.first.severity),
|
||||
color: rows.isEmpty
|
||||
? ChartColors.slot3Aqua
|
||||
: severityColor(rows.first.severity),
|
||||
),
|
||||
label: Text(
|
||||
rows.isEmpty ? 'ок' : '${rows.length} замечаний',
|
||||
),
|
||||
label: Text(rows.isEmpty ? 'ок' : '${rows.length} замечаний'),
|
||||
// Health page renders the same findings via DataQualityList — no
|
||||
// second implementation of this list here.
|
||||
onPressed: rows.isEmpty ? null : () => context.go('/health?tab=quality'),
|
||||
onPressed: rows.isEmpty
|
||||
? null
|
||||
: () => context.go('/health?tab=quality'),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
AsyncValueView(
|
||||
value: cards,
|
||||
onRetry: () => ref.invalidate(scopeCardsProvider),
|
||||
data: (cached) => cached.data.isEmpty
|
||||
? const SizedBox.shrink()
|
||||
: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(height: 20),
|
||||
const SectionHeader(title: 'Портфели'),
|
||||
const SizedBox(height: 12),
|
||||
ScopeCards(cards: cached.data),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
const SectionHeader(title: 'Капитал'),
|
||||
const SizedBox(height: 12),
|
||||
AsyncValueView(
|
||||
@@ -146,7 +205,8 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
AsyncValueView(
|
||||
value: runway,
|
||||
onRetry: () => ref.invalidate(runwayProvider),
|
||||
data: (cached) => TileCarousel(children: [_RunwayTile(runway: cached.data)]),
|
||||
data: (cached) =>
|
||||
TileCarousel(children: [_RunwayTile(runway: cached.data)]),
|
||||
),
|
||||
AsyncValueView(
|
||||
value: portfolio,
|
||||
@@ -175,7 +235,10 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
value: series,
|
||||
onRetry: () => ref.invalidate(netWorthSeriesProvider),
|
||||
data: (cached) => cached.data.isEmpty
|
||||
? const EmptyState(icon: Icons.show_chart, message: 'Пока нет данных.')
|
||||
? const EmptyState(
|
||||
icon: Icons.show_chart,
|
||||
message: 'Пока нет данных.',
|
||||
)
|
||||
: _NetWorthChart(rows: cached.data),
|
||||
),
|
||||
),
|
||||
@@ -188,7 +251,10 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
value: last12,
|
||||
onRetry: () => ref.invalidate(cashflowLast12Provider),
|
||||
data: (cached) => cached.data.isEmpty
|
||||
? const EmptyState(icon: Icons.bar_chart, message: 'Пока нет данных.')
|
||||
? const EmptyState(
|
||||
icon: Icons.bar_chart,
|
||||
message: 'Пока нет данных.',
|
||||
)
|
||||
: _IncomeExpenseChart(rows: cached.data),
|
||||
),
|
||||
),
|
||||
@@ -204,7 +270,11 @@ class _HomePageState extends ConsumerState<HomePage> {
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
children: [netWorthChart, const SizedBox(height: 16), cashflowChart],
|
||||
children: [
|
||||
netWorthChart,
|
||||
const SizedBox(height: 16),
|
||||
cashflowChart,
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -230,13 +300,30 @@ class _NetWorthTiles extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TileCarousel(children: [
|
||||
StatTile(label: 'Капитал сегодня', value: MoneyText(breakdown.totalRub, currency: 'RUB')),
|
||||
StatTile(label: 'Ликвидные', value: MoneyText(breakdown.liquidRub, currency: 'RUB')),
|
||||
StatTile(label: 'Сбережения', value: MoneyText(breakdown.savingsRub, currency: 'RUB')),
|
||||
StatTile(label: 'Инвестиции', value: MoneyText(breakdown.investmentRub, currency: 'RUB')),
|
||||
StatTile(label: 'Долги', value: MoneyText(breakdown.debtRub, currency: 'RUB')),
|
||||
]);
|
||||
return TileCarousel(
|
||||
children: [
|
||||
StatTile(
|
||||
label: 'Капитал сегодня',
|
||||
value: MoneyText(breakdown.totalRub, currency: 'RUB'),
|
||||
),
|
||||
StatTile(
|
||||
label: 'Ликвидные',
|
||||
value: MoneyText(breakdown.liquidRub, currency: 'RUB'),
|
||||
),
|
||||
StatTile(
|
||||
label: 'Сбережения',
|
||||
value: MoneyText(breakdown.savingsRub, currency: 'RUB'),
|
||||
),
|
||||
StatTile(
|
||||
label: 'Инвестиции',
|
||||
value: MoneyText(breakdown.investmentRub, currency: 'RUB'),
|
||||
),
|
||||
StatTile(
|
||||
label: 'Долги',
|
||||
value: MoneyText(breakdown.debtRub, currency: 'RUB'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,14 +334,27 @@ class _MonthTiles extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (month == null) {
|
||||
return const EmptyState(icon: Icons.event_note_outlined, message: 'Данных за этот месяц нет.');
|
||||
return const EmptyState(
|
||||
icon: Icons.event_note_outlined,
|
||||
message: 'Данных за этот месяц нет.',
|
||||
);
|
||||
}
|
||||
final rateText = month!.savingsRate == null ? '—' : '${(_d(month!.savingsRate!) * 100).toStringAsFixed(1)}%';
|
||||
return TileCarousel(children: [
|
||||
StatTile(label: 'Доход в этом месяце', value: MoneyText(month!.incomeRub, currency: 'RUB')),
|
||||
StatTile(label: 'Расход в этом месяце', value: MoneyText(month!.expenseRub, currency: 'RUB')),
|
||||
StatTile(label: 'Норма сбережений', value: Text(rateText)),
|
||||
]);
|
||||
final rateText = month!.savingsRate == null
|
||||
? '—'
|
||||
: '${(_d(month!.savingsRate!) * 100).toStringAsFixed(1)}%';
|
||||
return TileCarousel(
|
||||
children: [
|
||||
StatTile(
|
||||
label: 'Доход в этом месяце',
|
||||
value: MoneyText(month!.incomeRub, currency: 'RUB'),
|
||||
),
|
||||
StatTile(
|
||||
label: 'Расход в этом месяце',
|
||||
value: MoneyText(month!.expenseRub, currency: 'RUB'),
|
||||
),
|
||||
StatTile(label: 'Норма сбережений', value: Text(rateText)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -278,7 +378,8 @@ class _NetWorthChart extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final spots = [
|
||||
for (var i = 0; i < rows.length; i++) FlSpot(i.toDouble(), _d(rows[i].totalRub)),
|
||||
for (var i = 0; i < rows.length; i++)
|
||||
FlSpot(i.toDouble(), _d(rows[i].totalRub)),
|
||||
];
|
||||
return LineChart(
|
||||
LineChartData(
|
||||
@@ -323,7 +424,11 @@ class _IncomeExpenseChart extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final maxY = rows.fold<double>(
|
||||
0,
|
||||
(m, r) => [m, _d(r.incomeRub), _d(r.expenseRub)].reduce((a, b) => a > b ? a : b),
|
||||
(m, r) => [
|
||||
m,
|
||||
_d(r.incomeRub),
|
||||
_d(r.expenseRub),
|
||||
].reduce((a, b) => a > b ? a : b),
|
||||
);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -343,19 +448,28 @@ class _IncomeExpenseChart extends StatelessWidget {
|
||||
gridData: const FlGridData(drawVerticalLine: false),
|
||||
borderData: FlBorderData(show: false),
|
||||
titlesData: FlTitlesData(
|
||||
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||
leftTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||
topTitles: const AxisTitles(
|
||||
sideTitles: SideTitles(showTitles: false),
|
||||
),
|
||||
rightTitles: const AxisTitles(
|
||||
sideTitles: SideTitles(showTitles: false),
|
||||
),
|
||||
leftTitles: const AxisTitles(
|
||||
sideTitles: SideTitles(showTitles: false),
|
||||
),
|
||||
bottomTitles: AxisTitles(
|
||||
sideTitles: SideTitles(
|
||||
showTitles: true,
|
||||
getTitlesWidget: (value, meta) {
|
||||
final i = value.toInt();
|
||||
if (i < 0 || i >= rows.length) return const SizedBox.shrink();
|
||||
if (i < 0 || i >= rows.length)
|
||||
return const SizedBox.shrink();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child:
|
||||
Text(ruMonthYearShort(rows[i].month), style: const TextStyle(fontSize: 9)),
|
||||
child: Text(
|
||||
ruMonthYearShort(rows[i].month),
|
||||
style: const TextStyle(fontSize: 9),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -377,8 +491,16 @@ class _IncomeExpenseChart extends StatelessWidget {
|
||||
BarChartGroupData(
|
||||
x: i,
|
||||
barRods: [
|
||||
BarChartRodData(toY: _d(rows[i].incomeRub), color: ChartColors.income, width: 6),
|
||||
BarChartRodData(toY: _d(rows[i].expenseRub), color: ChartColors.expense, width: 6),
|
||||
BarChartRodData(
|
||||
toY: _d(rows[i].incomeRub),
|
||||
color: ChartColors.income,
|
||||
width: 6,
|
||||
),
|
||||
BarChartRodData(
|
||||
toY: _d(rows[i].expenseRub),
|
||||
color: ChartColors.expense,
|
||||
width: 6,
|
||||
),
|
||||
],
|
||||
barsSpace: 2,
|
||||
),
|
||||
@@ -401,7 +523,11 @@ class _LegendDot extends StatelessWidget {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(width: 10, height: 10, decoration: BoxDecoration(color: color, shape: BoxShape.circle)),
|
||||
Container(
|
||||
width: 10,
|
||||
height: 10,
|
||||
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(label, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
@@ -422,27 +548,23 @@ class _PortfolioTiles extends StatelessWidget {
|
||||
return InkWell(
|
||||
onTap: () => context.go('/portfolio'),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: TileCarousel(children: [
|
||||
StatTile(
|
||||
label: 'Портфель',
|
||||
value: MoneyText(summary.totalRub, currency: 'RUB'),
|
||||
),
|
||||
StatTile(
|
||||
label: 'Прибыль',
|
||||
value: summary.pnlTotalRub == null
|
||||
// null, not zero: something in the portfolio has no price today
|
||||
? const Text('—')
|
||||
: MoneyText(summary.pnlTotalRub!, currency: 'RUB'),
|
||||
),
|
||||
StatTile(
|
||||
label: 'XIRR, год',
|
||||
value: Text(_percent(yearly?.xirr)),
|
||||
),
|
||||
StatTile(
|
||||
label: 'TWR, год',
|
||||
value: Text(_percent(yearly?.twr)),
|
||||
),
|
||||
]),
|
||||
child: TileCarousel(
|
||||
children: [
|
||||
StatTile(
|
||||
label: 'Портфель',
|
||||
value: MoneyText(summary.totalRub, currency: 'RUB'),
|
||||
),
|
||||
StatTile(
|
||||
label: 'Прибыль',
|
||||
value: summary.pnlTotalRub == null
|
||||
// null, not zero: something in the portfolio has no price today
|
||||
? const Text('—')
|
||||
: MoneyText(summary.pnlTotalRub!, currency: 'RUB'),
|
||||
),
|
||||
StatTile(label: 'XIRR, год', value: Text(_percent(yearly?.xirr))),
|
||||
StatTile(label: 'TWR, год', value: Text(_percent(yearly?.twr))),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,54 +8,102 @@ import '../../core/cache/cached.dart';
|
||||
/// 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.cached;
|
||||
});
|
||||
final netWorthBreakdownProvider =
|
||||
FutureProvider.autoDispose<Cached<NetWorthBreakdown>>((ref) async {
|
||||
final r = await ref
|
||||
.watch(apiProvider)
|
||||
.getNetworthApi()
|
||||
.networthBreakdown();
|
||||
return r.cached;
|
||||
});
|
||||
|
||||
/// Daily net worth for the last 365 days.
|
||||
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,
|
||||
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 Cached(
|
||||
r.data ?? const [],
|
||||
fetchedAt: r.extra['fetchedAt'] as DateTime?,
|
||||
);
|
||||
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<Cached<CashFlowMonth?>>((ref) async {
|
||||
final r = await ref.watch(apiProvider).getCashflowApi().cashflowMonthly(months: 1);
|
||||
final rows = r.data ?? const [];
|
||||
return Cached(rows.isEmpty ? null : rows.last, fetchedAt: r.extra['fetchedAt'] as DateTime?);
|
||||
});
|
||||
final cashflowThisMonthProvider =
|
||||
FutureProvider.autoDispose<Cached<CashFlowMonth?>>((ref) async {
|
||||
final r = await ref
|
||||
.watch(apiProvider)
|
||||
.getCashflowApi()
|
||||
.cashflowMonthly(months: 1);
|
||||
final rows = r.data ?? const [];
|
||||
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<Cached<List<CashFlowMonth>>>((ref) async {
|
||||
final r = await ref.watch(apiProvider).getCashflowApi().cashflowMonthly(months: 12);
|
||||
return Cached(r.data ?? const [], fetchedAt: r.extra['fetchedAt'] as DateTime?);
|
||||
});
|
||||
final cashflowLast12Provider =
|
||||
FutureProvider.autoDispose<Cached<List<CashFlowMonth>>>((ref) async {
|
||||
final r = await ref
|
||||
.watch(apiProvider)
|
||||
.getCashflowApi()
|
||||
.cashflowMonthly(months: 12);
|
||||
return Cached(
|
||||
r.data ?? const [],
|
||||
fetchedAt: r.extra['fetchedAt'] as DateTime?,
|
||||
);
|
||||
});
|
||||
|
||||
final runwayProvider = FutureProvider.autoDispose<Cached<RunwayOut>>((ref) async {
|
||||
final runwayProvider = FutureProvider.autoDispose<Cached<RunwayOut>>((
|
||||
ref,
|
||||
) async {
|
||||
final r = await ref.watch(apiProvider).getCashflowApi().cashflowRunway();
|
||||
return r.cached;
|
||||
});
|
||||
|
||||
/// When the metric tables were last rebuilt; null before the first refresh.
|
||||
final metricsStatusProvider = FutureProvider.autoDispose<Cached<RefreshLogOut?>>((ref) async {
|
||||
try {
|
||||
final r = await ref.watch(apiProvider).getMetricsApi().metricsStatus();
|
||||
return r.cached;
|
||||
} on DioException catch (e) {
|
||||
if (e.response?.statusCode == 404) return const Cached(null);
|
||||
rethrow;
|
||||
}
|
||||
});
|
||||
/// When the metric tables were last rebuilt, whether they are one consistent snapshot, and
|
||||
/// whether another rebuild is on its way.
|
||||
final metricsStatusProvider =
|
||||
FutureProvider.autoDispose<Cached<MetricsStatusOut>>((ref) async {
|
||||
final r = await ref.watch(apiProvider).getMetricsApi().metricsStatus();
|
||||
return r.cached;
|
||||
});
|
||||
|
||||
final dataQualityProvider = FutureProvider.autoDispose<Cached<List<DataQualityRow>>>((ref) async {
|
||||
final r = await ref.watch(apiProvider).getMetricsApi().metricsDataQuality();
|
||||
return Cached(r.data ?? const [], fetchedAt: r.extra['fetchedAt'] as DateTime?);
|
||||
});
|
||||
/// Waits for a queued metrics rebuild to finish: `POST /metrics/refresh` only queues it, so the
|
||||
/// numbers are stale until `refreshing` turns false. Returns the last status seen, or null if
|
||||
/// [timeout] ran out first (a rebuild stuck behind a long sync, say).
|
||||
Future<MetricsStatusOut?> waitForMetricsRefresh(
|
||||
Future<MetricsStatusOut> Function() fetch, {
|
||||
Duration interval = const Duration(seconds: 2),
|
||||
Duration timeout = const Duration(minutes: 5),
|
||||
}) async {
|
||||
final clock = Stopwatch()..start();
|
||||
while (true) {
|
||||
final status = await fetch();
|
||||
if (!status.refreshing) return status;
|
||||
if (clock.elapsed >= timeout) return null;
|
||||
await Future<void>.delayed(interval);
|
||||
}
|
||||
}
|
||||
|
||||
final dataQualityProvider =
|
||||
FutureProvider.autoDispose<Cached<List<DataQualityRow>>>((ref) async {
|
||||
final r = await ref
|
||||
.watch(apiProvider)
|
||||
.getMetricsApi()
|
||||
.metricsDataQuality();
|
||||
return Cached(
|
||||
r.data ?? const [],
|
||||
fetchedAt: r.extra['fetchedAt'] as DateTime?,
|
||||
);
|
||||
});
|
||||
|
||||
/// Every dashboard provider, refreshed together after a manual
|
||||
/// `POST /metrics/refresh` or a pull-to-refresh.
|
||||
@@ -68,16 +116,35 @@ void invalidateHomeProviders(WidgetRef ref) {
|
||||
ref.invalidate(metricsStatusProvider);
|
||||
ref.invalidate(dataQualityProvider);
|
||||
ref.invalidate(portfolioSummaryHomeProvider);
|
||||
ref.invalidate(scopeCardsProvider);
|
||||
}
|
||||
|
||||
/// 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<Cached<SummaryOut?>>((ref) async {
|
||||
try {
|
||||
final r = await ref.watch(apiProvider).getAnalyticsApi().analyticsSummary();
|
||||
return r.cached;
|
||||
} on DioException catch (e) {
|
||||
if (e.response?.statusCode == 404) return const Cached(null);
|
||||
rethrow;
|
||||
}
|
||||
});
|
||||
final portfolioSummaryHomeProvider =
|
||||
FutureProvider.autoDispose<Cached<SummaryOut?>>((ref) async {
|
||||
try {
|
||||
final r = await ref
|
||||
.watch(apiProvider)
|
||||
.getAnalyticsApi()
|
||||
.analyticsSummary();
|
||||
return r.cached;
|
||||
} on DioException catch (e) {
|
||||
if (e.response?.statusCode == 404) return const Cached(null);
|
||||
rethrow;
|
||||
}
|
||||
});
|
||||
|
||||
/// One card per portfolio and account for the home grid (`GET /analytics/overview`): value,
|
||||
/// result, the last day's change, return and expected passive income, in one round trip.
|
||||
final scopeCardsProvider =
|
||||
FutureProvider.autoDispose<Cached<List<ScopeCardOut>>>((ref) async {
|
||||
final r = await ref
|
||||
.watch(apiProvider)
|
||||
.getAnalyticsApi()
|
||||
.analyticsOverview();
|
||||
return Cached(
|
||||
r.data ?? const [],
|
||||
fetchedAt: r.extra['fetchedAt'] as DateTime?,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import 'package:decimal/decimal.dart';
|
||||
import 'package:fintracker_api/fintracker_api.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/theme/chart_colors.dart';
|
||||
import '../../core/widgets/help_tip.dart';
|
||||
import '../../core/widgets/money_text.dart';
|
||||
import '../portfolio/labels.dart' show formatPercent, signColor;
|
||||
import '../portfolio/providers.dart' show scopeProvider;
|
||||
|
||||
/// The home grid: a card per portfolio and account — value, result, the last day, return and
|
||||
/// expected passive income at a glance. A tap opens Портфель scoped to that card.
|
||||
class ScopeCards extends ConsumerWidget {
|
||||
const ScopeCards({required this.cards, super.key});
|
||||
|
||||
final List<ScopeCardOut> cards;
|
||||
|
||||
static const _gap = 16.0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth;
|
||||
final columns = width >= 980 ? 3 : (width >= 620 ? 2 : 1);
|
||||
final itemWidth = (width - _gap * (columns - 1)) / columns;
|
||||
return Wrap(
|
||||
spacing: _gap,
|
||||
runSpacing: _gap,
|
||||
children: [
|
||||
for (final c in cards)
|
||||
SizedBox(
|
||||
width: itemWidth,
|
||||
child: ScopeCard(
|
||||
card: c,
|
||||
onTap: () {
|
||||
ref.read(scopeProvider.notifier).state = c.scope;
|
||||
context.go('/portfolio');
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
IconData _icon(String kind) => switch (kind) {
|
||||
'all' => Icons.layers_outlined,
|
||||
'portfolio' => Icons.layers,
|
||||
_ => Icons.account_balance_wallet_outlined,
|
||||
};
|
||||
|
||||
class ScopeCard extends StatelessWidget {
|
||||
const ScopeCard({required this.card, required this.onTap, super.key});
|
||||
|
||||
final ScopeCardOut card;
|
||||
final VoidCallback onTap;
|
||||
|
||||
static String _money(String? v) =>
|
||||
v == null ? '—' : MoneyText.format(v, 'RUB');
|
||||
|
||||
/// `+6 643,47 ₽` — a signed amount; a plain minus and plus, never a bare number.
|
||||
static String _signedMoney(String? v) {
|
||||
if (v == null) return '—';
|
||||
final d = Decimal.parse(v);
|
||||
final text = MoneyText.format(v, 'RUB');
|
||||
return d > Decimal.zero ? '+$text' : text;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final scheme = theme.colorScheme;
|
||||
final label = theme.textTheme.bodyMedium?.copyWith(
|
||||
color: scheme.onSurfaceVariant,
|
||||
);
|
||||
|
||||
Widget row(String name, Widget value) => Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: TermLabel(name, style: label),
|
||||
),
|
||||
),
|
||||
value,
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
/// «+6 643,47 ₽ (▲ 1,5 %)» in the colour of its sign.
|
||||
Widget change(String? amount, String? share) {
|
||||
if (amount == null) return const Text('—');
|
||||
final color = signColor(context, amount) ?? scheme.onSurface;
|
||||
final positive = Decimal.parse(amount) > Decimal.zero;
|
||||
final negative = Decimal.parse(amount) < Decimal.zero;
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(_signedMoney(amount), style: TextStyle(color: color)),
|
||||
if (share != null) ...[
|
||||
Text(' (', style: TextStyle(color: color)),
|
||||
if (positive || negative)
|
||||
Icon(
|
||||
positive ? Icons.arrow_drop_up : Icons.arrow_drop_down,
|
||||
size: 18,
|
||||
color: color,
|
||||
),
|
||||
Text(
|
||||
formatPercent(share, signed: false).replaceAll('-', ''),
|
||||
style: TextStyle(color: color),
|
||||
),
|
||||
Text(')', style: TextStyle(color: color)),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
final income = Decimal.parse(card.incomeYearRub);
|
||||
return Card(
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
_icon(card.kind),
|
||||
size: 18,
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
card.name.toUpperCase(),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.labelLarge?.copyWith(
|
||||
color: scheme.onSurface,
|
||||
letterSpacing: 0.4,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
_money(card.totalRub),
|
||||
style: theme.textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
row('Прибыль', change(card.pnlRub, card.pnlPct)),
|
||||
row('За день', change(card.dayChangeRub, card.dayChangePct)),
|
||||
row(
|
||||
'Доходность',
|
||||
Text(
|
||||
card.xirr == null
|
||||
? '—'
|
||||
: formatPercent(card.xirr, signed: false),
|
||||
style: TextStyle(color: signColor(context, card.xirr)),
|
||||
),
|
||||
),
|
||||
row(
|
||||
'Пассивный доход',
|
||||
Text(
|
||||
income == Decimal.zero
|
||||
? '—'
|
||||
: '${card.incomeYearPct == null ? '' : '${formatPercent(card.incomeYearPct, signed: false)} '}'
|
||||
'(${MoneyText.format(card.incomeYearRub, 'RUB')})',
|
||||
style: TextStyle(
|
||||
color: income == Decimal.zero
|
||||
? scheme.onSurfaceVariant
|
||||
: ChartColors.gain,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user