|
|
|
from .mongo_db import insert_document, find_documents, get_collection |
|
from datetime import datetime, timezone |
|
import logging |
|
from .database_init import get_mongodb |
|
|
|
logger = logging.getLogger(__name__) |
|
COLLECTION_NAME = 'chat_history-v3' |
|
|
|
def store_chat_history(username, messages, analysis_type='sidebar'): |
|
""" |
|
Guarda el historial del chat |
|
Args: |
|
username: nombre del usuario |
|
messages: lista de mensajes |
|
analysis_type: tipo de chat ('sidebar' por defecto) |
|
""" |
|
try: |
|
chat_document = { |
|
'username': username, |
|
'timestamp': datetime.now(timezone.utc).isoformat(), |
|
'messages': messages, |
|
'analysis_type': analysis_type |
|
} |
|
|
|
result = insert_document(COLLECTION_NAME, chat_document) |
|
if result: |
|
logger.info(f"Historial de chat guardado con ID: {result} para el usuario: {username}") |
|
return True |
|
return False |
|
except Exception as e: |
|
logger.error(f"Error al guardar historial de chat: {str(e)}") |
|
return False |
|
|
|
def get_chat_history(username, analysis_type='sidebar', limit=None): |
|
""" |
|
Recupera el historial del chat |
|
Args: |
|
username: nombre del usuario |
|
analysis_type: tipo de chat ('sidebar' por defecto) |
|
limit: límite de mensajes a recuperar |
|
Returns: |
|
list: Lista de conversaciones |
|
""" |
|
try: |
|
query = { |
|
"username": username, |
|
"analysis_type": analysis_type |
|
} |
|
|
|
db = get_mongodb() |
|
if not db: |
|
raise Exception("No se pudo conectar a la base de datos") |
|
|
|
collection = db[COLLECTION_NAME] |
|
|
|
cursor = collection.find(query).sort("timestamp", -1) |
|
if limit: |
|
cursor = cursor.limit(limit) |
|
|
|
return list(cursor) |
|
except Exception as e: |
|
logger.error(f"Error al recuperar historial de chat: {str(e)}") |
|
return [] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|