{% macro generate_kpis_aggregation(time_granularity, agg_models) %}
    select
        d.date,
        '{{ time_granularity }}' as time_granularity,
        d.dimension,
        d.dimension_value
        {%- for agg_model in agg_models if time_granularity in agg_model["name"] %}
            {%- for metric in agg_model["metrics"] %}
                , coalesce({{ ref(agg_model["name"]) }}.{{ metric }}, 0) as {{ metric }}
            {%- endfor %}
        {%- endfor %}
    from all_dates d
    {%- for agg_model in agg_models if time_granularity in agg_model["name"] %}
        left join
            {{ ref(agg_model["name"]) }}
            on d.date = {{ ref(agg_model["name"]) }}.{{ agg_model["date_field"] }}
            and d.dimension = {{ ref(agg_model["name"]) }}.dimension
            and d.dimension_value = {{ ref(agg_model["name"]) }}.dimension_value
    {%- endfor %}
    {% if time_granularity == "weekly" %} where d.is_end_of_week
    {% elif time_granularity == "monthly" %} where d.is_end_of_month
    {% endif %}
{% endmacro %}
