style(app): остальные экраны под новый визуальный язык и форматирование

Доходы, ребалансировка, налоги, импорт, цели, здоровье данных, правила, транзакции, категории, cashflow, pending: новые виджеты и токены темы, dart format. Тесты подстроены под новые модели.
This commit is contained in:
Dmitry
2026-09-19 22:14:27 +03:00
parent 62d36aa3e8
commit 322c60a359
55 changed files with 2158 additions and 1080 deletions
+33 -20
View File
@@ -60,7 +60,8 @@ class PendingInstrument {
return isin ?? sourceKey;
}
static PendingInstrument fromJson(Map<String, dynamic> json) => PendingInstrument(
static PendingInstrument fromJson(Map<String, dynamic> json) =>
PendingInstrument(
id: asInt(json['id'])!,
source: asString(json['source']) ?? '',
sourceKey: asString(json['source_key']) ?? '',
@@ -98,7 +99,8 @@ class PendingResolveResult {
final bool aliasCreated;
final bool metricsRefreshed;
static PendingResolveResult fromJson(Map<String, dynamic> json) => PendingResolveResult(
static PendingResolveResult fromJson(Map<String, dynamic> json) =>
PendingResolveResult(
id: asInt(json['id']) ?? 0,
status: asString(json['status']) ?? 'resolved',
instrumentId: asInt(json['instrument_id']),
@@ -131,14 +133,14 @@ class NewInstrument {
final int? lot;
Map<String, dynamic> toJson() => {
'asset_class': assetClass,
'name': name,
'currency': currency,
if (isin != null && isin!.isNotEmpty) 'isin': isin,
if (ticker != null && ticker!.isNotEmpty) 'ticker': ticker,
if (board != null && board!.isNotEmpty) 'board': board,
if (lot != null) 'lot': lot,
};
'asset_class': assetClass,
'name': name,
'currency': currency,
if (isin != null && isin!.isNotEmpty) 'isin': isin,
if (ticker != null && ticker!.isNotEmpty) 'ticker': ticker,
if (board != null && board!.isNotEmpty) 'board': board,
if (lot != null) 'lot': lot,
};
}
/// The asset classes the contract allows, as wire strings.
@@ -172,7 +174,10 @@ class PendingApi {
queryParameters: {'status': status, 'limit': limit, 'offset': offset},
);
return (r.data ?? const [])
.map((e) => PendingInstrument.fromJson(Map<String, dynamic>.from(e as Map)))
.map(
(e) =>
PendingInstrument.fromJson(Map<String, dynamic>.from(e as Map)),
)
.toList();
}
@@ -182,10 +187,17 @@ class PendingApi {
Future<PendingResolveResult> create(int id, NewInstrument instrument) =>
_resolve(id, {'action': 'create', 'instrument': instrument.toJson()});
Future<PendingResolveResult> ignore(int id) => _resolve(id, {'action': 'ignore'});
Future<PendingResolveResult> ignore(int id) =>
_resolve(id, {'action': 'ignore'});
Future<PendingResolveResult> _resolve(int id, Map<String, dynamic> body) async {
final r = await _dio.post<Map<String, dynamic>>('$_base/$id/resolve', data: body);
Future<PendingResolveResult> _resolve(
int id,
Map<String, dynamic> body,
) async {
final r = await _dio.post<Map<String, dynamic>>(
'$_base/$id/resolve',
data: body,
);
return PendingResolveResult.fromJson(r.data ?? const {});
}
}
@@ -196,14 +208,15 @@ class PendingApi {
// not convert to `double` anywhere — a numeric JSON value (should one ever appear) is kept
// as its lossless string form and parsed into `Decimal` at the point of display.
String? asString(Object? v) => v == null ? null : (v is String ? v : v.toString());
String? asString(Object? v) =>
v == null ? null : (v is String ? v : v.toString());
int? asInt(Object? v) => switch (v) {
null => null,
final int i => i,
final String s => int.tryParse(s),
_ => null,
};
null => null,
final int i => i,
final String s => int.tryParse(s),
_ => null,
};
DateTime? asDate(Object? v) {
final s = asString(v);
+51 -21
View File
@@ -18,16 +18,22 @@ class PendingInstrumentsPage extends ConsumerStatefulWidget {
const PendingInstrumentsPage({super.key});
@override
ConsumerState<PendingInstrumentsPage> createState() => _PendingInstrumentsPageState();
ConsumerState<PendingInstrumentsPage> createState() =>
_PendingInstrumentsPageState();
}
class _PendingInstrumentsPageState extends ConsumerState<PendingInstrumentsPage> {
class _PendingInstrumentsPageState
extends ConsumerState<PendingInstrumentsPage> {
int? _busyId;
void _snack(String message) =>
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(message)));
Future<void> _run(int id, Future<PendingResolveResult> Function() action) async {
Future<void> _run(
int id,
Future<PendingResolveResult> Function() action,
) async {
setState(() => _busyId = id);
try {
final result = await action();
@@ -36,10 +42,12 @@ class _PendingInstrumentsPageState extends ConsumerState<PendingInstrumentsPage>
ref.invalidate(pendingCountProvider);
// Events moved out of `pending`, so holdings, allocation and the event list changed.
invalidateLedgerDependents(ref);
_snack(result.status == 'ignored'
? 'Строка помечена как «не инструмент»'
: 'Привязано событий: ${result.eventsBound}'
'${result.aliasCreated ? ', добавлен алиас' : ''}');
_snack(
result.status == 'ignored'
? 'Строка помечена как «не инструмент»'
: 'Привязано событий: ${result.eventsBound}'
'${result.aliasCreated ? ', добавлен алиас' : ''}',
);
} catch (e) {
if (!mounted) return;
_snack(importErrorMessage(e));
@@ -56,7 +64,10 @@ class _PendingInstrumentsPageState extends ConsumerState<PendingInstrumentsPage>
),
);
if (instrumentId == null || !mounted) return;
await _run(p.id, () => ref.read(pendingApiProvider).link(p.id, instrumentId));
await _run(
p.id,
() => ref.read(pendingApiProvider).link(p.id, instrumentId),
);
}
Future<void> _create(PendingInstrument p) async {
@@ -65,7 +76,10 @@ class _PendingInstrumentsPageState extends ConsumerState<PendingInstrumentsPage>
builder: (_) => CreateInstrumentDialog(pending: p),
);
if (instrument == null || !mounted) return;
await _run(p.id, () => ref.read(pendingApiProvider).create(p.id, instrument));
await _run(
p.id,
() => ref.read(pendingApiProvider).create(p.id, instrument),
);
}
Future<void> _ignore(PendingInstrument p) async {
@@ -73,14 +87,19 @@ class _PendingInstrumentsPageState extends ConsumerState<PendingInstrumentsPage>
context: context,
builder: (context) => AlertDialog(
title: const Text('Игнорировать строку?'),
content: Text('«${p.title}» больше не будет предлагаться к резолву. '
'Её события останутся без инструмента.'),
content: Text(
'«${p.title}» больше не будет предлагаться к резолву. '
'Её события останутся без инструмента.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false), child: const Text('Отмена')),
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Отмена'),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Игнорировать')),
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Игнорировать'),
),
],
),
);
@@ -164,7 +183,8 @@ class _StatusFilter extends ConsumerWidget {
ChoiceChip(
label: Text(e.value),
selected: current == e.key,
onSelected: (_) => ref.read(pendingStatusFilterProvider.notifier).state = e.key,
onSelected: (_) =>
ref.read(pendingStatusFilterProvider.notifier).state = e.key,
),
],
);
@@ -197,7 +217,8 @@ class _PendingCard extends StatelessWidget {
if (p.ticker != null) 'тикер ${p.ticker}',
if (p.board != null) 'доска ${p.board}',
if (p.currency != null) p.currency!,
if (p.assetClassHint != null) 'в отчёте: ${assetClassLabel(p.assetClassHint)}',
if (p.assetClassHint != null)
'в отчёте: ${assetClassLabel(p.assetClassHint)}',
];
final sample = <String>[
'встречается ${p.occurrences} раз',
@@ -214,18 +235,25 @@ class _PendingCard extends StatelessWidget {
children: [
Row(
children: [
Expanded(child: Text(p.title, style: theme.textTheme.titleMedium)),
Expanded(
child: Text(p.title, style: theme.textTheme.titleMedium),
),
if (!open)
Chip(
visualDensity: VisualDensity.compact,
label: Text(p.status == 'ignored' ? 'игнорируется' : 'привязан'),
label: Text(
p.status == 'ignored' ? 'игнорируется' : 'привязан',
),
),
],
),
if (facts.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(facts.join(' · '), style: theme.textTheme.bodySmall),
child: Text(
facts.join(' · '),
style: theme.textTheme.bodySmall,
),
),
Padding(
padding: const EdgeInsets.only(top: 2),
@@ -236,7 +264,9 @@ class _PendingCard extends StatelessWidget {
child: Text(
'источник ${p.source} · ключ ${p.sourceKey}'
'${p.firstSeenFileId != null ? ' · файл №${p.firstSeenFileId}' : ''}',
style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.outline),
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.outline,
),
),
),
if (open) ...[
+15 -13
View File
@@ -4,16 +4,18 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/api/api_client.dart';
import 'data/pending_api.dart';
final pendingApiProvider = Provider<PendingApi>((ref) => PendingApi(ref.watch(apiProvider).dio));
final pendingApiProvider = Provider<PendingApi>(
(ref) => PendingApi(ref.watch(apiProvider).dio),
);
/// `pending | resolved | ignored | all` — the filter of the resolve screen.
final pendingStatusFilterProvider = StateProvider<String>((ref) => 'pending');
final pendingInstrumentsProvider =
FutureProvider.autoDispose<List<PendingInstrument>>((ref) async {
final status = ref.watch(pendingStatusFilterProvider);
return ref.watch(pendingApiProvider).list(status: status);
});
final status = ref.watch(pendingStatusFilterProvider);
return ref.watch(pendingApiProvider).list(status: status);
});
/// How many rows still await a decision — shown as a badge next to the import screen's link.
final pendingCountProvider = FutureProvider.autoDispose<int>((ref) async {
@@ -23,12 +25,12 @@ final pendingCountProvider = FutureProvider.autoDispose<int>((ref) async {
/// Instrument search for the "link to an existing instrument" dialog. This one endpoint is
/// already in the generated client, so it goes through it rather than raw Dio.
final instrumentSearchProvider =
FutureProvider.autoDispose.family<List<InstrumentOut>, String>((ref, query) async {
if (query.trim().length < 2) return const [];
final r = await ref
.watch(apiProvider)
.getInstrumentsApi()
.instrumentsList(q: query.trim(), limit: 25);
return r.data ?? const [];
});
final instrumentSearchProvider = FutureProvider.autoDispose
.family<List<InstrumentOut>, String>((ref, query) async {
if (query.trim().length < 2) return const [];
final r = await ref
.watch(apiProvider)
.getInstrumentsApi()
.instrumentsList(q: query.trim(), limit: 25);
return r.data ?? const [];
});
@@ -21,12 +21,15 @@ class _CreateInstrumentDialogState extends State<CreateInstrumentDialog> {
late final _ticker = TextEditingController(text: widget.pending.ticker ?? '');
late final _board = TextEditingController(text: widget.pending.board ?? '');
late final _name = TextEditingController(text: widget.pending.name ?? '');
late final _currency = TextEditingController(text: widget.pending.currency ?? 'RUB');
late final _currency = TextEditingController(
text: widget.pending.currency ?? 'RUB',
);
late final _lot = TextEditingController(text: '1');
/// `asset_class_hint` is what the report's own section said (e.g. the «Фонды» table), so
/// it is offered as the initial value of a control the user must still look at.
late String _assetClass = assetClassKeys.contains(widget.pending.assetClassHint)
late String _assetClass =
assetClassKeys.contains(widget.pending.assetClassHint)
? widget.pending.assetClassHint!
: 'share';
@@ -43,15 +46,17 @@ class _CreateInstrumentDialogState extends State<CreateInstrumentDialog> {
void _submit() {
if (!_formKey.currentState!.validate()) return;
Navigator.of(context).pop(NewInstrument(
assetClass: _assetClass,
name: _name.text.trim(),
currency: _currency.text.trim().toUpperCase(),
isin: _isin.text.trim(),
ticker: _ticker.text.trim(),
board: _board.text.trim(),
lot: int.tryParse(_lot.text.trim()),
));
Navigator.of(context).pop(
NewInstrument(
assetClass: _assetClass,
name: _name.text.trim(),
currency: _currency.text.trim().toUpperCase(),
isin: _isin.text.trim(),
ticker: _ticker.text.trim(),
board: _board.text.trim(),
lot: int.tryParse(_lot.text.trim()),
),
);
}
@override
@@ -72,27 +77,44 @@ class _CreateInstrumentDialogState extends State<CreateInstrumentDialog> {
decoration: const InputDecoration(labelText: 'Класс актива'),
items: [
for (final key in assetClassKeys)
DropdownMenuItem(value: key, child: Text('${assetClassLabel(key)} ($key)')),
DropdownMenuItem(
value: key,
child: Text('${assetClassLabel(key)} ($key)'),
),
],
onChanged: (v) => setState(() => _assetClass = v ?? _assetClass),
onChanged: (v) =>
setState(() => _assetClass = v ?? _assetClass),
),
_field(_name, 'Название', required: true),
_field(_isin, 'ISIN'),
_field(_ticker, 'Тикер'),
_field(_board, 'Доска (TQBR, TQTF…)'),
_field(_currency, 'Валюта', required: true),
_field(_lot, 'Лот', keyboard: TextInputType.number, validator: (v) {
if (v == null || v.trim().isEmpty) return null;
return int.tryParse(v.trim()) == null ? 'Целое число' : null;
}),
_field(
_lot,
'Лот',
keyboard: TextInputType.number,
validator: (v) {
if (v == null || v.trim().isEmpty) return null;
return int.tryParse(v.trim()) == null
? 'Целое число'
: null;
},
),
],
),
),
),
),
actions: [
TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Отмена')),
FilledButton(onPressed: _submit, child: const Text('Создать и привязать')),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Отмена'),
),
FilledButton(
onPressed: _submit,
child: const Text('Создать и привязать'),
),
],
);
}
@@ -110,9 +132,12 @@ class _CreateInstrumentDialogState extends State<CreateInstrumentDialog> {
controller: controller,
keyboardType: keyboard,
decoration: InputDecoration(labelText: label, isDense: true),
validator: validator ??
validator:
validator ??
(required
? (v) => (v == null || v.trim().isEmpty) ? 'Обязательное поле' : null
? (v) => (v == null || v.trim().isEmpty)
? 'Обязательное поле'
: null
: null),
),
);
@@ -18,12 +18,14 @@ class LinkInstrumentDialog extends ConsumerStatefulWidget {
final String initialQuery;
@override
ConsumerState<LinkInstrumentDialog> createState() => _LinkInstrumentDialogState();
ConsumerState<LinkInstrumentDialog> createState() =>
_LinkInstrumentDialogState();
}
class _LinkInstrumentDialogState extends ConsumerState<LinkInstrumentDialog> {
late final TextEditingController _controller =
TextEditingController(text: widget.initialQuery);
late final TextEditingController _controller = TextEditingController(
text: widget.initialQuery,
);
String _query = '';
Timer? _debounce;
@@ -75,7 +77,9 @@ class _LinkInstrumentDialogState extends ConsumerState<LinkInstrumentDialog> {
error: (e, _) => Center(child: Text('$e')),
data: (rows) {
if (_query.trim().length < 2) {
return const Center(child: Text('Введите минимум 2 символа'));
return const Center(
child: Text('Введите минимум 2 символа'),
);
}
if (rows.isEmpty) {
return const Center(child: Text('Ничего не найдено'));
@@ -108,10 +112,12 @@ class _LinkInstrumentDialogState extends ConsumerState<LinkInstrumentDialog> {
].join(' · ');
return ListTile(
dense: true,
title: Text([
if (instrument.ticker != null) instrument.ticker!,
instrument.name,
].join(' · ')),
title: Text(
[
if (instrument.ticker != null) instrument.ticker!,
instrument.name,
].join(' · '),
),
subtitle: Text(subtitle),
onTap: () => Navigator.of(context).pop(instrument.id),
);