Add Admin panel for team and projects management

This commit is contained in:
2026-03-27 19:08:43 +05:00
parent 6e428b4ede
commit 88db5daa6b
7 changed files with 970 additions and 0 deletions
+214
View File
@@ -0,0 +1,214 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/auth_provider.dart';
import '../models/user_model.dart';
class AdminScreen extends ConsumerWidget {
const AdminScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final user = ref.watch(currentUserProvider);
final isAdmin = user?.isAdmin ?? false;
return Scaffold(
appBar: AppBar(
title: const Text('Админка'),
actions: [
IconButton(
icon: const Icon(Icons.settings),
onPressed: () => context.push('/admin/settings'),
),
],
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
// Карточка пользователя
_buildUserCard(context, user),
const SizedBox(height: 24),
// Раздел администратора
if (isAdmin) ...[
_buildSectionTitle('Управление'),
const SizedBox(height: 12),
_buildAdminCard(
icon: Icons.people,
title: 'Команда',
subtitle: 'Управление участниками и ролями',
onTap: () => context.push('/admin/team'),
),
const SizedBox(height: 12),
_buildAdminCard(
icon: Icons.folder,
title: 'Проекты',
subtitle: 'Создание и настройка проектов',
onTap: () => context.push('/admin/projects'),
),
const SizedBox(height: 12),
_buildAdminCard(
icon: Icons.shield,
title: 'Роли и доступы',
subtitle: 'Настройка прав пользователей',
onTap: () => context.push('/admin/roles'),
),
const SizedBox(height: 24),
],
// Общий раздел
_buildSectionTitle('Настройки'),
const SizedBox(height: 12),
_buildSettingCard(
icon: Icons.person,
title: 'Профиль',
subtitle: 'Редактировать данные',
onTap: () => context.push('/admin/profile'),
),
const SizedBox(height: 12),
_buildSettingCard(
icon: Icons.notifications,
title: 'Уведомления',
subtitle: 'Настройка уведомлений',
onTap: () => context.push('/admin/notifications'),
),
const SizedBox(height: 12),
_buildSettingCard(
icon: Icons.palette,
title: 'Внешний вид',
subtitle: 'Тема и оформление',
onTap: () => context.push('/admin/appearance'),
),
const SizedBox(height: 12),
_buildSettingCard(
icon: Icons.storage,
title: 'Данные',
subtitle: 'Экспорт, импорт, очистка',
onTap: () => context.push('/admin/data'),
),
const SizedBox(height: 24),
// AI раздел
_buildSectionTitle('AI Настройки'),
const SizedBox(height: 12),
_buildSettingCard(
icon: Icons.auto_awesome,
title: 'DeepSeek API',
subtitle: 'Настройка AI сервиса',
onTap: () => context.push('/admin/ai'),
),
const SizedBox(height: 12),
_buildSettingCard(
icon: Icons.analytics,
title: 'AI Лимиты',
subtitle: 'Статистика использования',
onTap: () => context.push('/admin/ai-stats'),
),
],
),
);
}
Widget _buildUserCard(BuildContext context, UserModel? user) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
CircleAvatar(
radius: 40,
backgroundImage: user?.photoUrl != null
? NetworkImage(user!.photoUrl!)
: null,
child: user?.photoUrl == null
? const Icon(Icons.person, size: 40)
: null,
),
const SizedBox(height: 16),
Text(
user?.displayName ?? 'Пользователь',
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Text(
user?.email ?? '',
style: const TextStyle(color: Colors.grey),
),
const SizedBox(height: 12),
if (user?.isAdmin ?? false)
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: Colors.purple.withOpacity(0.2),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.purple),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.shield, size: 16, color: Colors.purple),
const SizedBox(width: 4),
const Text(
'Администратор',
style: TextStyle(color: Colors.purple, fontWeight: FontWeight.bold),
),
],
),
),
],
),
),
);
}
Widget _buildSectionTitle(String title) {
return Text(
title,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.grey,
),
);
}
Widget _buildAdminCard({
required IconData icon,
required String title,
required String subtitle,
required VoidCallback onTap,
}) {
return Card(
child: ListTile(
leading: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.purple.withOpacity(0.2),
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, color: Colors.purple),
),
title: Text(title),
subtitle: Text(subtitle),
trailing: const Icon(Icons.chevron_right),
onTap: onTap,
),
);
}
Widget _buildSettingCard({
required IconData icon,
required String title,
required String subtitle,
required VoidCallback onTap,
}) {
return Card(
child: ListTile(
leading: Icon(icon, color: Colors.blue),
title: Text(title),
subtitle: Text(subtitle),
trailing: const Icon(Icons.chevron_right),
onTap: onTap,
),
);
}
}
@@ -0,0 +1,331 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:uuid/uuid.dart';
import '../providers/auth_provider.dart';
import '../models/project_model.dart';
class ProjectsManagementScreen extends ConsumerStatefulWidget {
const ProjectsManagementScreen({super.key});
@override
ConsumerState<ProjectsManagementScreen> createState() => _ProjectsManagementScreenState();
}
class _ProjectsManagementScreenState extends ConsumerState<ProjectsManagementScreen> {
final _nameController = TextEditingController();
final _descriptionController = TextEditingController();
bool _isCreating = false;
@override
void dispose() {
_nameController.dispose();
_descriptionController.dispose();
super.dispose();
}
Future<void> _createProject() async {
if (_nameController.text.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Введите название проекта')),
);
return;
}
setState(() {
_isCreating = true;
});
try {
final user = ref.read(currentUserProvider);
if (user == null) throw Exception('Пользователь не авторизован');
final project = ProjectModel(
id: const Uuid().v4(),
name: _nameController.text,
description: _descriptionController.text,
teamId: 'default', // TODO: Выбрать команду
ownerId: user.id,
memberIds: [user.id],
startDate: DateTime.now(),
color: _getRandomColor(),
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
);
await FirebaseFirestore.instance
.collection('projects')
.doc(project.id)
.set(project.toFirestore());
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('✅ Проект создан'),
backgroundColor: Colors.green,
),
);
_nameController.clear();
_descriptionController.clear();
setState(() {
_isCreating = false;
});
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('❌ Ошибка: $e'),
backgroundColor: Colors.red,
),
);
setState(() {
_isCreating = false;
});
}
}
}
String _getRandomColor() {
final colors = ['#2196F3', '#4CAF50', '#FF9800', '#E91E63', '#9C27B0', '#00BCD4'];
return colors[DateTime.now().millisecond % colors.length];
}
Future<void> _deleteProject(String projectId) async {
try {
await FirebaseFirestore.instance.collection('projects').doc(projectId).delete();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('✅ Проект удалён')),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('❌ Ошибка: $e')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Проекты'),
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
// Создание проекта
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Создать новый проект',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
TextField(
controller: _nameController,
decoration: const InputDecoration(
labelText: 'Название проекта *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.folder),
),
),
const SizedBox(height: 16),
TextField(
controller: _descriptionController,
maxLines: 3,
decoration: const InputDecoration(
labelText: 'Описание',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.description),
alignLabelWithHint: true,
),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _isCreating ? null : _createProject,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: _isCreating
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Создать проект'),
),
],
),
),
),
const SizedBox(height: 24),
// Список проектов
const Text(
'Все проекты',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('projects')
.orderBy('createdAt', descending: true)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Ошибка: ${snapshot.error}');
}
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
final projects = snapshot.data!.docs;
if (projects.isEmpty) {
return Card(
child: Padding(
padding: const EdgeInsets.all(32),
child: Center(
child: Column(
children: [
const Icon(Icons.folder_outline, size: 48, color: Colors.grey),
const SizedBox(height: 16),
const Text(
'Нет проектов',
style: TextStyle(color: Colors.grey),
),
],
),
),
),
);
}
return ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: projects.length,
separatorBuilder: (context, index) => const SizedBox(height: 12),
itemBuilder: (context, index) {
final projectData = projects[index].data() as Map<String, dynamic>;
final projectId = projects[index].id;
final project = ProjectModel.fromFirestore(projects[index]);
return _ProjectCard(
project: project,
onDelete: () => _deleteProject(projectId),
);
},
);
},
),
],
),
);
}
}
class _ProjectCard extends StatelessWidget {
final ProjectModel project;
final VoidCallback onDelete;
const _ProjectCard({
required this.project,
required this.onDelete,
});
@override
Widget build(BuildContext context) {
return Card(
child: ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: _hexToColor(project.color),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.folder, color: Colors.white),
),
title: Text(project.name),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (project.description.isNotEmpty) ...[
const SizedBox(height: 4),
Text(
project.description,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
const SizedBox(height: 4),
Row(
children: [
const Icon(Icons.people, size: 12, color: Colors.grey),
const SizedBox(width: 4),
Text(
'${project.memberIds.length} участников',
style: const TextStyle(fontSize: 12, color: Colors.grey),
),
],
),
],
),
trailing: PopupMenuButton(
onSelected: (value) {
if (value == 'edit') {
// TODO: Редактирование
} else if (value == 'delete') {
_showDeleteDialog(context);
}
},
itemBuilder: (context) => [
const PopupMenuItem(value: 'edit', child: Text('Редактировать')),
const PopupMenuItem(value: 'delete', child: Text('Удалить')),
],
),
isThreeLine: true,
),
);
}
Color _hexToColor(String hex) {
hex = hex.replaceAll('#', '');
if (hex.length == 6) {
return Color(int.parse('0xFF$hex'));
}
return Colors.blue;
}
void _showDeleteDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Удалить проект?'),
content: const Text('Это действие нельзя отменить'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Отмена'),
),
TextButton(
onPressed: () {
Navigator.pop(context);
onDelete();
},
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: const Text('Удалить'),
),
],
),
);
}
}
@@ -0,0 +1,367 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../providers/auth_provider.dart';
import '../models/user_model.dart';
class TeamManagementScreen extends ConsumerStatefulWidget {
const TeamManagementScreen({super.key});
@override
ConsumerState<TeamManagementScreen> createState() => _TeamManagementScreenState();
}
class _TeamManagementScreenState extends ConsumerState<TeamManagementScreen> {
final _teamNameController = TextEditingController();
bool _isCreating = false;
@override
void dispose() {
_teamNameController.dispose();
super.dispose();
}
Future<void> _createTeam() async {
if (_teamNameController.text.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Введите название команды')),
);
return;
}
setState(() {
_isCreating = true;
});
try {
final user = ref.read(currentUserProvider);
if (user == null) throw Exception('Пользователь не авторизован');
final teamRef = FirebaseFirestore.instance.collection('teams').doc();
await teamRef.set({
'name': _teamNameController.text,
'ownerId': user.id,
'memberIds': [user.id],
'createdAt': FieldValue.serverTimestamp(),
'updatedAt': FieldValue.serverTimestamp(),
'description': '',
'settings': {},
});
// Добавляем teamId пользователю
await FirebaseFirestore.instance.collection('users').doc(user.id).update({
'teamIds': FieldValue.arrayUnion([teamRef.id]),
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('✅ Команда создана'),
backgroundColor: Colors.green,
),
);
_teamNameController.clear();
setState(() {
_isCreating = false;
});
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('❌ Ошибка: $e'),
backgroundColor: Colors.red,
),
);
setState(() {
_isCreating = false;
});
}
}
}
Future<void> _changeUserRole(String userId, String teamId, UserRole newRole) async {
try {
await FirebaseFirestore.instance
.collection('teams')
.doc(teamId)
.collection('members')
.doc(userId)
.update({'role': newRole.name});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('✅ Роль изменена')),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('❌ Ошибка: $e')),
);
}
}
Future<void> _removeMember(String userId, String teamId) async {
try {
await FirebaseFirestore.instance
.collection('teams')
.doc(teamId)
.update({
'memberIds': FieldValue.arrayRemove([userId]),
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('✅ Участник удалён')),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('❌ Ошибка: $e')),
);
}
}
@override
Widget build(BuildContext context) {
final user = ref.watch(currentUserProvider);
final isAdmin = user?.isAdmin ?? false;
return Scaffold(
appBar: AppBar(
title: const Text('Команда'),
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
// Создание команды
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Создать новую команду',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
TextField(
controller: _teamNameController,
decoration: const InputDecoration(
labelText: 'Название команды',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.people),
),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _isCreating ? null : _createTeam,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: _isCreating
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Создать команду'),
),
],
),
),
),
const SizedBox(height: 24),
// Список команд
const Text(
'Ваши команды',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('teams')
.where('memberIds', arrayContains: user?.id)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Ошибка: ${snapshot.error}');
}
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
final teams = snapshot.data!.docs;
if (teams.isEmpty) {
return Card(
child: Padding(
padding: const EdgeInsets.all(32),
child: Center(
child: Column(
children: [
const Icon(Icons.people_outline, size: 48, color: Colors.grey),
const SizedBox(height: 16),
const Text(
'Нет команд',
style: TextStyle(color: Colors.grey),
),
],
),
),
),
);
}
return ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: teams.length,
separatorBuilder: (context, index) => const SizedBox(height: 12),
itemBuilder: (context, index) {
final team = teams[index].data() as Map<String, dynamic>;
final teamId = teams[index].id;
final isOwner = team['ownerId'] == user?.id;
return _TeamCard(
teamId: teamId,
name: team['name'] ?? 'Без названия',
memberCount: (team['memberIds'] as List?)?.length ?? 0,
isOwner: isOwner,
onRemove: isOwner ? null : () => _removeMember(user!.id, teamId),
);
},
);
},
),
if (isAdmin) ...[
const SizedBox(height: 24),
const Text(
'Все пользователи',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
_buildUsersList(),
],
],
),
);
}
Widget _buildUsersList() {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('users').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Ошибка: ${snapshot.error}');
}
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
final users = snapshot.data!.docs;
return ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: users.length,
separatorBuilder: (context, index) => const SizedBox(height: 8),
itemBuilder: (context, index) {
final userData = users[index].data() as Map<String, dynamic>;
final userId = users[index].id;
final user = UserModel.fromFirestore(users[index]);
return Card(
child: ListTile(
leading: CircleAvatar(
backgroundImage: user.photoUrl != null
? NetworkImage(user.photoUrl!)
: null,
child: user.photoUrl == null
? const Icon(Icons.person)
: null,
),
title: Text(user.displayName ?? 'Без имени'),
subtitle: Text(user.email),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: user.isAdmin
? Colors.purple.withOpacity(0.2)
: Colors.blue.withOpacity(0.2),
borderRadius: BorderRadius.circular(12),
),
child: Text(
user.isAdmin ? 'Админ' : 'Участник',
style: TextStyle(
color: user.isAdmin ? Colors.purple : Colors.blue,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
),
],
),
),
);
},
);
},
);
}
}
class _TeamCard extends StatelessWidget {
final String teamId;
final String name;
final int memberCount;
final bool isOwner;
final VoidCallback? onRemove;
const _TeamCard({
required this.teamId,
required this.name,
required this.memberCount,
required this.isOwner,
this.onRemove,
});
@override
Widget build(BuildContext context) {
return Card(
child: ListTile(
leading: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.blue.withOpacity(0.2),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.people, color: Colors.blue),
),
title: Text(name),
subtitle: Text('Участников: $memberCount'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (isOwner)
const Chip(
label: Text('Владелец', style: TextStyle(fontSize: 12)),
backgroundColor: Colors.purple,
labelStyle: TextStyle(color: Colors.white, fontSize: 12),
),
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.chevron_right),
onPressed: () => context.push('/admin/team/$teamId'),
),
],
),
),
);
}
}