"""Helpers for sales_approve tasks.""" from lib import constants from lib.abacus_event import AbacusEvent from lib.utils import aws from lib.utils import event from lib.utils import ows from lib.utils import paths PARENT_TABLE_NAME = 'sales_file' def get_event_from_params(dag_run: dict, **kwargs) -> AbacusEvent: """Get event from params passed to task callbacks. Args: dag_run (dict): config of the DAG this task belongs to kwargs (dict): any other optional arguments Returns: instance of an AbacusEvent """ abacus_event = event.get_abacus_event(dag_run, **kwargs) event.validate_event_for_handler( abacus_event, event_name=constants.DAG_SALES_APPROVE_EVENT_NAME, target_type=constants.DAG_SALES_APPROVE_TARGET_TYPE ) return abacus_event def get_abacus_state(sales_file_id: int) -> dict: """Find the 'approve_sales' abacus_state record for the parent sales_file. Args: sales_file_id (int): ID of the sales_file Returns the 'approve_sales' abacus_state record """ abacus_states = ows.get_abacus_states(PARENT_TABLE_NAME, sales_file_id) approve_sales_acton = next( ( abacus_state for abacus_state in abacus_states if abacus_state['action_name'] == constants.SALES_FILE_ACTIONS.APPROVE_SALES ), None ) if not approve_sales_acton: raise ValueError( f'{constants.SALES_FILE_ACTIONS.APPROVE_SALES} state not found' ) return approve_sales_acton def get_event_records(abacus_event: AbacusEvent) -> tuple: """Get sales_file details and parent accounting_period details from the abacus_event. Args: abacus_event (AbacusEvent): the abacus_event that triggered the DAG Returns: a tuple of sales_file and accounting_period details """ sales_file = ows.get_sales_file_details(abacus_event.target_id) accounting_period_id = sales_file.get('accounting_period_id') accounting_period = ows.get_accounting_period_details(accounting_period_id) return sales_file, accounting_period def build_sales_file_main_url( accounting_period: dict, sales_file: dict ) -> aws.S3Location: """Build S3 path to resulting sales_file parquet on S3. Args: accounting_period (dict): parent accounting_period details sales_file (dict): sales_file details Returns: an S3Location tuple that includes a key and url as a strings example key: {accounting_period_id}-{accounting_period_name}/ eligible-sales/{sales_file_id}-{sales_file_name}/results/ example url: s3://{env}-royalties-sales-files/ {accounting_period_id}-{accounting_period_name}/ eligible-sales/{sales_file_id}-{sales_file_name}/results/ """ accounting_period_slug = paths.build_period_slug( accounting_period.get('accounting_period_id'), accounting_period.get('accounting_period_name') ) sales_file_slug = paths.build_sales_file_slug( sales_file.get('sales_file_id'), sales_file.get('file_name') ) return aws.location( accounting_period_slug, constants.DIRECTORY_ELIGIBLE_SALES, sales_file_slug, constants.FILE_NAME_RESULTS_PARQUET )