"""CRUD operations around phf_mechadmin_track table in art_relations db.""" from sqlalchemy import Column from sqlalchemy import Enum from sqlalchemy import ForeignKey from sqlalchemy import Numeric from sqlalchemy import Integer from sqlalchemy import SmallInteger from sqlalchemy import String from sqlalchemy import TIMESTAMP from sqlalchemy import text from sqlalchemy.orm import relationship import mysql from constants import models as models_constants class PhfPublishingEscrow(mysql.BaseModel): """Class represents the phf_publishing_escrow table.""" __tablename__ = 'phf_publishing_escrow' phf_transaction_id = Column(Integer, primary_key=True) track_id = Column( ForeignKey('phf_mechadmin_track.track_id'), nullable=False, index=True) store = Column(String(30), nullable=False) transaction_type = Column(String(10)) usage_type = Column(SmallInteger) qty = Column(Integer, nullable=False) ownership = Column(Integer, nullable=False, server_default='1') royalty_rate = Column(Numeric(20, 11)) royalty = Column(Numeric(20, 11)) royalty_rate_calculated = Column(Numeric(20, 11), nullable=False) royalty_calculated = Column(Numeric(20, 11), nullable=False) gross_revenue = Column(Numeric(20, 11)) net_revenue = Column(Numeric(20, 11)) dist_fee = Column(Numeric(20, 11)) admin_fee = Column(Numeric(20, 11)) period_id = Column(SmallInteger, index=True) sales_file_name = Column(String(255), nullable=False) active = Column(Enum('Y', 'N'), nullable=False, server_default=text("'Y'")) last_modified = Column( TIMESTAMP, nullable=False, server_default=text('CURRENT_TIMESTAMP')) track = relationship('PhfMechadminTrack') def to_dict(self): """Convert PhfPublishingEscrow data to dict.""" data = { 'phf_transaction_id': self.phf_transaction_id, 'track_id': self.track_id, 'store': self.store, 'transaction_type': self.transaction_type, 'usage_type': self.usage_type, 'qty': self.qty, 'ownership': self.ownership, 'royalty_rate': self.royalty_rate, 'royalty': self.royalty, 'royalty_rate_calculated': self.royalty_rate_calculated, 'royalty_calculated': self.royalty_calculated, 'gross_revenue': self.gross_revenue, 'net_revenue': self.net_revenue, 'dist_fee': self.dist_fee, 'admin_fee': self.admin_fee, 'period_id': self.period_id, 'sales_file_name': self.sales_file_name, 'active': self.active, 'last_modified': self.last_modified } return data def safe_cast(val, to_type, default=None): """Cast the value to given type. Args: val (int|str|float): value to cast. to_type (class): type class to convert the value to. default (int|str|float): value to return in result if conversion fails. Returns: value (int|str|float): Converted or default value. """ try: return to_type(val) except (ValueError, TypeError): return default @mysql.wrap_db_errors def insert_phf_publishing_escrow(escrow_data): """Put new record into phf_publishing_escrow table. Args: escrow_data (dict): dict with publishing escrow data. Returns: PhfPublishingEscrow.phf_transaction_id (int): Created record id. """ for field in models_constants.ESCROW_NULLABLE_FIELDS: escrow_data[field] = safe_cast(escrow_data.get(field), float) escrow_data['usage_type'] = safe_cast(escrow_data.get('usage_type'), int) escrow = PhfPublishingEscrow(**escrow_data) with mysql.ar_db_session() as session: session.add(escrow) return escrow.phf_transaction_id @mysql.wrap_db_errors def get_phf_publishing_escrow_by_sales_file_name(sales_file_name): """Get the phf_publishing_escrow records for the given sales_file_name. Args: sales_file_name (str): file name to get the phf_publishing_escrow records for. Returns: publishing_escrow_records (list): list of objects matching the given sales_file_name. """ with mysql.ar_db_session() as session: publishing_escrow_records = ( session.query(PhfPublishingEscrow).filter_by( sales_file_name=sales_file_name)).all() return [record.to_dict() for record in publishing_escrow_records] @mysql.wrap_db_errors def update(phf_transaction_id, values): """Update the phf_publishing_escrow record. Args: phf_transaction_id (int): phf_transaction_id of PhfPublishingEscrow object saved in database. values (dict): key-value pair to update the phf_publishing_escrow record. """ with mysql.ar_db_session() as session: for field in models_constants.ESCROW_NULLABLE_FIELDS: values[field] = safe_cast(values.get(field), float) values['usage_type'] = safe_cast(values.get('usage_type'), int) (session.query(PhfPublishingEscrow) .filter( PhfPublishingEscrow.phf_transaction_id == phf_transaction_id) .update(values)) @mysql.wrap_db_errors def bulk_insert_phf_publishing_escrow(escrows_data): """Put list of items into phf_publishing_escrow table. Args: escrows_data (list): list of dicts with required escrow fields. """ with mysql.ar_db_session() as session: escrows = [] for escrow in escrows_data: for field in models_constants.ESCROW_NULLABLE_FIELDS: escrow[field] = safe_cast(escrow.get(field), float) escrow['usage_type'] = safe_cast(escrow.get('usage_type'), int) escrow = PhfPublishingEscrow(**escrow) escrows.append(escrow) session.bulk_save_objects(escrows) @mysql.wrap_db_errors def set_all_publishing_escrows_from_file_inactive(sales_file_name): """Make all escrows from file inactive. Args: sales_file_name (str): name of file to set inactive for. """ with mysql.ar_db_session() as session: session.query(PhfPublishingEscrow).filter_by( sales_file_name=sales_file_name, active='Y').update( {PhfPublishingEscrow.active: 'N'}, synchronize_session=False)