File size: 3,634 Bytes
12ffa62
fa173b2
12ffa62
fa173b2
12ffa62
 
 
 
91e8db9
 
0a09d3c
12ffa62
0a09d3c
12ffa62
 
991247e
 
 
 
fa173b2
 
991247e
 
 
 
0a09d3c
 
12ffa62
 
0a09d3c
91e8db9
 
0a09d3c
12ffa62
fa173b2
91e8db9
0a09d3c
 
991247e
91e8db9
991247e
 
91e8db9
991247e
12ffa62
fa173b2
91e8db9
 
fa173b2
91e8db9
 
fa173b2
0a09d3c
12ffa62
fa173b2
12ffa62
0a09d3c
152cbec
 
 
 
 
 
 
 
 
fa173b2
152cbec
 
 
fa173b2
 
152cbec
 
fa173b2
152cbec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa173b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# modules/database/current_situation_mongo_db.py
from datetime import datetime, timezone, timedelta
import logging
from .mongo_db import get_collection

logger = logging.getLogger(__name__)
COLLECTION_NAME = 'student_current_situation'

# En modules/database/current_situation_mongo_db.py

def store_current_situation_result(username, text, metrics, feedback):
    """
    Guarda los resultados del an谩lisis de situaci贸n actual.
    """
    try:
        # Verificar par谩metros
        if not all([username, text, metrics]):
            logger.error("Faltan par谩metros requeridos")
            return False

        collection = get_collection(COLLECTION_NAME)
        if collection is None:
            logger.error("No se pudo obtener la colecci贸n")
            return False

        # Crear documento
        document = {
            'username': username,
            'timestamp': datetime.now(timezone.utc).isoformat(),
            'text': text,
            'metrics': metrics,
            'feedback': feedback or {},
            'analysis_type': 'current_situation'
        }

        # Insertar documento y verificar
        result = collection.insert_one(document)
        if result.inserted_id:
            logger.info(f"""
                An谩lisis de situaci贸n actual guardado:
                - Usuario: {username}
                - ID: {result.inserted_id}
                - Longitud texto: {len(text)}
            """)
            
            # Verificar almacenamiento
            storage_verified = verify_storage(username)
            if not storage_verified:
                logger.warning("Verificaci贸n de almacenamiento fall贸")
            
            return True

        logger.error("No se pudo insertar el documento")
        return False

    except Exception as e:
        logger.error(f"Error guardando an谩lisis de situaci贸n actual: {str(e)}")
        return False

def verify_storage(username):
    """
    Verifica que los datos se est谩n guardando correctamente.
    """
    try:
        collection = get_collection(COLLECTION_NAME)
        if collection is None:
            logger.error("No se pudo obtener la colecci贸n para verificaci贸n")
            return False
            
        # Buscar documentos recientes del usuario
        timestamp_threshold = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
        
        recent_docs = collection.find({
            'username': username,
            'timestamp': {'$gte': timestamp_threshold}
        }).sort('timestamp', -1).limit(1)

        docs = list(recent_docs)
        if docs:
            logger.info(f"""
                脷ltimo documento guardado:
                - ID: {docs[0]['_id']}
                - Timestamp: {docs[0]['timestamp']}
                - M茅tricas guardadas: {bool(docs[0].get('metrics'))}
            """)
            return True
        
        logger.warning(f"No se encontraron documentos recientes para {username}")
        return False

    except Exception as e:
        logger.error(f"Error verificando almacenamiento: {str(e)}")
        return False

def get_recent_situation_analysis(username, limit=5):
    """
    Obtiene los an谩lisis m谩s recientes de un usuario.
    """
    try:
        collection = get_collection(COLLECTION_NAME)
        if collection is None:
            return []
            
        results = collection.find(
            {'username': username}
        ).sort('timestamp', -1).limit(limit)
        
        return list(results)
        
    except Exception as e:
        logger.error(f"Error obteniendo an谩lisis recientes: {str(e)}")
        return []