historico

This commit is contained in:
2026-05-21 11:49:56 +01:00
parent 2f411d08a4
commit 5bda59f7af
5 changed files with 742 additions and 61 deletions

View File

@@ -0,0 +1,322 @@
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:go_router/go_router.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../../../../core/services/chat_memory_service.dart';
import '../../../../core/utils/logger.dart';
class ChatHistoryPage extends StatefulWidget {
const ChatHistoryPage({super.key});
@override
State<ChatHistoryPage> createState() => _ChatHistoryPageState();
}
class _ChatHistoryPageState extends State<ChatHistoryPage> {
List<Map<String, dynamic>> _conversations = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadConversations();
}
Future<void> _loadConversations() async {
setState(() => _isLoading = true);
try {
final conversations = await ChatMemoryService.getConversations();
if (mounted) {
setState(() {
_conversations = conversations;
_isLoading = false;
});
}
} catch (e) {
Logger.error('Error loading conversations: $e');
if (mounted) {
setState(() => _isLoading = false);
}
}
}
Future<void> _deleteConversation(String conversationId) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Eliminar conversa'),
content: const Text('Tem certeza que deseja eliminar esta conversa?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancelar'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: const Text('Eliminar'),
),
],
),
);
if (confirmed != true) return;
try {
await ChatMemoryService.deleteConversation(conversationId);
await _loadConversations();
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('Conversa eliminada')));
}
} catch (e) {
Logger.error('Error deleting conversation: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Erro ao eliminar conversa')),
);
}
}
}
String _formatDate(Timestamp? timestamp) {
if (timestamp == null) return '';
final date = timestamp.toDate();
final now = DateTime.now();
final difference = now.difference(date);
if (difference.inDays == 0) {
return 'Hoje ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
} else if (difference.inDays == 1) {
return 'Ontem';
} else if (difference.inDays < 7) {
return '${difference.inDays} dias atrás';
} else {
return '${date.day}/${date.month}/${date.year}';
}
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Scaffold(
backgroundColor: cs.surfaceContainerLowest,
appBar: AppBar(
backgroundColor: cs.surface,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: cs.onSurface),
onPressed: () => context.go('/student-dashboard'),
),
title: Text(
'Histórico de Conversas',
style: TextStyle(
color: cs.onSurface,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
actions: [
IconButton(
icon: Icon(Icons.refresh, color: cs.onSurface),
onPressed: _loadConversations,
),
],
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _conversations.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.chat_bubble_outline,
size: 64,
color: cs.onSurfaceVariant.withValues(alpha: 0.4),
),
const SizedBox(height: 16),
Text(
'Sem conversas ainda',
style: TextStyle(
color: cs.onSurfaceVariant,
fontSize: 16,
),
),
const SizedBox(height: 8),
Text(
'Começa uma conversa com o Vico!',
style: TextStyle(
color: cs.onSurfaceVariant.withValues(alpha: 0.7),
fontSize: 14,
),
),
],
),
),
)
: ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: _conversations.length,
separatorBuilder: (_, __) => const SizedBox(height: 12),
itemBuilder: (context, index) {
final conversation = _conversations[index];
return _buildConversationCard(conversation, cs);
},
),
);
}
Widget _buildConversationCard(
Map<String, dynamic> conversation,
ColorScheme cs,
) {
return Dismissible(
key: Key(conversation['id']),
direction: DismissDirection.endToStart,
onDismissed: (_) => _deleteConversation(conversation['id']),
background: Container(
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(16),
),
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: 20),
child: const Icon(Icons.delete, color: Colors.white),
),
child: InkWell(
onTap: () {
ChatMemoryService.setCurrentConversationId(conversation['id']);
context.go('/ai-tutor/${conversation['id']}');
},
borderRadius: BorderRadius.circular(16),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: cs.outline.withValues(alpha: 0.15)),
boxShadow: [
BoxShadow(
color: cs.shadow.withValues(alpha: 0.05),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: 48,
height: 48,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [cs.primary, cs.primary.withValues(alpha: 0.7)],
),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.chat_bubble,
color: Colors.white,
size: 24,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
conversation['title'],
style: TextStyle(
color: cs.onSurface,
fontSize: 16,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Row(
children: [
Icon(
Icons.access_time,
size: 12,
color: cs.onSurfaceVariant,
),
const SizedBox(width: 4),
Text(
_formatDate(conversation['updatedAt']),
style: TextStyle(
color: cs.onSurfaceVariant,
fontSize: 12,
),
),
const SizedBox(width: 12),
Icon(
Icons.message,
size: 12,
color: cs.onSurfaceVariant,
),
const SizedBox(width: 4),
Text(
'${conversation['messageCount']} msgs',
style: TextStyle(
color: cs.onSurfaceVariant,
fontSize: 12,
),
),
],
),
],
),
),
Icon(Icons.chevron_right, color: cs.onSurfaceVariant),
],
),
if (conversation['selectedMaterialIds'] != null &&
(conversation['selectedMaterialIds'] as List).isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Wrap(
spacing: 6,
runSpacing: 6,
children: (conversation['selectedMaterialIds'] as List)
.take(3)
.map<Widget>(
(id) => Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: cs.primary.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Text(
id.length > 15 ? '${id.substring(0, 15)}...' : id,
style: TextStyle(
color: cs.primary,
fontSize: 11,
fontWeight: FontWeight.w500,
),
),
),
)
.toList(),
),
),
],
),
),
),
).animate().slideX(duration: 300.ms).fadeIn(duration: 300.ms);
}
}

View File

@@ -12,7 +12,9 @@ import '../../../materials/presentation/pages/pdf_viewer_page.dart';
/// Simple AI Tutor chat interface page (for testing)
class TutorChatPageSimple extends StatefulWidget {
const TutorChatPageSimple({super.key});
final String? conversationId;
const TutorChatPageSimple({super.key, this.conversationId});
@override
State<TutorChatPageSimple> createState() => _TutorChatPageSimpleState();
@@ -36,6 +38,10 @@ class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
void initState() {
super.initState();
_loadAvailableMaterials();
if (widget.conversationId != null) {
ChatMemoryService.setCurrentConversationId(widget.conversationId);
_loadConversation(widget.conversationId!);
}
}
Future<void> _loadAvailableMaterials() async {
@@ -66,6 +72,46 @@ class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
}
}
Future<void> _loadConversation(String conversationId) async {
try {
final conversation = await ChatMemoryService.getConversation(
conversationId,
);
if (conversation == null) return;
final messages = await ChatMemoryService.getConversationMessages(
conversationId: conversationId,
limit: 50,
);
final materialIds = conversation['selectedMaterialIds'] as List<dynamic>?;
if (materialIds != null) {
setState(() {
_selectedMaterialIds = materialIds.cast<String>().toSet();
_materialsConfirmed = true;
});
}
// Load messages from Firestore
final loadedMessages = messages.map((msg) {
return {
'content': msg['content'] as String,
'isUser': msg['role'] == 'user',
'timestamp': msg['createdAt'] as Timestamp? ?? DateTime.now(),
};
}).toList();
if (mounted) {
setState(() {
_messages = loadedMessages;
});
_scrollToBottom();
}
} catch (e) {
Logger.error('Error loading conversation: $e');
}
}
@override
void dispose() {
_messageController.dispose();
@@ -202,6 +248,14 @@ class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
),
IconButton(
onPressed: () => context.go('/chat-history'),
icon: const Icon(
Icons.history,
color: Colors.white,
size: 20,
),
),
const SizedBox(width: 4),
],
),
@@ -1190,11 +1244,48 @@ class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
ElevatedButton(
onPressed: tempSelected.isEmpty
? null
: () {
: () async {
final isFirst = !_materialsConfirmed;
final selectionChanged =
!tempSelected.containsAll(_selectedMaterialIds) ||
!_selectedMaterialIds.containsAll(tempSelected);
// Create new conversation if materials changed or first time
if (isFirst || selectionChanged) {
final newConversationId =
await ChatMemoryService.createConversation(
selectedMaterialIds: tempSelected.toList(),
title: 'Nova conversa',
);
ChatMemoryService.setCurrentConversationId(
newConversationId,
);
// Update title based on first message if exists
if (_messages.isNotEmpty &&
_messages.first['isUser'] == true) {
final firstMessage =
_messages.first['content'] as String;
final title = firstMessage.length > 30
? '${firstMessage.substring(0, 30)}...'
: firstMessage;
await ChatMemoryService.updateConversationTitle(
conversationId: newConversationId,
title: title,
);
}
} else {
// Update materials in existing conversation
final currentId =
ChatMemoryService.currentConversationId;
if (currentId != null) {
await ChatMemoryService.updateConversationMaterials(
conversationId: currentId,
selectedMaterialIds: tempSelected.toList(),
);
}
}
setState(() {
_selectedMaterialIds = tempSelected;
_materialsConfirmed = true;
@@ -1207,7 +1298,6 @@ class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
});
if (isFirst) _addWelcomeMessage();
if (selectionChanged) {
ChatMemoryService.clearHistory();
RAGAIService.clearLastContext();
}
Navigator.of(dialogContext).pop();
@@ -1250,6 +1340,21 @@ class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
final userMessage = _messageController.text.trim();
// Save user message to Firestore
await ChatMemoryService.saveMessage(role: 'user', content: userMessage);
// Update conversation title if it's the first message
final currentId = ChatMemoryService.currentConversationId;
if (currentId != null && _messages.isEmpty) {
final title = userMessage.length > 30
? '${userMessage.substring(0, 30)}...'
: userMessage;
await ChatMemoryService.updateConversationTitle(
conversationId: currentId,
title: title,
);
}
// Add user message
setState(() {
_messages.add({
@@ -1279,6 +1384,12 @@ class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
: replyText;
Logger.info('Ollama response received: $preview...');
// Save assistant message to Firestore
await ChatMemoryService.saveMessage(
role: 'assistant',
content: replyText,
);
setState(() {
_messages.add({
'content': replyText,