Files
mono/shared/services/entry_associations.py
giles 8f8bc4fad9 Move entry_associations to shared — fix events cross-app import
entry_associations only uses HTTP fetch_data/call_action, no direct DB.
Events app imported it via ..post.services which doesn't exist in events.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 18:05:30 +00:00

76 lines
2.3 KiB
Python

"""Entry association helpers — shared across blog and events apps.
Only uses HTTP-based fetch_data/call_action, no direct DB access.
"""
from __future__ import annotations
from sqlalchemy.ext.asyncio import AsyncSession
from shared.infrastructure.actions import call_action, ActionError
from shared.infrastructure.data_client import fetch_data
from shared.contracts.dtos import CalendarEntryDTO, dto_from_dict
from shared.services.registry import services
async def toggle_entry_association(
session: AsyncSession,
post_id: int,
entry_id: int
) -> tuple[bool, str | None]:
"""
Toggle association between a post and calendar entry.
Returns (is_now_associated, error_message).
"""
post = await services.blog.get_post_by_id(session, post_id)
if not post:
return False, "Post not found"
try:
result = await call_action("events", "toggle-entry-post", payload={
"entry_id": entry_id, "content_type": "post", "content_id": post_id,
})
return result.get("is_associated", False), None
except ActionError as e:
return False, str(e)
async def get_post_entry_ids(
session: AsyncSession,
post_id: int
) -> set[int]:
"""
Get all entry IDs associated with this post.
Returns a set of entry IDs.
"""
raw = await fetch_data("events", "entry-ids-for-content",
params={"content_type": "post", "content_id": post_id},
required=False) or []
return set(raw)
async def get_associated_entries(
session: AsyncSession,
post_id: int,
page: int = 1,
per_page: int = 10
) -> dict:
"""
Get paginated associated entries for this post.
Returns dict with entries (CalendarEntryDTOs), total_count, and has_more.
"""
raw = await fetch_data("events", "associated-entries",
params={"content_type": "post", "content_id": post_id, "page": page},
required=False) or {"entries": [], "has_more": False}
entries = [dto_from_dict(CalendarEntryDTO, e) for e in raw.get("entries", [])]
has_more = raw.get("has_more", False)
total_count = len(entries) + (page - 1) * per_page
if has_more:
total_count += 1
return {
"entries": entries,
"total_count": total_count,
"has_more": has_more,
"page": page,
}