@@ -2,10 +2,18 @@ from pymongo import MongoClient
|
||||
from pymongo.collection import Collection
|
||||
from core.config import ConfSettings
|
||||
|
||||
# Conexión a MongoDB para Reportes
|
||||
mongo_client = MongoClient(ConfSettings.mongodb_url)
|
||||
mongodb = mongo_client[ConfSettings.mongodb_db]
|
||||
# Conexión a MongoDB para Reportes (Instancia Separada - Puerto 27017)
|
||||
mongo_client_reports = MongoClient(ConfSettings.mongodb_reports_url)
|
||||
mongodb_reports = mongo_client_reports[ConfSettings.mongodb_reports_db]
|
||||
|
||||
# Conexión a MongoDB para Notificaciones (Instancia Separada - Puerto 27018)
|
||||
mongo_client_notifications = MongoClient(ConfSettings.mongodb_notifications_url)
|
||||
mongodb_notifications = mongo_client_notifications[ConfSettings.mongodb_notifications_db]
|
||||
|
||||
def get_reports_collection() -> Collection:
|
||||
"""Obtiene la colección de reportes desde MongoDB"""
|
||||
return mongodb["reportes"]
|
||||
"""Obtiene la colección de reportes desde MongoDB (Instancia 1)"""
|
||||
return mongodb_reports["reportes"]
|
||||
|
||||
def get_notifications_collection() -> Collection:
|
||||
"""Obtiene la colección de notificaciones desde MongoDB (Instancia 2)"""
|
||||
return mongodb_notifications["notificaciones"]
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
from application.ports.notification_repository import NotificationRepository
|
||||
from domain.notifications import Notification
|
||||
from infrastructure.adapters.persistence.mongodb import get_notifications_collection
|
||||
from typing import List, Optional
|
||||
from bson import ObjectId
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class NotificationRepositoryMongo(NotificationRepository):
|
||||
"""Implementación del repositorio de Notificaciones usando MongoDB (Instancia Separada)"""
|
||||
|
||||
def __init__(self):
|
||||
self.collection = get_notifications_collection()
|
||||
|
||||
def create(self, notification: Notification) -> str:
|
||||
"""Crea una nueva notificación"""
|
||||
notification_dict = {
|
||||
"id_usuario": notification.id_usuario,
|
||||
"id_reporte": notification.id_reporte,
|
||||
"message": notification.message,
|
||||
"fecha": notification.fecha or datetime.utcnow(),
|
||||
"read": notification.read
|
||||
}
|
||||
result = self.collection.insert_one(notification_dict)
|
||||
return str(result.inserted_id)
|
||||
|
||||
def get_by_id(self, notification_id: str) -> Optional[Notification]:
|
||||
"""Obtiene una notificación por ID"""
|
||||
try:
|
||||
doc = self.collection.find_one({"_id": ObjectId(notification_id)})
|
||||
if doc:
|
||||
return self._to_domain(doc)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def get_by_user(self, user_id: int, limit: int = 50, offset: int = 0) -> List[Notification]:
|
||||
"""Obtiene notificaciones de un usuario ordenadas por fecha descendente"""
|
||||
docs = self.collection.find(
|
||||
{"id_usuario": user_id}
|
||||
).sort("fecha", -1).skip(offset).limit(limit)
|
||||
return [self._to_domain(doc) for doc in docs]
|
||||
|
||||
def mark_as_read(self, notification_id: str) -> bool:
|
||||
"""Marca una notificación como leída"""
|
||||
try:
|
||||
result = self.collection.update_one(
|
||||
{"_id": ObjectId(notification_id)},
|
||||
{"$set": {"read": True}}
|
||||
)
|
||||
return result.modified_count > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def mark_all_as_read(self, user_id: int) -> int:
|
||||
"""Marca todas las notificaciones de un usuario como leídas"""
|
||||
result = self.collection.update_many(
|
||||
{"id_usuario": user_id, "read": False},
|
||||
{"$set": {"read": True}}
|
||||
)
|
||||
return result.modified_count
|
||||
|
||||
def delete(self, notification_id: str) -> bool:
|
||||
"""Elimina una notificación"""
|
||||
try:
|
||||
result = self.collection.delete_one({"_id": ObjectId(notification_id)})
|
||||
return result.deleted_count > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def get_unread_count(self, user_id: int) -> int:
|
||||
"""Obtiene el número de notificaciones no leídas para un usuario"""
|
||||
return self.collection.count_documents({
|
||||
"id_usuario": user_id,
|
||||
"read": False
|
||||
})
|
||||
|
||||
def _to_domain(self, doc: dict) -> Notification:
|
||||
"""Convierte un documento de MongoDB a un objeto de dominio"""
|
||||
return Notification(
|
||||
id_notificacion=str(doc.get("_id")),
|
||||
id_usuario=doc.get("id_usuario"),
|
||||
id_reporte=doc.get("id_reporte"),
|
||||
message=doc.get("message"),
|
||||
fecha=doc.get("fecha"),
|
||||
read=doc.get("read", False)
|
||||
)
|
||||
@@ -17,6 +17,7 @@ class ReportEventType(str, Enum):
|
||||
"""Types of report events"""
|
||||
CREATE = "report.create"
|
||||
UPDATE_VISIBILITY = "report.update_visibility"
|
||||
UPDATE_STATUS = "report.update_status"
|
||||
DELETE = "report.delete"
|
||||
|
||||
|
||||
@@ -69,6 +70,10 @@ class ReportMessage:
|
||||
estado: Optional[str] = None # Estado del reporte: "en proceso", "no resuelto", "resuelto"
|
||||
fecha_creacion: Optional[str] = None # ISO format datetime string
|
||||
penalize_author: Optional[bool] = None # For update_visibility event
|
||||
old_estado: Optional[str] = None # Estado anterior (para UPDATE_STATUS)
|
||||
new_estado: Optional[str] = None # Nuevo estado (para UPDATE_STATUS)
|
||||
old_visibility: Optional[float] = None # Visibilidad anterior (para UPDATE_VISIBILITY)
|
||||
new_visibility: Optional[float] = None # Nueva visibilidad (para UPDATE_VISIBILITY)
|
||||
|
||||
def to_dict(self):
|
||||
"""Convert to dictionary"""
|
||||
|
||||
Reference in New Issue
Block a user