from typing import Optional, List from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.models.notification import Notification class NotificationRepository: def __init__(self, db: AsyncSession): self.db = db async def get_by_id(self, notification_id: int) -> Optional[Notification]: result = await self.db.execute( select(Notification).where(Notification.id == notification_id) ) return result.scalar_one_or_none() async def get_list( self, user_id: Optional[int] = None, is_read: Optional[bool] = None, type: Optional[str] = None, page: int = 1, page_size: int = 20 ) -> List[Notification]: query = select(Notification) if user_id: query = query.where(Notification.user_id == user_id) if is_read is not None: query = query.where(Notification.is_read == is_read) if type: query = query.where(Notification.type == type) query = query.order_by(Notification.created_at.desc()) query = query.offset((page - 1) * page_size).limit(page_size) result = await self.db.execute(query) return list(result.scalars().all()) async def create(self, data: dict) -> Notification: notification = Notification(**data) self.db.add(notification) await self.db.flush() return notification async def mark_as_read(self, notification_id: int) -> bool: notification = await self.get_by_id(notification_id) if not notification: return False notification.is_read = True return True async def mark_all_as_read(self, user_id: int) -> int: result = await self.db.execute( select(Notification).where( Notification.user_id == user_id, Notification.is_read == False ) ) notifications = list(result.scalars().all()) for notification in notifications: notification.is_read = True return len(notifications) async def delete(self, notification_id: int) -> bool: notification = await self.get_by_id(notification_id) if not notification: return False await self.db.delete(notification) return True