""" Store module for split rules. Split rules are defined at the store level. This module contains function to lookup split rules. """ from flows.cable_calculation.consts.cable import Rules from flows.cable_calculation.consts.cable import Stores def get_store_by_provider(provider_id): """Store lookup. Return the store corresponding to a given provider. Args: provider_id (int): provider ID. Returns: flows.cable_calculation.consts.cable.Store: store. """ for store in Stores: if provider_id in store.provider_ids: return store return None def get_sorted_store_rules(store_id): """Get a set of rules for a given store sorted by most recent. Filter rules by the given store and sort them by start date (most recent first). Args: store_id (int): store id. Returns: tuple: sorted rules. """ # First pass to filter by store store_rules = ( split_rule for split_rule in Rules if split_rule.store_id == store_id) # Then we sorted by more recent first return sorted( store_rules, key=lambda rule: rule.start, reverse=True) def get_split_rule(effective_date, store_id): """Look up a split rule by date and store id. Return the rule that is in effect for a given store at the date given in parameter. Args: effective_date (datetime.date): date when the rule applies. store_id (int): store id. Returns: splits.SplitRule: split rule object or None if not found. """ # Look for the rule that is currently in effect for r in get_sorted_store_rules(store_id): if r.start <= effective_date: return r return None