"""Model for ContractParty. "AFTER INSERT" mysql database trigger on the contract_party table leads to the insertion of a record into the schedule and schedule_attachment tables when the insertion record is of target_type "contributor". """ from abacus_common_logic.connectors.database import db from abacus_common_logic.models.base import BaseModel from sqlalchemy import Enum from abacus_contract.constants.constants import CONTRACT_PARTY_TARGET_TYPES class ContractParty(BaseModel): """ContractParty model.""" __tablename__ = 'contract_party' contract_party_id = db.Column(db.Integer, primary_key=True) contract_id = db.Column( db.Integer, db.ForeignKey('contract.contract_id'), nullable=False ) target_type = db.Column( Enum( *CONTRACT_PARTY_TARGET_TYPES, name='target_type', create_type=False ), 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_contract_party( cls, contract_id: int, target_id: str, target_type: str ) -> dict: """Get a contract_party. Args: contract_id (str): id of the related contract target_id (str): id of the target_type target_type (str): must be one of 'contributor', 'label' Returns: a matching contract_party record. """ query = cls.query.filter( cls.contract_id == contract_id, cls.target_id == target_id, cls.target_type == target_type ) return query.first() @classmethod def get_by_contract_id( cls, contract_id: int, limit: int, offset: int, target_type: str = None ) -> tuple: """Get contract parties for a specified contract_id and/or target_type. The query returns all contract parties if target_type is None. Arg: contract_id(int): id of the contract limit (int): pagination limit offset (int): pagination offset target_type (str)(Optional): must be one of 'contributor', 'label' Returns: A tuple containing items and total count """ query = cls.query.filter( cls.contract_id == contract_id, cls.deleted_at.is_(None), cls.deleted_by.is_(None) ) if target_type: query = query.filter(cls.target_type == target_type) items = query.limit(limit).offset(offset).all() total_count = query.count() return items, total_count