intermittent commit

This commit is contained in:
2026-07-14 13:22:11 +02:00
parent 3444a4920f
commit 6163c8f733
24 changed files with 2367 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
from __future__ import annotations

View File

@@ -0,0 +1,2 @@
from __future__ import annotations

View File

@@ -0,0 +1,39 @@
from __future__ import annotations
from collections.abc import Mapping
from govoplan_core.core.modules import ModuleContext
from govoplan_core.core.notifications import NotificationDispatchProvider, NotificationDispatchRequest
from govoplan_notifications.backend.service import deliver_notification, deliver_pending, enqueue_dispatch_request, notification_response
class SqlNotificationDispatchProvider(NotificationDispatchProvider):
def __init__(self, context: ModuleContext) -> None:
self._settings = context.settings
def enqueue_notification(
self,
session: object,
request: NotificationDispatchRequest,
*,
enqueue_delivery: bool = True,
) -> Mapping[str, object]:
notification = enqueue_dispatch_request(session, request, enqueue_delivery=enqueue_delivery) # type: ignore[arg-type]
return notification_response(notification)
def deliver_notification(self, session: object, *, notification_id: str) -> Mapping[str, object]:
notification = deliver_notification(session, notification_id=notification_id, settings=self._settings) # type: ignore[arg-type]
return notification_response(notification)
def deliver_pending(
self,
session: object,
*,
tenant_id: str | None = None,
limit: int = 50,
) -> Mapping[str, object]:
return deliver_pending(session, tenant_id=tenant_id, limit=limit, settings=self._settings) # type: ignore[arg-type]
def dispatch_capability(context: ModuleContext) -> SqlNotificationDispatchProvider:
return SqlNotificationDispatchProvider(context)

View File

@@ -0,0 +1,5 @@
from __future__ import annotations
from govoplan_notifications.backend.db.models import NotificationDeliveryAttempt, NotificationMessage, NotificationPreference
__all__ = ["NotificationDeliveryAttempt", "NotificationMessage", "NotificationPreference"]

View File

@@ -0,0 +1,104 @@
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from govoplan_core.db.base import Base, TimestampMixin
def new_uuid() -> str:
return str(uuid.uuid4())
class NotificationMessage(Base, TimestampMixin):
__tablename__ = "notification_messages"
__table_args__ = (
Index("ix_notification_messages_tenant_status", "tenant_id", "status"),
Index("ix_notification_messages_tenant_recipient", "tenant_id", "recipient_type", "recipient_id"),
Index("ix_notification_messages_source", "tenant_id", "source_module", "source_resource_type", "source_resource_id"),
Index("ix_notification_messages_due", "tenant_id", "status", "not_before_at"),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
source_module: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
source_resource_type: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
source_resource_id: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
event_kind: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
channel: Mapped[str] = mapped_column(String(40), default="inbox", nullable=False, index=True)
recipient: Mapped[str | None] = mapped_column(String(500), nullable=True, index=True)
recipient_type: Mapped[str | None] = mapped_column(String(40), nullable=True, index=True)
recipient_id: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
recipient_label: Mapped[str | None] = mapped_column(String(500), nullable=True)
subject: Mapped[str | None] = mapped_column(String(500), nullable=True)
body_text: Mapped[str | None] = mapped_column(Text, nullable=True)
body_html: Mapped[str | None] = mapped_column(Text, nullable=True)
action_url: Mapped[str | None] = mapped_column(String(1000), nullable=True)
priority: Mapped[int] = mapped_column(Integer, default=0, nullable=False, index=True)
status: Mapped[str] = mapped_column(String(40), default="pending", nullable=False, index=True)
not_before_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, index=True)
queued_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
sent_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
failed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
read_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
acknowledged_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
cancelled_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
attempt_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
last_error: Mapped[str | None] = mapped_column(Text, nullable=True)
external_message_id: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
payload: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False)
metadata_: Mapped[dict[str, Any]] = mapped_column("metadata", JSON, default=dict, nullable=False)
deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, index=True)
attempts: Mapped[list["NotificationDeliveryAttempt"]] = relationship(
back_populates="notification",
cascade="all, delete-orphan",
order_by="NotificationDeliveryAttempt.created_at",
)
class NotificationDeliveryAttempt(Base, TimestampMixin):
__tablename__ = "notification_delivery_attempts"
__table_args__ = (
Index("ix_notification_attempts_notification", "notification_id", "attempt_no"),
Index("ix_notification_attempts_tenant_status", "tenant_id", "status"),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
notification_id: Mapped[str] = mapped_column(ForeignKey("notification_messages.id", ondelete="CASCADE"), nullable=False, index=True)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
channel: Mapped[str] = mapped_column(String(40), nullable=False, index=True)
provider: Mapped[str | None] = mapped_column(String(100), nullable=True, index=True)
status: Mapped[str] = mapped_column(String(40), nullable=False, index=True)
started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
external_message_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
error: Mapped[str | None] = mapped_column(Text, nullable=True)
details: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False)
notification: Mapped[NotificationMessage] = relationship(back_populates="attempts")
class NotificationPreference(Base, TimestampMixin):
__tablename__ = "notification_preferences"
__table_args__ = (
UniqueConstraint("tenant_id", "user_id", name="uq_notification_preferences_tenant_user"),
Index("ix_notification_preferences_tenant_user", "tenant_id", "user_id"),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
user_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
show_unread_badge: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
email_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
email_digest_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
muted_source_modules: Mapped[list[str]] = mapped_column(JSON, default=list, nullable=False)
metadata_: Mapped[dict[str, Any]] = mapped_column("metadata", JSON, default=dict, nullable=False)
__all__ = ["NotificationDeliveryAttempt", "NotificationMessage", "NotificationPreference", "new_uuid"]

View File

@@ -0,0 +1,116 @@
from __future__ import annotations
from pathlib import Path
from govoplan_core.core.access import CAPABILITY_AUTH_PERMISSION_EVALUATOR, CAPABILITY_AUTH_PRINCIPAL_RESOLVER
from govoplan_core.core.module_guards import drop_table_retirement_provider, persistent_table_uninstall_guard
from govoplan_core.core.modules import MigrationSpec, ModuleContext, ModuleInterfaceProvider, ModuleManifest, PermissionDefinition, RoleTemplate
from govoplan_core.core.notifications import CAPABILITY_NOTIFICATIONS_DISPATCH
from govoplan_core.db.base import Base
from govoplan_notifications.backend.db import models as notification_models # noqa: F401 - populate Notifications ORM metadata
MODULE_ID = "notifications"
MODULE_NAME = "Notifications"
MODULE_VERSION = "0.1.8"
READ_SCOPE = "notifications:notification:read"
WRITE_SCOPE = "notifications:notification:write"
DISPATCH_SCOPE = "notifications:delivery:dispatch"
ADMIN_SCOPE = "notifications:notification:admin"
def _permission(scope: str, label: str, description: str) -> PermissionDefinition:
module_id, resource, action = scope.split(":", 2)
return PermissionDefinition(
scope=scope,
label=label,
description=description,
category="Notifications",
level="tenant",
module_id=module_id,
resource=resource,
action=action,
)
PERMISSIONS = (
_permission(READ_SCOPE, "View notifications", "Read notification inbox, outbox, and delivery state."),
_permission(WRITE_SCOPE, "Manage notifications", "Create, update, cancel, read, and acknowledge notifications."),
_permission(DISPATCH_SCOPE, "Dispatch notifications", "Run notification delivery attempts and delivery workers."),
_permission(ADMIN_SCOPE, "Administer notifications", "Manage tenant-wide notification delivery state."),
)
ROLE_TEMPLATES = (
RoleTemplate(
slug="notification_manager",
name="Notification manager",
description="Manage and dispatch tenant notifications.",
permissions=(READ_SCOPE, WRITE_SCOPE, DISPATCH_SCOPE),
),
RoleTemplate(
slug="notification_viewer",
name="Notification viewer",
description="Read notification state.",
permissions=(READ_SCOPE,),
),
)
def _tenant_summary(session, tenant_id: str) -> dict[str, int]:
from govoplan_notifications.backend.db.models import NotificationMessage
return {
"notifications": session.query(NotificationMessage).filter(NotificationMessage.tenant_id == tenant_id, NotificationMessage.deleted_at.is_(None)).count(),
"pending_notifications": session.query(NotificationMessage).filter(NotificationMessage.tenant_id == tenant_id, NotificationMessage.status.in_(("pending", "queued", "failed")), NotificationMessage.deleted_at.is_(None)).count(),
}
def _notifications_router(_context: ModuleContext):
from govoplan_notifications.backend.router import router
return router
manifest = ModuleManifest(
id=MODULE_ID,
name=MODULE_NAME,
version=MODULE_VERSION,
required_capabilities=(CAPABILITY_AUTH_PRINCIPAL_RESOLVER, CAPABILITY_AUTH_PERMISSION_EVALUATOR),
optional_dependencies=("mail", "tasks", "portal", "workflow", "calendar", "scheduling"),
provides_interfaces=(ModuleInterfaceProvider(name="notifications.dispatch", version="0.1.8"),),
permissions=PERMISSIONS,
role_templates=ROLE_TEMPLATES,
route_factory=_notifications_router,
tenant_summary_providers=(_tenant_summary,),
migration_spec=MigrationSpec(
module_id=MODULE_ID,
metadata=Base.metadata,
script_location=str(Path(__file__).with_name("migrations") / "versions"),
retirement_supported=True,
retirement_provider=drop_table_retirement_provider(
notification_models.NotificationMessage,
notification_models.NotificationDeliveryAttempt,
notification_models.NotificationPreference,
label="Notifications",
),
retirement_notes="Destructive retirement drops notification-owned database tables after the installer captures a database snapshot.",
),
uninstall_guard_providers=(
persistent_table_uninstall_guard(
notification_models.NotificationMessage,
notification_models.NotificationDeliveryAttempt,
notification_models.NotificationPreference,
label="Notifications",
),
),
capability_factories={
CAPABILITY_NOTIFICATIONS_DISPATCH: lambda context: __import__(
"govoplan_notifications.backend.capabilities",
fromlist=["dispatch_capability"],
).dispatch_capability(context),
},
)
def get_manifest() -> ModuleManifest:
return manifest

View File

@@ -0,0 +1,2 @@
from __future__ import annotations

View File

@@ -0,0 +1,110 @@
"""v0.1.8 notifications baseline
Revision ID: 5e6f7a8b9c0d
Revises: None
Create Date: 2026-07-13 00:00:00.000000
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "5e6f7a8b9c0d"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"notification_messages",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("source_module", sa.String(length=100), nullable=False),
sa.Column("source_resource_type", sa.String(length=100), nullable=False),
sa.Column("source_resource_id", sa.String(length=255), nullable=True),
sa.Column("event_kind", sa.String(length=100), nullable=False),
sa.Column("channel", sa.String(length=40), nullable=False),
sa.Column("recipient", sa.String(length=500), nullable=True),
sa.Column("recipient_type", sa.String(length=40), nullable=True),
sa.Column("recipient_id", sa.String(length=255), nullable=True),
sa.Column("recipient_label", sa.String(length=500), nullable=True),
sa.Column("subject", sa.String(length=500), nullable=True),
sa.Column("body_text", sa.Text(), nullable=True),
sa.Column("body_html", sa.Text(), nullable=True),
sa.Column("action_url", sa.String(length=1000), nullable=True),
sa.Column("priority", sa.Integer(), nullable=False),
sa.Column("status", sa.String(length=40), nullable=False),
sa.Column("not_before_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("queued_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("sent_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("failed_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("read_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("acknowledged_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("cancelled_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("attempt_count", sa.Integer(), nullable=False),
sa.Column("last_error", sa.Text(), nullable=True),
sa.Column("external_message_id", sa.String(length=255), nullable=True),
sa.Column("payload", sa.JSON(), nullable=False),
sa.Column("metadata", sa.JSON(), nullable=False),
sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_notification_messages")),
)
op.create_index(op.f("ix_notification_messages_channel"), "notification_messages", ["channel"], unique=False)
op.create_index(op.f("ix_notification_messages_deleted_at"), "notification_messages", ["deleted_at"], unique=False)
op.create_index(op.f("ix_notification_messages_event_kind"), "notification_messages", ["event_kind"], unique=False)
op.create_index(op.f("ix_notification_messages_external_message_id"), "notification_messages", ["external_message_id"], unique=False)
op.create_index(op.f("ix_notification_messages_not_before_at"), "notification_messages", ["not_before_at"], unique=False)
op.create_index(op.f("ix_notification_messages_priority"), "notification_messages", ["priority"], unique=False)
op.create_index(op.f("ix_notification_messages_recipient"), "notification_messages", ["recipient"], unique=False)
op.create_index(op.f("ix_notification_messages_recipient_id"), "notification_messages", ["recipient_id"], unique=False)
op.create_index(op.f("ix_notification_messages_recipient_type"), "notification_messages", ["recipient_type"], unique=False)
op.create_index(op.f("ix_notification_messages_source_module"), "notification_messages", ["source_module"], unique=False)
op.create_index(op.f("ix_notification_messages_source_resource_id"), "notification_messages", ["source_resource_id"], unique=False)
op.create_index(op.f("ix_notification_messages_source_resource_type"), "notification_messages", ["source_resource_type"], unique=False)
op.create_index(op.f("ix_notification_messages_status"), "notification_messages", ["status"], unique=False)
op.create_index(op.f("ix_notification_messages_tenant_id"), "notification_messages", ["tenant_id"], unique=False)
op.create_index("ix_notification_messages_due", "notification_messages", ["tenant_id", "status", "not_before_at"], unique=False)
op.create_index("ix_notification_messages_source", "notification_messages", ["tenant_id", "source_module", "source_resource_type", "source_resource_id"], unique=False)
op.create_index("ix_notification_messages_tenant_recipient", "notification_messages", ["tenant_id", "recipient_type", "recipient_id"], unique=False)
op.create_index("ix_notification_messages_tenant_status", "notification_messages", ["tenant_id", "status"], unique=False)
op.create_table(
"notification_delivery_attempts",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("notification_id", sa.String(length=36), nullable=False),
sa.Column("attempt_no", sa.Integer(), nullable=False),
sa.Column("channel", sa.String(length=40), nullable=False),
sa.Column("provider", sa.String(length=100), nullable=True),
sa.Column("status", sa.String(length=40), nullable=False),
sa.Column("started_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("external_message_id", sa.String(length=255), nullable=True),
sa.Column("error", sa.Text(), nullable=True),
sa.Column("details", sa.JSON(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(
["notification_id"],
["notification_messages.id"],
name=op.f("fk_notification_delivery_attempts_notification_id_notification_messages"),
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_notification_delivery_attempts")),
)
op.create_index(op.f("ix_notification_delivery_attempts_channel"), "notification_delivery_attempts", ["channel"], unique=False)
op.create_index(op.f("ix_notification_delivery_attempts_notification_id"), "notification_delivery_attempts", ["notification_id"], unique=False)
op.create_index(op.f("ix_notification_delivery_attempts_provider"), "notification_delivery_attempts", ["provider"], unique=False)
op.create_index(op.f("ix_notification_delivery_attempts_status"), "notification_delivery_attempts", ["status"], unique=False)
op.create_index(op.f("ix_notification_delivery_attempts_tenant_id"), "notification_delivery_attempts", ["tenant_id"], unique=False)
op.create_index("ix_notification_attempts_notification", "notification_delivery_attempts", ["notification_id", "attempt_no"], unique=False)
op.create_index("ix_notification_attempts_tenant_status", "notification_delivery_attempts", ["tenant_id", "status"], unique=False)
def downgrade() -> None:
op.drop_table("notification_delivery_attempts")
op.drop_table("notification_messages")

View File

@@ -0,0 +1,41 @@
"""notification preferences
Revision ID: 6f7a8b9c0d1e
Revises: 5e6f7a8b9c0d
Create Date: 2026-07-13 00:00:00.000000
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "6f7a8b9c0d1e"
down_revision = "5e6f7a8b9c0d"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"notification_preferences",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("user_id", sa.String(length=36), nullable=False),
sa.Column("show_unread_badge", sa.Boolean(), nullable=False),
sa.Column("email_enabled", sa.Boolean(), nullable=False),
sa.Column("email_digest_enabled", sa.Boolean(), nullable=False),
sa.Column("muted_source_modules", sa.JSON(), nullable=False),
sa.Column("metadata", sa.JSON(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_notification_preferences")),
sa.UniqueConstraint("tenant_id", "user_id", name="uq_notification_preferences_tenant_user"),
)
op.create_index(op.f("ix_notification_preferences_tenant_id"), "notification_preferences", ["tenant_id"], unique=False)
op.create_index("ix_notification_preferences_tenant_user", "notification_preferences", ["tenant_id", "user_id"], unique=False)
op.create_index(op.f("ix_notification_preferences_user_id"), "notification_preferences", ["user_id"], unique=False)
def downgrade() -> None:
op.drop_table("notification_preferences")

View File

@@ -0,0 +1,2 @@
from __future__ import annotations

View File

@@ -0,0 +1,188 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from govoplan_core.auth import ApiPrincipal, get_api_principal, has_scope
from govoplan_core.db.session import get_session
from govoplan_notifications.backend.manifest import ADMIN_SCOPE, DISPATCH_SCOPE, READ_SCOPE, WRITE_SCOPE
from govoplan_notifications.backend.schemas import (
NotificationCreateRequest,
NotificationDeliverPendingRequest,
NotificationDeliveryResultResponse,
NotificationListResponse,
NotificationPreferencesResponse,
NotificationPreferencesUpdateRequest,
NotificationResponse,
NotificationSummaryResponse,
NotificationUpdateRequest,
)
from govoplan_notifications.backend.service import (
NotificationError,
create_notification,
deliver_notification,
deliver_pending,
get_notification,
get_notification_preferences,
list_notifications,
notification_preferences_response,
notification_response,
notification_summary,
update_notification_preferences,
update_notification,
)
router = APIRouter(prefix="/notifications", tags=["notifications"])
def _require_scope(principal: ApiPrincipal, scope: str) -> None:
if not has_scope(principal, scope):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"Missing scope: {scope}")
def _notification_http_error(exc: NotificationError) -> HTTPException:
if str(exc) == "Notification not found":
return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
def _response(notification) -> NotificationResponse:
return NotificationResponse.model_validate(notification_response(notification))
@router.get("", response_model=NotificationListResponse)
def api_list_notifications(
status_filter: str | None = Query(default=None, alias="status"),
channel: str | None = None,
source_module: str | None = None,
recipient_id: str | None = None,
limit: int = Query(default=100, ge=1, le=500),
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> NotificationListResponse:
_require_scope(principal, READ_SCOPE)
notifications = list_notifications(
session,
tenant_id=principal.tenant_id,
status=status_filter,
channel=channel,
source_module=source_module,
recipient_id=recipient_id,
limit=limit,
)
return NotificationListResponse(notifications=[_response(notification) for notification in notifications])
@router.get("/summary", response_model=NotificationSummaryResponse)
def api_notification_summary(
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> NotificationSummaryResponse:
_require_scope(principal, READ_SCOPE)
return NotificationSummaryResponse.model_validate(notification_summary(session, tenant_id=principal.tenant_id, user_id=principal.user.id))
@router.get("/preferences/me", response_model=NotificationPreferencesResponse)
def api_get_my_notification_preferences(
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> NotificationPreferencesResponse:
_require_scope(principal, READ_SCOPE)
preference = get_notification_preferences(session, tenant_id=principal.tenant_id, user_id=principal.user.id)
return NotificationPreferencesResponse.model_validate(notification_preferences_response(preference))
@router.put("/preferences/me", response_model=NotificationPreferencesResponse)
def api_update_my_notification_preferences(
payload: NotificationPreferencesUpdateRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> NotificationPreferencesResponse:
_require_scope(principal, WRITE_SCOPE)
preference = update_notification_preferences(session, tenant_id=principal.tenant_id, user_id=principal.user.id, payload=payload)
session.commit()
return NotificationPreferencesResponse.model_validate(notification_preferences_response(preference))
@router.post("", response_model=NotificationResponse, status_code=status.HTTP_201_CREATED)
def api_create_notification(
payload: NotificationCreateRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> NotificationResponse:
_require_scope(principal, WRITE_SCOPE)
try:
notification = create_notification(session, tenant_id=principal.tenant_id, payload=payload)
except NotificationError as exc:
raise _notification_http_error(exc) from exc
session.commit()
return _response(notification)
@router.post("/deliver-pending", response_model=NotificationDeliveryResultResponse)
def api_deliver_pending(
payload: NotificationDeliverPendingRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> NotificationDeliveryResultResponse:
_require_scope(principal, DISPATCH_SCOPE)
if payload.tenant_id is not None:
_require_scope(principal, ADMIN_SCOPE)
result = deliver_pending(session, tenant_id=payload.tenant_id or principal.tenant_id, limit=payload.limit)
session.commit()
return NotificationDeliveryResultResponse.model_validate(result)
@router.get("/{notification_id}", response_model=NotificationResponse)
def api_get_notification(
notification_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> NotificationResponse:
_require_scope(principal, READ_SCOPE)
try:
return _response(get_notification(session, tenant_id=principal.tenant_id, notification_id=notification_id))
except NotificationError as exc:
raise _notification_http_error(exc) from exc
@router.patch("/{notification_id}", response_model=NotificationResponse)
def api_update_notification(
notification_id: str,
payload: NotificationUpdateRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> NotificationResponse:
_require_scope(principal, WRITE_SCOPE)
try:
notification = update_notification(session, tenant_id=principal.tenant_id, notification_id=notification_id, payload=payload)
except NotificationError as exc:
raise _notification_http_error(exc) from exc
session.commit()
return _response(notification)
@router.post("/{notification_id}/deliver", response_model=NotificationDeliveryResultResponse)
def api_deliver_notification(
notification_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> NotificationDeliveryResultResponse:
_require_scope(principal, DISPATCH_SCOPE)
try:
notification = deliver_notification(session, notification_id=notification_id)
except NotificationError as exc:
raise _notification_http_error(exc) from exc
session.commit()
sent = 1 if notification.status == "sent" else 0
failed = 1 if notification.status == "failed" else 0
skipped = 1 if notification.status == "skipped" else 0
return NotificationDeliveryResultResponse(
notification=_response(notification),
processed=1,
sent=sent,
failed=failed,
skipped=skipped,
errors=[notification.last_error] if notification.last_error else [],
)

View File

@@ -0,0 +1,138 @@
from __future__ import annotations
from datetime import datetime
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
NotificationStatus = Literal["pending", "queued", "sending", "sent", "failed", "skipped", "cancelled"]
class NotificationCreateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
source_module: str = Field(min_length=1, max_length=100)
source_resource_type: str = Field(min_length=1, max_length=100)
source_resource_id: str | None = Field(default=None, max_length=255)
event_kind: str = Field(min_length=1, max_length=100)
channel: str = Field(default="inbox", max_length=40)
recipient: str | None = Field(default=None, max_length=500)
recipient_type: str | None = Field(default=None, max_length=40)
recipient_id: str | None = Field(default=None, max_length=255)
recipient_label: str | None = Field(default=None, max_length=500)
subject: str | None = Field(default=None, max_length=500)
body_text: str | None = None
body_html: str | None = None
action_url: str | None = Field(default=None, max_length=1000)
priority: int = 0
not_before_at: datetime | None = None
enqueue_delivery: bool = True
payload: dict[str, Any] = Field(default_factory=dict)
metadata: dict[str, Any] = Field(default_factory=dict)
class NotificationUpdateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
status: Literal["read", "acknowledged", "cancelled"] | None = None
metadata: dict[str, Any] | None = None
class NotificationDeliverPendingRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
tenant_id: str | None = Field(default=None, max_length=36)
limit: int = Field(default=50, ge=1, le=500)
class NotificationPreferencesUpdateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
show_unread_badge: bool | None = None
email_enabled: bool | None = None
email_digest_enabled: bool | None = None
muted_source_modules: list[str] | None = None
metadata: dict[str, Any] | None = None
class NotificationPreferencesResponse(BaseModel):
tenant_id: str
user_id: str
show_unread_badge: bool = True
email_enabled: bool = False
email_digest_enabled: bool = False
muted_source_modules: list[str] = Field(default_factory=list)
metadata: dict[str, Any] = Field(default_factory=dict)
class NotificationDeliveryAttemptResponse(BaseModel):
id: str
notification_id: str
attempt_no: int
channel: str
provider: str | None = None
status: str
started_at: datetime | None = None
finished_at: datetime | None = None
external_message_id: str | None = None
error: str | None = None
details: dict[str, Any] = Field(default_factory=dict)
created_at: datetime
updated_at: datetime
class NotificationResponse(BaseModel):
id: str
tenant_id: str
source_module: str
source_resource_type: str
source_resource_id: str | None = None
event_kind: str
channel: str
recipient: str | None = None
recipient_type: str | None = None
recipient_id: str | None = None
recipient_label: str | None = None
subject: str | None = None
body_text: str | None = None
body_html: str | None = None
action_url: str | None = None
priority: int
status: str
not_before_at: datetime | None = None
queued_at: datetime | None = None
sent_at: datetime | None = None
failed_at: datetime | None = None
read_at: datetime | None = None
acknowledged_at: datetime | None = None
cancelled_at: datetime | None = None
attempt_count: int
last_error: str | None = None
external_message_id: str | None = None
payload: dict[str, Any] = Field(default_factory=dict)
metadata: dict[str, Any] = Field(default_factory=dict)
attempts: list[NotificationDeliveryAttemptResponse] = Field(default_factory=list)
created_at: datetime
updated_at: datetime
class NotificationListResponse(BaseModel):
notifications: list[NotificationResponse] = Field(default_factory=list)
class NotificationSummaryResponse(BaseModel):
total: int = 0
unread: int = 0
pending: int = 0
failed: int = 0
show_unread_badge: bool = True
class NotificationDeliveryResultResponse(BaseModel):
notification: NotificationResponse | None = None
processed: int = 0
sent: int = 0
failed: int = 0
skipped: int = 0
errors: list[str] = Field(default_factory=list)

View File

@@ -0,0 +1,466 @@
from __future__ import annotations
from collections.abc import Mapping
from datetime import datetime, timezone
from email.message import EmailMessage
from pathlib import Path
from typing import Any
from sqlalchemy import or_
from sqlalchemy.orm import Session
from govoplan_core.core.notifications import NotificationDispatchRequest
from govoplan_core.db.base import utcnow
from govoplan_notifications.backend.db.models import NotificationDeliveryAttempt, NotificationMessage, NotificationPreference
from govoplan_notifications.backend.schemas import NotificationCreateRequest, NotificationPreferencesUpdateRequest, NotificationUpdateRequest
class NotificationError(ValueError):
pass
PENDING_STATUSES = {"pending", "queued", "failed"}
def response_datetime(value: datetime | None) -> datetime | None:
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def _now() -> datetime:
return utcnow()
def _clean_channel(value: str) -> str:
channel = value.strip().lower()
if not channel:
raise NotificationError("Notification channel is required")
return channel
def _clean_source_modules(values: list[str]) -> list[str]:
cleaned: list[str] = []
seen: set[str] = set()
for value in values:
item = str(value).strip().lower()
if not item or item in seen:
continue
cleaned.append(item[:100])
seen.add(item)
return cleaned
def create_notification(
session: Session,
*,
tenant_id: str,
payload: NotificationCreateRequest,
) -> NotificationMessage:
notification = NotificationMessage(
tenant_id=tenant_id,
source_module=payload.source_module,
source_resource_type=payload.source_resource_type,
source_resource_id=payload.source_resource_id,
event_kind=payload.event_kind,
channel=_clean_channel(payload.channel),
recipient=payload.recipient,
recipient_type=payload.recipient_type,
recipient_id=payload.recipient_id,
recipient_label=payload.recipient_label,
subject=payload.subject,
body_text=payload.body_text,
body_html=payload.body_html,
action_url=payload.action_url,
priority=payload.priority,
not_before_at=payload.not_before_at,
status="queued" if payload.enqueue_delivery else "pending",
queued_at=_now() if payload.enqueue_delivery else None,
payload=payload.payload,
metadata_=payload.metadata,
)
if notification.channel == "mail" and not notification.recipient:
notification.status = "skipped"
notification.last_error = "Mail notification has no recipient address"
session.add(notification)
session.flush()
if payload.enqueue_delivery and notification.status == "queued":
_enqueue_celery_delivery(notification.id)
return notification
def enqueue_dispatch_request(
session: Session,
request: NotificationDispatchRequest,
*,
enqueue_delivery: bool = True,
) -> NotificationMessage:
return create_notification(
session,
tenant_id=request.tenant_id,
payload=NotificationCreateRequest(
source_module=request.source_module,
source_resource_type=request.source_resource_type,
source_resource_id=request.source_resource_id,
event_kind=request.event_kind,
channel=request.channel,
recipient=request.recipient,
recipient_type=request.recipient_type,
recipient_id=request.recipient_id,
recipient_label=request.recipient_label,
subject=request.subject,
body_text=request.body_text,
body_html=request.body_html,
action_url=request.action_url,
priority=request.priority,
not_before_at=request.not_before_at,
enqueue_delivery=enqueue_delivery,
payload=dict(request.payload),
metadata=dict(request.metadata),
),
)
def list_notifications(
session: Session,
*,
tenant_id: str,
status: str | None = None,
channel: str | None = None,
source_module: str | None = None,
recipient_id: str | None = None,
limit: int = 100,
) -> list[NotificationMessage]:
query = session.query(NotificationMessage).filter(
NotificationMessage.tenant_id == tenant_id,
NotificationMessage.deleted_at.is_(None),
)
if status:
query = query.filter(NotificationMessage.status == status)
if channel:
query = query.filter(NotificationMessage.channel == _clean_channel(channel))
if source_module:
query = query.filter(NotificationMessage.source_module == source_module)
if recipient_id:
query = query.filter(NotificationMessage.recipient_id == recipient_id)
return query.order_by(NotificationMessage.created_at.desc(), NotificationMessage.id.asc()).limit(limit).all()
def notification_summary(session: Session, *, tenant_id: str, user_id: str | None = None) -> dict[str, int | bool]:
base_query = session.query(NotificationMessage).filter(
NotificationMessage.tenant_id == tenant_id,
NotificationMessage.deleted_at.is_(None),
)
active_query = base_query.filter(NotificationMessage.status.notin_(["cancelled", "skipped"]))
show_unread_badge = True
if user_id:
show_unread_badge = get_notification_preferences(session, tenant_id=tenant_id, user_id=user_id).show_unread_badge
return {
"total": base_query.count(),
"unread": active_query.filter(NotificationMessage.read_at.is_(None)).count(),
"pending": active_query.filter(NotificationMessage.status.in_(sorted(PENDING_STATUSES))).count(),
"failed": active_query.filter(NotificationMessage.status == "failed").count(),
"show_unread_badge": show_unread_badge,
}
def get_notification(session: Session, *, tenant_id: str, notification_id: str) -> NotificationMessage:
notification = (
session.query(NotificationMessage)
.filter(
NotificationMessage.tenant_id == tenant_id,
NotificationMessage.id == notification_id,
NotificationMessage.deleted_at.is_(None),
)
.first()
)
if notification is None:
raise NotificationError("Notification not found")
return notification
def update_notification(
session: Session,
*,
tenant_id: str,
notification_id: str,
payload: NotificationUpdateRequest,
) -> NotificationMessage:
notification = get_notification(session, tenant_id=tenant_id, notification_id=notification_id)
now = _now()
if payload.status == "read":
notification.read_at = notification.read_at or now
elif payload.status == "acknowledged":
notification.read_at = notification.read_at or now
notification.acknowledged_at = notification.acknowledged_at or now
elif payload.status == "cancelled":
notification.status = "cancelled"
notification.cancelled_at = notification.cancelled_at or now
if payload.metadata is not None:
notification.metadata_ = payload.metadata
session.flush()
return notification
def deliver_notification(
session: Session,
*,
notification_id: str,
settings: object | None = None,
) -> NotificationMessage:
notification = session.get(NotificationMessage, notification_id)
if notification is None or notification.deleted_at is not None:
raise NotificationError("Notification not found")
if notification.status in {"sent", "skipped", "cancelled"}:
return notification
if notification.not_before_at is not None and response_datetime(notification.not_before_at) > _now():
notification.status = "queued"
session.flush()
return notification
attempt = _start_attempt(notification)
try:
result = _deliver_by_channel(notification, settings=settings)
except Exception as exc: # noqa: BLE001 - persisted as delivery failure.
_finish_attempt(attempt, status="failed", error=str(exc))
notification.status = "failed"
notification.failed_at = _now()
notification.last_error = str(exc)
session.flush()
return notification
_finish_attempt(attempt, status=result["status"], provider=result.get("provider"), details=result)
notification.status = result["status"]
notification.sent_at = _now() if result["status"] == "sent" else notification.sent_at
notification.failed_at = _now() if result["status"] == "failed" else notification.failed_at
notification.last_error = result.get("error")
notification.external_message_id = result.get("external_message_id")
session.flush()
return notification
def deliver_pending(
session: Session,
*,
tenant_id: str | None = None,
limit: int = 50,
settings: object | None = None,
) -> dict[str, Any]:
now = _now()
query = session.query(NotificationMessage).filter(
NotificationMessage.deleted_at.is_(None),
NotificationMessage.status.in_(sorted(PENDING_STATUSES)),
or_(NotificationMessage.not_before_at.is_(None), NotificationMessage.not_before_at <= now),
)
if tenant_id:
query = query.filter(NotificationMessage.tenant_id == tenant_id)
notifications = query.order_by(NotificationMessage.priority.desc(), NotificationMessage.created_at.asc()).limit(limit).all()
result = {"processed": 0, "sent": 0, "failed": 0, "skipped": 0, "errors": []}
for notification in notifications:
result["processed"] += 1
delivered = deliver_notification(session, notification_id=notification.id, settings=settings)
if delivered.status == "sent":
result["sent"] += 1
elif delivered.status == "skipped":
result["skipped"] += 1
elif delivered.status == "failed":
result["failed"] += 1
if delivered.last_error:
result["errors"].append(delivered.last_error)
return result
def get_notification_preferences(session: Session, *, tenant_id: str, user_id: str, create: bool = False) -> NotificationPreference:
preference = (
session.query(NotificationPreference)
.filter(
NotificationPreference.tenant_id == tenant_id,
NotificationPreference.user_id == user_id,
)
.first()
)
if preference is not None:
return preference
if not create:
return NotificationPreference(
tenant_id=tenant_id,
user_id=user_id,
show_unread_badge=True,
email_enabled=False,
email_digest_enabled=False,
muted_source_modules=[],
metadata_={},
)
preference = NotificationPreference(
tenant_id=tenant_id,
user_id=user_id,
show_unread_badge=True,
email_enabled=False,
email_digest_enabled=False,
muted_source_modules=[],
metadata_={},
)
session.add(preference)
session.flush()
return preference
def update_notification_preferences(
session: Session,
*,
tenant_id: str,
user_id: str,
payload: NotificationPreferencesUpdateRequest,
) -> NotificationPreference:
preference = get_notification_preferences(session, tenant_id=tenant_id, user_id=user_id, create=True)
if payload.show_unread_badge is not None:
preference.show_unread_badge = payload.show_unread_badge
if payload.email_enabled is not None:
preference.email_enabled = payload.email_enabled
if payload.email_digest_enabled is not None:
preference.email_digest_enabled = payload.email_digest_enabled
if payload.muted_source_modules is not None:
preference.muted_source_modules = _clean_source_modules(payload.muted_source_modules)
if payload.metadata is not None:
preference.metadata_ = payload.metadata
session.flush()
return preference
def notification_preferences_response(preference: NotificationPreference) -> dict[str, Any]:
return {
"tenant_id": preference.tenant_id,
"user_id": preference.user_id,
"show_unread_badge": preference.show_unread_badge,
"email_enabled": preference.email_enabled,
"email_digest_enabled": preference.email_digest_enabled,
"muted_source_modules": _clean_source_modules(preference.muted_source_modules or []),
"metadata": preference.metadata_ or {},
}
def _start_attempt(notification: NotificationMessage) -> NotificationDeliveryAttempt:
notification.status = "sending"
notification.attempt_count += 1
attempt = NotificationDeliveryAttempt(
tenant_id=notification.tenant_id,
notification_id=notification.id,
attempt_no=notification.attempt_count,
channel=notification.channel,
status="sending",
started_at=_now(),
details={},
)
notification.attempts.append(attempt)
return attempt
def _finish_attempt(
attempt: NotificationDeliveryAttempt,
*,
status: str,
provider: str | None = None,
error: str | None = None,
details: Mapping[str, object] | None = None,
) -> None:
attempt.status = status
attempt.provider = provider
attempt.error = error
attempt.details = dict(details or {})
attempt.finished_at = _now()
if details and isinstance(details.get("external_message_id"), str):
attempt.external_message_id = str(details["external_message_id"])
def _deliver_by_channel(notification: NotificationMessage, *, settings: object | None) -> dict[str, Any]:
if notification.channel == "inbox":
return {"status": "sent", "provider": "inbox", "external_message_id": notification.id}
if notification.channel == "mail":
if not notification.recipient:
return {"status": "skipped", "provider": "mail", "error": "Mail notification has no recipient address"}
path = _write_local_mail(notification, settings=settings)
return {"status": "sent", "provider": "local_file_mail", "external_message_id": str(path), "path": str(path)}
return {"status": "skipped", "provider": notification.channel, "error": f"No delivery adapter configured for channel {notification.channel!r}"}
def _write_local_mail(notification: NotificationMessage, *, settings: object | None) -> Path:
root = Path(str(getattr(settings, "mock_mailbox_dir", "runtime/mock-mailbox"))) / "notifications"
root.mkdir(parents=True, exist_ok=True)
message = EmailMessage()
message["Subject"] = notification.subject or f"Notification: {notification.event_kind}"
message["From"] = "notifications@govoplan.local"
message["To"] = notification.recipient or "undisclosed-recipients:;"
message.set_content(notification.body_text or notification.subject or notification.event_kind)
if notification.body_html:
message.add_alternative(notification.body_html, subtype="html")
filename = f"{notification.created_at.strftime('%Y%m%d%H%M%S')}-{notification.id}.eml"
path = root / filename
path.write_bytes(bytes(message))
return path
def _enqueue_celery_delivery(notification_id: str) -> None:
try:
from govoplan_core.celery_app import celery
from govoplan_core.settings import settings
except Exception:
return
if not getattr(settings, "celery_enabled", False):
return
celery.send_task("govoplan.notifications.deliver", args=[notification_id], queue="notifications")
def notification_response(notification: NotificationMessage) -> dict[str, Any]:
return {
"id": notification.id,
"tenant_id": notification.tenant_id,
"source_module": notification.source_module,
"source_resource_type": notification.source_resource_type,
"source_resource_id": notification.source_resource_id,
"event_kind": notification.event_kind,
"channel": notification.channel,
"recipient": notification.recipient,
"recipient_type": notification.recipient_type,
"recipient_id": notification.recipient_id,
"recipient_label": notification.recipient_label,
"subject": notification.subject,
"body_text": notification.body_text,
"body_html": notification.body_html,
"action_url": notification.action_url,
"priority": notification.priority,
"status": notification.status,
"not_before_at": response_datetime(notification.not_before_at),
"queued_at": response_datetime(notification.queued_at),
"sent_at": response_datetime(notification.sent_at),
"failed_at": response_datetime(notification.failed_at),
"read_at": response_datetime(notification.read_at),
"acknowledged_at": response_datetime(notification.acknowledged_at),
"cancelled_at": response_datetime(notification.cancelled_at),
"attempt_count": notification.attempt_count,
"last_error": notification.last_error,
"external_message_id": notification.external_message_id,
"payload": notification.payload or {},
"metadata": notification.metadata_ or {},
"created_at": response_datetime(notification.created_at),
"updated_at": response_datetime(notification.updated_at),
"attempts": [notification_attempt_response(attempt) for attempt in notification.attempts],
}
def notification_attempt_response(attempt: NotificationDeliveryAttempt) -> dict[str, Any]:
return {
"id": attempt.id,
"notification_id": attempt.notification_id,
"attempt_no": attempt.attempt_no,
"channel": attempt.channel,
"provider": attempt.provider,
"status": attempt.status,
"started_at": response_datetime(attempt.started_at),
"finished_at": response_datetime(attempt.finished_at),
"external_message_id": attempt.external_message_id,
"error": attempt.error,
"details": attempt.details or {},
"created_at": response_datetime(attempt.created_at),
"updated_at": response_datetime(attempt.updated_at),
}

View File

@@ -0,0 +1 @@