Files
rengine/shared/services/notification.py
T
Yogesh Ojha c6c5c61389 Refactor project and tag management, enhance error handling, and improve UI components
- Updated project slug generation to ensure uniqueness by checking active projects.
- Modified project retrieval functions to only fetch active projects.
- Introduced unique slug generation for tags associated with specific projects.
- Enhanced user authentication flow with improved error handling and session management.
- Added session expiration handling in the API client and SSE client for better user experience.
- Improved UI components for better accessibility and user feedback, including copy buttons and activity drawers.
- Refactored notification handling to ensure proper session management and state reset on logout.
- Removed unused enrichment components to streamline the codebase.
- Updated notification model to simplify JSONB handling and ensure proper expiration logic.
2026-05-23 14:33:19 +05:30

144 lines
4.0 KiB
Python

from sqlalchemy import delete, update
from sqlalchemy.ext.asyncio import AsyncSession
from shared.enums.notification import NotificationSeverity, NotificationType
from shared.enums.sse import SSEChannel, SSEEventType
from shared.logging import get_logger
from shared.models.notification import Notification, NotificationMetadata
from shared.sse import sse_manager
from shared.utils.datetime import utc_now
logger = get_logger(__name__)
class NotificationManager:
@staticmethod
async def publish(
session: AsyncSession,
type: NotificationType,
severity: NotificationSeverity,
title: str,
message: str,
metadata: NotificationMetadata | dict | None = None,
commit: bool = True,
) -> Notification:
if isinstance(metadata, NotificationMetadata):
metadata_dict = metadata.model_dump(exclude_none=True)
elif isinstance(metadata, dict):
validated = NotificationMetadata(**metadata)
metadata_dict = validated.model_dump(exclude_none=True)
else:
metadata_dict = {}
notification = Notification(
type=type,
severity=severity,
title=title[:200],
message=message,
notification_metadata=metadata_dict,
)
session.add(notification)
if commit:
await session.commit()
await session.refresh(notification)
await sse_manager.publish(
channel=SSEChannel.BROADCAST,
event_type=SSEEventType.NOTIFICATION,
data={
"id": notification.id,
"type": notification.type.value,
"severity": notification.severity.value,
"title": notification.title,
"message": notification.message,
"notification_metadata": notification.notification_metadata,
"is_read": notification.is_read,
"created_at": notification.created_at.isoformat(),
},
)
logger.info(f"Published notification: {type.value}/{severity.value} - {title}")
return notification
@staticmethod
async def mark_as_read(
session: AsyncSession,
notification_id: int,
commit: bool = True,
) -> bool:
result = await session.execute(
update(Notification)
.where(Notification.id == notification_id)
.values(is_read=True)
)
if commit:
await session.commit()
return result.rowcount > 0
@staticmethod
async def mark_all_as_read(
session: AsyncSession,
commit: bool = True,
) -> int:
result = await session.execute(
update(Notification)
.where(Notification.is_read.is_(False))
.values(is_read=True)
)
if commit:
await session.commit()
return result.rowcount
@staticmethod
async def delete_notification(
session: AsyncSession,
notification_id: int,
commit: bool = True,
) -> bool:
result = await session.execute(
delete(Notification).where(Notification.id == notification_id)
)
if commit:
await session.commit()
return result.rowcount > 0
@staticmethod
async def clear_all(
session: AsyncSession,
commit: bool = True,
) -> int:
result = await session.execute(delete(Notification))
if commit:
await session.commit()
return result.rowcount
@staticmethod
async def cleanup_expired(
session: AsyncSession,
commit: bool = True,
) -> int:
now = utc_now()
result = await session.execute(
delete(Notification).where(Notification.expires_at < now)
)
if commit:
await session.commit()
deleted_count = result.rowcount
if deleted_count > 0:
logger.info(f"Cleaned up {deleted_count} expired notifications")
return deleted_count