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:
@@ -0,0 +1,212 @@
|
||||
/// Hand-written client for `/api/v1/instruments/pending`.
|
||||
///
|
||||
/// **Temporary.** These routes do not exist in `openapi/openapi.json` yet, so
|
||||
/// `app/packages/api_client` has no generated methods or models for them. The models and
|
||||
/// calls here follow `docs/ai/import-contract.md` literally and are meant to be **deleted**
|
||||
/// once the routes land in the spec and `just gen-client` regenerates the real client —
|
||||
/// at that point the providers should switch to `getInstrumentsApi()` and these classes
|
||||
/// should give way to the generated ones.
|
||||
///
|
||||
/// Raw Dio comes from `ref.read(apiProvider).dio`: base URL, the bearer header and the
|
||||
/// one-shot refresh on 401 are already wired there, so this layer only shapes URLs and JSON.
|
||||
library;
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
/// A report line whose instrument the server refused to guess. Mirrors
|
||||
/// `PendingInstrumentOut`; the extra fields (`firstSeenFileId`, `createdAt`) are absent
|
||||
/// from the copy embedded in `ImportPreview.pending_instruments`, hence nullable.
|
||||
class PendingInstrument {
|
||||
const PendingInstrument({
|
||||
required this.id,
|
||||
required this.source,
|
||||
required this.sourceKey,
|
||||
required this.status,
|
||||
this.isin,
|
||||
this.ticker,
|
||||
this.board,
|
||||
this.name,
|
||||
this.currency,
|
||||
this.assetClassHint,
|
||||
this.occurrences = 0,
|
||||
this.sampleQuantity,
|
||||
this.samplePrice,
|
||||
this.instrumentId,
|
||||
this.firstSeenFileId,
|
||||
this.createdAt,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String source;
|
||||
final String sourceKey;
|
||||
final String status;
|
||||
final String? isin;
|
||||
final String? ticker;
|
||||
final String? board;
|
||||
final String? name;
|
||||
final String? currency;
|
||||
final String? assetClassHint;
|
||||
final int occurrences;
|
||||
final String? sampleQuantity;
|
||||
final String? samplePrice;
|
||||
final int? instrumentId;
|
||||
final int? firstSeenFileId;
|
||||
final DateTime? createdAt;
|
||||
|
||||
/// The best human label available, never a guess about which instrument this is.
|
||||
String get title {
|
||||
final parts = [?ticker, ?name];
|
||||
if (parts.isNotEmpty) return parts.join(' · ');
|
||||
return isin ?? sourceKey;
|
||||
}
|
||||
|
||||
static PendingInstrument fromJson(Map<String, dynamic> json) => PendingInstrument(
|
||||
id: asInt(json['id'])!,
|
||||
source: asString(json['source']) ?? '',
|
||||
sourceKey: asString(json['source_key']) ?? '',
|
||||
status: asString(json['status']) ?? 'pending',
|
||||
isin: asString(json['isin']),
|
||||
ticker: asString(json['ticker']),
|
||||
board: asString(json['board']),
|
||||
name: asString(json['name']),
|
||||
currency: asString(json['currency']),
|
||||
assetClassHint: asString(json['asset_class_hint']),
|
||||
occurrences: asInt(json['occurrences']) ?? 0,
|
||||
sampleQuantity: asString(json['sample_quantity']),
|
||||
samplePrice: asString(json['sample_price']),
|
||||
instrumentId: asInt(json['instrument_id']),
|
||||
firstSeenFileId: asInt(json['first_seen_file_id']),
|
||||
createdAt: asDate(json['created_at']),
|
||||
);
|
||||
}
|
||||
|
||||
/// What `POST /instruments/pending/{id}/resolve` reports back.
|
||||
class PendingResolveResult {
|
||||
const PendingResolveResult({
|
||||
required this.id,
|
||||
required this.status,
|
||||
this.instrumentId,
|
||||
this.eventsBound = 0,
|
||||
this.aliasCreated = false,
|
||||
this.metricsRefreshed = false,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String status;
|
||||
final int? instrumentId;
|
||||
final int eventsBound;
|
||||
final bool aliasCreated;
|
||||
final bool metricsRefreshed;
|
||||
|
||||
static PendingResolveResult fromJson(Map<String, dynamic> json) => PendingResolveResult(
|
||||
id: asInt(json['id']) ?? 0,
|
||||
status: asString(json['status']) ?? 'resolved',
|
||||
instrumentId: asInt(json['instrument_id']),
|
||||
eventsBound: asInt(json['events_bound']) ?? 0,
|
||||
aliasCreated: json['alias_created'] == true,
|
||||
metricsRefreshed: json['metrics_refreshed'] == true,
|
||||
);
|
||||
}
|
||||
|
||||
/// The body of `action: "create"` — the user's own answer, typed in by hand.
|
||||
class NewInstrument {
|
||||
const NewInstrument({
|
||||
required this.assetClass,
|
||||
required this.name,
|
||||
required this.currency,
|
||||
this.isin,
|
||||
this.ticker,
|
||||
this.board,
|
||||
this.lot,
|
||||
});
|
||||
|
||||
/// A plain string on the wire: `AssetClass` is deliberately not exposed by the API
|
||||
/// (`index` cannot be a Dart enum member — it collides with `Enum.index`).
|
||||
final String assetClass;
|
||||
final String name;
|
||||
final String currency;
|
||||
final String? isin;
|
||||
final String? ticker;
|
||||
final String? board;
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// The asset classes the contract allows, as wire strings.
|
||||
const assetClassKeys = [
|
||||
'share',
|
||||
'bond',
|
||||
'etf',
|
||||
'fund',
|
||||
'currency',
|
||||
'index',
|
||||
'deposit',
|
||||
'real_estate',
|
||||
'crypto',
|
||||
'custom',
|
||||
];
|
||||
|
||||
class PendingApi {
|
||||
const PendingApi(this._dio);
|
||||
|
||||
final Dio _dio;
|
||||
|
||||
static const _base = '/api/v1/instruments/pending';
|
||||
|
||||
Future<List<PendingInstrument>> list({
|
||||
String status = 'pending',
|
||||
int limit = 100,
|
||||
int offset = 0,
|
||||
}) async {
|
||||
final r = await _dio.get<List<dynamic>>(
|
||||
_base,
|
||||
queryParameters: {'status': status, 'limit': limit, 'offset': offset},
|
||||
);
|
||||
return (r.data ?? const [])
|
||||
.map((e) => PendingInstrument.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<PendingResolveResult> link(int id, int instrumentId) =>
|
||||
_resolve(id, {'action': 'link', 'instrument_id': instrumentId});
|
||||
|
||||
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> _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 {});
|
||||
}
|
||||
}
|
||||
|
||||
// --- JSON coercion helpers, shared with the imports layer -------------------------------
|
||||
//
|
||||
// The server sends money and quantities as strings and never as numbers; these helpers do
|
||||
// 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());
|
||||
|
||||
int? asInt(Object? v) => switch (v) {
|
||||
null => null,
|
||||
final int i => i,
|
||||
final String s => int.tryParse(s),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
DateTime? asDate(Object? v) {
|
||||
final s = asString(v);
|
||||
if (s == null || s.isEmpty) return null;
|
||||
return DateTime.tryParse(s);
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../core/widgets/async_value_view.dart';
|
||||
import '../../core/widgets/empty_state.dart';
|
||||
import '../../core/widgets/money_text.dart';
|
||||
import '../imports/data/imports_api.dart' show importErrorMessage;
|
||||
import '../imports/providers.dart' show invalidateLedgerDependents;
|
||||
import '../portfolio/labels.dart' show assetClassLabel, formatQty;
|
||||
import 'data/pending_api.dart';
|
||||
import 'providers.dart';
|
||||
import 'widgets/create_instrument_dialog.dart';
|
||||
import 'widgets/link_instrument_dialog.dart';
|
||||
|
||||
/// Нераспознанные инструменты: the queue of report lines whose instrument the server
|
||||
/// refused to guess. Every row waits for an explicit decision — link, create or ignore.
|
||||
class PendingInstrumentsPage extends ConsumerStatefulWidget {
|
||||
const PendingInstrumentsPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<PendingInstrumentsPage> createState() => _PendingInstrumentsPageState();
|
||||
}
|
||||
|
||||
class _PendingInstrumentsPageState extends ConsumerState<PendingInstrumentsPage> {
|
||||
int? _busyId;
|
||||
|
||||
void _snack(String message) =>
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
|
||||
Future<void> _run(int id, Future<PendingResolveResult> Function() action) async {
|
||||
setState(() => _busyId = id);
|
||||
try {
|
||||
final result = await action();
|
||||
if (!mounted) return;
|
||||
ref.invalidate(pendingInstrumentsProvider);
|
||||
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 ? ', добавлен алиас' : ''}');
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
_snack(importErrorMessage(e));
|
||||
} finally {
|
||||
if (mounted) setState(() => _busyId = null);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _link(PendingInstrument p) async {
|
||||
final instrumentId = await showDialog<int>(
|
||||
context: context,
|
||||
builder: (_) => LinkInstrumentDialog(
|
||||
initialQuery: p.isin ?? p.ticker ?? p.name ?? '',
|
||||
),
|
||||
);
|
||||
if (instrumentId == null || !mounted) return;
|
||||
await _run(p.id, () => ref.read(pendingApiProvider).link(p.id, instrumentId));
|
||||
}
|
||||
|
||||
Future<void> _create(PendingInstrument p) async {
|
||||
final instrument = await showDialog<NewInstrument>(
|
||||
context: context,
|
||||
builder: (_) => CreateInstrumentDialog(pending: p),
|
||||
);
|
||||
if (instrument == null || !mounted) return;
|
||||
await _run(p.id, () => ref.read(pendingApiProvider).create(p.id, instrument));
|
||||
}
|
||||
|
||||
Future<void> _ignore(PendingInstrument p) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Игнорировать строку?'),
|
||||
content: Text('«${p.title}» больше не будет предлагаться к резолву. '
|
||||
'Её события останутся без инструмента.'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false), child: const Text('Отмена')),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Игнорировать')),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true || !mounted) return;
|
||||
await _run(p.id, () => ref.read(pendingApiProvider).ignore(p.id));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final rows = ref.watch(pendingInstrumentsProvider);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Нераспознанные инструменты'),
|
||||
actions: [
|
||||
IconButton(
|
||||
tooltip: 'Обновить',
|
||||
icon: const Icon(Icons.refresh),
|
||||
onPressed: () {
|
||||
ref.invalidate(pendingInstrumentsProvider);
|
||||
ref.invalidate(pendingCountProvider);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () async => ref.invalidate(pendingInstrumentsProvider),
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
const _StatusFilter(),
|
||||
const SizedBox(height: 8),
|
||||
AsyncValueView(
|
||||
value: rows,
|
||||
onRetry: () => ref.invalidate(pendingInstrumentsProvider),
|
||||
data: (items) => items.isEmpty
|
||||
? const Padding(
|
||||
padding: EdgeInsets.only(top: 48),
|
||||
child: EmptyState(
|
||||
icon: Icons.check_circle_outline,
|
||||
message: 'Нераспознанных инструментов нет.',
|
||||
),
|
||||
)
|
||||
: Column(
|
||||
children: [
|
||||
for (final p in items)
|
||||
_PendingCard(
|
||||
pending: p,
|
||||
busy: _busyId == p.id,
|
||||
onLink: () => _link(p),
|
||||
onCreate: () => _create(p),
|
||||
onIgnore: () => _ignore(p),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StatusFilter extends ConsumerWidget {
|
||||
const _StatusFilter();
|
||||
|
||||
static const _options = {
|
||||
'pending': 'Ждут решения',
|
||||
'resolved': 'Привязаны',
|
||||
'ignored': 'Игнорируются',
|
||||
'all': 'Все',
|
||||
};
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final current = ref.watch(pendingStatusFilterProvider);
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
for (final e in _options.entries)
|
||||
ChoiceChip(
|
||||
label: Text(e.value),
|
||||
selected: current == e.key,
|
||||
onSelected: (_) => ref.read(pendingStatusFilterProvider.notifier).state = e.key,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PendingCard extends StatelessWidget {
|
||||
const _PendingCard({
|
||||
required this.pending,
|
||||
required this.busy,
|
||||
required this.onLink,
|
||||
required this.onCreate,
|
||||
required this.onIgnore,
|
||||
});
|
||||
|
||||
final PendingInstrument pending;
|
||||
final bool busy;
|
||||
final VoidCallback onLink;
|
||||
final VoidCallback onCreate;
|
||||
final VoidCallback onIgnore;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final p = pending;
|
||||
final open = p.status == 'pending';
|
||||
|
||||
final facts = <String>[
|
||||
if (p.isin != null) 'ISIN ${p.isin}',
|
||||
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)}',
|
||||
];
|
||||
final sample = <String>[
|
||||
'встречается ${p.occurrences} раз',
|
||||
if (p.sampleQuantity != null) 'кол-во ${formatQty(p.sampleQuantity!)}',
|
||||
if (p.samplePrice != null)
|
||||
'цена ${MoneyText.format(p.samplePrice!, p.currency ?? 'RUB')}',
|
||||
];
|
||||
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: Text(p.title, style: theme.textTheme.titleMedium)),
|
||||
if (!open)
|
||||
Chip(
|
||||
visualDensity: VisualDensity.compact,
|
||||
label: Text(p.status == 'ignored' ? 'игнорируется' : 'привязан'),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (facts.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(facts.join(' · '), style: theme.textTheme.bodySmall),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 2),
|
||||
child: Text(sample.join(' · '), style: theme.textTheme.bodySmall),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 2),
|
||||
child: Text(
|
||||
'источник ${p.source} · ключ ${p.sourceKey}'
|
||||
'${p.firstSeenFileId != null ? ' · файл №${p.firstSeenFileId}' : ''}',
|
||||
style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.outline),
|
||||
),
|
||||
),
|
||||
if (open) ...[
|
||||
const SizedBox(height: 12),
|
||||
if (busy)
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 8),
|
||||
child: LinearProgressIndicator(),
|
||||
)
|
||||
else
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: onLink,
|
||||
icon: const Icon(Icons.link, size: 18),
|
||||
label: const Text('Привязать к существующему'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: onCreate,
|
||||
icon: const Icon(Icons.add, size: 18),
|
||||
label: const Text('Создать новый'),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: onIgnore,
|
||||
icon: const Icon(Icons.block, size: 18),
|
||||
label: const Text('Игнорировать'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'package:fintracker_api/fintracker_api.dart';
|
||||
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));
|
||||
|
||||
/// `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);
|
||||
});
|
||||
|
||||
/// 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 {
|
||||
final rows = await ref.watch(pendingApiProvider).list(status: 'pending');
|
||||
return rows.length;
|
||||
});
|
||||
|
||||
/// 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 [];
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../portfolio/labels.dart' show assetClassLabel;
|
||||
import '../data/pending_api.dart';
|
||||
|
||||
/// The form behind `action: "create"`. Fields are prefilled from what the report literally
|
||||
/// said about this line (ISIN, ticker, name, currency) — that is transcription, not a guess
|
||||
/// about which instrument it is; the user still confirms every field before submitting.
|
||||
class CreateInstrumentDialog extends StatefulWidget {
|
||||
const CreateInstrumentDialog({required this.pending, super.key});
|
||||
|
||||
final PendingInstrument pending;
|
||||
|
||||
@override
|
||||
State<CreateInstrumentDialog> createState() => _CreateInstrumentDialogState();
|
||||
}
|
||||
|
||||
class _CreateInstrumentDialogState extends State<CreateInstrumentDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
late final _isin = TextEditingController(text: widget.pending.isin ?? '');
|
||||
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 _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)
|
||||
? widget.pending.assetClassHint!
|
||||
: 'share';
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_isin.dispose();
|
||||
_ticker.dispose();
|
||||
_board.dispose();
|
||||
_name.dispose();
|
||||
_currency.dispose();
|
||||
_lot.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
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()),
|
||||
));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Создать инструмент'),
|
||||
content: SizedBox(
|
||||
width: 480,
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: _assetClass,
|
||||
isExpanded: true,
|
||||
decoration: const InputDecoration(labelText: 'Класс актива'),
|
||||
items: [
|
||||
for (final key in assetClassKeys)
|
||||
DropdownMenuItem(value: key, child: Text('${assetClassLabel(key)} ($key)')),
|
||||
],
|
||||
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;
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Отмена')),
|
||||
FilledButton(onPressed: _submit, child: const Text('Создать и привязать')),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _field(
|
||||
TextEditingController controller,
|
||||
String label, {
|
||||
bool required = false,
|
||||
TextInputType? keyboard,
|
||||
String? Function(String?)? validator,
|
||||
}) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: TextFormField(
|
||||
controller: controller,
|
||||
keyboardType: keyboard,
|
||||
decoration: InputDecoration(labelText: label, isDense: true),
|
||||
validator: validator ??
|
||||
(required
|
||||
? (v) => (v == null || v.trim().isEmpty) ? 'Обязательное поле' : null
|
||||
: null),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:fintracker_api/fintracker_api.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../portfolio/labels.dart' show assetClassLabel;
|
||||
import '../providers.dart';
|
||||
|
||||
/// Search-and-pick over `GET /instruments?q=`. Deliberately dumb: it shows what the search
|
||||
/// returned and nothing else — no "probably this one" pre-selection, no highlighted best
|
||||
/// guess. The binding is the user's statement, not the app's inference.
|
||||
class LinkInstrumentDialog extends ConsumerStatefulWidget {
|
||||
const LinkInstrumentDialog({required this.initialQuery, super.key});
|
||||
|
||||
/// Prefilled search text (the ISIN or ticker from the report). It only fills the search
|
||||
/// box — nothing is selected until the user taps a row.
|
||||
final String initialQuery;
|
||||
|
||||
@override
|
||||
ConsumerState<LinkInstrumentDialog> createState() => _LinkInstrumentDialogState();
|
||||
}
|
||||
|
||||
class _LinkInstrumentDialogState extends ConsumerState<LinkInstrumentDialog> {
|
||||
late final TextEditingController _controller =
|
||||
TextEditingController(text: widget.initialQuery);
|
||||
String _query = '';
|
||||
Timer? _debounce;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_query = widget.initialQuery;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_debounce?.cancel();
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onChanged(String value) {
|
||||
_debounce?.cancel();
|
||||
_debounce = Timer(const Duration(milliseconds: 350), () {
|
||||
if (mounted) setState(() => _query = value);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final results = ref.watch(instrumentSearchProvider(_query));
|
||||
return AlertDialog(
|
||||
title: const Text('Привязать к инструменту'),
|
||||
content: SizedBox(
|
||||
width: 520,
|
||||
height: 420,
|
||||
child: Column(
|
||||
children: [
|
||||
TextField(
|
||||
controller: _controller,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(
|
||||
prefixIcon: Icon(Icons.search),
|
||||
hintText: 'Тикер, ISIN или название',
|
||||
border: OutlineInputBorder(),
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: _onChanged,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(
|
||||
child: results.when(
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (e, _) => Center(child: Text('$e')),
|
||||
data: (rows) {
|
||||
if (_query.trim().length < 2) {
|
||||
return const Center(child: Text('Введите минимум 2 символа'));
|
||||
}
|
||||
if (rows.isEmpty) {
|
||||
return const Center(child: Text('Ничего не найдено'));
|
||||
}
|
||||
return ListView.builder(
|
||||
itemCount: rows.length,
|
||||
itemBuilder: (context, i) => _row(rows[i]),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Отмена'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _row(InstrumentOut instrument) {
|
||||
final subtitle = [
|
||||
assetClassLabel(instrument.assetClass),
|
||||
if (instrument.isin != null) instrument.isin!,
|
||||
if (instrument.board != null) instrument.board!,
|
||||
instrument.currency,
|
||||
].join(' · ');
|
||||
return ListTile(
|
||||
dense: true,
|
||||
title: Text([
|
||||
if (instrument.ticker != null) instrument.ticker!,
|
||||
instrument.name,
|
||||
].join(' · ')),
|
||||
subtitle: Text(subtitle),
|
||||
onTap: () => Navigator.of(context).pop(instrument.id),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user