"""Archive existing summary report if one exist.""" from lib import config from lib.constants import PAYMENT_GROUP_PAYMENT_REPORT_TYPES from lib.utils import aws from lib.utils import ows from tasks.payments_generate_export import helpers def archive_existing_summary_report_task(dag_run: dict, **kwargs): """Check if any reports exist in S3 bucket and copy them to an archive directory. Args: dag_run (dict): a dag's config """ event = helpers.get_event_from_params(dag_run, **kwargs) reports = ows.get_payment_group_payment_reports(event.target_id) if not reports: return summary_report = next( ( report for report in reports if report['report_type'] == PAYMENT_GROUP_PAYMENT_REPORT_TYPES.SUMMARY ), None ) report_export_url = summary_report.get('report_export_url') file_exists = report_export_url and aws.file_exists(report_export_url) if file_exists: payment_group_payment = ows.get_payment_group_payment_details(event.target_id) source = aws.split_path(report_export_url) destination = helpers.build_report_summary_archive_location( event.target_id, payment_group_payment.get('payment_name') ) aws.copy_file( source_bucket=config.S3_PAYMENTS_BUCKET_NAME, source_key=source.key, dest_key=destination.key ) aws.delete_files(bucket=config.S3_PAYMENTS_BUCKET_NAME, key=source.key)