- Adds new localization keys for transaction details. - Deletes obsolete localization files, switching to a single ARB file per language. - Adds `Equatable` to data models (`Category`, `Tag`, `TransactionRecord`, `User`) for improved state management and change detection. - Introduces the transaction creation dialog. - Adds development note to GEMINI.md Improves internationalization and data models - Adds new localization keys for transaction details, supporting enhanced user experience. - Migrates to single ARB file for each language, streamlining the localization process. - Implements Equatable in data models (Category, Tag, TransactionRecord, User) for improved state management and simplified change detection. - Introduces transaction creation dialog, simplifying the transaction creation process. - Adds development note to GEMINI.md
288 lines
11 KiB
Dart
288 lines
11 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:get_it/get_it.dart';
|
|
|
|
import '/l10n/app_localizations.dart';
|
|
import '../../logic/auth/auth_bloc.dart';
|
|
import '../../logic/transaction/transaction_bloc.dart';
|
|
import '../../services/user_service.dart';
|
|
import '../home/widgets/summary_widget.dart'; // Импортируем новый виджет сводки
|
|
import '../reports_page.dart'; // Импортируем новую страницу отчетов
|
|
import '../settings_page.dart';
|
|
import 'widgets/add_transaction_dialog.dart'; // Добавлен импорт для UserService
|
|
|
|
class HomePage extends StatefulWidget {
|
|
const HomePage({super.key});
|
|
|
|
@override
|
|
State<HomePage> createState() => _HomePageState();
|
|
}
|
|
|
|
class _HomePageState extends State<HomePage> {
|
|
int _selectedIndex = 0; // Индекс выбранной вкладки
|
|
late String _currentUserId; // ID текущего пользователя
|
|
|
|
// Список виджетов для каждой вкладки нижней навигации
|
|
static final List<Widget> _widgetOptions = <Widget>[
|
|
const TransactionsPage(), // Главная страница с транзакциями
|
|
const ReportsPage(), // Страница отчетов
|
|
const SettingsPage(), // Страница настроек
|
|
];
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
// Получаем ID текущего пользователя из AuthBloc
|
|
final authState = context.read<AuthBloc>().state;
|
|
if (authState is AuthAuthenticated) {
|
|
_currentUserId = authState.user.id;
|
|
} else {
|
|
// Если пользователь не аутентифицирован, можно перенаправить на страницу входа
|
|
// или использовать ID по умолчанию, если это применимо.
|
|
// В данном случае, для простоты, мы предполагаем, что пользователь всегда аутентифицирован.
|
|
_currentUserId = 'default_user'; // Заглушка, если что-то пошло не так
|
|
}
|
|
}
|
|
|
|
void _onItemTapped(int index) {
|
|
setState(() {
|
|
_selectedIndex = index;
|
|
});
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final localizations = AppLocalizations.of(
|
|
context,
|
|
)!; // Получаем экземпляр локализации
|
|
|
|
return BlocProvider(
|
|
create: (context) {
|
|
return GetIt.instance<TransactionBloc>()
|
|
..add(LoadTransactions(userId: _currentUserId));
|
|
},
|
|
child: Scaffold(
|
|
appBar: AppBar(
|
|
title: Text(localizations.appTitle), // Локализованный заголовок
|
|
// Кнопки действий в AppBar теперь не нужны, так как настройки перенесены в BottomNavigationBar
|
|
),
|
|
body: Center(
|
|
child: _widgetOptions[_selectedIndex], // Отображаем выбранный виджет
|
|
),
|
|
floatingActionButton: FloatingActionButton(
|
|
onPressed: () {
|
|
showDialog(
|
|
context: context,
|
|
builder: (BuildContext context) {
|
|
return const AddTransactionDialog();
|
|
},
|
|
);
|
|
},
|
|
child: const Icon(Icons.add),
|
|
),
|
|
bottomNavigationBar: BottomNavigationBar(
|
|
items: <BottomNavigationBarItem>[
|
|
BottomNavigationBarItem(
|
|
icon: const Icon(Icons.home),
|
|
label: localizations.homePageTitle, // Локализованный текст
|
|
),
|
|
BottomNavigationBarItem(
|
|
icon: const Icon(Icons.bar_chart),
|
|
label: localizations.reportsPageTitle, // Локализованный текст
|
|
),
|
|
BottomNavigationBarItem(
|
|
icon: const Icon(Icons.settings),
|
|
label: localizations.settingsPageTitle, // Локализованный текст
|
|
),
|
|
],
|
|
currentIndex: _selectedIndex,
|
|
selectedItemColor: Theme.of(context).colorScheme.primary,
|
|
onTap: _onItemTapped,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
// Отдельный виджет для страницы транзакций, чтобы HomeView был чище
|
|
class TransactionsPage extends StatelessWidget {
|
|
const TransactionsPage({super.key});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final localizations = AppLocalizations.of(
|
|
context,
|
|
)!; // Получаем экземпляр локализации
|
|
|
|
return BlocBuilder<TransactionBloc, TransactionState>(
|
|
builder: (context, state) {
|
|
if (state is TransactionLoading) {
|
|
return const Center(child: CircularProgressIndicator());
|
|
} else if (state is TransactionLoaded) {
|
|
// Используем ListView для вертикальной прокрутки
|
|
return ListView(
|
|
children: [
|
|
// Виджет сводки
|
|
// Рассчитываем доходы, расходы и баланс из транзакций
|
|
Builder(
|
|
builder: (context) {
|
|
double income = 0.0;
|
|
double expense = 0.0;
|
|
for (var transaction in state.transactions) {
|
|
if (transaction.isIncome) {
|
|
income += transaction.amount;
|
|
} else {
|
|
expense += transaction.amount;
|
|
}
|
|
}
|
|
final balance = income - expense;
|
|
// Получаем текущего пользователя для определения валюты
|
|
final userService = GetIt.instance<UserService>();
|
|
final currencySymbol =
|
|
userService.currentUser?.defaultCurrency ??
|
|
'₽'; // Валюта по умолчанию, если не найдена
|
|
|
|
return SummaryWidget(
|
|
income: income,
|
|
expense: expense,
|
|
balance: balance,
|
|
currencySymbol: currencySymbol, // Передаем символ валюты
|
|
); // Передаем реальные данные в SummaryWidget
|
|
},
|
|
),
|
|
// Заголовок для списка транзакций
|
|
Padding(
|
|
padding: const EdgeInsets.all(16.0),
|
|
child: Text(
|
|
localizations.transactionsHistoryTitle,
|
|
style: Theme.of(context).textTheme.titleLarge,
|
|
),
|
|
),
|
|
// Список транзакций
|
|
if (state.transactions.isEmpty)
|
|
Center(
|
|
child: Text(localizations.noTransactionsText),
|
|
) // Локализованный текст
|
|
else
|
|
ListView.builder(
|
|
shrinkWrap: true,
|
|
physics: const NeverScrollableScrollPhysics(),
|
|
itemCount: state.transactions.length,
|
|
itemBuilder: (context, index) {
|
|
final transaction = state.transactions[index];
|
|
return ListTile(
|
|
leading: Icon(
|
|
transaction.category.icon,
|
|
color: transaction.category.color,
|
|
),
|
|
title: Text(transaction.vendor),
|
|
subtitle: Text(transaction.category.name),
|
|
trailing: Text(
|
|
'${transaction.amount.toStringAsFixed(2)} ${transaction.currency}',
|
|
style: TextStyle(
|
|
color: transaction.isIncome
|
|
? Colors.green
|
|
: Colors.red,
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
],
|
|
);
|
|
} else if (state is TransactionError) {
|
|
return Center(
|
|
child: Text(localizations.transactionErrorText(state.message)),
|
|
); // Локализованный текст
|
|
} else {
|
|
return Center(
|
|
child: Text(localizations.loadingTransactionsText),
|
|
); // Локализованный текст
|
|
}
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
class HomeView extends StatelessWidget {
|
|
const HomeView({super.key});
|
|
|
|
// //
|
|
// Основной метод построения интерфейса виджета.
|
|
//
|
|
// Возвращает Scaffold - базовую структуру страницы Material Design,
|
|
// которая включает:
|
|
// 1. AppBar (верхнюю панель)
|
|
// 2. Body (основное содержимое)
|
|
// //
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final localizations = AppLocalizations.of(
|
|
context,
|
|
)!; // Получаем экземпляр локализации
|
|
|
|
return Scaffold(
|
|
// Верхняя панель приложения
|
|
appBar: AppBar(
|
|
// Заголовок приложения
|
|
title: const Text('Budget App'),
|
|
|
|
// Кнопки в правой части AppBar
|
|
actions: [
|
|
// Кнопка настроек
|
|
IconButton(
|
|
icon: const Icon(Icons.settings),
|
|
onPressed: () {
|
|
Navigator.push(
|
|
context,
|
|
MaterialPageRoute(builder: (context) => const SettingsPage()),
|
|
);
|
|
},
|
|
tooltip: 'Настройки',
|
|
),
|
|
],
|
|
),
|
|
|
|
body: BlocBuilder<TransactionBloc, TransactionState>(
|
|
builder: (context, state) {
|
|
if (state is TransactionLoading) {
|
|
return const Center(child: CircularProgressIndicator());
|
|
} else if (state is TransactionLoaded) {
|
|
if (state.transactions.isEmpty) {
|
|
return const Center(child: Text('Нет транзакций'));
|
|
}
|
|
return ListView.builder(
|
|
itemCount: state.transactions.length,
|
|
itemBuilder: (context, index) {
|
|
final transaction = state.transactions[index];
|
|
return ListTile(
|
|
leading: Icon(
|
|
transaction.category.icon,
|
|
color: transaction.category.color,
|
|
),
|
|
title: Text(transaction.vendor),
|
|
subtitle: Text(transaction.category.name),
|
|
trailing: Text(
|
|
'${transaction.amount.toStringAsFixed(2)} ${transaction.currency}',
|
|
style: TextStyle(
|
|
color: transaction.isIncome ? Colors.green : Colors.red,
|
|
),
|
|
),
|
|
);
|
|
},
|
|
);
|
|
} else if (state is TransactionError) {
|
|
return Center(
|
|
child: Text(localizations.transactionErrorText(state.message)),
|
|
); // Локализованный текст
|
|
} else {
|
|
return Center(
|
|
child: Text(localizations.loadingTransactionsText),
|
|
); // Локализованный текст
|
|
}
|
|
},
|
|
),
|
|
);
|
|
}
|
|
}
|