Neda/Back/domains/notifications/service.py
2026-03-07 19:09:49 +03:30

75 lines
2.1 KiB
Python

from sqlalchemy.ext.asyncio import AsyncSession
from domains.notifications.models import Notification, NotificationType
from domains.notifications.repo import (
create_notification,
get_user_notifications,
get_notification_by_id,
update_notification
)
async def send_public_notification(
db: AsyncSession,
title: str,
description: str,
sender_id: str,
receiver_ids: list[str]
):
notifications = []
for receiver_id in receiver_ids:
notification = Notification(
title=title,
description=description,
type=NotificationType.PUBLIC,
sender_id=sender_id,
receiver_id=receiver_id
)
db.add(notification)
notifications.append(notification)
await db.commit()
return notifications
async def send_join_request(
db: AsyncSession,
sender_id: str,
receiver_id: str,
group_id: str,
title: str,
description: str | None = None
):
notification = Notification(
title=title,
description=description,
type=NotificationType.JOIN_REQUEST,
sender_id=sender_id,
receiver_id=receiver_id,
group_id=group_id
)
return await create_notification(db, notification)
async def list_my_notifications(db: AsyncSession, user_id):
return await get_user_notifications(db, user_id)
async def respond_to_notification(
db: AsyncSession,
notification_id: str,
user_id: str,
is_accepted: bool
):
notification = await get_notification_by_id(db, notification_id)
if not notification:
raise ValueError("Notification not found")
if str(notification.receiver_id) != str(user_id):
raise ValueError("Permission denied")
notification.is_accepted = is_accepted
await update_notification(db, notification)
# If it's a join request and accepted, add user to group
if notification.type == NotificationType.JOIN_REQUEST and is_accepted:
from domains.groups.service import add_member_to_group
await add_member_to_group(db, notification.group_id, user_id)
return notification