feat(app): экраны импорта отчётов, целей, доходов, ребалансировки, налогов и бенчмарков

Импорт (/imports, /instruments/pending) и фаза 4 (/goals, /income,
/rebalance, /tax, аналитика-хаб с benchmarks_card) — по
docs/ai/import-contract.md и docs/ai/phase4-contract.md. file_picker для
загрузки отчёта.
This commit is contained in:
Dmitry
2026-09-19 10:44:38 +03:00
parent 15f5812ea4
commit b69bb4a0c9
52 changed files with 7404 additions and 13 deletions
+151
View File
@@ -0,0 +1,151 @@
/// Hand-written client for `/api/v1/goals`.
///
/// **Temporary.** The goal routes are not in `openapi/openapi.json` yet, so
/// `app/packages/api_client` has no generated models or methods for them. Everything here
/// follows `docs/ai/phase4-contract.md` §4 literally and is meant to be **replaced by the
/// generated client** once the routes land in the spec and `just gen-client` runs.
///
/// Raw Dio comes from `ref.read(apiProvider).dio`: base URL, bearer header and the one-shot
/// refresh on 401 are already wired there.
library;
import 'package:dio/dio.dart';
import '../../../core/utils/json.dart';
class Goal {
const Goal({
required this.id,
required this.name,
required this.scope,
required this.targetAmount,
required this.currency,
this.targetDate,
this.monthlyContribution,
this.note,
this.archived = false,
});
final int id;
final String name;
final String scope;
final String targetAmount;
final String currency;
final DateTime? targetDate;
final String? monthlyContribution;
final String? note;
final bool archived;
/// The create/patch body. `id` is never sent; `null` fields are omitted so a PATCH that
/// touches one field does not blank the rest.
Map<String, dynamic> toJson() => {
'name': name,
'scope': scope,
'target_amount': targetAmount,
'currency': currency,
'target_date': ?_isoDate(targetDate),
'monthly_contribution': ?monthlyContribution,
'note': ?note,
'archived': archived,
};
static Goal fromJson(Map<String, dynamic> json) => Goal(
id: asInt(json['id']) ?? 0,
name: asString(json['name']) ?? 'Без названия',
scope: asString(json['scope']) ?? 'all',
targetAmount: asString(json['target_amount']) ?? '0',
currency: asString(json['currency']) ?? 'RUB',
targetDate: asDate(json['target_date']),
monthlyContribution: asString(json['monthly_contribution']),
note: asString(json['note']),
archived: asBool(json['archived']),
);
static String? _isoDate(DateTime? d) => d == null
? null
: '${d.year.toString().padLeft(4, '0')}-'
'${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';
}
class GoalProgress {
const GoalProgress({
required this.goalId,
required this.basis,
required this.onTrack,
this.asOf,
this.currentValueRub,
this.targetAmountRub,
this.progress,
this.projectedDate,
this.assumedRate,
this.monthlyNeededRub,
});
final int goalId;
final DateTime? asOf;
final String? currentValueRub;
final String? targetAmountRub;
/// A share: `"0.4128"` is 41,28 %.
final String? progress;
/// **Null means the goal is not reached at the current trend** — an honest answer, and the
/// contract forbids substituting a far-off date for it. The UI must say so in words.
final DateTime? projectedDate;
/// `xirr | contribution | none` — what the projection is built on.
final String basis;
final String? assumedRate;
final String? monthlyNeededRub;
final bool onTrack;
/// The projection exists only when a date came back. `basis == 'none'` means there was
/// nothing to project from in the first place.
bool get isUnreachable => projectedDate == null && basis != 'none';
static GoalProgress fromJson(Map<String, dynamic> json) => GoalProgress(
goalId: asInt(json['goal_id']) ?? 0,
asOf: asDate(json['as_of']),
currentValueRub: asString(json['current_value_rub']),
targetAmountRub: asString(json['target_amount_rub']),
progress: asString(json['progress']),
projectedDate: asDate(json['projected_date']),
basis: asString(json['basis']) ?? 'none',
assumedRate: asString(json['assumed_rate']),
monthlyNeededRub: asString(json['monthly_needed_rub']),
onTrack: asBool(json['on_track']),
);
}
class GoalsApi {
const GoalsApi(this._dio);
final Dio _dio;
static const _base = '/api/v1/goals';
Future<List<Goal>> list() async {
final r = await _dio.get<List<dynamic>>(_base);
return (r.data ?? const [])
.map((e) => Goal.fromJson(Map<String, dynamic>.from(e as Map)))
.toList();
}
Future<Goal> create(Goal goal) async {
final r = await _dio.post<Map<String, dynamic>>(_base, data: goal.toJson());
return Goal.fromJson(r.data ?? const {});
}
Future<Goal> patch(int id, Map<String, dynamic> changes) async {
final r = await _dio.patch<Map<String, dynamic>>('$_base/$id', data: changes);
return Goal.fromJson(r.data ?? const {});
}
Future<void> delete(int id) => _dio.delete<void>('$_base/$id');
Future<GoalProgress> progress(int id) async {
final r = await _dio.get<Map<String, dynamic>>('$_base/$id/progress');
return GoalProgress.fromJson(r.data ?? const {});
}
}
+201
View File
@@ -0,0 +1,201 @@
import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/utils/ru_date.dart';
import '../../core/widgets/async_value_view.dart';
import '../../core/widgets/money_text.dart';
import '../portfolio/labels.dart' show formatPercent;
import 'data/goals_api.dart';
import 'providers.dart';
/// What the projection is built on. `none` is not an error — it means there is no trend to
/// extrapolate yet, which is different from "the goal is not reachable".
const goalBasisLabels = {
'xirr': 'по доходности',
'contribution': 'по взносам',
'none': 'нет данных',
};
const goalBasisDescriptions = {
'xirr': 'Прогноз построен на фактической доходности портфеля (XIRR).',
'contribution': 'Прогноз построен на регулярных взносах, без учёта доходности.',
'none': 'Данных для прогноза нет: ни доходности, ни истории взносов.',
};
String goalBasisLabel(String basis) => goalBasisLabels[basis] ?? basis;
/// One goal with its server-computed progress.
///
/// The load-bearing line is the projected date: `projected_date == null` means **the goal
/// is not reached at the current trend**, and it is written out in those words. Leaving the
/// spot blank, or filling it with a far-off date, would both read as an answer.
class GoalCard extends ConsumerWidget {
const GoalCard({required this.goal, super.key, this.onEdit, this.onDelete});
final Goal goal;
final VoidCallback? onEdit;
final VoidCallback? onDelete;
@override
Widget build(BuildContext context, WidgetRef ref) {
final progress = ref.watch(goalProgressProvider(goal.id));
final theme = Theme.of(context);
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(goal.name, style: theme.textTheme.titleMedium),
Text(
[
'цель ${MoneyText.format(goal.targetAmount, goal.currency)}',
if (goal.targetDate != null) 'к ${ruDate(goal.targetDate!)}',
if (goal.monthlyContribution != null)
'взнос ${MoneyText.format(goal.monthlyContribution!, goal.currency)}/мес',
if (goal.archived) 'в архиве',
].join(' · '),
style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
),
],
),
),
if (onEdit != null)
IconButton(
tooltip: 'Изменить',
icon: const Icon(Icons.edit_outlined),
onPressed: onEdit,
),
if (onDelete != null)
IconButton(
tooltip: 'Удалить',
icon: const Icon(Icons.delete_outline),
onPressed: onDelete,
),
],
),
const SizedBox(height: 12),
AsyncValueView(
value: progress,
onRetry: () => ref.invalidate(goalProgressProvider(goal.id)),
data: (p) => GoalProgressView(goal: goal, progress: p),
),
],
),
),
);
}
}
/// The progress body, split out of [GoalCard] so it can be rendered (and tested) without a
/// provider container.
class GoalProgressView extends StatelessWidget {
const GoalProgressView({required this.goal, required this.progress, super.key});
final Goal goal;
final GoalProgress progress;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final share = Decimal.tryParse(progress.progress ?? '') ?? Decimal.zero;
final clamped = share.toDouble().clamp(0.0, 1.0);
final unreachable = progress.projectedDate == null;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(value: clamped, minHeight: 8),
),
const SizedBox(height: 6),
Row(
children: [
Text(
formatPercent(progress.progress, signed: false),
style: theme.textTheme.titleSmall,
),
const SizedBox(width: 8),
Expanded(
child: Text(
'${progress.currentValueRub == null ? '' : MoneyText.format(progress.currentValueRub!, 'RUB')}'
' из '
'${progress.targetAmountRub == null ? '' : MoneyText.format(progress.targetAmountRub!, 'RUB')}',
style: theme.textTheme.bodySmall,
),
),
Tooltip(
message: goalBasisDescriptions[progress.basis] ?? progress.basis,
child: Chip(
label: Text('Основание: ${goalBasisLabel(progress.basis)}'),
visualDensity: VisualDensity.compact,
),
),
],
),
const SizedBox(height: 10),
// The whole point of the screen. Null is a statement, not an absence.
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
unreachable ? Icons.trending_flat : Icons.flag_outlined,
size: 18,
color: unreachable ? theme.colorScheme.error : theme.colorScheme.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
unreachable
? (progress.basis == 'none'
? 'Прогноз недоступен: данных для оценки тренда пока нет'
: 'При текущем тренде цель не достигается')
: 'Прогнозная дата достижения: ${ruDate(progress.projectedDate!)}',
style: theme.textTheme.bodyMedium?.copyWith(
color: unreachable ? theme.colorScheme.error : null,
fontWeight: FontWeight.w500,
),
),
),
],
),
const SizedBox(height: 6),
Wrap(
spacing: 16,
runSpacing: 4,
children: [
Text(
progress.monthlyNeededRub == null
? 'Нужный ежемесячный взнос: — (нет целевой даты)'
: 'Нужно докладывать: '
'${MoneyText.format(progress.monthlyNeededRub!, 'RUB')}/мес',
style: theme.textTheme.bodySmall,
),
if (progress.assumedRate != null)
Text(
'Заложенная доходность: ${formatPercent(progress.assumedRate, signed: false)}',
style: theme.textTheme.bodySmall,
),
Text(
progress.onTrack ? 'Идёт по плану' : 'Отстаёт от плана',
style: theme.textTheme.bodySmall?.copyWith(
color: progress.onTrack ? null : theme.colorScheme.error,
),
),
if (progress.asOf != null)
Text('на ${ruDate(progress.asOf!)}', style: theme.textTheme.bodySmall),
],
),
],
);
}
}
@@ -0,0 +1,171 @@
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 '../../core/utils/ru_date.dart';
import '../portfolio/providers.dart' show scopesProvider;
import 'data/goals_api.dart';
/// Create/edit form for a goal. Returns the goal to save, or null when cancelled.
class GoalEditDialog extends ConsumerStatefulWidget {
const GoalEditDialog({super.key, this.initial});
final Goal? initial;
@override
ConsumerState<GoalEditDialog> createState() => _GoalEditDialogState();
}
class _GoalEditDialogState extends ConsumerState<GoalEditDialog> {
final _formKey = GlobalKey<FormState>();
late final _name = TextEditingController(text: widget.initial?.name ?? '');
late final _amount = TextEditingController(text: widget.initial?.targetAmount ?? '');
late final _contribution =
TextEditingController(text: widget.initial?.monthlyContribution ?? '');
late final _note = TextEditingController(text: widget.initial?.note ?? '');
late String _scope = widget.initial?.scope ?? 'all';
late DateTime? _targetDate = widget.initial?.targetDate;
late bool _archived = widget.initial?.archived ?? false;
@override
void dispose() {
_name.dispose();
_amount.dispose();
_contribution.dispose();
_note.dispose();
super.dispose();
}
String? _decimalValidator(String? v, {bool required = true}) {
final text = (v ?? '').trim().replaceAll(',', '.');
if (text.isEmpty) return required ? 'Обязательное поле' : null;
return Decimal.tryParse(text) == null ? 'Нужно число' : null;
}
static String? _decimal(String text) {
final normalized = text.trim().replaceAll(',', '.').replaceAll(' ', '');
if (normalized.isEmpty) return null;
return Decimal.tryParse(normalized)?.toString();
}
@override
Widget build(BuildContext context) {
final scopes = ref.watch(scopesProvider).valueOrNull ?? const <ScopeOut>[];
return AlertDialog(
title: Text(widget.initial == null ? 'Новая цель' : 'Цель'),
content: SizedBox(
width: 420,
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: _name,
decoration: const InputDecoration(labelText: 'Название'),
validator: (v) =>
(v ?? '').trim().isEmpty ? 'Обязательное поле' : null,
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
initialValue: scopes.any((s) => s.scope == _scope) || _scope == 'all'
? _scope
: 'all',
decoration: const InputDecoration(labelText: 'Что считаем'),
items: [
if (!scopes.any((s) => s.scope == 'all'))
const DropdownMenuItem(value: 'all', child: Text('Всё')),
for (final s in scopes)
DropdownMenuItem(value: s.scope, child: Text(s.name)),
],
onChanged: (v) => setState(() => _scope = v ?? 'all'),
),
const SizedBox(height: 12),
TextFormField(
controller: _amount,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: const InputDecoration(labelText: 'Целевая сумма, ₽'),
validator: _decimalValidator,
),
const SizedBox(height: 12),
TextFormField(
controller: _contribution,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: const InputDecoration(
labelText: 'Ежемесячный взнос, ₽',
helperText: 'необязательно',
),
validator: (v) => _decimalValidator(v, required: false),
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: Text(_targetDate == null
? 'Целевая дата не задана'
: 'Целевая дата: ${ruDate(_targetDate!)}'),
),
TextButton(
onPressed: () async {
final now = DateTime.now();
final picked = await showDatePicker(
context: context,
initialDate: _targetDate ?? DateTime(now.year + 3, now.month, now.day),
firstDate: DateTime(now.year - 1),
lastDate: DateTime(now.year + 50),
);
if (picked != null) setState(() => _targetDate = picked);
},
child: const Text('Выбрать'),
),
if (_targetDate != null)
IconButton(
tooltip: 'Убрать дату',
icon: const Icon(Icons.clear),
onPressed: () => setState(() => _targetDate = null),
),
],
),
const SizedBox(height: 12),
TextFormField(
controller: _note,
decoration: const InputDecoration(labelText: 'Заметка'),
),
if (widget.initial != null)
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('В архиве'),
value: _archived,
onChanged: (v) => setState(() => _archived = v),
),
],
),
),
),
),
actions: [
TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Отмена')),
FilledButton(
onPressed: () {
if (!(_formKey.currentState?.validate() ?? false)) return;
Navigator.of(context).pop(Goal(
id: widget.initial?.id ?? 0,
name: _name.text.trim(),
scope: _scope,
targetAmount: _decimal(_amount.text) ?? '0',
currency: widget.initial?.currency ?? 'RUB',
targetDate: _targetDate,
monthlyContribution: _decimal(_contribution.text),
note: _note.text.trim().isEmpty ? null : _note.text.trim(),
archived: _archived,
));
},
child: const Text('Сохранить'),
),
],
);
}
}
+144
View File
@@ -0,0 +1,144 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/utils/json.dart';
import '../../core/widgets/async_value_view.dart';
import '../../core/widgets/empty_state.dart';
import 'data/goals_api.dart';
import 'goal_card.dart';
import 'goal_edit_dialog.dart';
import 'providers.dart';
/// Цели: the goal list, each card carrying its server-computed progress.
class GoalsPage extends ConsumerStatefulWidget {
const GoalsPage({super.key});
@override
ConsumerState<GoalsPage> createState() => _GoalsPageState();
}
class _GoalsPageState extends ConsumerState<GoalsPage> {
bool _showArchived = false;
void _snack(String message) =>
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
Future<void> _create() async {
final goal = await showDialog<Goal>(
context: context,
builder: (_) => const GoalEditDialog(),
);
if (goal == null) return;
try {
await ref.read(goalsApiProvider).create(goal);
if (!mounted) return;
invalidateGoals(ref);
} catch (e) {
if (mounted) _snack(apiErrorMessage(e));
}
}
Future<void> _edit(Goal goal) async {
final updated = await showDialog<Goal>(
context: context,
builder: (_) => GoalEditDialog(initial: goal),
);
if (updated == null) return;
try {
await ref.read(goalsApiProvider).patch(goal.id, updated.toJson());
if (!mounted) return;
invalidateGoals(ref);
} catch (e) {
if (mounted) _snack(apiErrorMessage(e));
}
}
Future<void> _delete(Goal goal) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Удалить цель?'),
content: Text('«${goal.name}» будет удалена безвозвратно.'),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('Отмена')),
FilledButton(onPressed: () => Navigator.of(ctx).pop(true), child: const Text('Удалить')),
],
),
);
if (confirmed != true) return;
try {
await ref.read(goalsApiProvider).delete(goal.id);
if (!mounted) return;
invalidateGoals(ref);
} catch (e) {
if (mounted) _snack(apiErrorMessage(e));
}
}
@override
Widget build(BuildContext context) {
final goals = ref.watch(goalsProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Цели'),
actions: [
IconButton(
tooltip: _showArchived ? 'Скрыть архив' : 'Показать архив',
icon: Icon(_showArchived ? Icons.inventory_2 : Icons.inventory_2_outlined),
onPressed: () => setState(() => _showArchived = !_showArchived),
),
IconButton(
tooltip: 'Обновить',
icon: const Icon(Icons.refresh),
onPressed: () => invalidateGoals(ref),
),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: _create,
icon: const Icon(Icons.add),
label: const Text('Новая цель'),
),
body: RefreshIndicator(
onRefresh: () async => invalidateGoals(ref),
child: AsyncValueView(
value: goals,
onRetry: () => ref.invalidate(goalsProvider),
data: (all) {
final rows = _showArchived ? all : all.where((g) => !g.archived).toList();
if (rows.isEmpty) {
return ListView(
padding: const EdgeInsets.all(16),
children: [
const SizedBox(height: 48),
EmptyState(
icon: Icons.flag_outlined,
message: all.isEmpty
? 'Целей пока нет.\nЦель — это сумма и (необязательно) дата; '
'прогноз считает сервер по доходности или по взносам.'
: 'Все цели в архиве — включите показ архива.',
),
],
);
}
return ListView(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 88),
children: [
for (final g in rows)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: GoalCard(
goal: g,
onEdit: () => _edit(g),
onDelete: () => _delete(g),
),
),
],
);
},
),
),
);
}
}
+23
View File
@@ -0,0 +1,23 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/api/api_client.dart';
import 'data/goals_api.dart';
final goalsApiProvider = Provider<GoalsApi>((ref) => GoalsApi(ref.watch(apiProvider).dio));
final goalsProvider =
FutureProvider.autoDispose<List<Goal>>((ref) => ref.watch(goalsApiProvider).list());
/// Progress is computed server-side and refetched per goal — the client never projects
/// anything itself.
final goalProgressProvider =
FutureProvider.autoDispose.family<GoalProgress, int>((ref, id) async {
return ref.watch(goalsApiProvider).progress(id);
});
/// After any create/patch/delete the list and every progress card are refetched: the
/// numbers are recomputed on the server, not patched in the app.
void invalidateGoals(WidgetRef ref) {
ref.invalidate(goalsProvider);
ref.invalidate(goalProgressProvider);
}