"""Logic for store outages.""" from typing import Dict, List from analytics.config import STORES from analytics.constants.store import ALL_SOURCES from analytics.utils.data_availability import ( FIELD_STORE_ID, FIELD_TYPES, get_available_feeds, get_feeds_with_outages_v2, get_outage_stores, ) def get_stores(store_ids: List[str]) -> List[Dict]: """Get store metadata for store IDs. Args: store_ids (list): List of store IDs. Returns: list: A list of dicts containing store metadata. """ stores = [] feeds_with_outages = get_feeds_with_outages_v2().get("feed_statuses") for store_id in store_ids: store = None int_store_id = int(store_id) if int_store_id in STORES: store_name = STORES.get(int_store_id) store = {"store_id": int_store_id, "store_name": store_name} distributors = [] errors = [] for item in feeds_with_outages: if int_store_id == item.get("store_id"): distributor = item.get("distributor") if distributor not in distributors: distributors.append(item.get("distributor")) if "error" in item: errors.append( { "distributor": distributor, "error": item.get("error"), "feed_id": item.get("feed_id"), "feed_name": item.get("feed_name"), } ) store = {**store, "distributors": distributors, "errors": errors} stores.append(store) return stores def add_outage_error_to_stores(sources=ALL_SOURCES): """Add outage errors to stores if they are experiencing outages. Args: sources (list): A list of dicts {'id': storeid, 'name': storename}. Returns: list: A list of dicts enriched with errors, if there are any. """ outage_stores = get_outage_stores(get_available_feeds()) def _add_error_if_outage(store): store_outage = next( ( outage for outage in outage_stores if outage[FIELD_STORE_ID] == store["id"] ), None, ) if not store_outage: return {**store} return { **store, "error": {"types": store_outage[FIELD_TYPES], "code": "unreliable"}, } return list(map(_add_error_if_outage, sources))