from typing import List from sqlalchemy.orm import Session from app.models.notification import Notification from app.schemas.notification import NotificationCreate, NotificationUpdate from app.services.base import CRUDBase class CRUDNotification(CRUDBase[Notification, NotificationCreate, NotificationUpdate]): def create_with_recipients(self, db: Session, *, obj_in: NotificationCreate, sender_id: int) -> Notification: recipient_ids = obj_in.recipient_ids obj_in_data = obj_in.dict(exclude={"recipient_ids"}) obj_in_data["sender_id"] = sender_id db_obj = Notification(**obj_in_data) db.add(db_obj) db.flush() for recipient_id in recipient_ids: db.execute( "INSERT INTO notification_recipients (notification_id, user_id) VALUES (?, ?)", (db_obj.id, recipient_id) ) db.commit() db.refresh(db_obj) return db_obj def get_by_sender(self, db: Session, *, sender_id: int) -> List[Notification]: return db.query(Notification).filter(Notification.sender_id == sender_id).all() def get_by_recipient(self, db: Session, *, recipient_id: int) -> List[Notification]: return db.query(Notification).join( Notification.recipients ).filter_by(id=recipient_id).all() notification_service = CRUDNotification(Notification)