from .interface import AnalyticsModuleInterface from .params import Param, ParamSchema class AttributeGenderValueCount(AnalyticsModuleInterface): """This analytics' module purpose is to handle some oddities arising with set collections (or combined datasets), where fan counts grouped by gender don't add up to total fan count. This is fixing a symptom, whereas a fix to the root cause should handle it at the enrichment level.""" description = """ """ inputs = [ ParamSchema, Param("field_name"), Param("attribute_id", configurable=False), Param("collection_id", required=False), Param("collection_ids", list, required=False), ] outputs = [Param("label", idx=0), Param("value", int, idx=1)] @staticmethod def get_query( # type: ignore schema: str, collection_id: str = None, collection_ids: list = None, **kwargs ) -> str: """Generate SQL query based on the fields. We don't need almost any of the params we have for other charts.""" join_collection = "" parents_filter = "" """ In case we get one collection. Note that in case we get multiple collections, we also get collection_id, so order of this statement and the next is important """ if collection_id is not None: join_collection = f"join {schema}.collection c on fa.collection_id = c.id" parents_filter = f" and c.parent_id in ({collection_id})" # In case we get multiple collections, we join collection table and filter by parent collection ids. if collection_ids: join_collection = f"join {schema}.collection c on fa.collection_id = c.id" parents_filter = f" and c.parent_id in ({', '.join(str(int(i)) for i in collection_ids)})" result_query = f""" select coalesce(fa2.value, 'unknown') as label, count(distinct fa.fan_id) as value from {schema}.fan_attribute fa left join ( select distinct on (fan_id) fan_id, value from {schema}.fan_attribute fa {join_collection} where 1=1 {parents_filter} and fa.attribute_id = %(attribute_id)s and fa.value != 'unknown' ) fa2 on fa.fan_id = fa2.fan_id {join_collection} where 1=1 {parents_filter} group by 1 ; """ return result_query