"""Utility Functions for grats.""" from itertools import groupby from oto import response from backend.constants import error from backend.models import ows_carveouts def group_grats_by_tuid(grats): """Group list of grats by tuid field. Args: grats (list): List of InstantGrat.to_dict() objects. Returns: List of dicts in format [{'tuid': tuid, 'grats': [grats]}, ...]. """ items = [] for tuid, group in groupby(grats, lambda grat: grat.get('tuid')): item = {'tuid': tuid} grats_data = [] for item_grat in list(group): item_grat.pop('tuid') grats_data.append(item_grat) item['grats'] = grats_data items.append(item) return items def validate_provided_instant_grats_stores(store_ids): """Compare provided stores to a list of allowed stores from db. Args: store_ids (list): List of stores ids to validate. Returns: response.Response """ allowed_stores_res = ows_carveouts.get_stores_allowed_for_instant_grats() if not allowed_stores_res: return allowed_stores_res allowed_stores = allowed_stores_res.message allowed_store_ids = {store['id'] for store in allowed_stores} disallowed_stores = set(store_ids) - allowed_store_ids if disallowed_stores: invalid_stores = {str(store_id) for store_id in disallowed_stores} return response.create_error_response( code=error.VALIDATION_ERROR_CODE, message=error.VALIDATION_ERROR_INVALID_STORES_PROVIDED.format( ','.join(invalid_stores))) return response.Response()