"""import-delivery-history-ext-ddex.""" import uuid from ddex_ingester_common.constants.ddex_providers import ALTAFONTE, AWAL from ddex_ingester_common.helpers.s3_ddex import load_ddex_json from ddex_ingester_common.logging import utils as logging_utils from ddex_ingester_common.schemas.s3_schema import S3Schema from ddex_ingester_common.schemas.state_machine_schema import \ StateMachineSchema from lambdacommon.graphql import graphql import config from config import graphql_gateway from constants import queries logger = logging_utils.get_logger(config.app_logger) def handler(event, context): """Lambda entry point.""" context = StateMachineSchema().load(event) correlation_id = context.correlation_id or str(uuid.uuid4()) context.correlation_id = correlation_id logging_utils.update_logger_correlation_id(logger, correlation_id) logging_utils.update_logger_with_message_ids( logger, context.message_id, context.message_thread_id, context.execution_name ) logger.info(f'Received productId: {context.product.product_id}') parsed_ddex = S3Schema().load(load_ddex_json(event)) if not parsed_ddex.product.stores or context.ddex_provider == ALTAFONTE: return StateMachineSchema().dump(context) graphql_gateway.set_headers( { 'Orchard-User-Id': config.OA_USER, 'Correlation-Id': correlation_id, } ) if context.ddex_provider == AWAL: encoder_id = config.AWAL_ENCODER_ID else: encoder_id = config.SME_ENCODER_ID upc = str(context.product.upc) payload = parse_delivery_history( parsed_ddex.product.stores, upc, encoder_id ) try: graphql_gateway.execute( queries.import_delivery_history, {'data': {'deliveryHistory': payload}} ) except graphql.GraphQLError as err: raise Exception('Graphql error') from err except Exception as exp: raise Exception(f'Error importing delivery history.\n{exp}') from exp return StateMachineSchema().dump(context) def parse_delivery_history(delivery_history, upc, encoder_id): """Parse delivery history. Example delivery history: "DeliveryHistory": [ { "store_id": "spotify", "link": "spotify:album:368TKDyiyzFTwCyHJ0uWqc", "delivery_date": "2020-12-03" }, { "store_id": "apple", "link": "186235393", "delivery_date": "2020-12-02" }, { "store_id": "deezer", "link": "www.deezer.com/album/186235392", "delivery_date": null }, { "store_id": "vevo", "link": null, "delivery_date": "2020-12-01" } ] Args: delivery_history (list): Delivery history data upc (str): UPC Returns: list """ items = [] for store in delivery_history: if store.delivery_date and store.store_id: store_id = store.store_id.strip() store_id = config.STORES_MAPPING.get(store_id) or int(store_id) items.append( { 'storeId': store_id, 'dateDelivered': store.delivery_date.strip(), 'encoderId': encoder_id, 'upc': upc, } ) return items