chore: translate all Spanish comments and log messages to English

This commit is contained in:
Dionisio
2026-02-12 09:41:25 +01:00
parent bc169de8f6
commit d31a413e57
89 changed files with 2480 additions and 2482 deletions
@@ -20,9 +20,9 @@ impl CalendarEventPgRepository {
#[async_trait]
impl CalendarEventRepository for CalendarEventPgRepository {
async fn create_event(&self, event: CalendarEvent) -> CalendarEventRepositoryResult<CalendarEvent> {
// Este método necesitaría una implementación completa que construya el CalendarEvent
// desde el resultado de la query, utilizando métodos del constructor
// Para esta demostración, vamos a retornar el mismo evento
// This method would need a full implementation that builds the CalendarEvent
// from the query result, using constructor methods
// For this demonstration, we return the same event
sqlx::query(
r#"
@@ -50,7 +50,7 @@ impl CalendarEventRepository for CalendarEventPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to create calendar event: {}", e)))?;
// Devolvemos el mismo evento en vez de un resultado
// We return the same event instead of a result
Ok(event)
}
@@ -86,8 +86,8 @@ impl CalendarEventRepository for CalendarEventPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to update calendar event: {}", e)))?;
// En una implementación completa, recuperaríamos el evento actualizado
// Por simplicidad, devolvemos el mismo evento que recibimos
// In a full implementation, we would retrieve the updated event
// For simplicity, we return the same event we received
Ok(event)
}
@@ -176,9 +176,9 @@ impl CalendarEventRepository for CalendarEventPgRepository {
.map_err(|e| DomainError::database_error(format!("Failed to get calendar event by id: {}", e)))?
.ok_or_else(|| DomainError::not_found("Calendar Event", id.to_string()))?;
// En una implementación real, construiríamos un objeto CalendarEvent completo
// Por simplicidad, creamos un objeto con valores predeterminados para
// demostrar el enfoque sin macros
// In a real implementation, we would build a complete CalendarEvent object
// For simplicity, we create an object with default values to
// demonstrate the approach without macros
let event = CalendarEvent::with_id(
row.get("id"),
@@ -32,14 +32,14 @@ impl CalendarRepository for CalendarPgRepository {
.bind(calendar.owner_id())
.bind(calendar.description())
.bind(calendar.color())
.bind(false) // is_public no existe como campo
.bind(false) // is_public doesn't exist as a field
.bind(calendar.created_at())
.bind(calendar.updated_at())
.fetch_one(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to create calendar: {}", e)))?;
// Construir el objeto Calendar utilizando su constructor with_id
// Build the Calendar object using its with_id constructor
let result = Calendar::with_id(
row.get("id"),
row.get("name"),
@@ -66,14 +66,14 @@ impl CalendarRepository for CalendarPgRepository {
.bind(calendar.name())
.bind(calendar.description())
.bind(calendar.color())
.bind(false) // is_public no existe como campo
.bind(false) // is_public doesn't exist as a field
.bind(now)
.bind(calendar.id())
.fetch_one(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to update calendar: {}", e)))?;
// Construir el objeto Calendar utilizando su constructor with_id
// Build the Calendar object using its with_id constructor
let result = Calendar::with_id(
row.get("id"),
row.get("name"),
@@ -8,7 +8,7 @@ use crate::application::dtos::favorites_dto::FavoriteItemDto;
use crate::application::ports::favorites_ports::FavoritesRepositoryPort;
use crate::common::errors::{Result, DomainError, ErrorKind};
/// Implementación PostgreSQL del puerto de persistencia de favoritos.
/// PostgreSQL implementation of the favorites persistence port.
pub struct FavoritesPgRepository {
db_pool: Arc<PgPool>,
}
@@ -8,7 +8,7 @@ use crate::application::dtos::recent_dto::RecentItemDto;
use crate::application::ports::recent_ports::RecentItemsRepositoryPort;
use crate::common::errors::{Result, DomainError, ErrorKind};
/// Implementación PostgreSQL del puerto de persistencia de elementos recientes.
/// PostgreSQL implementation of the recent items persistence port.
pub struct RecentItemsPgRepository {
db_pool: Arc<PgPool>,
}
@@ -10,7 +10,7 @@ use crate::application::ports::auth_ports::SessionStoragePort;
use crate::common::errors::DomainError;
use crate::infrastructure::repositories::pg::transaction_utils::with_transaction;
// Implementar From<sqlx::Error> para SessionRepositoryError para permitir conversiones automáticas
// Implement From<sqlx::Error> for SessionRepositoryError to allow automatic conversions
impl From<sqlx::Error> for SessionRepositoryError {
fn from(err: sqlx::Error) -> Self {
SessionPgRepository::map_sqlx_error(err)
@@ -26,14 +26,14 @@ impl SessionPgRepository {
Self { pool }
}
// Método auxiliar para mapear errores SQL a errores de dominio
// Helper method to map SQL errors to domain errors
pub fn map_sqlx_error(err: sqlx::Error) -> SessionRepositoryError {
match err {
sqlx::Error::RowNotFound => {
SessionRepositoryError::NotFound("Sesión no encontrada".to_string())
SessionRepositoryError::NotFound("Session not found".to_string())
},
_ => SessionRepositoryError::DatabaseError(
format!("Error de base de datos: {}", err)
format!("Database error: {}", err)
),
}
}
@@ -41,9 +41,9 @@ impl SessionPgRepository {
#[async_trait]
impl SessionRepository for SessionPgRepository {
/// Crea una nueva sesión utilizando una transacción
/// Creates a new session using a transaction
async fn create_session(&self, session: Session) -> SessionRepositoryResult<Session> {
// Crear una copia de la sesión para el closure
// Create a copy of the session for the closure
let session_clone = session.clone();
with_transaction(
@@ -51,7 +51,7 @@ impl SessionRepository for SessionPgRepository {
"create_session",
|tx| {
Box::pin(async move {
// Insertar la sesión
// Insert the session
sqlx::query(
r#"
INSERT INTO auth.sessions (
@@ -74,8 +74,8 @@ impl SessionRepository for SessionPgRepository {
.await
.map_err(Self::map_sqlx_error)?;
// Opcionalmente, actualizar el último login del usuario
// dentro de la misma transacción
// Optionally, update the user's last login
// within the same transaction
sqlx::query(
r#"
UPDATE auth.users
@@ -87,12 +87,12 @@ impl SessionRepository for SessionPgRepository {
.execute(&mut **tx)
.await
.map_err(|e| {
// Convertimos el error pero sin interrumpir la creación
// de la sesión si falla la actualización
tracing::warn!("No se pudo actualizar last_login_at para usuario {}: {}",
// Convert the error but without interrupting session
// creation if the update fails
tracing::warn!("Could not update last_login_at for user {}: {}",
session_clone.user_id(), e);
SessionRepositoryError::DatabaseError(format!(
"Sesión creada pero no se pudo actualizar last_login_at: {}", e
"Session created but could not update last_login_at: {}", e
))
})?;
@@ -104,7 +104,7 @@ impl SessionRepository for SessionPgRepository {
Ok(session)
}
/// Obtiene una sesión por ID
/// Gets a session by ID
async fn get_session_by_id(&self, id: &str) -> SessionRepositoryResult<Session> {
let row = sqlx::query(
r#"
@@ -132,7 +132,7 @@ impl SessionRepository for SessionPgRepository {
))
}
/// Obtiene una sesión por token de actualización
/// Gets a session by refresh token
async fn get_session_by_refresh_token(&self, refresh_token: &str) -> SessionRepositoryResult<Session> {
let row = sqlx::query(
r#"
@@ -160,7 +160,7 @@ impl SessionRepository for SessionPgRepository {
))
}
/// Obtiene todas las sesiones de un usuario
/// Gets all sessions for a user
async fn get_sessions_by_user_id(&self, user_id: &str) -> SessionRepositoryResult<Vec<Session>> {
let rows = sqlx::query(
r#"
@@ -195,16 +195,16 @@ impl SessionRepository for SessionPgRepository {
Ok(sessions)
}
/// Revoca una sesión específica utilizando una transacción
/// Revokes a specific session using a transaction
async fn revoke_session(&self, session_id: &str) -> SessionRepositoryResult<()> {
let id = session_id.to_string(); // Clone para uso en closure
let id = session_id.to_string(); // Clone for use in closure
with_transaction(
&self.pool,
"revoke_session",
|tx| {
Box::pin(async move {
// Revocar la sesión
// Revoke the session
let result = sqlx::query(
r#"
UPDATE auth.sessions
@@ -218,14 +218,14 @@ impl SessionRepository for SessionPgRepository {
.await
.map_err(Self::map_sqlx_error)?;
// Si encontramos la sesión, podemos registrar un evento de seguridad
// If we found the session, we can log a security event
if let Some(row) = result {
let user_id: String = row.try_get("user_id").unwrap_or_default();
// Registrar evento de seguridad (en una tabla de seguridad)
// Esto es opcional pero muestra cómo se puede realizar operaciones
// adicionales en la misma transacción
tracing::info!("Sesión con ID {} del usuario {} revocada", id, user_id);
// Log security event (in a security table)
// This is optional but shows how additional operations
// can be performed in the same transaction
tracing::info!("Session with ID {} for user {} revoked", id, user_id);
}
Ok(())
@@ -234,16 +234,16 @@ impl SessionRepository for SessionPgRepository {
).await
}
/// Revoca todas las sesiones de un usuario utilizando una transacción
/// Revokes all sessions for a user using a transaction
async fn revoke_all_user_sessions(&self, user_id: &str) -> SessionRepositoryResult<u64> {
let user_id_clone = user_id.to_string(); // Clone para uso en closure
let user_id_clone = user_id.to_string(); // Clone for use in closure
with_transaction(
&self.pool,
"revoke_all_user_sessions",
|tx| {
Box::pin(async move {
// Revocar todas las sesiones del usuario
// Revoke all sessions for the user
let result = sqlx::query(
r#"
UPDATE auth.sessions
@@ -258,9 +258,9 @@ impl SessionRepository for SessionPgRepository {
let affected = result.rows_affected();
// Registrar evento de seguridad
// Log security event
if affected > 0 {
tracing::info!("Revocadas {} sesiones del usuario {}", affected, user_id_clone);
tracing::info!("Revoked {} sessions for user {}", affected, user_id_clone);
}
Ok(affected)
@@ -269,7 +269,7 @@ impl SessionRepository for SessionPgRepository {
).await
}
/// Elimina sesiones expiradas
/// Deletes expired sessions
async fn delete_expired_sessions(&self) -> SessionRepositoryResult<u64> {
let now = Utc::now();
@@ -288,7 +288,7 @@ impl SessionRepository for SessionPgRepository {
}
}
// Implementación del puerto de almacenamiento para la capa de aplicación
// Implementation of the storage port for the application layer
#[async_trait]
impl SessionStoragePort for SessionPgRepository {
async fn create_session(&self, session: Session) -> Result<Session, DomainError> {
@@ -9,7 +9,7 @@ use crate::application::ports::auth_ports::UserStoragePort;
use crate::common::errors::DomainError;
use crate::infrastructure::repositories::pg::transaction_utils::with_transaction;
// Implementar From<sqlx::Error> para UserRepositoryError para permitir conversiones automáticas
// Implement From<sqlx::Error> for UserRepositoryError to allow automatic conversions
impl From<sqlx::Error> for UserRepositoryError {
fn from(err: sqlx::Error) -> Self {
UserPgRepository::map_sqlx_error(err)
@@ -25,26 +25,26 @@ impl UserPgRepository {
Self { pool }
}
// Método auxiliar para mapear errores SQL a errores de dominio
// Helper method to map SQL errors to domain errors
pub fn map_sqlx_error(err: sqlx::Error) -> UserRepositoryError {
match err {
sqlx::Error::RowNotFound => {
UserRepositoryError::NotFound("Usuario no encontrado".to_string())
UserRepositoryError::NotFound("User not found".to_string())
},
sqlx::Error::Database(db_err) => {
if db_err.code().map_or(false, |code| code == "23505") {
// Código para violación de unicidad en PostgreSQL
// PostgreSQL uniqueness violation code
UserRepositoryError::AlreadyExists(
"Usuario o email ya existe".to_string()
"User or email already exists".to_string()
)
} else {
UserRepositoryError::DatabaseError(
format!("Error de base de datos: {}", db_err)
format!("Database error: {}", db_err)
)
}
},
_ => UserRepositoryError::DatabaseError(
format!("Error de base de datos: {}", err)
format!("Database error: {}", err)
),
}
}
@@ -52,7 +52,7 @@ impl UserPgRepository {
#[async_trait]
impl UserRepository for UserPgRepository {
/// Crea un nuevo usuario utilizando una transacción
/// Creates a new user using a transaction
async fn create_user(&self, user: User) -> UserRepositoryResult<User> {
// Creamos una copia del usuario para el closure
let user_clone = user.clone();
@@ -61,14 +61,14 @@ impl UserRepository for UserPgRepository {
&self.pool,
"create_user",
|tx| {
// Necesitamos mover el closure a un BoxFuture para devolver dentro
// de la llamada with_transaction
// We need to move the closure into a BoxFuture to return inside
// the with_transaction call
Box::pin(async move {
// Usamos los getters para extraer los valores
// Convertimos user.role() a string para pasarlo como texto plano
// Use getters to extract the values
// Convert user.role() to string to pass it as plain text
let role_str = user_clone.role().to_string();
// Modificar el SQL para hacer un cast explícito al tipo auth.userrole
// Modify the SQL to do an explicit cast to the auth.userrole type
let _result = sqlx::query(
r#"
INSERT INTO auth.users (
@@ -87,7 +87,7 @@ impl UserRepository for UserPgRepository {
.bind(user_clone.username())
.bind(user_clone.email())
.bind(user_clone.password_hash())
.bind(&role_str) // Convertir a string pero con cast explícito en SQL
.bind(&role_str) // Convert to string but with explicit cast in SQL
.bind(user_clone.storage_quota_bytes())
.bind(user_clone.storage_used_bytes())
.bind(user_clone.created_at())
@@ -100,18 +100,18 @@ impl UserRepository for UserPgRepository {
.await
.map_err(Self::map_sqlx_error)?;
// Podríamos realizar operaciones adicionales aquí,
// como configurar permisos, roles, etc.
// We could perform additional operations here,
// such as configuring permissions, roles, etc.
Ok(user_clone)
}) as BoxFuture<'_, UserRepositoryResult<User>>
}
).await?;
Ok(user) // Devolvemos el usuario original por simplicidad
Ok(user) // Return the original user for simplicity
}
/// Obtiene un usuario por ID
/// Gets a user by ID
async fn get_user_by_id(&self, id: &str) -> UserRepositoryResult<User> {
let row = sqlx::query(
r#"
@@ -153,7 +153,7 @@ impl UserRepository for UserPgRepository {
))
}
/// Obtiene un usuario por nombre de usuario
/// Gets a user by username
async fn get_user_by_username(&self, username: &str) -> UserRepositoryResult<User> {
let row = sqlx::query(
r#"
@@ -195,7 +195,7 @@ impl UserRepository for UserPgRepository {
))
}
/// Obtiene un usuario por correo electrónico
/// Gets a user by email
async fn get_user_by_email(&self, email: &str) -> UserRepositoryResult<User> {
let row = sqlx::query(
r#"
@@ -237,9 +237,9 @@ impl UserRepository for UserPgRepository {
))
}
/// Actualiza un usuario existente utilizando una transacción
/// Updates an existing user using a transaction
async fn update_user(&self, user: User) -> UserRepositoryResult<User> {
// Creamos una copia del usuario para el closure
// Create a copy of the user for the closure
let user_clone = user.clone();
with_transaction(
@@ -247,7 +247,7 @@ impl UserRepository for UserPgRepository {
"update_user",
|tx| {
Box::pin(async move {
// Actualizar el usuario
// Update the user
sqlx::query(
r#"
UPDATE auth.users
@@ -278,8 +278,8 @@ impl UserRepository for UserPgRepository {
.await
.map_err(Self::map_sqlx_error)?;
// Podríamos realizar operaciones adicionales aquí dentro
// de la misma transacción, como actualizar permisos, etc.
// We could perform additional operations here inside
// the same transaction, such as updating permissions, etc.
Ok(user_clone)
}) as BoxFuture<'_, UserRepositoryResult<User>>
@@ -289,7 +289,7 @@ impl UserRepository for UserPgRepository {
Ok(user)
}
/// Actualiza solo el uso de almacenamiento de un usuario
/// Updates only the storage usage of a user
async fn update_storage_usage(&self, user_id: &str, usage_bytes: i64) -> UserRepositoryResult<()> {
sqlx::query(
r#"
@@ -309,7 +309,7 @@ impl UserRepository for UserPgRepository {
Ok(())
}
/// Actualiza la fecha de último inicio de sesión
/// Updates the last login date
async fn update_last_login(&self, user_id: &str) -> UserRepositoryResult<()> {
sqlx::query(
r#"
@@ -328,7 +328,7 @@ impl UserRepository for UserPgRepository {
Ok(())
}
/// Lista usuarios con paginación
/// Lists users with pagination
async fn list_users(&self, limit: i64, offset: i64) -> UserRepositoryResult<Vec<User>> {
let rows = sqlx::query(
r#"
@@ -378,7 +378,7 @@ impl UserRepository for UserPgRepository {
Ok(users)
}
/// Activa o desactiva un usuario
/// Activates or deactivates a user
async fn set_user_active_status(&self, user_id: &str, active: bool) -> UserRepositoryResult<()> {
sqlx::query(
r#"
@@ -398,7 +398,7 @@ impl UserRepository for UserPgRepository {
Ok(())
}
/// Cambia la contraseña de un usuario
/// Changes a user's password
async fn change_password(&self, user_id: &str, password_hash: &str) -> UserRepositoryResult<()> {
sqlx::query(
r#"
@@ -418,9 +418,9 @@ impl UserRepository for UserPgRepository {
Ok(())
}
/// Cambia el rol de un usuario
/// Changes a user's role
async fn change_role(&self, user_id: &str, role: UserRole) -> UserRepositoryResult<()> {
// Convertir el rol a string para el binding
// Convert the role to string for the binding
let role_str = role.to_string();
sqlx::query(
@@ -441,7 +441,7 @@ impl UserRepository for UserPgRepository {
Ok(())
}
/// Lista usuarios por rol
/// Lists users by role
async fn list_users_by_role(&self, role: &str) -> UserRepositoryResult<Vec<User>> {
let rows = sqlx::query(
r#"
@@ -490,7 +490,7 @@ impl UserRepository for UserPgRepository {
Ok(users)
}
/// Elimina un usuario
/// Deletes a user
async fn delete_user(&self, user_id: &str) -> UserRepositoryResult<()> {
sqlx::query(
r#"
@@ -548,7 +548,7 @@ impl UserRepository for UserPgRepository {
))
}
/// Actualiza la cuota de almacenamiento de un usuario
/// Updates a user's storage quota
async fn update_storage_quota(&self, user_id: &str, quota_bytes: i64) -> UserRepositoryResult<()> {
sqlx::query(
r#"
@@ -568,7 +568,7 @@ impl UserRepository for UserPgRepository {
Ok(())
}
/// Cuenta el número total de usuarios
/// Counts the total number of users
async fn count_users(&self) -> UserRepositoryResult<i64> {
let row = sqlx::query(
"SELECT COUNT(*) as count FROM auth.users"
@@ -581,7 +581,7 @@ impl UserRepository for UserPgRepository {
Ok(count)
}
/// Obtiene estadísticas de almacenamiento agregadas
/// Gets aggregated storage statistics
async fn get_storage_stats(&self) -> UserRepositoryResult<StorageStats> {
let row = sqlx::query(
r#"
@@ -610,7 +610,7 @@ impl UserRepository for UserPgRepository {
}
}
// Implementación del puerto de almacenamiento para la capa de aplicación
// Storage port implementation for the application layer
#[async_trait]
impl UserStoragePort for UserPgRepository {
async fn create_user(&self, user: User) -> Result<User, DomainError> {