"""Update booked_vendor_contract_snapshot. Populate booked_vendor_contract_snapshot table by adding all vendor's active contracts data values. For any vendors without an active contract, it will add the default contract data values to this table. """ from accounting import bvcs_queries from accounting import config from accounting.adapters.log import getlogger from accounting.data import get_db_adapter def update_bvcs(): """Update the booked_vendor_contract_snapshot table. Inserts vendors with contracts. For each vendor that doesn't have an active contract, use previous period's booked_vendor_contract details. If there are still vendors that have no past booked_vendor_contract, then insert default. This case will occur for vendors that don't have current or past contracts. """ db_adapter = get_db_adapter() logger = getlogger() logger.info('Updating vendors with contracts.') db_adapter.execute('START TRANSACTION;') try: db_adapter.execute( bvcs_queries.POPULATE_BVCS_SQL.format(config.PERIOD_ID)) no_contract_labels = get_labels_no_contracts() if no_contract_labels: db_adapter.execute( bvcs_queries.REPLACE_FROM_PREVIOUS_PERIOD_SQL.format( period_id=config.PERIOD_ID, last_period_id=config.PERIOD_ID - 1, label_ids=', '.join(str(i) for i in no_contract_labels))) no_bvcs_label_ids = get_labels_no_bvcs() if no_bvcs_label_ids: populate_default_contracts(no_bvcs_label_ids) except Exception as error: db_adapter.execute('ROLLBACK;') raise error db_adapter.execute('COMMIT;') def get_labels_no_contracts(): """Return a list of labels with no contracts. Returns: list """ db_adapter = get_db_adapter() label_ids = [] for label in db_adapter.fetch_rows(bvcs_queries.LABEL_NO_CONTRACT_SQL): label_ids.append(label[0]) return label_ids def get_labels_no_bvcs(): """Return a list of labels with no bvcs entries. Returns: list """ db_adapter = get_db_adapter() label_ids = [] labels = db_adapter.fetch_rows(bvcs_queries.LABELS_NO_BVCS_SQL.format( config.PERIOD_ID)) for label in labels: label_ids.append(label[0]) return label_ids def populate_default_contracts(label_ids): """Populate labels with no current or past contracts with default values. Args: label_ids (list): list of int label ids. """ db_adapter = get_db_adapter() sql_values = [] for label_id in label_ids: sql_values.append('({}, NOW(), {})'.format(config.PERIOD_ID, label_id)) db_adapter.execute(bvcs_queries.POPULATE_DEFAULT_CONTRACTS_SQL.format( ','.join(sql_values)))