AIdeaText commited on
Commit
4d4f074
verified
1 Parent(s): 4293485

Update modules/database/sql_db.py

Browse files
Files changed (1) hide show
  1. modules/database/sql_db.py +92 -93
modules/database/sql_db.py CHANGED
@@ -1,4 +1,5 @@
1
- #modules/database/sql_db.py
 
2
  from .database_init import get_container
3
  from datetime import datetime, timezone
4
  import logging
@@ -10,17 +11,10 @@ logger = logging.getLogger(__name__)
10
  def get_user(username, role=None):
11
  container = get_container("users")
12
  try:
13
- # Consulta b谩sica por ID que es el partition key
14
- items = list(container.query_items(
15
- query=f"SELECT * FROM c WHERE c.id = @username",
16
- parameters=[{"name": "@username", "value": username}],
17
- partition_key=username
18
- ))
19
-
20
- # Si se especifica rol, filtrar por rol
21
- if role and items:
22
- items = [item for item in items if item['role'] == role]
23
-
24
  return items[0] if items else None
25
  except Exception as e:
26
  logger.error(f"Error al obtener usuario {username}: {str(e)}")
@@ -44,18 +38,16 @@ def create_user(username, password, role, additional_info=None):
44
 
45
  try:
46
  user_data = {
47
- 'id': username, # Este campo es el partition key
48
  'password': password,
49
  'role': role,
50
  'timestamp': datetime.now(timezone.utc).isoformat(),
51
- 'additional_info': additional_info or {}
 
52
  }
53
 
54
- # Usar el id como partition key
55
- container.create_item(
56
- body=user_data,
57
- partition_key=username
58
- )
59
  logger.info(f"Usuario {role} creado: {username}")
60
  return True
61
 
@@ -86,13 +78,11 @@ def record_login(username):
86
  "type": "session",
87
  "username": username,
88
  "loginTime": datetime.now(timezone.utc).isoformat(),
89
- "additional_info": {}
 
90
  }
91
 
92
- result = container.create_item(
93
- body=session_doc,
94
- enable_cross_partition_query=True
95
- )
96
  logger.info(f"Sesi贸n {session_id} registrada para {username}")
97
  return session_id
98
  except Exception as e:
@@ -107,13 +97,15 @@ def record_logout(username, session_id):
107
  logger.error("No se pudo obtener el contenedor users_sessions")
108
  return False
109
 
 
 
 
 
 
 
110
  items = list(container.query_items(
111
- query="SELECT * FROM c WHERE c.id = @id AND c.username = @username",
112
- parameters=[
113
- {"name": "@id", "value": session_id},
114
- {"name": "@username", "value": username}
115
- ],
116
- enable_cross_partition_query=True
117
  ))
118
 
119
  if not items:
@@ -127,13 +119,11 @@ def record_logout(username, session_id):
127
 
128
  session.update({
129
  "logoutTime": logout_time.isoformat(),
130
- "sessionDuration": duration
 
131
  })
132
 
133
- container.upsert_item(
134
- body=session,
135
- enable_cross_partition_query=True
136
- )
137
  logger.info(f"Sesi贸n {session_id} cerrada para {username}, duraci贸n: {duration}s")
138
  return True
139
  except Exception as e:
@@ -148,16 +138,17 @@ def get_recent_sessions(limit=10):
148
  logger.error("No se pudo obtener el contenedor users_sessions")
149
  return []
150
 
 
 
 
 
 
 
 
 
151
  sessions = list(container.query_items(
152
- query="""
153
- SELECT c.username, c.loginTime, c.logoutTime, c.sessionDuration
154
- FROM c
155
- WHERE c.type = 'session'
156
- ORDER BY c.loginTime DESC
157
- OFFSET 0 LIMIT @limit
158
- """,
159
- parameters=[{"name": "@limit", "value": limit}],
160
- enable_cross_partition_query=True
161
  ))
162
 
163
  clean_sessions = []
@@ -185,16 +176,17 @@ def get_user_total_time(username):
185
  if not container:
186
  return None
187
 
 
 
 
 
 
 
 
 
188
  result = list(container.query_items(
189
- query="""
190
- SELECT VALUE SUM(c.sessionDuration)
191
- FROM c
192
- WHERE c.type = 'session'
193
- AND c.username = @username
194
- AND IS_DEFINED(c.sessionDuration)
195
- """,
196
- parameters=[{"name": "@username", "value": username}],
197
- enable_cross_partition_query=True
198
  ))
199
 
200
  return result[0] if result and result[0] is not None else 0
@@ -202,27 +194,14 @@ def get_user_total_time(username):
202
  logger.error(f"Error obteniendo tiempo total: {str(e)}")
203
  return 0
204
 
205
-
206
- # Agregar estas funciones en sql_db.py
207
-
208
  def update_student_user(username, new_info):
209
- """Actualiza la informaci贸n de un estudiante"""
210
- container = get_container("users")
211
  try:
212
- # Primero obtener el usuario existente
213
  user = get_student_user(username)
214
  if user:
215
- # Actualizar la informaci贸n
216
- if 'additional_info' in user:
217
- user['additional_info'].update(new_info)
218
- else:
219
- user['additional_info'] = new_info
220
-
221
- # Actualizar el documento usando el partition key correcto
222
- container.upsert_item(
223
- body=user,
224
- partition_key=username
225
- )
226
  logger.info(f"Informaci贸n del estudiante actualizada: {username}")
227
  return True
228
  else:
@@ -233,17 +212,12 @@ def update_student_user(username, new_info):
233
  return False
234
 
235
  def delete_student_user(username):
236
- """Elimina un estudiante"""
237
  container = get_container("users")
238
  try:
239
- # Verificar que el usuario existe y es un estudiante
240
  user = get_student_user(username)
241
  if user:
242
- # Eliminar usando el partition key correcto
243
- container.delete_item(
244
- item=user['id'],
245
- partition_key=username
246
- )
247
  logger.info(f"Estudiante eliminado: {username}")
248
  return True
249
  else:
@@ -253,19 +227,44 @@ def delete_student_user(username):
253
  logger.error(f"Error al eliminar estudiante {username}: {str(e)}")
254
  return False
255
 
256
- __all__ = [
257
- 'get_user',
258
- 'get_admin_user',
259
- 'get_student_user',
260
- 'get_teacher_user',
261
- 'create_user',
262
- 'create_student_user',
263
- 'create_teacher_user',
264
- 'create_admin_user',
265
- 'update_student_user', # Agregada
266
- 'delete_student_user', # Agregada
267
- 'record_login',
268
- 'record_logout',
269
- 'get_recent_sessions',
270
- 'get_user_total_time'
271
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modules/database/sql_db.py
2
+
3
  from .database_init import get_container
4
  from datetime import datetime, timezone
5
  import logging
 
11
  def get_user(username, role=None):
12
  container = get_container("users")
13
  try:
14
+ query = f"SELECT * FROM c WHERE c.id = '{username}'"
15
+ if role:
16
+ query += f" AND c.role = '{role}'"
17
+ items = list(container.query_items(query=query))
 
 
 
 
 
 
 
18
  return items[0] if items else None
19
  except Exception as e:
20
  logger.error(f"Error al obtener usuario {username}: {str(e)}")
 
38
 
39
  try:
40
  user_data = {
41
+ 'id': username,
42
  'password': password,
43
  'role': role,
44
  'timestamp': datetime.now(timezone.utc).isoformat(),
45
+ 'additional_info': additional_info or {},
46
+ 'partitionKey': username # Agregar partition key
47
  }
48
 
49
+ # Crear item sin especificar partition_key en el m茅todo
50
+ container.create_item(body=user_data)
 
 
 
51
  logger.info(f"Usuario {role} creado: {username}")
52
  return True
53
 
 
78
  "type": "session",
79
  "username": username,
80
  "loginTime": datetime.now(timezone.utc).isoformat(),
81
+ "additional_info": {},
82
+ "partitionKey": username
83
  }
84
 
85
+ result = container.create_item(body=session_doc)
 
 
 
86
  logger.info(f"Sesi贸n {session_id} registrada para {username}")
87
  return session_id
88
  except Exception as e:
 
97
  logger.error("No se pudo obtener el contenedor users_sessions")
98
  return False
99
 
100
+ query = "SELECT * FROM c WHERE c.id = @id AND c.username = @username"
101
+ params = [
102
+ {"name": "@id", "value": session_id},
103
+ {"name": "@username", "value": username}
104
+ ]
105
+
106
  items = list(container.query_items(
107
+ query=query,
108
+ parameters=params
 
 
 
 
109
  ))
110
 
111
  if not items:
 
119
 
120
  session.update({
121
  "logoutTime": logout_time.isoformat(),
122
+ "sessionDuration": duration,
123
+ "partitionKey": username
124
  })
125
 
126
+ container.upsert_item(body=session)
 
 
 
127
  logger.info(f"Sesi贸n {session_id} cerrada para {username}, duraci贸n: {duration}s")
128
  return True
129
  except Exception as e:
 
138
  logger.error("No se pudo obtener el contenedor users_sessions")
139
  return []
140
 
141
+ query = """
142
+ SELECT c.username, c.loginTime, c.logoutTime, c.sessionDuration
143
+ FROM c
144
+ WHERE c.type = 'session'
145
+ ORDER BY c.loginTime DESC
146
+ OFFSET 0 LIMIT @limit
147
+ """
148
+
149
  sessions = list(container.query_items(
150
+ query=query,
151
+ parameters=[{"name": "@limit", "value": limit}]
 
 
 
 
 
 
 
152
  ))
153
 
154
  clean_sessions = []
 
176
  if not container:
177
  return None
178
 
179
+ query = """
180
+ SELECT VALUE SUM(c.sessionDuration)
181
+ FROM c
182
+ WHERE c.type = 'session'
183
+ AND c.username = @username
184
+ AND IS_DEFINED(c.sessionDuration)
185
+ """
186
+
187
  result = list(container.query_items(
188
+ query=query,
189
+ parameters=[{"name": "@username", "value": username}]
 
 
 
 
 
 
 
190
  ))
191
 
192
  return result[0] if result and result[0] is not None else 0
 
194
  logger.error(f"Error obteniendo tiempo total: {str(e)}")
195
  return 0
196
 
 
 
 
197
  def update_student_user(username, new_info):
198
+ container = get_container("users")
 
199
  try:
 
200
  user = get_student_user(username)
201
  if user:
202
+ user['additional_info'].update(new_info)
203
+ user['partitionKey'] = username
204
+ container.upsert_item(body=user)
 
 
 
 
 
 
 
 
205
  logger.info(f"Informaci贸n del estudiante actualizada: {username}")
206
  return True
207
  else:
 
212
  return False
213
 
214
  def delete_student_user(username):
 
215
  container = get_container("users")
216
  try:
 
217
  user = get_student_user(username)
218
  if user:
219
+ # El ID es suficiente para eliminaci贸n ya que partitionKey est谩 en el documento
220
+ container.delete_item(item=user['id'])
 
 
 
221
  logger.info(f"Estudiante eliminado: {username}")
222
  return True
223
  else:
 
227
  logger.error(f"Error al eliminar estudiante {username}: {str(e)}")
228
  return False
229
 
230
+ def store_application_request(name, lastname, email, institution, current_role, desired_role, reason):
231
+ container = get_container("application_requests")
232
+ try:
233
+ application_request = {
234
+ "id": str(uuid.uuid4()),
235
+ "name": name,
236
+ "lastname": lastname,
237
+ "email": email,
238
+ "institution": institution,
239
+ "current_role": current_role,
240
+ "desired_role": desired_role,
241
+ "reason": reason,
242
+ "requestDate": datetime.utcnow().isoformat(),
243
+ "partitionKey": email # Usar email como partition key
244
+ }
245
+ container.create_item(body=application_request)
246
+ logger.info(f"Solicitud de aplicaci贸n almacenada para el email: {email}")
247
+ return True
248
+ except Exception as e:
249
+ logger.error(f"Error al almacenar la solicitud de aplicaci贸n: {str(e)}")
250
+ return False
251
+
252
+ def store_student_feedback(username, name, email, feedback):
253
+ container = get_container("user_feedback")
254
+ try:
255
+ feedback_item = {
256
+ "id": str(uuid.uuid4()),
257
+ "username": username,
258
+ "name": name,
259
+ "email": email,
260
+ "feedback": feedback,
261
+ "role": "Estudiante",
262
+ "timestamp": datetime.now(timezone.utc).isoformat(),
263
+ "partitionKey": username # Usar username como partition key
264
+ }
265
+ result = container.create_item(body=feedback_item)
266
+ logger.info(f"Feedback de estudiante almacenado con ID: {result['id']} para el usuario: {username}")
267
+ return True
268
+ except Exception as e:
269
+ logger.error(f"Error al almacenar el feedback del estudiante {username}: {str(e)}")
270
+ return False