"""ScheduleAttachment model. Besides the PUT endpoint, the insertion trigger on the contract_party table leads to the insertion of a record into the schedule_attachment table when the insertion record is of target_type "contributor". Both schedule and schedule_attachment point to the same entity. """ from abacus_common_logic.connectors.database import db from abacus_common_logic.models.base import BaseModel from sqlalchemy import Enum from abacus_schedule.constants.constants import SCHEDULE_ATTACHMENT_TARGET_TYPE class ScheduleAttachment(BaseModel): """ScheduleAttachment model.""" __tablename__ = 'schedule_attachment' schedule_attachment_id = db.Column(db.Integer, primary_key=True) schedule_id = db.Column( db.Integer, db.ForeignKey('schedule.schedule_id'), nullable=False ) target_type = db.Column( Enum(*SCHEDULE_ATTACHMENT_TARGET_TYPE, name='TARGET_TYPE', create_type=False), default=SCHEDULE_ATTACHMENT_TARGET_TYPE.CONTRIBUTION, nullable=False, ) target_id = db.Column(db.String(180), nullable=False) deleted_at = db.Column(db.DateTime, nullable=True) deleted_by = db.Column(db.String(180), nullable=True) @classmethod def get_by_id(cls, schedule_attachment_id: int): """Override to get non-deleted record. Args: schedule_attachment_id (int): Id of schedule_attachment. Returns: A schedule_attachment record. """ return cls.query.filter( cls.schedule_attachment_id == schedule_attachment_id, cls.deleted_by.is_(None), cls.deleted_at.is_(None), ).one_or_none() @classmethod def get_schedule_attachments_by_schedule_id( cls, schedule_id: int, limit: int, offset: int ) -> list: """Get a list of schedule_attachment's by schedule id. Args: schedule_id(int): Id of schedule. limit (int): The number of items to return; the size of the page. offset (int): The number of items to skip before returning results; the page num. Returns: A list of schedule attachments. """ query = cls.query.filter( cls.schedule_id == schedule_id, cls.deleted_by.is_(None), cls.deleted_at.is_(None), ) items = query.offset(offset).limit(limit).all() total_count = query.count() return items, total_count @classmethod def get_schedule_attachments( cls, schedule_id: int, target_ids: list, target_type: str ) -> list: """Get a list of schedule_attachment's. Args: schedule_id (int): id of the schedule target_ids (list): a list of target ids target_type (int): target type of schedule_attachment Returns: A list of schedule attachments. """ query = cls.query.filter( cls.schedule_id == schedule_id, cls.target_id.in_(target_ids), cls.target_type == target_type, ) return query.all()