AIdeaText commited on
Commit
aeefc06
verified
1 Parent(s): b03c30e

Update modules/admin/admin_ui.py

Browse files
Files changed (1) hide show
  1. modules/admin/admin_ui.py +182 -49
modules/admin/admin_ui.py CHANGED
@@ -1,49 +1,182 @@
1
- import streamlit as st
2
- from ..database.sql_db import (
3
- get_user,
4
- get_student_user,
5
- get_admin_user,
6
- get_teacher_user,
7
- create_student_user,
8
- update_student_user,
9
- delete_student_user
10
- )
11
-
12
- from ..database.morphosintax_mongo_db import get_student_morphosyntax_analysis
13
-
14
- def admin_page():
15
- st.title("Panel de Administraci贸n")
16
- st.write(f"Bienvenido, {st.session_state.username}")
17
-
18
- # Secci贸n para crear nuevos usuarios estudiantes
19
- st.header("Crear Nuevo Usuario Estudiante")
20
- new_username = st.text_input("Correo electr贸nico del nuevo usuario", key="admin_new_username")
21
- new_password = st.text_input("Contrase帽a", type="password", key="admin_new_password")
22
- if st.button("Crear Usuario", key="admin_create_user"):
23
- if create_student_user(new_username, new_password):
24
- st.success(f"Usuario estudiante {new_username} creado exitosamente")
25
- else:
26
- st.error("Error al crear el usuario estudiante")
27
-
28
- # Secci贸n para ver datos de estudiantes
29
- st.header("Ver Datos de Estudiantes")
30
- student_username = st.text_input("Nombre de usuario del estudiante", key="admin_view_student")
31
- if st.button("Ver Datos", key="admin_view_student_data"):
32
- student = get_student_user(student_username)
33
- if student:
34
- st.write(f"Informaci贸n del estudiante {student_username}:")
35
- st.json(student)
36
-
37
- student_data = get_student_morphosyntax_analysis(student_username)
38
- if student_data:
39
- st.write("Datos de an谩lisis del estudiante:")
40
- st.json(student_data)
41
- else:
42
- st.info("No hay datos de an谩lisis para este estudiante.")
43
- else:
44
- st.error("Estudiante no encontrado")
45
-
46
- # Bot贸n para cerrar sesi贸n
47
- if st.button("Cerrar Sesi贸n", key="admin_logout"):
48
- st.session_state.clear()
49
- st.experimental_rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from datetime import datetime
3
+ from ..database.sql_db import (
4
+ get_user,
5
+ get_student_user,
6
+ get_admin_user,
7
+ get_teacher_user,
8
+ create_student_user,
9
+ update_student_user,
10
+ delete_student_user,
11
+ record_login,
12
+ record_logout,
13
+ get_recent_sessions,
14
+ get_user_total_time
15
+ )
16
+ from ..database.morphosintax_mongo_db import get_student_morphosyntax_analysis
17
+
18
+ def format_duration(seconds):
19
+ """Convierte segundos a formato legible"""
20
+ if not seconds:
21
+ return "0h 0m"
22
+ hours = seconds // 3600
23
+ minutes = (seconds % 3600) // 60
24
+ return f"{hours}h {minutes}m"
25
+
26
+ def admin_page():
27
+ st.title("Panel de Administraci贸n")
28
+ st.write(f"Bienvenido, {st.session_state.username}")
29
+
30
+ # Crear tres tabs para las diferentes secciones
31
+ tab1, tab2, tab3 = st.tabs([
32
+ "Gesti贸n de Usuarios",
33
+ "B煤squeda de Usuarios",
34
+ "Actividad de la Plataforma"
35
+ ])
36
+
37
+ # Tab 1: Gesti贸n de Usuarios
38
+ with tab1:
39
+ st.header("Crear Nuevo Usuario Estudiante")
40
+
41
+ # Crear dos columnas para el formulario
42
+ col1, col2 = st.columns(2)
43
+
44
+ with col1:
45
+ new_username = st.text_input(
46
+ "Correo electr贸nico del nuevo usuario",
47
+ key="admin_new_username"
48
+ )
49
+
50
+ with col2:
51
+ new_password = st.text_input(
52
+ "Contrase帽a",
53
+ type="password",
54
+ key="admin_new_password"
55
+ )
56
+
57
+ if st.button("Crear Usuario", key="admin_create_user", type="primary"):
58
+ if create_student_user(new_username, new_password):
59
+ st.success(f"Usuario estudiante {new_username} creado exitosamente")
60
+ else:
61
+ st.error("Error al crear el usuario estudiante")
62
+
63
+ # Tab 2: B煤squeda de Usuarios
64
+ with tab2:
65
+ st.header("B煤squeda de Usuarios")
66
+
67
+ search_col1, search_col2 = st.columns([2,1])
68
+
69
+ with search_col1:
70
+ student_username = st.text_input(
71
+ "Nombre de usuario del estudiante",
72
+ key="admin_view_student"
73
+ )
74
+
75
+ with search_col2:
76
+ search_button = st.button(
77
+ "Buscar",
78
+ key="admin_view_student_data",
79
+ type="primary"
80
+ )
81
+
82
+ if search_button:
83
+ student = get_student_user(student_username)
84
+ if student:
85
+ # Crear tabs para diferentes tipos de informaci贸n
86
+ info_tab1, info_tab2, info_tab3 = st.tabs([
87
+ "Informaci贸n B谩sica",
88
+ "An谩lisis Realizados",
89
+ "Tiempo en Plataforma"
90
+ ])
91
+
92
+ with info_tab1:
93
+ st.subheader("Informaci贸n del Usuario")
94
+ st.json(student)
95
+
96
+ with info_tab2:
97
+ st.subheader("An谩lisis Realizados")
98
+ student_data = get_student_morphosyntax_analysis(student_username)
99
+ if student_data:
100
+ st.json(student_data)
101
+ else:
102
+ st.info("No hay datos de an谩lisis para este estudiante.")
103
+
104
+ with info_tab3:
105
+ st.subheader("Tiempo en Plataforma")
106
+ total_time = get_user_total_time(student_username)
107
+ if total_time:
108
+ st.metric(
109
+ "Tiempo Total",
110
+ format_duration(total_time)
111
+ )
112
+ else:
113
+ st.info("No hay registros de tiempo para este usuario")
114
+ else:
115
+ st.error("Estudiante no encontrado")
116
+
117
+ # Tab 3: Actividad de la Plataforma
118
+ with tab3:
119
+ st.header("Actividad Reciente")
120
+
121
+ # Obtener sesiones recientes
122
+ recent_sessions = get_recent_sessions(10)
123
+
124
+ if recent_sessions:
125
+ # Crear dataframe para mostrar los datos
126
+ sessions_data = []
127
+ for session in recent_sessions:
128
+ sessions_data.append({
129
+ "Usuario": session['username'],
130
+ "Inicio de Sesi贸n": datetime.fromisoformat(
131
+ session['loginTime'].rstrip('Z')
132
+ ).strftime("%Y-%m-%d %H:%M:%S"),
133
+ "Fin de Sesi贸n": datetime.fromisoformat(
134
+ session['logoutTime'].rstrip('Z')
135
+ ).strftime("%Y-%m-%d %H:%M:%S") if session.get('logoutTime') else "Activo",
136
+ "Duraci贸n": format_duration(session.get('sessionDuration', 0))
137
+ })
138
+
139
+ # Mostrar tabla con estilos
140
+ st.dataframe(
141
+ sessions_data,
142
+ hide_index=True,
143
+ column_config={
144
+ "Usuario": st.column_config.TextColumn(
145
+ "Usuario",
146
+ width="medium"
147
+ ),
148
+ "Inicio de Sesi贸n": st.column_config.TextColumn(
149
+ "Inicio de Sesi贸n",
150
+ width="medium"
151
+ ),
152
+ "Fin de Sesi贸n": st.column_config.TextColumn(
153
+ "Fin de Sesi贸n",
154
+ width="medium"
155
+ ),
156
+ "Duraci贸n": st.column_config.TextColumn(
157
+ "Duraci贸n",
158
+ width="small"
159
+ )
160
+ }
161
+ )
162
+
163
+ # A帽adir m茅tricas resumen
164
+ total_sessions = len(sessions_data)
165
+ total_users = len(set(session['Usuario'] for session in sessions_data))
166
+
167
+ metric_col1, metric_col2 = st.columns(2)
168
+ with metric_col1:
169
+ st.metric("Total de Sesiones", total_sessions)
170
+ with metric_col2:
171
+ st.metric("Usuarios 脷nicos", total_users)
172
+
173
+ else:
174
+ st.info("No hay registros de sesiones recientes")
175
+
176
+ # Bot贸n para cerrar sesi贸n (fuera de los tabs)
177
+ st.sidebar.button(
178
+ "Cerrar Sesi贸n",
179
+ key="admin_logout",
180
+ type="primary",
181
+ on_click=lambda: [st.session_state.clear(), st.experimental_rerun()]
182
+ )