Files
core/orm/notification.py

133 lines
4.8 KiB
Python
Raw Normal View History

2025-07-25 01:04:15 +03:00
from datetime import datetime
2025-07-25 08:49:12 +03:00
from enum import Enum
2025-07-31 18:55:59 +03:00
from typing import Any
2024-03-04 10:35:33 +03:00
2025-07-31 18:55:59 +03:00
from sqlalchemy import JSON, DateTime, ForeignKey, Index, Integer, PrimaryKeyConstraint, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
2024-03-04 10:35:33 +03:00
2025-07-25 01:18:50 +03:00
from auth.orm import Author
2025-07-25 01:04:15 +03:00
from orm.base import BaseModel as Base
2025-07-25 01:21:18 +03:00
from utils.logger import root_logger as logger
2025-07-25 01:04:15 +03:00
2025-07-25 08:49:12 +03:00
class NotificationEntity(Enum):
"""
Перечисление сущностей для уведомлений.
Определяет типы объектов, к которым относятся уведомления.
"""
2025-07-25 01:04:15 +03:00
TOPIC = "topic"
COMMENT = "comment"
2024-04-17 18:32:23 +03:00
SHOUT = "shout"
2025-07-25 01:04:15 +03:00
AUTHOR = "author"
2024-10-21 12:15:44 +03:00
COMMUNITY = "community"
2025-07-31 18:55:59 +03:00
REACTION = "reaction"
2024-03-04 10:35:33 +03:00
2024-10-21 12:15:44 +03:00
@classmethod
2025-07-25 01:04:15 +03:00
def from_string(cls, value: str) -> "NotificationEntity":
"""
Создает экземпляр сущности уведомления из строки.
Args:
value (str): Строковое представление сущности.
Returns:
NotificationEntity: Экземпляр сущности уведомления.
"""
try:
return cls(value)
except ValueError:
logger.error(f"Неверная сущность уведомления: {value}")
raise ValueError("Неверная сущность уведомления") # noqa: B904
2024-03-04 10:35:33 +03:00
2024-10-21 12:15:44 +03:00
2025-07-25 08:49:12 +03:00
class NotificationAction(Enum):
"""
Перечисление действий для уведомлений.
Определяет типы событий, которые могут происходить с сущностями.
"""
2025-07-25 01:04:15 +03:00
2024-04-17 18:32:23 +03:00
CREATE = "create"
UPDATE = "update"
DELETE = "delete"
2025-07-25 01:04:15 +03:00
MENTION = "mention"
REACT = "react"
2025-07-25 08:49:12 +03:00
FOLLOW = "follow"
INVITE = "invite"
2024-03-04 10:35:33 +03:00
2024-10-21 12:15:44 +03:00
@classmethod
2025-07-25 01:04:15 +03:00
def from_string(cls, value: str) -> "NotificationAction":
"""
Создает экземпляр действия уведомления из строки.
Args:
value (str): Строковое представление действия.
Returns:
NotificationAction: Экземпляр действия уведомления.
"""
try:
return cls(value)
except ValueError:
logger.error(f"Неверное действие уведомления: {value}")
raise ValueError("Неверное действие уведомления") # noqa: B904
2024-10-21 12:15:44 +03:00
2024-03-04 10:35:33 +03:00
2025-07-25 08:49:12 +03:00
# Оставляем для обратной совместимости
NotificationStatus = Enum("NotificationStatus", ["UNREAD", "READ", "ARCHIVED"])
NotificationKind = NotificationAction # Для совместимости со старым кодом
2024-03-04 10:35:33 +03:00
class NotificationSeen(Base):
2024-04-17 18:32:23 +03:00
__tablename__ = "notification_seen"
2024-03-04 10:35:33 +03:00
2025-07-31 18:55:59 +03:00
viewer: Mapped[int] = mapped_column(ForeignKey("author.id"))
notification: Mapped[int] = mapped_column(ForeignKey("notification.id"))
__table_args__ = (
PrimaryKeyConstraint(viewer, notification),
Index("idx_notification_seen_viewer", "viewer"),
Index("idx_notification_seen_notification", "notification"),
{"extend_existing": True},
)
2024-03-04 10:35:33 +03:00
class Notification(Base):
2024-04-17 18:32:23 +03:00
__tablename__ = "notification"
2024-03-04 10:35:33 +03:00
2025-07-31 18:55:59 +03:00
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
updated_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
2025-07-25 01:04:15 +03:00
2025-07-31 18:55:59 +03:00
entity: Mapped[str] = mapped_column(String, nullable=False)
action: Mapped[str] = mapped_column(String, nullable=False)
payload: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
2024-03-04 10:35:33 +03:00
2025-07-31 18:55:59 +03:00
status: Mapped[NotificationStatus] = mapped_column(default=NotificationStatus.UNREAD)
kind: Mapped[NotificationKind] = mapped_column(nullable=False)
2025-07-25 01:04:15 +03:00
2024-10-21 12:15:44 +03:00
seen = relationship(Author, secondary="notification_seen")
2025-07-31 18:55:59 +03:00
__table_args__ = (
Index("idx_notification_created_at", "created_at"),
Index("idx_notification_status", "status"),
Index("idx_notification_kind", "kind"),
{"extend_existing": True},
)
def set_entity(self, entity: NotificationEntity) -> None:
2025-07-25 01:04:15 +03:00
"""Устанавливает сущность уведомления."""
self.entity = entity.value
2024-10-21 12:15:44 +03:00
def get_entity(self) -> NotificationEntity:
2025-07-25 01:04:15 +03:00
"""Возвращает сущность уведомления."""
2024-10-21 12:15:44 +03:00
return NotificationEntity.from_string(self.entity)
2025-07-31 18:55:59 +03:00
def set_action(self, action: NotificationAction) -> None:
2025-07-25 01:04:15 +03:00
"""Устанавливает действие уведомления."""
self.action = action.value
2024-10-21 12:15:44 +03:00
def get_action(self) -> NotificationAction:
2025-07-25 01:04:15 +03:00
"""Возвращает действие уведомления."""
2024-10-21 12:15:44 +03:00
return NotificationAction.from_string(self.action)