refactor: 重构 Agent 模块为 AgentScope,删除旧版 CrewAI/LiteLLM 实现
This commit is contained in:
@@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from core.auth.models import CurrentUser
|
||||
from core.db import get_db
|
||||
from v1.inbox_messages.repository import SQLAlchemyInboxMessageRepository
|
||||
from v1.schedule_items.repository import SQLAlchemyScheduleItemRepository
|
||||
from v1.schedule_items.service import ScheduleItemService
|
||||
from v1.users.dependencies import get_current_user
|
||||
@@ -17,8 +18,10 @@ def get_schedule_item_service(
|
||||
user: Annotated[CurrentUser, Depends(get_current_user)],
|
||||
) -> ScheduleItemService:
|
||||
repository = SQLAlchemyScheduleItemRepository(session)
|
||||
inbox_repository = SQLAlchemyInboxMessageRepository(session)
|
||||
return ScheduleItemService(
|
||||
repository=repository,
|
||||
session=session,
|
||||
current_user=user,
|
||||
inbox_repository=inbox_repository,
|
||||
)
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
from typing import TYPE_CHECKING, Protocol, Sequence
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import func, select, update
|
||||
from sqlalchemy import func, select, update, delete
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from core.db.base_repository import BaseRepository
|
||||
from core.logging import get_logger
|
||||
from models.schedule_items import ScheduleItem
|
||||
from models.schedule_subscriptions import ScheduleSubscription
|
||||
from models.schedule_subscriptions import ScheduleSubscription, SubscriptionStatus
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
@@ -41,11 +41,31 @@ class ScheduleItemRepository(Protocol):
|
||||
page_size: int,
|
||||
) -> tuple[list[ScheduleItem], int]: ...
|
||||
async def create_subscription(self, data: dict) -> ScheduleSubscription: ...
|
||||
async def get_subscriptions_by_item_id(
|
||||
self, item_id: UUID
|
||||
) -> list[ScheduleSubscription]: ...
|
||||
async def get_subscription(
|
||||
self, item_id: UUID, subscriber_id: UUID
|
||||
) -> ScheduleSubscription | None: ...
|
||||
async def update_subscription_status(
|
||||
self, item_id: UUID, subscriber_id: UUID, status: SubscriptionStatus
|
||||
): ...
|
||||
async def delete_subscriptions_by_item_id(self, item_id: UUID): ...
|
||||
async def get_user_subscriptions(
|
||||
self, subscriber_id: UUID
|
||||
) -> list[ScheduleSubscription]: ...
|
||||
async def list_subscribed_items_by_date_range(
|
||||
self,
|
||||
subscriber_id: UUID,
|
||||
start_at: datetime,
|
||||
end_at: datetime,
|
||||
) -> Sequence[tuple[ScheduleItem, ScheduleSubscription]]: ...
|
||||
|
||||
|
||||
class SQLAlchemyScheduleItemRepository(BaseRepository[ScheduleItem]):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
super().__init__(session, ScheduleItem)
|
||||
self._session = session
|
||||
|
||||
async def get_by_item_id(
|
||||
self, item_id: UUID, owner_id: UUID
|
||||
@@ -181,3 +201,100 @@ class SQLAlchemyScheduleItemRepository(BaseRepository[ScheduleItem]):
|
||||
self._session.add(sub)
|
||||
await self._session.flush()
|
||||
return sub
|
||||
|
||||
async def get_subscriptions_by_item_id(
|
||||
self, item_id: UUID
|
||||
) -> list[ScheduleSubscription]:
|
||||
try:
|
||||
stmt = select(ScheduleSubscription).where(
|
||||
ScheduleSubscription.item_id == item_id,
|
||||
ScheduleSubscription.status == SubscriptionStatus.ACTIVE,
|
||||
)
|
||||
result = await self._session.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
except SQLAlchemyError:
|
||||
logger.exception("Failed to get subscriptions", item_id=str(item_id))
|
||||
raise
|
||||
|
||||
async def get_subscription(
|
||||
self, item_id: UUID, subscriber_id: UUID
|
||||
) -> ScheduleSubscription | None:
|
||||
try:
|
||||
stmt = select(ScheduleSubscription).where(
|
||||
ScheduleSubscription.item_id == item_id,
|
||||
ScheduleSubscription.subscriber_id == subscriber_id,
|
||||
)
|
||||
result = await self._session.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
except SQLAlchemyError:
|
||||
logger.exception("Failed to get subscription")
|
||||
raise
|
||||
|
||||
async def update_subscription_status(
|
||||
self, item_id: UUID, subscriber_id: UUID, status: SubscriptionStatus
|
||||
):
|
||||
try:
|
||||
stmt = (
|
||||
update(ScheduleSubscription)
|
||||
.where(
|
||||
ScheduleSubscription.item_id == item_id,
|
||||
ScheduleSubscription.subscriber_id == subscriber_id,
|
||||
)
|
||||
.values(status=status)
|
||||
)
|
||||
await self._session.execute(stmt)
|
||||
await self._session.flush()
|
||||
except SQLAlchemyError:
|
||||
logger.exception("Failed to update subscription status")
|
||||
raise
|
||||
|
||||
async def delete_subscriptions_by_item_id(self, item_id: UUID):
|
||||
try:
|
||||
stmt = delete(ScheduleSubscription).where(
|
||||
ScheduleSubscription.item_id == item_id
|
||||
)
|
||||
await self._session.execute(stmt)
|
||||
await self._session.flush()
|
||||
except SQLAlchemyError:
|
||||
logger.exception("Failed to delete subscriptions")
|
||||
raise
|
||||
|
||||
async def get_user_subscriptions(
|
||||
self, subscriber_id: UUID
|
||||
) -> list[ScheduleSubscription]:
|
||||
try:
|
||||
stmt = select(ScheduleSubscription).where(
|
||||
ScheduleSubscription.subscriber_id == subscriber_id,
|
||||
ScheduleSubscription.status == SubscriptionStatus.ACTIVE,
|
||||
)
|
||||
result = await self._session.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
except SQLAlchemyError:
|
||||
logger.exception("Failed to get user subscriptions")
|
||||
raise
|
||||
|
||||
async def list_subscribed_items_by_date_range(
|
||||
self,
|
||||
subscriber_id: UUID,
|
||||
start_at: datetime,
|
||||
end_at: datetime,
|
||||
) -> Sequence[tuple[ScheduleItem, ScheduleSubscription]]:
|
||||
try:
|
||||
stmt = (
|
||||
select(ScheduleItem, ScheduleSubscription)
|
||||
.join(
|
||||
ScheduleSubscription,
|
||||
ScheduleSubscription.item_id == ScheduleItem.id,
|
||||
)
|
||||
.where(ScheduleSubscription.subscriber_id == subscriber_id)
|
||||
.where(ScheduleSubscription.status == SubscriptionStatus.ACTIVE)
|
||||
.where(ScheduleItem.deleted_at.is_(None))
|
||||
.where(ScheduleItem.start_at >= start_at)
|
||||
.where(ScheduleItem.start_at <= end_at)
|
||||
.order_by(ScheduleItem.start_at.asc())
|
||||
)
|
||||
result = await self._session.execute(stmt)
|
||||
return [tuple(row) for row in result.all()]
|
||||
except SQLAlchemyError:
|
||||
logger.exception("Failed to list subscribed items")
|
||||
raise
|
||||
|
||||
@@ -71,3 +71,19 @@ async def share_schedule_item(
|
||||
service: Annotated[ScheduleItemService, Depends(get_schedule_item_service)],
|
||||
) -> ScheduleItemShareResponse:
|
||||
return await service.share(item_id, request)
|
||||
|
||||
|
||||
@router.post("/{item_id}/accept", response_model=dict)
|
||||
async def accept_subscription(
|
||||
item_id: UUID,
|
||||
service: Annotated[ScheduleItemService, Depends(get_schedule_item_service)],
|
||||
) -> dict:
|
||||
return await service.accept_subscription(item_id)
|
||||
|
||||
|
||||
@router.post("/{item_id}/reject", response_model=dict)
|
||||
async def reject_subscription(
|
||||
item_id: UUID,
|
||||
service: Annotated[ScheduleItemService, Depends(get_schedule_item_service)],
|
||||
) -> dict:
|
||||
return await service.reject_subscription(item_id)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Literal
|
||||
from typing import ClassVar
|
||||
from typing import Literal, ClassVar, Union
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field
|
||||
@@ -76,6 +76,7 @@ class ScheduleItemResponse(BaseModel):
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(from_attributes=True)
|
||||
|
||||
id: UUID
|
||||
owner_id: UUID
|
||||
title: str
|
||||
description: str | None = None
|
||||
start_at: datetime
|
||||
@@ -86,6 +87,8 @@ class ScheduleItemResponse(BaseModel):
|
||||
source_type: ScheduleItemSourceType
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
permission: int = 1
|
||||
is_owner: bool = False
|
||||
|
||||
|
||||
class ScheduleItemListItem(BaseModel):
|
||||
@@ -131,3 +134,50 @@ class ScheduleItemShareRequest(BaseModel):
|
||||
|
||||
class ScheduleItemShareResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
class CalendarInviteContent(BaseModel):
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["invite"]
|
||||
permission: int = Field(..., description="权限: 1=view, 4=edit, 8=invite")
|
||||
action: Literal["pending"] = "pending"
|
||||
|
||||
|
||||
class CalendarUpdateContent(BaseModel):
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["update"]
|
||||
title: str = Field(..., description="事件标题")
|
||||
action: Literal["updated"] = "updated"
|
||||
|
||||
|
||||
class CalendarDeleteContent(BaseModel):
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["delete"]
|
||||
title: str = Field(..., description="事件标题")
|
||||
action: Literal["deleted"] = "deleted"
|
||||
|
||||
|
||||
CalendarContent = Union[
|
||||
CalendarInviteContent, CalendarUpdateContent, CalendarDeleteContent
|
||||
]
|
||||
|
||||
|
||||
def parse_calendar_content(content: str | None) -> CalendarContent | None:
|
||||
if not content:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(content)
|
||||
content_type = data.get("type")
|
||||
if content_type == "invite":
|
||||
return CalendarInviteContent(**data)
|
||||
elif content_type == "update":
|
||||
return CalendarUpdateContent(**data)
|
||||
elif content_type == "delete":
|
||||
return CalendarDeleteContent(**data)
|
||||
else:
|
||||
raise ValueError(f"Unknown calendar content type: {content_type}")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
from typing import TYPE_CHECKING, Protocol, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import HTTPException
|
||||
@@ -10,9 +10,11 @@ from sqlalchemy.exc import SQLAlchemyError
|
||||
from core.auth.models import CurrentUser
|
||||
from core.db.base_service import BaseService
|
||||
from core.logging import get_logger
|
||||
from models.inbox_messages import InboxMessage, InboxMessageType
|
||||
from models.inbox_messages import InboxMessage, InboxMessageType, InboxMessageStatus
|
||||
from models.schedule_items import ScheduleItem
|
||||
from models.schedule_subscriptions import SubscriptionPermission, SubscriptionStatus
|
||||
from v1.auth.gateway import SupabaseAuthGateway
|
||||
from v1.inbox_messages.repository import InboxMessageRepository
|
||||
from v1.schedule_items.repository import ScheduleItemRepository
|
||||
from v1.schedule_items.schemas import (
|
||||
ScheduleItemCreateRequest,
|
||||
@@ -42,6 +44,7 @@ class ScheduleItemService(BaseService):
|
||||
_repository: ScheduleItemRepository
|
||||
_session: AsyncSession
|
||||
_auth_gateway: AuthByEmailGateway
|
||||
_inbox_repository: InboxMessageRepository
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -49,11 +52,15 @@ class ScheduleItemService(BaseService):
|
||||
session: AsyncSession,
|
||||
current_user: CurrentUser | None,
|
||||
auth_gateway: AuthByEmailGateway | None = None,
|
||||
inbox_repository: InboxMessageRepository | None = None,
|
||||
) -> None:
|
||||
super().__init__(current_user=current_user)
|
||||
self._repository = repository
|
||||
self._session = session
|
||||
self._auth_gateway = auth_gateway or SupabaseAuthGateway()
|
||||
if inbox_repository is None:
|
||||
raise ValueError("inbox_repository is required")
|
||||
self._inbox_repository = inbox_repository
|
||||
|
||||
async def create(self, request: ScheduleItemCreateRequest) -> ScheduleItemResponse:
|
||||
return await self._create_with_source(
|
||||
@@ -95,6 +102,15 @@ class ScheduleItemService(BaseService):
|
||||
|
||||
try:
|
||||
item = await self._repository.create(data)
|
||||
await self._repository.create_subscription(
|
||||
{
|
||||
"item_id": item.id,
|
||||
"subscriber_id": user_id,
|
||||
"permission": SubscriptionPermission.OWNER,
|
||||
"status": SubscriptionStatus.ACTIVE,
|
||||
"created_by": user_id,
|
||||
}
|
||||
)
|
||||
await self._session.commit()
|
||||
except SQLAlchemyError:
|
||||
await self._session.rollback()
|
||||
@@ -109,7 +125,7 @@ class ScheduleItemService(BaseService):
|
||||
user_id = self.require_user_id()
|
||||
|
||||
try:
|
||||
item = await self._repository.get_by_item_id(item_id, user_id)
|
||||
item = await self._repository.get_by_id(item_id)
|
||||
except SQLAlchemyError:
|
||||
logger.exception("Failed to get schedule item", item_id=str(item_id))
|
||||
raise HTTPException(
|
||||
@@ -119,7 +135,14 @@ class ScheduleItemService(BaseService):
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="Schedule item not found")
|
||||
|
||||
return self._to_response(item)
|
||||
is_owner = item.owner_id == user_id
|
||||
permission = 1
|
||||
if not is_owner:
|
||||
subscription = await self._repository.get_subscription(item_id, user_id)
|
||||
if subscription:
|
||||
permission = subscription.permission
|
||||
|
||||
return self._to_response(item, is_owner=is_owner, permission=permission)
|
||||
|
||||
async def update(
|
||||
self, item_id: UUID, request: ScheduleItemUpdateRequest
|
||||
@@ -157,6 +180,7 @@ class ScheduleItemService(BaseService):
|
||||
item = await self._repository.update_by_item_id(
|
||||
item_id, user_id, update_data
|
||||
)
|
||||
await self._notify_subscribers(item_id, existing.title, "updated")
|
||||
await self._session.commit()
|
||||
except SQLAlchemyError:
|
||||
await self._session.rollback()
|
||||
@@ -178,6 +202,9 @@ class ScheduleItemService(BaseService):
|
||||
if existing is None:
|
||||
raise HTTPException(status_code=404, detail="Schedule item not found")
|
||||
|
||||
title = existing.title
|
||||
await self._repository.delete_subscriptions_by_item_id(item_id)
|
||||
await self._notify_subscribers(item_id, title, "deleted")
|
||||
await self._repository.delete_by_item_id(item_id, user_id)
|
||||
await self._session.commit()
|
||||
except SQLAlchemyError:
|
||||
@@ -196,17 +223,30 @@ class ScheduleItemService(BaseService):
|
||||
raise HTTPException(status_code=400, detail="end_at must be after start_at")
|
||||
|
||||
try:
|
||||
items = await self._repository.list_by_date_range(
|
||||
user_id, request.start_at, request.end_at
|
||||
subscribed_items = (
|
||||
await self._repository.list_subscribed_items_by_date_range(
|
||||
user_id, request.start_at, request.end_at
|
||||
)
|
||||
)
|
||||
|
||||
results = []
|
||||
for item, subscription in subscribed_items:
|
||||
is_owner = item.owner_id == user_id
|
||||
results.append(
|
||||
self._to_response(
|
||||
item, is_owner=is_owner, permission=subscription.permission
|
||||
)
|
||||
)
|
||||
|
||||
results.sort(key=lambda x: x.start_at)
|
||||
|
||||
return results
|
||||
except SQLAlchemyError:
|
||||
logger.exception("Failed to list schedule items")
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Schedule item store unavailable"
|
||||
)
|
||||
|
||||
return [self._to_response(item) for item in items]
|
||||
|
||||
async def list_paginated(
|
||||
self,
|
||||
*,
|
||||
@@ -244,23 +284,91 @@ class ScheduleItemService(BaseService):
|
||||
item = await self._repository.get_by_id(item_id)
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="Schedule item not found")
|
||||
|
||||
inviter_permission = SubscriptionPermission.OWNER
|
||||
if item.owner_id != user_id:
|
||||
inviter_sub = await self._repository.get_subscription(item_id, user_id)
|
||||
if inviter_sub is None:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="You don't have permission to share this calendar",
|
||||
)
|
||||
inviter_permission = SubscriptionPermission(inviter_sub.permission)
|
||||
|
||||
request_permission = request._permission_value()
|
||||
if request_permission > inviter_permission:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Only owner can share this schedule item",
|
||||
detail=f"You can only share with permissions up to {inviter_permission}",
|
||||
)
|
||||
|
||||
target_user = await self._auth_gateway.get_user_by_email(request.email)
|
||||
recipient_id = UUID(target_user.id)
|
||||
message = InboxMessage(
|
||||
recipient_id=recipient_id,
|
||||
sender_id=user_id,
|
||||
message_type=InboxMessageType.CALENDAR,
|
||||
schedule_item_id=item.id,
|
||||
content=json.dumps({"permission": request._permission_value()}),
|
||||
created_by=user_id,
|
||||
|
||||
existing = await self._repository.get_subscription(item_id, recipient_id)
|
||||
if existing:
|
||||
if existing.status == SubscriptionStatus.PENDING:
|
||||
pass
|
||||
elif existing.status == SubscriptionStatus.UNSUBSCRIBED:
|
||||
await self._repository.update_subscription_status(
|
||||
item_id, recipient_id, SubscriptionStatus.PENDING
|
||||
)
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="User already has an active subscription to this calendar",
|
||||
)
|
||||
else:
|
||||
await self._repository.create_subscription(
|
||||
{
|
||||
"item_id": item.id,
|
||||
"subscriber_id": recipient_id,
|
||||
"permission": request_permission,
|
||||
"status": SubscriptionStatus.PENDING,
|
||||
"created_by": user_id,
|
||||
}
|
||||
)
|
||||
|
||||
existing_msg = await self._inbox_repository.get_calendar_invite(
|
||||
item.id, recipient_id
|
||||
)
|
||||
self._session.add(message)
|
||||
if existing_msg:
|
||||
if existing_msg.status == InboxMessageStatus.ACCEPTED:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="User already subscribed to this calendar",
|
||||
)
|
||||
elif existing_msg.status == InboxMessageStatus.PENDING:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="User already has a pending invitation to this calendar",
|
||||
)
|
||||
elif existing_msg.status == InboxMessageStatus.REJECTED:
|
||||
existing_msg.status = InboxMessageStatus.PENDING
|
||||
existing_msg.content = json.dumps(
|
||||
{
|
||||
"type": "invite",
|
||||
"permission": request_permission,
|
||||
"action": "pending",
|
||||
}
|
||||
)
|
||||
else:
|
||||
message = InboxMessage(
|
||||
recipient_id=recipient_id,
|
||||
sender_id=user_id,
|
||||
message_type=InboxMessageType.CALENDAR,
|
||||
schedule_item_id=item.id,
|
||||
content=json.dumps(
|
||||
{
|
||||
"type": "invite",
|
||||
"permission": request_permission,
|
||||
"action": "pending",
|
||||
}
|
||||
),
|
||||
created_by=user_id,
|
||||
)
|
||||
self._session.add(message)
|
||||
|
||||
await self._session.commit()
|
||||
except HTTPException:
|
||||
raise
|
||||
@@ -279,7 +387,12 @@ class ScheduleItemService(BaseService):
|
||||
|
||||
return ScheduleItemShareResponse(message="Calendar invitation sent")
|
||||
|
||||
def _to_response(self, item: ScheduleItem) -> ScheduleItemResponse:
|
||||
def _to_response(
|
||||
self,
|
||||
item: ScheduleItem,
|
||||
is_owner: bool = False,
|
||||
permission: int = 1,
|
||||
) -> ScheduleItemResponse:
|
||||
status_value = (
|
||||
item.status.value if hasattr(item.status, "value") else item.status
|
||||
)
|
||||
@@ -290,6 +403,7 @@ class ScheduleItemService(BaseService):
|
||||
)
|
||||
return ScheduleItemResponse(
|
||||
id=item.id,
|
||||
owner_id=item.owner_id,
|
||||
title=item.title,
|
||||
description=item.description,
|
||||
start_at=item.start_at,
|
||||
@@ -302,4 +416,112 @@ class ScheduleItemService(BaseService):
|
||||
source_type=ScheduleItemSourceType(str(source_type_value)),
|
||||
created_at=item.created_at,
|
||||
updated_at=item.updated_at,
|
||||
permission=permission if not is_owner else 7,
|
||||
is_owner=is_owner,
|
||||
)
|
||||
|
||||
async def accept_subscription(self, item_id: UUID) -> dict:
|
||||
user_id = self.require_user_id()
|
||||
|
||||
try:
|
||||
inbox = await self._inbox_repository.get_pending_calendar_invite(
|
||||
item_id, user_id
|
||||
)
|
||||
if inbox is None:
|
||||
raise HTTPException(
|
||||
status_code=404, detail="No pending invitation found"
|
||||
)
|
||||
|
||||
content = json.loads(inbox.content or "{}")
|
||||
permission = content.get("permission", 1)
|
||||
|
||||
existing = await self._repository.get_subscription(item_id, user_id)
|
||||
if existing:
|
||||
await self._repository.update_subscription_status(
|
||||
item_id, user_id, SubscriptionStatus.ACTIVE
|
||||
)
|
||||
else:
|
||||
await self._repository.create_subscription(
|
||||
{
|
||||
"item_id": item_id,
|
||||
"subscriber_id": user_id,
|
||||
"permission": permission,
|
||||
"status": SubscriptionStatus.ACTIVE,
|
||||
"created_by": inbox.sender_id,
|
||||
}
|
||||
)
|
||||
|
||||
inbox.status = InboxMessageStatus.ACCEPTED
|
||||
await self._session.commit()
|
||||
|
||||
return {"message": "Subscription accepted"}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
await self._session.rollback()
|
||||
logger.exception("Failed to accept subscription")
|
||||
raise HTTPException(status_code=503, detail="Failed to accept subscription")
|
||||
|
||||
async def reject_subscription(self, item_id: UUID) -> dict:
|
||||
user_id = self.require_user_id()
|
||||
|
||||
try:
|
||||
inbox = await self._inbox_repository.get_pending_calendar_invite(
|
||||
item_id, user_id
|
||||
)
|
||||
if inbox is None:
|
||||
raise HTTPException(
|
||||
status_code=404, detail="No pending invitation found"
|
||||
)
|
||||
|
||||
existing = await self._repository.get_subscription(item_id, user_id)
|
||||
if existing:
|
||||
await self._repository.update_subscription_status(
|
||||
item_id, user_id, SubscriptionStatus.UNSUBSCRIBED
|
||||
)
|
||||
|
||||
inbox.status = InboxMessageStatus.REJECTED
|
||||
await self._session.commit()
|
||||
|
||||
return {"message": "Subscription rejected"}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
await self._session.rollback()
|
||||
logger.exception("Failed to reject subscription")
|
||||
raise HTTPException(status_code=503, detail="Failed to reject subscription")
|
||||
|
||||
async def _notify_subscribers(
|
||||
self,
|
||||
item_id: UUID,
|
||||
title: str,
|
||||
action_type: Literal["updated", "deleted"],
|
||||
):
|
||||
user_id = self.require_user_id()
|
||||
|
||||
subscriptions = await self._repository.get_subscriptions_by_item_id(item_id)
|
||||
|
||||
for sub in subscriptions:
|
||||
if sub.subscriber_id == user_id:
|
||||
continue
|
||||
|
||||
content = json.dumps(
|
||||
{
|
||||
"type": action_type,
|
||||
"title": title,
|
||||
"action": action_type,
|
||||
}
|
||||
)
|
||||
|
||||
message = InboxMessage(
|
||||
recipient_id=sub.subscriber_id,
|
||||
sender_id=user_id,
|
||||
message_type=InboxMessageType.CALENDAR,
|
||||
schedule_item_id=item_id,
|
||||
content=content,
|
||||
created_by=user_id,
|
||||
)
|
||||
self._session.add(message)
|
||||
|
||||
if subscriptions:
|
||||
await self._session.commit()
|
||||
|
||||
Reference in New Issue
Block a user