Beispiel #1
0
class ProductBlockingKpi(UnifiedCalculationsScript):

    def __init__(self, data_provider, config_params=None, **kwargs):
        super(ProductBlockingKpi, self).__init__(data_provider, config_params=config_params, **kwargs)
        self.util = PepsicoUtil(None, data_provider)
        self.block = None

    def kpi_type(self):
        pass

    def calculate(self):
        if not self.util.filtered_matches.empty:
            self.util.filtered_scif, self.util.filtered_matches = \
                self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                     self.util.filtered_matches,
                                                                                     self.util.PRODUCT_BLOCKING)
            filtered_matches = self.util.filtered_matches.copy()
            if 'sub_category_fk' in filtered_matches.columns:
                filtered_matches = filtered_matches.drop(columns=['sub_category_fk'])
            self.block = Block(self.data_provider, custom_scif=self.util.filtered_scif,
                               custom_matches=filtered_matches)
            if not self.util.filtered_matches.empty:
                self.calculate_product_blocking()
            self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def calculate_product_blocking(self):
        external_targets = self.util.all_targets_unpacked[self.util.all_targets_unpacked['type'] == self.util.PRODUCT_BLOCKING]
        additional_block_params = {'check_vertical_horizontal': True, 'minimum_facing_for_block': 3,
                                   'include_stacking': True,
                                   'allowed_products_filters': {'product_type': ['Empty']}}
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(self.util.PRODUCT_BLOCKING)

        for i, row in external_targets.iterrows():
            # print row['Group Name']
            group_fk = self.util.custom_entities[self.util.custom_entities['name'] == row['Group Name']]['pk'].values[0]
            # filters = self.util.get_block_and_adjacency_filters(row)
            filters = self.util.get_block_filters(row)
            target = row['Target']
            additional_block_params.update({'minimum_block_ratio': float(target)/100})

            result_df = self.block.network_x_block_together(filters, additional=additional_block_params)
            score = max_ratio = 0
            result = self.util.commontools.get_yes_no_result(0)
            if not result_df.empty:
                max_ratio = result_df['facing_percentage'].max()
                result_df = result_df[result_df['is_block']==True]
                if not result_df.empty:
                    max_ratio = result_df['facing_percentage'].max()
                    result_df = result_df[result_df['facing_percentage'] == max_ratio]
                    result = self.util.commontools.get_yes_no_result(1)
                    orientation = result_df['orientation'].values[0]
                    score = self.util.commontools.get_kpi_result_value_pk_by_value(orientation.upper())
            # print score
            self.write_to_db_result(fk=kpi_fk, numerator_id=group_fk, denominator_id=self.util.store_id,
                                    numerator_result=max_ratio * 100,
                                    score=score, result=result, target=target, by_scene=True)
            self.util.block_results = self.util.block_results.append(pd.DataFrame([{'Group Name': row['Group Name'],
                                                                                    'Score':
                                                                                        result_df['is_block'].values[
                                                                                            0] if not result_df.empty else False}]))
class SosBrandOfSegmentKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(SosBrandOfSegmentKpi, self).__init__(data_provider,
                                                   config_params=config_params,
                                                   **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.BRAND_SOS_OF_SEGMENT)
        self.calculate_brand_out_of_sub_category_sos()
        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def calculate_brand_out_of_sub_category_sos(self):
        location_type_fk = self.util.all_templates[self.util.all_templates[ScifConsts.LOCATION_TYPE] == 'Primary Shelf'] \
            [ScifConsts.LOCATION_TYPE_FK].values[0]
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(
            self.util.BRAND_SOS_OF_SEGMENT)
        filtered_matches = self.util.filtered_matches[~(
            self.util.filtered_matches[ScifConsts.SUB_CATEGORY_FK].isnull())]
        products_df = self.util.all_products[[
            MatchesConsts.PRODUCT_FK, ScifConsts.BRAND_FK,
            ScifConsts.CATEGORY_FK
        ]]
        filtered_matches = filtered_matches.merge(products_df,
                                                  on=MatchesConsts.PRODUCT_FK,
                                                  how='left')
        sub_cat_df = filtered_matches.groupby(
            [ScifConsts.SUB_CATEGORY_FK],
            as_index=False).agg({MatchesConsts.WIDTH_MM_ADVANCE: np.sum})
        sub_cat_df.rename(
            columns={MatchesConsts.WIDTH_MM_ADVANCE: 'sub_cat_len'},
            inplace=True)
        brand_sub_cat_df = filtered_matches.groupby(
            [ScifConsts.BRAND_FK, ScifConsts.SUB_CATEGORY_FK],
            as_index=False).agg({MatchesConsts.WIDTH_MM_ADVANCE: np.sum})
        brand_sub_cat_df = brand_sub_cat_df.merge(
            sub_cat_df, on=ScifConsts.SUB_CATEGORY_FK, how='left')
        brand_sub_cat_df['sos'] = brand_sub_cat_df[
            MatchesConsts.WIDTH_MM_ADVANCE] / brand_sub_cat_df['sub_cat_len']
        for i, row in brand_sub_cat_df.iterrows():
            self.write_to_db_result(
                fk=kpi_fk,
                numerator_id=row[ScifConsts.BRAND_FK],
                numerator_result=row[MatchesConsts.WIDTH_MM_ADVANCE],
                denominator_id=row[ScifConsts.SUB_CATEGORY_FK],
                denominator_result=row['sub_cat_len'],
                result=row['sos'] * 100,
                context_id=location_type_fk)
            self.util.add_kpi_result_to_kpi_results_df([
                kpi_fk, row[ScifConsts.BRAND_FK],
                row[ScifConsts.SUB_CATEGORY_FK], row['sos'] * 100, None, None
            ])
class HeroAvailabilitySkuKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(HeroAvailabilitySkuKpi,
              self).__init__(data_provider,
                             config_params=config_params,
                             **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def calculate(self):
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.HERO_SKU_AVAILABILITY_SKU)
        self.calculate_kpi_for_main_shelf()
        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def kpi_type(self):
        pass

    def calculate_kpi_for_main_shelf(self):
        location_type_fk = self.util.all_templates[self.util.all_templates[ScifConsts.LOCATION_TYPE] == 'Primary Shelf'] \
            [ScifConsts.LOCATION_TYPE_FK].values[0]
        lvl3_ass_res = self.util.lvl3_ass_result
        if lvl3_ass_res.empty:
            return

        if not self.util.filtered_scif.empty:
            products_in_session = self.util.filtered_scif.loc[
                self.util.filtered_scif['facings'] > 0]['product_fk'].values
            products_df = self.util.all_products[[
                ScifConsts.PRODUCT_FK, ScifConsts.MANUFACTURER_FK
            ]]
            lvl3_ass_res.loc[
                lvl3_ass_res['product_fk'].isin(products_in_session),
                'in_store'] = 1
            lvl3_ass_res = lvl3_ass_res.merge(products_df,
                                              on=ScifConsts.PRODUCT_FK,
                                              how='left')
            for i, result in lvl3_ass_res.iterrows():
                score = result.in_store * 100
                custom_res = self.util.commontools.get_yes_no_result(score)
                self.write_to_db_result(fk=result.kpi_fk_lvl3,
                                        numerator_id=result.product_fk,
                                        numerator_result=result.in_store,
                                        result=custom_res,
                                        denominator_id=result.manufacturer_fk,
                                        denominator_result=1,
                                        score=score,
                                        context_id=location_type_fk)
                self.util.add_kpi_result_to_kpi_results_df([
                    result['kpi_fk_lvl3'], result['product_fk'],
                    self.util.store_id, custom_res, score, None
                ])
Beispiel #4
0
class SosVsTargetBrandKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(SosVsTargetBrandKpi, self).__init__(data_provider,
                                                  config_params=config_params,
                                                  **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.BRAND_SOS)
        self.calculate_brand_out_of_category_sos()
        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def calculate_brand_out_of_category_sos(self):
        location_type_fk = self.util.all_templates[self.util.all_templates[ScifConsts.LOCATION_TYPE] == 'Primary Shelf'] \
            [ScifConsts.LOCATION_TYPE_FK].values[0]
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(self.util.BRAND_SOS)
        filtered_scif = self.util.filtered_scif
        category_df = filtered_scif.groupby([ScifConsts.CATEGORY_FK],
                                            as_index=False).agg({
                                                'updated_gross_length':
                                                np.sum
                                            })
        category_df.rename(columns={'updated_gross_length': 'cat_len'},
                           inplace=True)
        brand_cat_df = filtered_scif.groupby(
            [ScifConsts.BRAND_FK, ScifConsts.CATEGORY_FK],
            as_index=False).agg({'updated_gross_length': np.sum})
        brand_cat_df = brand_cat_df.merge(category_df,
                                          on=ScifConsts.CATEGORY_FK,
                                          how='left')
        brand_cat_df['sos'] = brand_cat_df[
            'updated_gross_length'] / brand_cat_df['cat_len']
        for i, row in brand_cat_df.iterrows():
            self.write_to_db_result(
                fk=kpi_fk,
                numerator_id=row[ScifConsts.BRAND_FK],
                numerator_result=row['updated_gross_length'],
                denominator_id=row[ScifConsts.CATEGORY_FK],
                denominator_result=row['cat_len'],
                result=row['sos'] * 100,
                context_id=location_type_fk)
            self.util.add_kpi_result_to_kpi_results_df([
                kpi_fk, row[ScifConsts.BRAND_FK], row[ScifConsts.CATEGORY_FK],
                row['sos'] * 100, None, None
            ])
Beispiel #5
0
class BrandFullBayKpi(UnifiedCalculationsScript):

    def __init__(self, data_provider, config_params=None, **kwargs):
        super(BrandFullBayKpi, self).__init__(data_provider, config_params=config_params, **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.BRAND_FULL_BAY)
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(self.util.BRAND_FULL_BAY)
        external_kpi_targets = self.util.commontools.all_targets_unpacked[
            self.util.commontools.all_targets_unpacked['kpi_level_2_fk'] == kpi_fk]
        external_kpi_targets = external_kpi_targets.reset_index(drop=True)
        if not external_kpi_targets.empty:
            external_kpi_targets['group_fk'] = external_kpi_targets['Group Name'].apply(lambda x:
                                                                                        self.util.custom_entities[
                                                                                            self.util.custom_entities[
                                                                                                'name'] == x][
                                                                                            'pk'].values[0])
            filtered_matches = self.util.filtered_matches[~(self.util.filtered_matches['bay_number'] == -1)]
            if not filtered_matches.empty:
                scene_bay_product = filtered_matches.groupby(['scene_fk', 'bay_number', 'product_fk'],
                                                             as_index=False).agg({'count': np.sum})
                scene_bay_product = scene_bay_product.merge(self.util.all_products, on='product_fk', how='left')
                scene_bay = scene_bay_product.groupby(['scene_fk', 'bay_number'], as_index=False).agg({'count': np.sum})
                scene_bay.rename(columns={'count': 'total_facings'}, inplace=True)
                for i, row in external_kpi_targets.iterrows():
                    filters = self.util.get_full_bay_and_positional_filters(row)
                    brand_relevant_df = scene_bay_product[
                        self.util.toolbox.get_filter_condition(scene_bay_product, **filters)]
                    result_df = brand_relevant_df.groupby(['scene_fk', 'bay_number'], as_index=False).agg(
                        {'count': np.sum})
                    result_df = result_df.merge(scene_bay, on=['scene_fk', 'bay_number'], how='left')
                    result_df['ratio'] = result_df['count'] / result_df['total_facings']
                    target_ratio = float(self._config_params['ratio'])
                    result = len(result_df[result_df['ratio'] >= target_ratio])
                    self.write_to_db_result(fk=row['kpi_level_2_fk'], numerator_id=row['group_fk'], result=result,
                                            score=result, target=target_ratio*100)
                    self.util.add_kpi_result_to_kpi_results_df(
                        [row['kpi_level_2_fk'], row['group_fk'], None, None, result, None])

        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()
Beispiel #6
0
class HeroAvailabilitySkuKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(HeroAvailabilitySkuKpi,
              self).__init__(data_provider,
                             config_params=config_params,
                             **kwargs)
        self.util = PepsicoUtil(None, data_provider)
        self.kpi_name = self._config_params['kpi_type']

    def calculate(self):
        if self.util.commontools.are_all_bins_tagged:
            self.util.filtered_scif_secondary, self.util.filtered_matches_secondary = \
                self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif_secondary,
                                                                                     self.util.filtered_matches_secondary,
                                                                                     self.kpi_name)
            self.calculate_kpi_for_secondary_shelf()
            self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def kpi_type(self):
        pass

    def calculate_kpi_for_secondary_shelf(self):
        # scif for secondary should have display and store_area breakdown

        lvl3_ass_res = self.util.lvl3_ass_result
        if lvl3_ass_res.empty:
            return
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(self.kpi_name)
        ass_list = lvl3_ass_res[ScifConsts.PRODUCT_FK].values.tolist()
        filtered_scif = self.util.filtered_scif_secondary[self.util.filtered_scif_secondary[ScifConsts.PRODUCT_FK]. \
            isin(ass_list)]
        # products_in_session = filtered_scif.loc[filtered_scif['facings'] > 0]['product_fk'].values
        # lvl3_ass_res.loc[lvl3_ass_res['product_fk'].isin(products_in_session), 'in_store'] = 1
        assortment_scif = filtered_scif.drop_duplicates(subset=[
            ScifConsts.TEMPLATE_FK, 'store_area_fk', ScifConsts.PRODUCT_FK
        ])
        for i, result in assortment_scif.iterrows():
            score = 100
            custom_res = self.util.commontools.get_yes_no_result(score)
            self.write_to_db_result(fk=kpi_fk,
                                    numerator_id=result.product_fk,
                                    numerator_result=1,
                                    result=custom_res,
                                    denominator_id=result.template_fk,
                                    denominator_result=1,
                                    score=score,
                                    context_id=result.store_area_fk)
Beispiel #7
0
class PromoPriceKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(PromoPriceKpi, self).__init__(data_provider,
                                            config_params=config_params,
                                            **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.PROMO_PRICE_SCENE)
        sku_list = self.util.filtered_scif[ScifConsts.PRODUCT_FK]
        promo_price_kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(
            self.util.PROMO_PRICE_SCENE)
        for sku in sku_list:
            self.calculate_hero_sku_promo_price(sku, promo_price_kpi_fk)
        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def calculate_hero_sku_promo_price(self, sku, kpi_fk):
        price = 0
        prices_df = self.util.filtered_matches[(~(self.util.filtered_matches[
            MatchesConsts.PROMOTION_PRICE].isnull())) & (
                self.util.filtered_matches[ScifConsts.PRODUCT_FK] == sku)]
        if not prices_df.empty:
            price = 1
        result = self.util.commontools.get_yes_no_result(price)
        self.write_to_db_result(fk=kpi_fk,
                                numerator_id=sku,
                                denominator_id=sku,
                                result=result)
        self.util.add_kpi_result_to_kpi_results_df(
            [kpi_fk, sku, None, price, None, None])
class SosVsTargetSegmentKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(SosVsTargetSegmentKpi,
              self).__init__(data_provider,
                             config_params=config_params,
                             **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        # sos_targets = self.util.sos_vs_target_targets.copy()
        # sos_targets = sos_targets[sos_targets['type'] == self._config_params['kpi_type']]
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.PEPSICO_SEGMENT_SOS)
        # self.calculate_pepsico_segment_space_sos_vs_target(sos_targets)
        self.calculate_pepsico_segment_space_sos()
        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def calculate_pepsico_segment_space_sos(self):
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(
            self.util.PEPSICO_SEGMENT_SOS)
        filtered_matches = self.util.filtered_matches
        products_df = self.util.all_products[[
            MatchesConsts.PRODUCT_FK, ScifConsts.BRAND_FK,
            ScifConsts.CATEGORY_FK
        ]]
        filtered_matches = filtered_matches.merge(products_df,
                                                  on=MatchesConsts.PRODUCT_FK,
                                                  how='left')
        cat_df = filtered_matches.groupby([ScifConsts.CATEGORY_FK],
                                          as_index=False).agg({
                                              MatchesConsts.WIDTH_MM_ADVANCE:
                                              np.sum
                                          })
        cat_df.rename(columns={MatchesConsts.WIDTH_MM_ADVANCE: 'cat_len'},
                      inplace=True)
        # filtered_scif = filtered_scif[filtered_scif[ScifConsts.MANUFACTURER_FK] == self.util.own_manuf_fk]
        location_type_fk = self.util.all_templates[self.util.all_templates[ScifConsts.LOCATION_TYPE] == 'Primary Shelf'] \
            [ScifConsts.LOCATION_TYPE_FK].values[0]
        if not filtered_matches.empty:
            sub_cat_df = filtered_matches.groupby(
                [ScifConsts.SUB_CATEGORY_FK, ScifConsts.CATEGORY_FK],
                as_index=False).agg({MatchesConsts.WIDTH_MM_ADVANCE: np.sum})
            if not sub_cat_df.empty:
                sub_cat_df = sub_cat_df.merge(cat_df,
                                              on=ScifConsts.CATEGORY_FK,
                                              how='left')
                sub_cat_df['sos'] = sub_cat_df[
                    MatchesConsts.WIDTH_MM_ADVANCE] / sub_cat_df['cat_len']
                for i, row in sub_cat_df.iterrows():
                    self.write_to_db_result(
                        fk=kpi_fk,
                        numerator_id=row[ScifConsts.SUB_CATEGORY_FK],
                        numerator_result=row[MatchesConsts.WIDTH_MM_ADVANCE],
                        denominator_id=row[ScifConsts.CATEGORY_FK],
                        denominator_result=row['cat_len'],
                        result=row['sos'] * 100,
                        context_id=location_type_fk)
                    self.util.add_kpi_result_to_kpi_results_df([
                        kpi_fk, row[ScifConsts.SUB_CATEGORY_FK],
                        row[ScifConsts.CATEGORY_FK], row['sos'] * 100, None,
                        None
                    ])
Beispiel #9
0
class CategoryFullBayKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(CategoryFullBayKpi, self).__init__(data_provider,
                                                 config_params=config_params,
                                                 **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.CATEGORY_FULL_BAY)
        category_fk = self.util.all_products[self.util.all_products[ProductsConsts.CATEGORY] == self.util.CSN]\
            [ProductsConsts.CATEGORY_FK].values[0]
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(
            self.util.CATEGORY_FULL_BAY)
        filtered_matches = self.util.filtered_matches[~(
            self.util.filtered_matches[MatchesConsts.BAY_NUMBER] == -1)]
        if not filtered_matches.empty:
            scene_bay_product = filtered_matches.groupby([
                MatchesConsts.SCENE_FK, MatchesConsts.BAY_NUMBER,
                ScifConsts.PRODUCT_FK
            ],
                                                         as_index=False).agg(
                                                             {'count': np.sum})
            scene_bay_product = scene_bay_product.merge(
                self.util.all_products,
                on=ProductsConsts.PRODUCT_FK,
                how='left')
            scene_bay = scene_bay_product.groupby(
                [MatchesConsts.SCENE_FK, MatchesConsts.BAY_NUMBER],
                as_index=False).agg({'count': np.sum})
            scene_bay.rename(columns={'count': 'total_facings'}, inplace=True)

            cat_relevant_df = scene_bay_product[scene_bay_product[
                ProductsConsts.CATEGORY_FK] == category_fk]
            result_df = cat_relevant_df.groupby(
                [MatchesConsts.SCENE_FK, MatchesConsts.BAY_NUMBER],
                as_index=False).agg({'count': np.sum})
            result_df = result_df.merge(
                scene_bay,
                on=[MatchesConsts.SCENE_FK, MatchesConsts.BAY_NUMBER],
                how='left')
            result_df[
                'ratio'] = result_df['count'] / result_df['total_facings']
            target_ratio = float(self._config_params['ratio'])
            result = len(result_df[result_df['ratio'] >= target_ratio])
            self.write_to_db_result(
                fk=kpi_fk,
                numerator_id=category_fk,
                denominator_id=self.util.store_id,
                score=result,
                result=result,
                target=float(self._config_params['ratio']) * 100)
            self.util.add_kpi_result_to_kpi_results_df([
                kpi_fk, category_fk, self.util.store_id, result, result, None
            ])

        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()
class SosVsTargetHeroSkuKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(SosVsTargetHeroSkuKpi,
              self).__init__(data_provider,
                             config_params=config_params,
                             **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.HERO_SKU_SOS)
        self.calculate_hero_sku_sos()
        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def calculate_hero_sku_sos(self):
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(
            self.util.HERO_SKU_SOS)
        filtered_scif = self.util.filtered_scif
        location_type_fk = self.util.all_templates[self.util.all_templates[ScifConsts.LOCATION_TYPE] == 'Primary Shelf'] \
            [ScifConsts.LOCATION_TYPE_FK].values[0]
        if (not filtered_scif.empty) and (not self.dependencies_data.empty):
            category_df = filtered_scif.groupby([ScifConsts.CATEGORY_FK],
                                                as_index=False).agg({
                                                    'updated_gross_length':
                                                    np.sum
                                                })
            category_df.rename(columns={'updated_gross_length': 'cat_len'},
                               inplace=True)

            av_hero_list = self.util.get_available_hero_sku_list(
                self.dependencies_data)
            filtered_scif = filtered_scif[filtered_scif[
                ScifConsts.PRODUCT_FK].isin(av_hero_list)]

            unav_hero_list = self.util.get_unavailable_hero_sku_list(
                self.dependencies_data)
            unav_hero_df = self.util.all_products[self.util.all_products[ScifConsts.PRODUCT_FK].isin(unav_hero_list)] \
                [[ScifConsts.PRODUCT_FK, ScifConsts.CATEGORY_FK]]
            unav_hero_df['updated_gross_length'] = 0
            filtered_scif = filtered_scif.append(unav_hero_df)

            hero_cat_df = filtered_scif.groupby(
                [ScifConsts.PRODUCT_FK, ScifConsts.CATEGORY_FK],
                as_index=False).agg({'updated_gross_length': np.sum})
            hero_cat_df = hero_cat_df.merge(category_df,
                                            on=ScifConsts.CATEGORY_FK,
                                            how='left')
            hero_cat_df['cat_len'] = hero_cat_df['cat_len'].fillna(0)
            hero_cat_df['sos'] = hero_cat_df.apply(self.calculate_sos, axis=1)
            for i, row in hero_cat_df.iterrows():
                self.write_to_db_result(
                    fk=kpi_fk,
                    numerator_id=row[ScifConsts.PRODUCT_FK],
                    numerator_result=row['updated_gross_length'],
                    denominator_id=row[ScifConsts.CATEGORY_FK],
                    denominator_result=row['cat_len'],
                    result=row['sos'],
                    context_id=location_type_fk)
                self.util.add_kpi_result_to_kpi_results_df([
                    kpi_fk, row[ScifConsts.PRODUCT_FK],
                    row[ScifConsts.CATEGORY_FK], row['sos'], None, None
                ])

    @staticmethod
    def calculate_sos(row):
        sos = 0
        if row['cat_len'] != 0:
            sos = float(row['updated_gross_length']) / row['cat_len'] * 100
        return sos
Beispiel #11
0
class SosVsTargetSubBrandKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(SosVsTargetSubBrandKpi,
              self).__init__(data_provider,
                             config_params=config_params,
                             **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        sos_targets = self.util.sos_vs_target_targets.copy()
        # sos_targets = sos_targets[sos_targets['type'] == self._config_params['kpi_type']]
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.SUB_BRAND_SPACE_TO_SALES_INDEX)
        self.calculate_sub_brand_sos_vs_target(sos_targets)
        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def calculate_sub_brand_sos_vs_target(self, sos_targets):
        sos_targets = sos_targets[sos_targets['type'] ==
                                  self.util.SUB_BRAND_SPACE_TO_SALES_INDEX]
        session_sub_brands = self.util.filtered_scif['sub_brand'].unique(
        ).tolist()
        session_sub_brands = filter(lambda v: v == v, session_sub_brands)
        session_sub_brands = filter(lambda v: v is not None,
                                    session_sub_brands)
        targets_sub_brands = sos_targets['numerator_value'].values.tolist()
        additional_sub_brands = list(
            set(session_sub_brands) - set(targets_sub_brands))
        category_fk = self.util.all_products[self.util.all_products['category']
                                             == 'CSN']['category_fk'].values[0]
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(
            self.util.SUB_BRAND_SPACE_TO_SALES_INDEX)
        kpi_parent = self.util.common.get_kpi_fk_by_kpi_type(
            self.util.SUB_BRAND_SPACE_SOS_VS_TARGET)

        additional_rows = []
        for sub_brand in additional_sub_brands:
            sub_brand_df = self.util.custom_entities[
                self.util.custom_entities['name'] == sub_brand]
            sub_brand_fk = sub_brand_df['pk'].values[0] if len(
                sub_brand_df) > 0 else None
            if sub_brand_fk is None:
                Log.warning(
                    'Sub_brand: {} is not in custom_entity table. Please add'.
                    format(sub_brand))
            else:
                values_to_append = {
                    'numerator_id':
                    sub_brand_fk,
                    'numerator_type':
                    'sub_brand',
                    'numerator_value':
                    sub_brand,
                    'denominator_type':
                    'category_fk',
                    'denominator_value':
                    category_fk,
                    'Target':
                    None,
                    'denominator_id':
                    category_fk,
                    'kpi_level_2_fk':
                    kpi_fk,
                    'KPI Parent':
                    kpi_parent,
                    'identifier_parent':
                    self.util.common.get_dictionary(
                        kpi_fk=int(float(kpi_parent)))
                }
                additional_rows.append(values_to_append)

        df_to_append = pd.DataFrame.from_records(additional_rows)
        sos_targets = sos_targets.append(df_to_append)

        sos_targets = sos_targets[sos_targets['numerator_value'].isin(
            session_sub_brands)]
        self.calculate_and_write_to_db_sos_vs_target_kpi_results(sos_targets)

    def calculate_and_write_to_db_sos_vs_target_kpi_results(self, sos_targets):
        for i, row in sos_targets.iterrows():
            general_filters = {
                row['denominator_type']: row['denominator_value']
            }
            sos_filters = {row['numerator_type']: row['numerator_value']}
            numerator_linear, denominator_linear = self.util.calculate_sos(
                sos_filters, **general_filters)

            result = numerator_linear / denominator_linear if denominator_linear != 0 else 0
            score = result / row['Target'] if row['Target'] else 0
            if row['Target']:
                self.write_to_db_result(fk=row.kpi_level_2_fk,
                                        numerator_id=row.numerator_id,
                                        numerator_result=numerator_linear,
                                        denominator_id=row.denominator_id,
                                        denominator_result=denominator_linear,
                                        result=result * 100,
                                        score=score,
                                        target=row['Target'] * 100)
            else:
                self.write_to_db_result(fk=row.kpi_level_2_fk,
                                        numerator_id=row.numerator_id,
                                        numerator_result=numerator_linear,
                                        denominator_id=row.denominator_id,
                                        denominator_result=denominator_linear,
                                        result=result * 100)
            self.util.add_kpi_result_to_kpi_results_df([
                row.kpi_level_2_fk, row.numerator_id, row.denominator_id,
                result * 100, score
            ])
class FacingsPerProductKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(FacingsPerProductKpi, self).__init__(data_provider,
                                                   config_params=config_params,
                                                   **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.FACINGS_PER_PRODUCT)
        if not self.util.filtered_matches.empty:
            kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(
                self.util.FACINGS_PER_PRODUCT)
            filtered_matches = self.util.filtered_matches.copy()
            shelves_arr = np.sort(filtered_matches[
                MatchesConsts.SHELF_NUMBER].unique()).tolist()
            filtered_matches[MatchesConsts.SHELF_NUMBER] = filtered_matches[MatchesConsts.SHELF_NUMBER]. \
                apply(lambda x: shelves_arr.index(x)+1)
            filtered_matches = filtered_matches.merge(
                self.util.all_products,
                on=MatchesConsts.PRODUCT_FK,
                how='left')
            filtered_matches.loc[filtered_matches['att1'] == 'display cardboard box', 'count'] = \
                filtered_matches['count'] * 3
            result_df = filtered_matches.groupby([
                MatchesConsts.PRODUCT_FK, MatchesConsts.SHELF_NUMBER,
                MatchesConsts.BAY_NUMBER
            ],
                                                 as_index=False).agg(
                                                     {'count': np.sum})

            shelves_cust_entity = self.util.custom_entities[
                self.util.custom_entities['entity_type'] == 'shelf_number']
            shelves_cust_entity['name'] = shelves_cust_entity['name'].astype(
                int)
            bays_cust_entity = self.util.custom_entities[
                self.util.custom_entities['entity_type'] == 'bay_number']
            bays_cust_entity['name'] = bays_cust_entity['name'].astype(int)

            result_df = result_df.merge(shelves_cust_entity,
                                        left_on=MatchesConsts.SHELF_NUMBER,
                                        right_on='name',
                                        how='left')
            result_df.rename(columns={'pk': 'shelf_fk'}, inplace=True)
            result_df = result_df.merge(bays_cust_entity,
                                        left_on=MatchesConsts.BAY_NUMBER,
                                        right_on='name',
                                        how='left')
            result_df.rename(columns={'pk': 'bay_fk'}, inplace=True)

            for i, row in result_df.iterrows():
                self.write_to_db_result(
                    fk=kpi_fk,
                    numerator_result=row[MatchesConsts.SHELF_NUMBER],
                    result=row['count'],
                    numerator_id=row[MatchesConsts.PRODUCT_FK],
                    denominator_id=row[MatchesConsts.PRODUCT_FK],
                    denominator_result=row[MatchesConsts.BAY_NUMBER],
                    context_id=row['shelf_fk'],
                    by_scene=True)
                self.util.add_kpi_result_to_kpi_results_df([
                    kpi_fk, row[MatchesConsts.PRODUCT_FK], row['bay_fk'],
                    row['count'], None, row['shelf_fk']
                ])

        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()
class SosVsTargetHeroSkuKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(SosVsTargetHeroSkuKpi,
              self).__init__(data_provider,
                             config_params=config_params,
                             **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        sos_targets = self.util.sos_vs_target_targets.copy()
        # sos_targets = sos_targets[sos_targets['type'] == self._config_params['kpi_type']]
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.HERO_SKU_SPACE_TO_SALES_INDEX)
        self.calculate_hero_sku_sos_vs_target(sos_targets)
        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def calculate_hero_sku_sos_vs_target(self, sos_targets):
        kpi_filtered_products = self.util.filtered_scif['product_fk'].unique(
        ).tolist()
        # hero_list = self.util.lvl3_ass_result[self.util.lvl3_ass_result['in_store'] == 1]['product_fk'].unique().tolist()
        hero_list = self.util.get_available_hero_sku_list(
            self.dependencies_data)
        hero_list = filter(lambda x: x in kpi_filtered_products, hero_list)

        sos_targets = sos_targets[sos_targets['type'] ==
                                  self.util.HERO_SKU_SPACE_TO_SALES_INDEX]
        sos_targets_hero_list = sos_targets['numerator_value'].values.tolist()
        additional_skus = list(set(hero_list) - set(sos_targets_hero_list))
        category_fk = self.util.all_products[self.util.all_products['category']
                                             == 'CSN']['category_fk'].values[0]
        hero_kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(
            self.util.HERO_SKU_SPACE_TO_SALES_INDEX)
        kpi_hero_parent = self.util.common.get_kpi_fk_by_kpi_type(
            self.util.HERO_SKU_SOS_VS_TARGET)
        additional_rows = []
        for sku in additional_skus:
            values_to_append = {
                'numerator_id':
                sku,
                'numerator_type':
                'product_fk',
                'numerator_value':
                sku,
                'denominator_type':
                'category_fk',
                'denominator_value':
                category_fk,
                'Target':
                None,
                'denominator_id':
                category_fk,
                'kpi_level_2_fk':
                hero_kpi_fk,
                'KPI Parent':
                kpi_hero_parent,
                'identifier_parent':
                self.util.common.get_dictionary(
                    kpi_fk=int(float(kpi_hero_parent)))
            }
            additional_rows.append(values_to_append)
        df_to_append = pd.DataFrame.from_records(additional_rows)
        sos_targets = sos_targets.append(df_to_append)

        sos_targets = sos_targets[sos_targets['numerator_value'].isin(
            hero_list)]
        self.calculate_and_write_to_db_sos_vs_target_kpi_results(sos_targets)

    def calculate_and_write_to_db_sos_vs_target_kpi_results(self, sos_targets):
        for i, row in sos_targets.iterrows():
            general_filters = {
                row['denominator_type']: row['denominator_value']
            }
            sos_filters = {row['numerator_type']: row['numerator_value']}
            numerator_linear, denominator_linear = self.util.calculate_sos(
                sos_filters, **general_filters)

            result = numerator_linear / denominator_linear if denominator_linear != 0 else 0
            score = result / row['Target'] if row['Target'] else 0
            if row['Target']:
                self.write_to_db_result(fk=row.kpi_level_2_fk,
                                        numerator_id=row.numerator_id,
                                        numerator_result=numerator_linear,
                                        denominator_id=row.denominator_id,
                                        denominator_result=denominator_linear,
                                        result=result * 100,
                                        score=score,
                                        target=row['Target'] * 100)
            else:
                self.write_to_db_result(fk=row.kpi_level_2_fk,
                                        numerator_id=row.numerator_id,
                                        numerator_result=numerator_linear,
                                        denominator_id=row.denominator_id,
                                        denominator_result=denominator_linear,
                                        result=result * 100)
            self.util.add_kpi_result_to_kpi_results_df([
                row.kpi_level_2_fk, row.numerator_id, row.denominator_id,
                result * 100, score
            ])
class SosVsTargetSegmentKpi(UnifiedCalculationsScript):

    def __init__(self, data_provider, config_params=None, **kwargs):
        super(SosVsTargetSegmentKpi, self).__init__(data_provider, config_params=config_params, **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        sos_targets = self.util.sos_vs_target_targets.copy()
        # sos_targets = sos_targets[sos_targets['type'] == self._config_params['kpi_type']]
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self.util.PEPSICO_SEGMENT_SPACE_TO_SALES_INDEX)
        self.calculate_pepsico_segment_space_sos_vs_target(sos_targets)
        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()

    def calculate_pepsico_segment_space_sos_vs_target(self, sos_targets):
        sos_targets = sos_targets[sos_targets['type'] == self.util.PEPSICO_SEGMENT_SPACE_TO_SALES_INDEX]
        session_sub_category_list = self.util.filtered_scif['sub_category_fk'].unique().tolist()
        session_sub_category_list = filter(lambda v: v == v, session_sub_category_list)
        session_sub_category_list = filter(lambda v: v is not None, session_sub_category_list)
        targets_sub_category_list = sos_targets['denominator_value'].values.tolist()
        additional_sub_categories = list(set(session_sub_category_list) - set(targets_sub_category_list))
        kpi_fk = self.util.common.get_kpi_fk_by_kpi_type(self.util.PEPSICO_SEGMENT_SPACE_TO_SALES_INDEX)
        kpi_parent = self.util.common.get_kpi_fk_by_kpi_type(self.util.PEPSICO_SEGMENT_SOS_VS_TARGET)

        additional_rows = []
        for sub_category in additional_sub_categories:
            values_to_append = {'numerator_id': self.util.own_manuf_fk, 'numerator_type': 'manufacturer_fk',
                                'numerator_value': self.util.own_manuf_fk, 'denominator_type': 'sub_category_fk',
                                'denominator_value': sub_category, 'Target': None, 'denominator_id': sub_category,
                                'kpi_level_2_fk': kpi_fk, 'KPI Parent': kpi_parent,
                                'identifier_parent': self.util.common.get_dictionary(kpi_fk=int(float(kpi_parent)))}
            additional_rows.append(values_to_append)
        df_to_append = pd.DataFrame.from_records(additional_rows)
        sos_targets = sos_targets.append(df_to_append)

        sos_targets = sos_targets[sos_targets['denominator_value'].isin(session_sub_category_list)]
        self.calculate_and_write_to_db_sos_vs_target_kpi_results(sos_targets)

    def calculate_and_write_to_db_sos_vs_target_kpi_results(self, sos_targets):
        for i, row in sos_targets.iterrows():
            general_filters = {row['denominator_type']: row['denominator_value']}
            sos_filters = {row['numerator_type']: row['numerator_value']}
            numerator_linear, denominator_linear = self.util.calculate_sos(sos_filters, **general_filters)

            result = numerator_linear / denominator_linear if denominator_linear != 0 else 0
            score = result / row['Target'] if row['Target'] else 0
            if row['Target']:
                self.write_to_db_result(fk=row.kpi_level_2_fk, numerator_id=row.numerator_id,
                                        numerator_result=numerator_linear, denominator_id=row.denominator_id,
                                        denominator_result=denominator_linear, result=result * 100, score=score,
                                        target=row['Target'] * 100)
            else:
                self.write_to_db_result(fk=row.kpi_level_2_fk, numerator_id=row.numerator_id,
                                        numerator_result=numerator_linear, denominator_id=row.denominator_id,
                                        denominator_result=denominator_linear, result=result * 100)
            self.util.add_kpi_result_to_kpi_results_df(
                [row.kpi_level_2_fk, row.numerator_id, row.denominator_id, result * 100,
                 score])
class LinearBrandVsBrandIndexKpi(UnifiedCalculationsScript):
    def __init__(self, data_provider, config_params=None, **kwargs):
        super(LinearBrandVsBrandIndexKpi,
              self).__init__(data_provider,
                             config_params=config_params,
                             **kwargs)
        self.util = PepsicoUtil(None, data_provider)

    def kpi_type(self):
        pass

    def calculate(self):
        self.util.filtered_scif, self.util.filtered_matches = \
            self.util.commontools.set_filtered_scif_and_matches_for_specific_kpi(self.util.filtered_scif,
                                                                                 self.util.filtered_matches,
                                                                                 self._config_params['kpi_type'])

        index_targets = self.util.get_relevant_sos_vs_target_kpi_targets(
            brand_vs_brand=True)
        index_targets['numerator_id'] = index_targets.apply(
            self.util.retrieve_relevant_item_pks,
            axis=1,
            args=('numerator_type', 'numerator_value'))
        index_targets['denominator_id'] = index_targets.apply(
            self.util.retrieve_relevant_item_pks,
            axis=1,
            args=('denominator_type', 'denominator_value'))
        index_targets['identifier_parent'] = index_targets['KPI Parent'].apply(
            lambda x: self.util.common.get_dictionary(kpi_fk=int(float(x))))
        index_targets = index_targets[index_targets['type'] ==
                                      self._config_params['kpi_type']]
        location_type_fk = self.util.all_templates[self.util.all_templates[ScifConsts.LOCATION_TYPE] == 'Primary Shelf'] \
            [ScifConsts.LOCATION_TYPE_FK].values[0]
        for i, row in index_targets.iterrows():
            general_filters = {
                row['additional_filter_type_1']:
                row['additional_filter_value_1']
            }
            numerator_sos_filters = {
                row['numerator_type']: row['numerator_value']
            }
            num_num_linear, num_denom_linear = self.util.calculate_sos(
                numerator_sos_filters, **general_filters)
            numerator_sos = num_num_linear / num_denom_linear if num_denom_linear else 0

            denominator_sos_filters = {
                row['denominator_type']: row['denominator_value']
            }
            denom_num_linear, denom_denom_linear = self.util.calculate_sos(
                denominator_sos_filters, **general_filters)
            denominator_sos = denom_num_linear / denom_denom_linear if denom_denom_linear else 0

            if denominator_sos == 0:
                index = 0 if numerator_sos == 0 else 1
            else:
                index = numerator_sos / denominator_sos

            self.write_to_db_result(fk=row.kpi_level_2_fk,
                                    numerator_id=row.numerator_id,
                                    numerator_result=num_num_linear,
                                    denominator_id=row.denominator_id,
                                    denominator_result=denom_num_linear,
                                    result=index,
                                    score=index,
                                    context_id=location_type_fk)
            self.util.add_kpi_result_to_kpi_results_df([
                row.kpi_level_2_fk, row.numerator_id, row.denominator_id,
                index, index, None
            ])

        self.util.reset_filtered_scif_and_matches_to_exclusion_all_state()