File size: 1,468 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import uuid
from datetime import datetime

from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, String, UniqueConstraint, text
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column

from app.common.base_model import Base, CreatedAtMixin, IdMixin

KINDS = ("review", "drill", "armcare", "result", "report")


class Notification(IdMixin, CreatedAtMixin, Base):
    """One in-app inbox item. event_key deduplicates retries of the same domain event per recipient."""

    __tablename__ = "notifications"
    __table_args__ = (
        CheckConstraint(f"kind IN ({', '.join(repr(k) for k in KINDS)})", name="kind"),
        UniqueConstraint("recipient_id", "event_key"),
        Index("ix_notifications_recipient_id_created_at", "recipient_id", text("created_at DESC"), "id"),
        Index("ix_notifications_unread", "recipient_id", postgresql_where=text("read_at IS NULL")),
    )

    recipient_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE")
    )
    kind: Mapped[str] = mapped_column(String(10))
    title: Mapped[str] = mapped_column(String(120))
    body: Mapped[str] = mapped_column(String(300), server_default="")
    target: Mapped[dict] = mapped_column(JSONB, server_default=text("'{}'::jsonb"))
    event_key: Mapped[str] = mapped_column(String(160))
    read_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))